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;
   73use zed_predict_tos::ZedPredictTos;
   74
   75use code_context_menus::{
   76    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   77    CompletionEntry, CompletionsMenu, ContextMenuOrigin,
   78};
   79use git::blame::GitBlame;
   80use gpui::{
   81    div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, AppContext,
   82    AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
   83    DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView, FontId,
   84    FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, ModelContext,
   85    MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
   86    Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
   87    UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
   88    WeakView, WindowContext,
   89};
   90use highlight_matching_bracket::refresh_matching_bracket_highlights;
   91use hover_popover::{hide_hover, HoverState};
   92pub(crate) use hunk_diff::HoveredHunk;
   93use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
   94use indent_guides::ActiveIndentGuidesState;
   95use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   96pub use inline_completion::Direction;
   97use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
   98pub use items::MAX_TAB_TITLE_LEN;
   99use itertools::Itertools;
  100use language::{
  101    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
  102    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  103    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
  104    Point, Selection, SelectionGoal, TransactionId,
  105};
  106use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  107use linked_editing_ranges::refresh_linked_ranges;
  108use mouse_context_menu::MouseContextMenu;
  109pub use proposed_changes_editor::{
  110    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  111};
  112use similar::{ChangeTag, TextDiff};
  113use std::iter::Peekable;
  114use task::{ResolvedTask, TaskTemplate, TaskVariables};
  115
  116use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  117pub use lsp::CompletionContext;
  118use lsp::{
  119    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  120    LanguageServerId, LanguageServerName,
  121};
  122
  123use movement::TextLayoutDetails;
  124pub use multi_buffer::{
  125    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  126    ToPoint,
  127};
  128use multi_buffer::{
  129    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  130};
  131use project::{
  132    buffer_store::BufferChangeSet,
  133    lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  134    project_settings::{GitGutterSetting, ProjectSettings},
  135    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  136    LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  137};
  138use rand::prelude::*;
  139use rpc::{proto::*, ErrorExt};
  140use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  141use selections_collection::{
  142    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  143};
  144use serde::{Deserialize, Serialize};
  145use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  146use smallvec::SmallVec;
  147use snippet::Snippet;
  148use std::{
  149    any::TypeId,
  150    borrow::Cow,
  151    cell::RefCell,
  152    cmp::{self, Ordering, Reverse},
  153    mem,
  154    num::NonZeroU32,
  155    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  156    path::{Path, PathBuf},
  157    rc::Rc,
  158    sync::Arc,
  159    time::{Duration, Instant},
  160};
  161pub use sum_tree::Bias;
  162use sum_tree::TreeMap;
  163use text::{BufferId, OffsetUtf16, Rope};
  164use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
  165use ui::{
  166    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  167    PopoverMenuHandle, Tooltip,
  168};
  169use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  170use workspace::item::{ItemHandle, PreviewTabsSettings};
  171use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  172use workspace::{
  173    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  174};
  175use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  176
  177use crate::hover_links::{find_url, find_url_from_range};
  178use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  179
  180pub const FILE_HEADER_HEIGHT: u32 = 2;
  181pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  182pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  183pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  184const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  185const MAX_LINE_LEN: usize = 1024;
  186const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  187const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  188pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  189#[doc(hidden)]
  190pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  191
  192pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  193pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  194
  195pub fn render_parsed_markdown(
  196    element_id: impl Into<ElementId>,
  197    parsed: &language::ParsedMarkdown,
  198    editor_style: &EditorStyle,
  199    workspace: Option<WeakView<Workspace>>,
  200    cx: &mut WindowContext,
  201) -> InteractiveText {
  202    let code_span_background_color = cx
  203        .theme()
  204        .colors()
  205        .editor_document_highlight_read_background;
  206
  207    let highlights = gpui::combine_highlights(
  208        parsed.highlights.iter().filter_map(|(range, highlight)| {
  209            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  210            Some((range.clone(), highlight))
  211        }),
  212        parsed
  213            .regions
  214            .iter()
  215            .zip(&parsed.region_ranges)
  216            .filter_map(|(region, range)| {
  217                if region.code {
  218                    Some((
  219                        range.clone(),
  220                        HighlightStyle {
  221                            background_color: Some(code_span_background_color),
  222                            ..Default::default()
  223                        },
  224                    ))
  225                } else {
  226                    None
  227                }
  228            }),
  229    );
  230
  231    let mut links = Vec::new();
  232    let mut link_ranges = Vec::new();
  233    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  234        if let Some(link) = region.link.clone() {
  235            links.push(link);
  236            link_ranges.push(range.clone());
  237        }
  238    }
  239
  240    InteractiveText::new(
  241        element_id,
  242        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  243    )
  244    .on_click(link_ranges, move |clicked_range_ix, cx| {
  245        match &links[clicked_range_ix] {
  246            markdown::Link::Web { url } => cx.open_url(url),
  247            markdown::Link::Path { path } => {
  248                if let Some(workspace) = &workspace {
  249                    _ = workspace.update(cx, |workspace, cx| {
  250                        workspace.open_abs_path(path.clone(), false, cx).detach();
  251                    });
  252                }
  253            }
  254        }
  255    })
  256}
  257
  258#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  259pub enum InlayId {
  260    InlineCompletion(usize),
  261    Hint(usize),
  262}
  263
  264impl InlayId {
  265    fn id(&self) -> usize {
  266        match self {
  267            Self::InlineCompletion(id) => *id,
  268            Self::Hint(id) => *id,
  269        }
  270    }
  271}
  272
  273enum DiffRowHighlight {}
  274enum DocumentHighlightRead {}
  275enum DocumentHighlightWrite {}
  276enum InputComposition {}
  277
  278#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  279pub enum Navigated {
  280    Yes,
  281    No,
  282}
  283
  284impl Navigated {
  285    pub fn from_bool(yes: bool) -> Navigated {
  286        if yes {
  287            Navigated::Yes
  288        } else {
  289            Navigated::No
  290        }
  291    }
  292}
  293
  294pub fn init_settings(cx: &mut AppContext) {
  295    EditorSettings::register(cx);
  296}
  297
  298pub fn init(cx: &mut AppContext) {
  299    init_settings(cx);
  300
  301    workspace::register_project_item::<Editor>(cx);
  302    workspace::FollowableViewRegistry::register::<Editor>(cx);
  303    workspace::register_serializable_item::<Editor>(cx);
  304
  305    cx.observe_new_views(
  306        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  307            workspace.register_action(Editor::new_file);
  308            workspace.register_action(Editor::new_file_vertical);
  309            workspace.register_action(Editor::new_file_horizontal);
  310        },
  311    )
  312    .detach();
  313
  314    cx.on_action(move |_: &workspace::NewFile, cx| {
  315        let app_state = workspace::AppState::global(cx);
  316        if let Some(app_state) = app_state.upgrade() {
  317            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  318                Editor::new_file(workspace, &Default::default(), cx)
  319            })
  320            .detach();
  321        }
  322    });
  323    cx.on_action(move |_: &workspace::NewWindow, cx| {
  324        let app_state = workspace::AppState::global(cx);
  325        if let Some(app_state) = app_state.upgrade() {
  326            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  327                Editor::new_file(workspace, &Default::default(), cx)
  328            })
  329            .detach();
  330        }
  331    });
  332    git::project_diff::init(cx);
  333}
  334
  335pub struct SearchWithinRange;
  336
  337trait InvalidationRegion {
  338    fn ranges(&self) -> &[Range<Anchor>];
  339}
  340
  341#[derive(Clone, Debug, PartialEq)]
  342pub enum SelectPhase {
  343    Begin {
  344        position: DisplayPoint,
  345        add: bool,
  346        click_count: usize,
  347    },
  348    BeginColumnar {
  349        position: DisplayPoint,
  350        reset: bool,
  351        goal_column: u32,
  352    },
  353    Extend {
  354        position: DisplayPoint,
  355        click_count: usize,
  356    },
  357    Update {
  358        position: DisplayPoint,
  359        goal_column: u32,
  360        scroll_delta: gpui::Point<f32>,
  361    },
  362    End,
  363}
  364
  365#[derive(Clone, Debug)]
  366pub enum SelectMode {
  367    Character,
  368    Word(Range<Anchor>),
  369    Line(Range<Anchor>),
  370    All,
  371}
  372
  373#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  374pub enum EditorMode {
  375    SingleLine { auto_width: bool },
  376    AutoHeight { max_lines: usize },
  377    Full,
  378}
  379
  380#[derive(Copy, Clone, Debug)]
  381pub enum SoftWrap {
  382    /// Prefer not to wrap at all.
  383    ///
  384    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  385    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  386    GitDiff,
  387    /// Prefer a single line generally, unless an overly long line is encountered.
  388    None,
  389    /// Soft wrap lines that exceed the editor width.
  390    EditorWidth,
  391    /// Soft wrap lines at the preferred line length.
  392    Column(u32),
  393    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  394    Bounded(u32),
  395}
  396
  397#[derive(Clone)]
  398pub struct EditorStyle {
  399    pub background: Hsla,
  400    pub local_player: PlayerColor,
  401    pub text: TextStyle,
  402    pub scrollbar_width: Pixels,
  403    pub syntax: Arc<SyntaxTheme>,
  404    pub status: StatusColors,
  405    pub inlay_hints_style: HighlightStyle,
  406    pub inline_completion_styles: InlineCompletionStyles,
  407    pub unnecessary_code_fade: f32,
  408}
  409
  410impl Default for EditorStyle {
  411    fn default() -> Self {
  412        Self {
  413            background: Hsla::default(),
  414            local_player: PlayerColor::default(),
  415            text: TextStyle::default(),
  416            scrollbar_width: Pixels::default(),
  417            syntax: Default::default(),
  418            // HACK: Status colors don't have a real default.
  419            // We should look into removing the status colors from the editor
  420            // style and retrieve them directly from the theme.
  421            status: StatusColors::dark(),
  422            inlay_hints_style: HighlightStyle::default(),
  423            inline_completion_styles: InlineCompletionStyles {
  424                insertion: HighlightStyle::default(),
  425                whitespace: HighlightStyle::default(),
  426            },
  427            unnecessary_code_fade: Default::default(),
  428        }
  429    }
  430}
  431
  432pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  433    let show_background = language_settings::language_settings(None, None, cx)
  434        .inlay_hints
  435        .show_background;
  436
  437    HighlightStyle {
  438        color: Some(cx.theme().status().hint),
  439        background_color: show_background.then(|| cx.theme().status().hint_background),
  440        ..HighlightStyle::default()
  441    }
  442}
  443
  444pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
  445    InlineCompletionStyles {
  446        insertion: HighlightStyle {
  447            color: Some(cx.theme().status().predictive),
  448            ..HighlightStyle::default()
  449        },
  450        whitespace: HighlightStyle {
  451            background_color: Some(cx.theme().status().created_background),
  452            ..HighlightStyle::default()
  453        },
  454    }
  455}
  456
  457type CompletionId = usize;
  458
  459#[derive(Debug, Clone)]
  460enum InlineCompletionMenuHint {
  461    Loading,
  462    Loaded { text: InlineCompletionText },
  463    PendingTermsAcceptance,
  464    None,
  465}
  466
  467impl InlineCompletionMenuHint {
  468    pub fn label(&self) -> &'static str {
  469        match self {
  470            InlineCompletionMenuHint::Loading | InlineCompletionMenuHint::Loaded { .. } => {
  471                "Edit Prediction"
  472            }
  473            InlineCompletionMenuHint::PendingTermsAcceptance => "Accept Terms of Service",
  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 {
  490        edits: Vec<(Range<Anchor>, String)>,
  491        single_line: bool,
  492    },
  493    Move(Anchor),
  494}
  495
  496struct InlineCompletionState {
  497    inlay_ids: Vec<InlayId>,
  498    completion: InlineCompletion,
  499    invalidation_range: Range<Anchor>,
  500}
  501
  502enum InlineCompletionHighlight {}
  503
  504#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  505struct EditorActionId(usize);
  506
  507impl EditorActionId {
  508    pub fn post_inc(&mut self) -> Self {
  509        let answer = self.0;
  510
  511        *self = Self(answer + 1);
  512
  513        Self(answer)
  514    }
  515}
  516
  517// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  518// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  519
  520type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  521type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  522
  523#[derive(Default)]
  524struct ScrollbarMarkerState {
  525    scrollbar_size: Size<Pixels>,
  526    dirty: bool,
  527    markers: Arc<[PaintQuad]>,
  528    pending_refresh: Option<Task<Result<()>>>,
  529}
  530
  531impl ScrollbarMarkerState {
  532    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  533        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  534    }
  535}
  536
  537#[derive(Clone, Debug)]
  538struct RunnableTasks {
  539    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  540    offset: MultiBufferOffset,
  541    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  542    column: u32,
  543    // Values of all named captures, including those starting with '_'
  544    extra_variables: HashMap<String, String>,
  545    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  546    context_range: Range<BufferOffset>,
  547}
  548
  549impl RunnableTasks {
  550    fn resolve<'a>(
  551        &'a self,
  552        cx: &'a task::TaskContext,
  553    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  554        self.templates.iter().filter_map(|(kind, template)| {
  555            template
  556                .resolve_task(&kind.to_id_base(), cx)
  557                .map(|task| (kind.clone(), task))
  558        })
  559    }
  560}
  561
  562#[derive(Clone)]
  563struct ResolvedTasks {
  564    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  565    position: Anchor,
  566}
  567#[derive(Copy, Clone, Debug)]
  568struct MultiBufferOffset(usize);
  569#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  570struct BufferOffset(usize);
  571
  572// Addons allow storing per-editor state in other crates (e.g. Vim)
  573pub trait Addon: 'static {
  574    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  575
  576    fn to_any(&self) -> &dyn std::any::Any;
  577}
  578
  579#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  580pub enum IsVimMode {
  581    Yes,
  582    No,
  583}
  584
  585/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  586///
  587/// See the [module level documentation](self) for more information.
  588pub struct Editor {
  589    focus_handle: FocusHandle,
  590    last_focused_descendant: Option<WeakFocusHandle>,
  591    /// The text buffer being edited
  592    buffer: Model<MultiBuffer>,
  593    /// Map of how text in the buffer should be displayed.
  594    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  595    pub display_map: Model<DisplayMap>,
  596    pub selections: SelectionsCollection,
  597    pub scroll_manager: ScrollManager,
  598    /// When inline assist editors are linked, they all render cursors because
  599    /// typing enters text into each of them, even the ones that aren't focused.
  600    pub(crate) show_cursor_when_unfocused: bool,
  601    columnar_selection_tail: Option<Anchor>,
  602    add_selections_state: Option<AddSelectionsState>,
  603    select_next_state: Option<SelectNextState>,
  604    select_prev_state: Option<SelectNextState>,
  605    selection_history: SelectionHistory,
  606    autoclose_regions: Vec<AutocloseRegion>,
  607    snippet_stack: InvalidationStack<SnippetState>,
  608    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  609    ime_transaction: Option<TransactionId>,
  610    active_diagnostics: Option<ActiveDiagnosticGroup>,
  611    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  612
  613    project: Option<Model<Project>>,
  614    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  615    completion_provider: Option<Box<dyn CompletionProvider>>,
  616    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  617    blink_manager: Model<BlinkManager>,
  618    show_cursor_names: bool,
  619    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  620    pub show_local_selections: bool,
  621    mode: EditorMode,
  622    show_breadcrumbs: bool,
  623    show_gutter: bool,
  624    show_scrollbars: bool,
  625    show_line_numbers: Option<bool>,
  626    use_relative_line_numbers: Option<bool>,
  627    show_git_diff_gutter: Option<bool>,
  628    show_code_actions: Option<bool>,
  629    show_runnables: Option<bool>,
  630    show_wrap_guides: Option<bool>,
  631    show_indent_guides: Option<bool>,
  632    placeholder_text: Option<Arc<str>>,
  633    highlight_order: usize,
  634    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  635    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  636    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  637    scrollbar_marker_state: ScrollbarMarkerState,
  638    active_indent_guides_state: ActiveIndentGuidesState,
  639    nav_history: Option<ItemNavHistory>,
  640    context_menu: RefCell<Option<CodeContextMenu>>,
  641    mouse_context_menu: Option<MouseContextMenu>,
  642    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  643    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  644    signature_help_state: SignatureHelpState,
  645    auto_signature_help: Option<bool>,
  646    find_all_references_task_sources: Vec<Anchor>,
  647    next_completion_id: CompletionId,
  648    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  649    code_actions_task: Option<Task<Result<()>>>,
  650    document_highlights_task: Option<Task<()>>,
  651    linked_editing_range_task: Option<Task<Option<()>>>,
  652    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  653    pending_rename: Option<RenameState>,
  654    searchable: bool,
  655    cursor_shape: CursorShape,
  656    current_line_highlight: Option<CurrentLineHighlight>,
  657    collapse_matches: bool,
  658    autoindent_mode: Option<AutoindentMode>,
  659    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  660    input_enabled: bool,
  661    use_modal_editing: bool,
  662    read_only: bool,
  663    leader_peer_id: Option<PeerId>,
  664    remote_id: Option<ViewId>,
  665    hover_state: HoverState,
  666    gutter_hovered: bool,
  667    hovered_link_state: Option<HoveredLinkState>,
  668    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  669    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  670    active_inline_completion: Option<InlineCompletionState>,
  671    // enable_inline_completions is a switch that Vim can use to disable
  672    // inline completions based on its mode.
  673    enable_inline_completions: bool,
  674    show_inline_completions_override: Option<bool>,
  675    inlay_hint_cache: InlayHintCache,
  676    diff_map: DiffMap,
  677    next_inlay_id: usize,
  678    _subscriptions: Vec<Subscription>,
  679    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  680    gutter_dimensions: GutterDimensions,
  681    style: Option<EditorStyle>,
  682    text_style_refinement: Option<TextStyleRefinement>,
  683    next_editor_action_id: EditorActionId,
  684    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  685    use_autoclose: bool,
  686    use_auto_surround: bool,
  687    auto_replace_emoji_shortcode: bool,
  688    show_git_blame_gutter: bool,
  689    show_git_blame_inline: bool,
  690    show_git_blame_inline_delay_task: Option<Task<()>>,
  691    git_blame_inline_enabled: bool,
  692    serialize_dirty_buffers: bool,
  693    show_selection_menu: Option<bool>,
  694    blame: Option<Model<GitBlame>>,
  695    blame_subscription: Option<Subscription>,
  696    custom_context_menu: Option<
  697        Box<
  698            dyn 'static
  699                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  700        >,
  701    >,
  702    last_bounds: Option<Bounds<Pixels>>,
  703    expect_bounds_change: Option<Bounds<Pixels>>,
  704    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  705    tasks_update_task: Option<Task<()>>,
  706    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  707    breadcrumb_header: Option<String>,
  708    focused_block: Option<FocusedBlock>,
  709    next_scroll_position: NextScrollCursorCenterTopBottom,
  710    addons: HashMap<TypeId, Box<dyn Addon>>,
  711    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  712    selection_mark_mode: bool,
  713    toggle_fold_multiple_buffers: Task<()>,
  714    _scroll_cursor_center_top_bottom_task: Task<()>,
  715}
  716
  717#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  718enum NextScrollCursorCenterTopBottom {
  719    #[default]
  720    Center,
  721    Top,
  722    Bottom,
  723}
  724
  725impl NextScrollCursorCenterTopBottom {
  726    fn next(&self) -> Self {
  727        match self {
  728            Self::Center => Self::Top,
  729            Self::Top => Self::Bottom,
  730            Self::Bottom => Self::Center,
  731        }
  732    }
  733}
  734
  735#[derive(Clone)]
  736pub struct EditorSnapshot {
  737    pub mode: EditorMode,
  738    show_gutter: bool,
  739    show_line_numbers: Option<bool>,
  740    show_git_diff_gutter: Option<bool>,
  741    show_code_actions: Option<bool>,
  742    show_runnables: Option<bool>,
  743    git_blame_gutter_max_author_length: Option<usize>,
  744    pub display_snapshot: DisplaySnapshot,
  745    pub placeholder_text: Option<Arc<str>>,
  746    diff_map: DiffMapSnapshot,
  747    is_focused: bool,
  748    scroll_anchor: ScrollAnchor,
  749    ongoing_scroll: OngoingScroll,
  750    current_line_highlight: CurrentLineHighlight,
  751    gutter_hovered: bool,
  752}
  753
  754const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  755
  756#[derive(Default, Debug, Clone, Copy)]
  757pub struct GutterDimensions {
  758    pub left_padding: Pixels,
  759    pub right_padding: Pixels,
  760    pub width: Pixels,
  761    pub margin: Pixels,
  762    pub git_blame_entries_width: Option<Pixels>,
  763}
  764
  765impl GutterDimensions {
  766    /// The full width of the space taken up by the gutter.
  767    pub fn full_width(&self) -> Pixels {
  768        self.margin + self.width
  769    }
  770
  771    /// The width of the space reserved for the fold indicators,
  772    /// use alongside 'justify_end' and `gutter_width` to
  773    /// right align content with the line numbers
  774    pub fn fold_area_width(&self) -> Pixels {
  775        self.margin + self.right_padding
  776    }
  777}
  778
  779#[derive(Debug)]
  780pub struct RemoteSelection {
  781    pub replica_id: ReplicaId,
  782    pub selection: Selection<Anchor>,
  783    pub cursor_shape: CursorShape,
  784    pub peer_id: PeerId,
  785    pub line_mode: bool,
  786    pub participant_index: Option<ParticipantIndex>,
  787    pub user_name: Option<SharedString>,
  788}
  789
  790#[derive(Clone, Debug)]
  791struct SelectionHistoryEntry {
  792    selections: Arc<[Selection<Anchor>]>,
  793    select_next_state: Option<SelectNextState>,
  794    select_prev_state: Option<SelectNextState>,
  795    add_selections_state: Option<AddSelectionsState>,
  796}
  797
  798enum SelectionHistoryMode {
  799    Normal,
  800    Undoing,
  801    Redoing,
  802}
  803
  804#[derive(Clone, PartialEq, Eq, Hash)]
  805struct HoveredCursor {
  806    replica_id: u16,
  807    selection_id: usize,
  808}
  809
  810impl Default for SelectionHistoryMode {
  811    fn default() -> Self {
  812        Self::Normal
  813    }
  814}
  815
  816#[derive(Default)]
  817struct SelectionHistory {
  818    #[allow(clippy::type_complexity)]
  819    selections_by_transaction:
  820        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  821    mode: SelectionHistoryMode,
  822    undo_stack: VecDeque<SelectionHistoryEntry>,
  823    redo_stack: VecDeque<SelectionHistoryEntry>,
  824}
  825
  826impl SelectionHistory {
  827    fn insert_transaction(
  828        &mut self,
  829        transaction_id: TransactionId,
  830        selections: Arc<[Selection<Anchor>]>,
  831    ) {
  832        self.selections_by_transaction
  833            .insert(transaction_id, (selections, None));
  834    }
  835
  836    #[allow(clippy::type_complexity)]
  837    fn transaction(
  838        &self,
  839        transaction_id: TransactionId,
  840    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  841        self.selections_by_transaction.get(&transaction_id)
  842    }
  843
  844    #[allow(clippy::type_complexity)]
  845    fn transaction_mut(
  846        &mut self,
  847        transaction_id: TransactionId,
  848    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  849        self.selections_by_transaction.get_mut(&transaction_id)
  850    }
  851
  852    fn push(&mut self, entry: SelectionHistoryEntry) {
  853        if !entry.selections.is_empty() {
  854            match self.mode {
  855                SelectionHistoryMode::Normal => {
  856                    self.push_undo(entry);
  857                    self.redo_stack.clear();
  858                }
  859                SelectionHistoryMode::Undoing => self.push_redo(entry),
  860                SelectionHistoryMode::Redoing => self.push_undo(entry),
  861            }
  862        }
  863    }
  864
  865    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  866        if self
  867            .undo_stack
  868            .back()
  869            .map_or(true, |e| e.selections != entry.selections)
  870        {
  871            self.undo_stack.push_back(entry);
  872            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  873                self.undo_stack.pop_front();
  874            }
  875        }
  876    }
  877
  878    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  879        if self
  880            .redo_stack
  881            .back()
  882            .map_or(true, |e| e.selections != entry.selections)
  883        {
  884            self.redo_stack.push_back(entry);
  885            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  886                self.redo_stack.pop_front();
  887            }
  888        }
  889    }
  890}
  891
  892struct RowHighlight {
  893    index: usize,
  894    range: Range<Anchor>,
  895    color: Hsla,
  896    should_autoscroll: bool,
  897}
  898
  899#[derive(Clone, Debug)]
  900struct AddSelectionsState {
  901    above: bool,
  902    stack: Vec<usize>,
  903}
  904
  905#[derive(Clone)]
  906struct SelectNextState {
  907    query: AhoCorasick,
  908    wordwise: bool,
  909    done: bool,
  910}
  911
  912impl std::fmt::Debug for SelectNextState {
  913    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  914        f.debug_struct(std::any::type_name::<Self>())
  915            .field("wordwise", &self.wordwise)
  916            .field("done", &self.done)
  917            .finish()
  918    }
  919}
  920
  921#[derive(Debug)]
  922struct AutocloseRegion {
  923    selection_id: usize,
  924    range: Range<Anchor>,
  925    pair: BracketPair,
  926}
  927
  928#[derive(Debug)]
  929struct SnippetState {
  930    ranges: Vec<Vec<Range<Anchor>>>,
  931    active_index: usize,
  932    choices: Vec<Option<Vec<String>>>,
  933}
  934
  935#[doc(hidden)]
  936pub struct RenameState {
  937    pub range: Range<Anchor>,
  938    pub old_name: Arc<str>,
  939    pub editor: View<Editor>,
  940    block_id: CustomBlockId,
  941}
  942
  943struct InvalidationStack<T>(Vec<T>);
  944
  945struct RegisteredInlineCompletionProvider {
  946    provider: Arc<dyn InlineCompletionProviderHandle>,
  947    _subscription: Subscription,
  948}
  949
  950#[derive(Debug)]
  951struct ActiveDiagnosticGroup {
  952    primary_range: Range<Anchor>,
  953    primary_message: String,
  954    group_id: usize,
  955    blocks: HashMap<CustomBlockId, Diagnostic>,
  956    is_valid: bool,
  957}
  958
  959#[derive(Serialize, Deserialize, Clone, Debug)]
  960pub struct ClipboardSelection {
  961    pub len: usize,
  962    pub is_entire_line: bool,
  963    pub first_line_indent: u32,
  964}
  965
  966#[derive(Debug)]
  967pub(crate) struct NavigationData {
  968    cursor_anchor: Anchor,
  969    cursor_position: Point,
  970    scroll_anchor: ScrollAnchor,
  971    scroll_top_row: u32,
  972}
  973
  974#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  975pub enum GotoDefinitionKind {
  976    Symbol,
  977    Declaration,
  978    Type,
  979    Implementation,
  980}
  981
  982#[derive(Debug, Clone)]
  983enum InlayHintRefreshReason {
  984    Toggle(bool),
  985    SettingsChange(InlayHintSettings),
  986    NewLinesShown,
  987    BufferEdited(HashSet<Arc<Language>>),
  988    RefreshRequested,
  989    ExcerptsRemoved(Vec<ExcerptId>),
  990}
  991
  992impl InlayHintRefreshReason {
  993    fn description(&self) -> &'static str {
  994        match self {
  995            Self::Toggle(_) => "toggle",
  996            Self::SettingsChange(_) => "settings change",
  997            Self::NewLinesShown => "new lines shown",
  998            Self::BufferEdited(_) => "buffer edited",
  999            Self::RefreshRequested => "refresh requested",
 1000            Self::ExcerptsRemoved(_) => "excerpts removed",
 1001        }
 1002    }
 1003}
 1004
 1005pub enum FormatTarget {
 1006    Buffers,
 1007    Ranges(Vec<Range<MultiBufferPoint>>),
 1008}
 1009
 1010pub(crate) struct FocusedBlock {
 1011    id: BlockId,
 1012    focus_handle: WeakFocusHandle,
 1013}
 1014
 1015#[derive(Clone)]
 1016enum JumpData {
 1017    MultiBufferRow {
 1018        row: MultiBufferRow,
 1019        line_offset_from_top: u32,
 1020    },
 1021    MultiBufferPoint {
 1022        excerpt_id: ExcerptId,
 1023        position: Point,
 1024        anchor: text::Anchor,
 1025        line_offset_from_top: u32,
 1026    },
 1027}
 1028
 1029impl Editor {
 1030    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1031        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1032        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1033        Self::new(
 1034            EditorMode::SingleLine { auto_width: false },
 1035            buffer,
 1036            None,
 1037            false,
 1038            cx,
 1039        )
 1040    }
 1041
 1042    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1043        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1044        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1045        Self::new(EditorMode::Full, buffer, None, false, cx)
 1046    }
 1047
 1048    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1049        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1050        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1051        Self::new(
 1052            EditorMode::SingleLine { auto_width: true },
 1053            buffer,
 1054            None,
 1055            false,
 1056            cx,
 1057        )
 1058    }
 1059
 1060    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1061        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1062        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1063        Self::new(
 1064            EditorMode::AutoHeight { max_lines },
 1065            buffer,
 1066            None,
 1067            false,
 1068            cx,
 1069        )
 1070    }
 1071
 1072    pub fn for_buffer(
 1073        buffer: Model<Buffer>,
 1074        project: Option<Model<Project>>,
 1075        cx: &mut ViewContext<Self>,
 1076    ) -> Self {
 1077        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1078        Self::new(EditorMode::Full, buffer, project, false, cx)
 1079    }
 1080
 1081    pub fn for_multibuffer(
 1082        buffer: Model<MultiBuffer>,
 1083        project: Option<Model<Project>>,
 1084        show_excerpt_controls: bool,
 1085        cx: &mut ViewContext<Self>,
 1086    ) -> Self {
 1087        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1088    }
 1089
 1090    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1091        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1092        let mut clone = Self::new(
 1093            self.mode,
 1094            self.buffer.clone(),
 1095            self.project.clone(),
 1096            show_excerpt_controls,
 1097            cx,
 1098        );
 1099        self.display_map.update(cx, |display_map, cx| {
 1100            let snapshot = display_map.snapshot(cx);
 1101            clone.display_map.update(cx, |display_map, cx| {
 1102                display_map.set_state(&snapshot, cx);
 1103            });
 1104        });
 1105        clone.selections.clone_state(&self.selections);
 1106        clone.scroll_manager.clone_state(&self.scroll_manager);
 1107        clone.searchable = self.searchable;
 1108        clone
 1109    }
 1110
 1111    pub fn new(
 1112        mode: EditorMode,
 1113        buffer: Model<MultiBuffer>,
 1114        project: Option<Model<Project>>,
 1115        show_excerpt_controls: bool,
 1116        cx: &mut ViewContext<Self>,
 1117    ) -> Self {
 1118        let style = cx.text_style();
 1119        let font_size = style.font_size.to_pixels(cx.rem_size());
 1120        let editor = cx.view().downgrade();
 1121        let fold_placeholder = FoldPlaceholder {
 1122            constrain_width: true,
 1123            render: Arc::new(move |fold_id, fold_range, cx| {
 1124                let editor = editor.clone();
 1125                div()
 1126                    .id(fold_id)
 1127                    .bg(cx.theme().colors().ghost_element_background)
 1128                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1129                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1130                    .rounded_sm()
 1131                    .size_full()
 1132                    .cursor_pointer()
 1133                    .child("")
 1134                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1135                    .on_click(move |_, cx| {
 1136                        editor
 1137                            .update(cx, |editor, cx| {
 1138                                editor.unfold_ranges(
 1139                                    &[fold_range.start..fold_range.end],
 1140                                    true,
 1141                                    false,
 1142                                    cx,
 1143                                );
 1144                                cx.stop_propagation();
 1145                            })
 1146                            .ok();
 1147                    })
 1148                    .into_any()
 1149            }),
 1150            merge_adjacent: true,
 1151            ..Default::default()
 1152        };
 1153        let display_map = cx.new_model(|cx| {
 1154            DisplayMap::new(
 1155                buffer.clone(),
 1156                style.font(),
 1157                font_size,
 1158                None,
 1159                show_excerpt_controls,
 1160                FILE_HEADER_HEIGHT,
 1161                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1162                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1163                fold_placeholder,
 1164                cx,
 1165            )
 1166        });
 1167
 1168        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1169
 1170        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1171
 1172        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1173            .then(|| language_settings::SoftWrap::None);
 1174
 1175        let mut project_subscriptions = Vec::new();
 1176        if mode == EditorMode::Full {
 1177            if let Some(project) = project.as_ref() {
 1178                if buffer.read(cx).is_singleton() {
 1179                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1180                        cx.emit(EditorEvent::TitleChanged);
 1181                    }));
 1182                }
 1183                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1184                    if let project::Event::RefreshInlayHints = event {
 1185                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1186                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1187                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1188                            let focus_handle = editor.focus_handle(cx);
 1189                            if focus_handle.is_focused(cx) {
 1190                                let snapshot = buffer.read(cx).snapshot();
 1191                                for (range, snippet) in snippet_edits {
 1192                                    let editor_range =
 1193                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1194                                    editor
 1195                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1196                                        .ok();
 1197                                }
 1198                            }
 1199                        }
 1200                    }
 1201                }));
 1202                if let Some(task_inventory) = project
 1203                    .read(cx)
 1204                    .task_store()
 1205                    .read(cx)
 1206                    .task_inventory()
 1207                    .cloned()
 1208                {
 1209                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1210                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1211                    }));
 1212                }
 1213            }
 1214        }
 1215
 1216        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1217
 1218        let inlay_hint_settings =
 1219            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1220        let focus_handle = cx.focus_handle();
 1221        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1222        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1223            .detach();
 1224        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1225            .detach();
 1226        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1227
 1228        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1229            Some(false)
 1230        } else {
 1231            None
 1232        };
 1233
 1234        let mut code_action_providers = Vec::new();
 1235        if let Some(project) = project.clone() {
 1236            get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
 1237            code_action_providers.push(Rc::new(project) as Rc<_>);
 1238        }
 1239
 1240        let mut this = Self {
 1241            focus_handle,
 1242            show_cursor_when_unfocused: false,
 1243            last_focused_descendant: None,
 1244            buffer: buffer.clone(),
 1245            display_map: display_map.clone(),
 1246            selections,
 1247            scroll_manager: ScrollManager::new(cx),
 1248            columnar_selection_tail: None,
 1249            add_selections_state: None,
 1250            select_next_state: None,
 1251            select_prev_state: None,
 1252            selection_history: Default::default(),
 1253            autoclose_regions: Default::default(),
 1254            snippet_stack: Default::default(),
 1255            select_larger_syntax_node_stack: Vec::new(),
 1256            ime_transaction: Default::default(),
 1257            active_diagnostics: None,
 1258            soft_wrap_mode_override,
 1259            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1260            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1261            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1262            project,
 1263            blink_manager: blink_manager.clone(),
 1264            show_local_selections: true,
 1265            show_scrollbars: true,
 1266            mode,
 1267            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1268            show_gutter: mode == EditorMode::Full,
 1269            show_line_numbers: None,
 1270            use_relative_line_numbers: None,
 1271            show_git_diff_gutter: None,
 1272            show_code_actions: None,
 1273            show_runnables: None,
 1274            show_wrap_guides: None,
 1275            show_indent_guides,
 1276            placeholder_text: None,
 1277            highlight_order: 0,
 1278            highlighted_rows: HashMap::default(),
 1279            background_highlights: Default::default(),
 1280            gutter_highlights: TreeMap::default(),
 1281            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1282            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1283            nav_history: None,
 1284            context_menu: RefCell::new(None),
 1285            mouse_context_menu: None,
 1286            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1287            completion_tasks: Default::default(),
 1288            signature_help_state: SignatureHelpState::default(),
 1289            auto_signature_help: None,
 1290            find_all_references_task_sources: Vec::new(),
 1291            next_completion_id: 0,
 1292            next_inlay_id: 0,
 1293            code_action_providers,
 1294            available_code_actions: Default::default(),
 1295            code_actions_task: Default::default(),
 1296            document_highlights_task: Default::default(),
 1297            linked_editing_range_task: Default::default(),
 1298            pending_rename: Default::default(),
 1299            searchable: true,
 1300            cursor_shape: EditorSettings::get_global(cx)
 1301                .cursor_shape
 1302                .unwrap_or_default(),
 1303            current_line_highlight: None,
 1304            autoindent_mode: Some(AutoindentMode::EachLine),
 1305            collapse_matches: false,
 1306            workspace: None,
 1307            input_enabled: true,
 1308            use_modal_editing: mode == EditorMode::Full,
 1309            read_only: false,
 1310            use_autoclose: true,
 1311            use_auto_surround: true,
 1312            auto_replace_emoji_shortcode: false,
 1313            leader_peer_id: None,
 1314            remote_id: None,
 1315            hover_state: Default::default(),
 1316            hovered_link_state: Default::default(),
 1317            inline_completion_provider: None,
 1318            active_inline_completion: None,
 1319            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1320            diff_map: DiffMap::default(),
 1321            gutter_hovered: false,
 1322            pixel_position_of_newest_cursor: None,
 1323            last_bounds: None,
 1324            expect_bounds_change: None,
 1325            gutter_dimensions: GutterDimensions::default(),
 1326            style: None,
 1327            show_cursor_names: false,
 1328            hovered_cursors: Default::default(),
 1329            next_editor_action_id: EditorActionId::default(),
 1330            editor_actions: Rc::default(),
 1331            show_inline_completions_override: None,
 1332            enable_inline_completions: true,
 1333            custom_context_menu: None,
 1334            show_git_blame_gutter: false,
 1335            show_git_blame_inline: false,
 1336            show_selection_menu: None,
 1337            show_git_blame_inline_delay_task: None,
 1338            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1339            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1340                .session
 1341                .restore_unsaved_buffers,
 1342            blame: None,
 1343            blame_subscription: None,
 1344            tasks: Default::default(),
 1345            _subscriptions: vec![
 1346                cx.observe(&buffer, Self::on_buffer_changed),
 1347                cx.subscribe(&buffer, Self::on_buffer_event),
 1348                cx.observe(&display_map, Self::on_display_map_changed),
 1349                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1350                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1351                cx.observe_window_activation(|editor, cx| {
 1352                    let active = cx.is_window_active();
 1353                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1354                        if active {
 1355                            blink_manager.enable(cx);
 1356                        } else {
 1357                            blink_manager.disable(cx);
 1358                        }
 1359                    });
 1360                }),
 1361            ],
 1362            tasks_update_task: None,
 1363            linked_edit_ranges: Default::default(),
 1364            previous_search_ranges: None,
 1365            breadcrumb_header: None,
 1366            focused_block: None,
 1367            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1368            addons: HashMap::default(),
 1369            registered_buffers: HashMap::default(),
 1370            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1371            selection_mark_mode: false,
 1372            toggle_fold_multiple_buffers: Task::ready(()),
 1373            text_style_refinement: None,
 1374        };
 1375        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1376        this._subscriptions.extend(project_subscriptions);
 1377
 1378        this.end_selection(cx);
 1379        this.scroll_manager.show_scrollbar(cx);
 1380
 1381        if mode == EditorMode::Full {
 1382            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1383            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1384
 1385            if this.git_blame_inline_enabled {
 1386                this.git_blame_inline_enabled = true;
 1387                this.start_git_blame_inline(false, cx);
 1388            }
 1389
 1390            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1391                if let Some(project) = this.project.as_ref() {
 1392                    let lsp_store = project.read(cx).lsp_store();
 1393                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1394                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1395                    });
 1396                    this.registered_buffers
 1397                        .insert(buffer.read(cx).remote_id(), handle);
 1398                }
 1399            }
 1400        }
 1401
 1402        this.report_editor_event("Editor Opened", None, cx);
 1403        this
 1404    }
 1405
 1406    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 1407        self.mouse_context_menu
 1408            .as_ref()
 1409            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1410    }
 1411
 1412    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 1413        let mut key_context = KeyContext::new_with_defaults();
 1414        key_context.add("Editor");
 1415        let mode = match self.mode {
 1416            EditorMode::SingleLine { .. } => "single_line",
 1417            EditorMode::AutoHeight { .. } => "auto_height",
 1418            EditorMode::Full => "full",
 1419        };
 1420
 1421        if EditorSettings::jupyter_enabled(cx) {
 1422            key_context.add("jupyter");
 1423        }
 1424
 1425        key_context.set("mode", mode);
 1426        if self.pending_rename.is_some() {
 1427            key_context.add("renaming");
 1428        }
 1429        match self.context_menu.borrow().as_ref() {
 1430            Some(CodeContextMenu::Completions(_)) => {
 1431                key_context.add("menu");
 1432                key_context.add("showing_completions")
 1433            }
 1434            Some(CodeContextMenu::CodeActions(_)) => {
 1435                key_context.add("menu");
 1436                key_context.add("showing_code_actions")
 1437            }
 1438            None => {}
 1439        }
 1440
 1441        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1442        if !self.focus_handle(cx).contains_focused(cx)
 1443            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 1444        {
 1445            for addon in self.addons.values() {
 1446                addon.extend_key_context(&mut key_context, cx)
 1447            }
 1448        }
 1449
 1450        if let Some(extension) = self
 1451            .buffer
 1452            .read(cx)
 1453            .as_singleton()
 1454            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1455        {
 1456            key_context.set("extension", extension.to_string());
 1457        }
 1458
 1459        if self.has_active_inline_completion() {
 1460            key_context.add("copilot_suggestion");
 1461            key_context.add("inline_completion");
 1462        }
 1463
 1464        if self.selection_mark_mode {
 1465            key_context.add("selection_mode");
 1466        }
 1467
 1468        key_context
 1469    }
 1470
 1471    pub fn new_file(
 1472        workspace: &mut Workspace,
 1473        _: &workspace::NewFile,
 1474        cx: &mut ViewContext<Workspace>,
 1475    ) {
 1476        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1477            "Failed to create buffer",
 1478            cx,
 1479            |e, _| match e.error_code() {
 1480                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1481                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1482                e.error_tag("required").unwrap_or("the latest version")
 1483            )),
 1484                _ => None,
 1485            },
 1486        );
 1487    }
 1488
 1489    pub fn new_in_workspace(
 1490        workspace: &mut Workspace,
 1491        cx: &mut ViewContext<Workspace>,
 1492    ) -> Task<Result<View<Editor>>> {
 1493        let project = workspace.project().clone();
 1494        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1495
 1496        cx.spawn(|workspace, mut cx| async move {
 1497            let buffer = create.await?;
 1498            workspace.update(&mut cx, |workspace, cx| {
 1499                let editor =
 1500                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 1501                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 1502                editor
 1503            })
 1504        })
 1505    }
 1506
 1507    fn new_file_vertical(
 1508        workspace: &mut Workspace,
 1509        _: &workspace::NewFileSplitVertical,
 1510        cx: &mut ViewContext<Workspace>,
 1511    ) {
 1512        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 1513    }
 1514
 1515    fn new_file_horizontal(
 1516        workspace: &mut Workspace,
 1517        _: &workspace::NewFileSplitHorizontal,
 1518        cx: &mut ViewContext<Workspace>,
 1519    ) {
 1520        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 1521    }
 1522
 1523    fn new_file_in_direction(
 1524        workspace: &mut Workspace,
 1525        direction: SplitDirection,
 1526        cx: &mut ViewContext<Workspace>,
 1527    ) {
 1528        let project = workspace.project().clone();
 1529        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1530
 1531        cx.spawn(|workspace, mut cx| async move {
 1532            let buffer = create.await?;
 1533            workspace.update(&mut cx, move |workspace, cx| {
 1534                workspace.split_item(
 1535                    direction,
 1536                    Box::new(
 1537                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1538                    ),
 1539                    cx,
 1540                )
 1541            })?;
 1542            anyhow::Ok(())
 1543        })
 1544        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1545            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1546                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1547                e.error_tag("required").unwrap_or("the latest version")
 1548            )),
 1549            _ => None,
 1550        });
 1551    }
 1552
 1553    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1554        self.leader_peer_id
 1555    }
 1556
 1557    pub fn buffer(&self) -> &Model<MultiBuffer> {
 1558        &self.buffer
 1559    }
 1560
 1561    pub fn workspace(&self) -> Option<View<Workspace>> {
 1562        self.workspace.as_ref()?.0.upgrade()
 1563    }
 1564
 1565    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 1566        self.buffer().read(cx).title(cx)
 1567    }
 1568
 1569    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 1570        let git_blame_gutter_max_author_length = self
 1571            .render_git_blame_gutter(cx)
 1572            .then(|| {
 1573                if let Some(blame) = self.blame.as_ref() {
 1574                    let max_author_length =
 1575                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1576                    Some(max_author_length)
 1577                } else {
 1578                    None
 1579                }
 1580            })
 1581            .flatten();
 1582
 1583        EditorSnapshot {
 1584            mode: self.mode,
 1585            show_gutter: self.show_gutter,
 1586            show_line_numbers: self.show_line_numbers,
 1587            show_git_diff_gutter: self.show_git_diff_gutter,
 1588            show_code_actions: self.show_code_actions,
 1589            show_runnables: self.show_runnables,
 1590            git_blame_gutter_max_author_length,
 1591            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1592            scroll_anchor: self.scroll_manager.anchor(),
 1593            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1594            placeholder_text: self.placeholder_text.clone(),
 1595            diff_map: self.diff_map.snapshot(),
 1596            is_focused: self.focus_handle.is_focused(cx),
 1597            current_line_highlight: self
 1598                .current_line_highlight
 1599                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1600            gutter_hovered: self.gutter_hovered,
 1601        }
 1602    }
 1603
 1604    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 1605        self.buffer.read(cx).language_at(point, cx)
 1606    }
 1607
 1608    pub fn file_at<T: ToOffset>(
 1609        &self,
 1610        point: T,
 1611        cx: &AppContext,
 1612    ) -> Option<Arc<dyn language::File>> {
 1613        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1614    }
 1615
 1616    pub fn active_excerpt(
 1617        &self,
 1618        cx: &AppContext,
 1619    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 1620        self.buffer
 1621            .read(cx)
 1622            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1623    }
 1624
 1625    pub fn mode(&self) -> EditorMode {
 1626        self.mode
 1627    }
 1628
 1629    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1630        self.collaboration_hub.as_deref()
 1631    }
 1632
 1633    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1634        self.collaboration_hub = Some(hub);
 1635    }
 1636
 1637    pub fn set_custom_context_menu(
 1638        &mut self,
 1639        f: impl 'static
 1640            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 1641    ) {
 1642        self.custom_context_menu = Some(Box::new(f))
 1643    }
 1644
 1645    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1646        self.completion_provider = provider;
 1647    }
 1648
 1649    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1650        self.semantics_provider.clone()
 1651    }
 1652
 1653    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1654        self.semantics_provider = provider;
 1655    }
 1656
 1657    pub fn set_inline_completion_provider<T>(
 1658        &mut self,
 1659        provider: Option<Model<T>>,
 1660        cx: &mut ViewContext<Self>,
 1661    ) where
 1662        T: InlineCompletionProvider,
 1663    {
 1664        self.inline_completion_provider =
 1665            provider.map(|provider| RegisteredInlineCompletionProvider {
 1666                _subscription: cx.observe(&provider, |this, _, cx| {
 1667                    if this.focus_handle.is_focused(cx) {
 1668                        this.update_visible_inline_completion(cx);
 1669                    }
 1670                }),
 1671                provider: Arc::new(provider),
 1672            });
 1673        self.refresh_inline_completion(false, false, cx);
 1674    }
 1675
 1676    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 1677        self.placeholder_text.as_deref()
 1678    }
 1679
 1680    pub fn set_placeholder_text(
 1681        &mut self,
 1682        placeholder_text: impl Into<Arc<str>>,
 1683        cx: &mut ViewContext<Self>,
 1684    ) {
 1685        let placeholder_text = Some(placeholder_text.into());
 1686        if self.placeholder_text != placeholder_text {
 1687            self.placeholder_text = placeholder_text;
 1688            cx.notify();
 1689        }
 1690    }
 1691
 1692    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 1693        self.cursor_shape = cursor_shape;
 1694
 1695        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1696        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1697
 1698        cx.notify();
 1699    }
 1700
 1701    pub fn set_current_line_highlight(
 1702        &mut self,
 1703        current_line_highlight: Option<CurrentLineHighlight>,
 1704    ) {
 1705        self.current_line_highlight = current_line_highlight;
 1706    }
 1707
 1708    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1709        self.collapse_matches = collapse_matches;
 1710    }
 1711
 1712    pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
 1713        let buffers = self.buffer.read(cx).all_buffers();
 1714        let Some(lsp_store) = self.lsp_store(cx) else {
 1715            return;
 1716        };
 1717        lsp_store.update(cx, |lsp_store, cx| {
 1718            for buffer in buffers {
 1719                self.registered_buffers
 1720                    .entry(buffer.read(cx).remote_id())
 1721                    .or_insert_with(|| {
 1722                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1723                    });
 1724            }
 1725        })
 1726    }
 1727
 1728    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1729        if self.collapse_matches {
 1730            return range.start..range.start;
 1731        }
 1732        range.clone()
 1733    }
 1734
 1735    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 1736        if self.display_map.read(cx).clip_at_line_ends != clip {
 1737            self.display_map
 1738                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1739        }
 1740    }
 1741
 1742    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1743        self.input_enabled = input_enabled;
 1744    }
 1745
 1746    pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut ViewContext<Self>) {
 1747        self.enable_inline_completions = enabled;
 1748        if !self.enable_inline_completions {
 1749            self.take_active_inline_completion(cx);
 1750            cx.notify();
 1751        }
 1752    }
 1753
 1754    pub fn set_autoindent(&mut self, autoindent: bool) {
 1755        if autoindent {
 1756            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1757        } else {
 1758            self.autoindent_mode = None;
 1759        }
 1760    }
 1761
 1762    pub fn read_only(&self, cx: &AppContext) -> bool {
 1763        self.read_only || self.buffer.read(cx).read_only()
 1764    }
 1765
 1766    pub fn set_read_only(&mut self, read_only: bool) {
 1767        self.read_only = read_only;
 1768    }
 1769
 1770    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1771        self.use_autoclose = autoclose;
 1772    }
 1773
 1774    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1775        self.use_auto_surround = auto_surround;
 1776    }
 1777
 1778    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1779        self.auto_replace_emoji_shortcode = auto_replace;
 1780    }
 1781
 1782    pub fn toggle_inline_completions(
 1783        &mut self,
 1784        _: &ToggleInlineCompletions,
 1785        cx: &mut ViewContext<Self>,
 1786    ) {
 1787        if self.show_inline_completions_override.is_some() {
 1788            self.set_show_inline_completions(None, cx);
 1789        } else {
 1790            let cursor = self.selections.newest_anchor().head();
 1791            if let Some((buffer, cursor_buffer_position)) =
 1792                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1793            {
 1794                let show_inline_completions =
 1795                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1796                self.set_show_inline_completions(Some(show_inline_completions), cx);
 1797            }
 1798        }
 1799    }
 1800
 1801    pub fn set_show_inline_completions(
 1802        &mut self,
 1803        show_inline_completions: Option<bool>,
 1804        cx: &mut ViewContext<Self>,
 1805    ) {
 1806        self.show_inline_completions_override = show_inline_completions;
 1807        self.refresh_inline_completion(false, true, cx);
 1808    }
 1809
 1810    pub fn inline_completions_enabled(&self, cx: &AppContext) -> bool {
 1811        let cursor = self.selections.newest_anchor().head();
 1812        if let Some((buffer, buffer_position)) =
 1813            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1814        {
 1815            self.should_show_inline_completions(&buffer, buffer_position, cx)
 1816        } else {
 1817            false
 1818        }
 1819    }
 1820
 1821    fn should_show_inline_completions(
 1822        &self,
 1823        buffer: &Model<Buffer>,
 1824        buffer_position: language::Anchor,
 1825        cx: &AppContext,
 1826    ) -> bool {
 1827        if !self.snippet_stack.is_empty() {
 1828            return false;
 1829        }
 1830
 1831        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1832            return false;
 1833        }
 1834
 1835        if let Some(provider) = self.inline_completion_provider() {
 1836            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1837                show_inline_completions
 1838            } else {
 1839                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1840            }
 1841        } else {
 1842            false
 1843        }
 1844    }
 1845
 1846    fn inline_completions_disabled_in_scope(
 1847        &self,
 1848        buffer: &Model<Buffer>,
 1849        buffer_position: language::Anchor,
 1850        cx: &AppContext,
 1851    ) -> bool {
 1852        let snapshot = buffer.read(cx).snapshot();
 1853        let settings = snapshot.settings_at(buffer_position, cx);
 1854
 1855        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1856            return false;
 1857        };
 1858
 1859        scope.override_name().map_or(false, |scope_name| {
 1860            settings
 1861                .inline_completions_disabled_in
 1862                .iter()
 1863                .any(|s| s == scope_name)
 1864        })
 1865    }
 1866
 1867    pub fn set_use_modal_editing(&mut self, to: bool) {
 1868        self.use_modal_editing = to;
 1869    }
 1870
 1871    pub fn use_modal_editing(&self) -> bool {
 1872        self.use_modal_editing
 1873    }
 1874
 1875    fn selections_did_change(
 1876        &mut self,
 1877        local: bool,
 1878        old_cursor_position: &Anchor,
 1879        show_completions: bool,
 1880        cx: &mut ViewContext<Self>,
 1881    ) {
 1882        cx.invalidate_character_coordinates();
 1883
 1884        // Copy selections to primary selection buffer
 1885        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1886        if local {
 1887            let selections = self.selections.all::<usize>(cx);
 1888            let buffer_handle = self.buffer.read(cx).read(cx);
 1889
 1890            let mut text = String::new();
 1891            for (index, selection) in selections.iter().enumerate() {
 1892                let text_for_selection = buffer_handle
 1893                    .text_for_range(selection.start..selection.end)
 1894                    .collect::<String>();
 1895
 1896                text.push_str(&text_for_selection);
 1897                if index != selections.len() - 1 {
 1898                    text.push('\n');
 1899                }
 1900            }
 1901
 1902            if !text.is_empty() {
 1903                cx.write_to_primary(ClipboardItem::new_string(text));
 1904            }
 1905        }
 1906
 1907        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 1908            self.buffer.update(cx, |buffer, cx| {
 1909                buffer.set_active_selections(
 1910                    &self.selections.disjoint_anchors(),
 1911                    self.selections.line_mode,
 1912                    self.cursor_shape,
 1913                    cx,
 1914                )
 1915            });
 1916        }
 1917        let display_map = self
 1918            .display_map
 1919            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1920        let buffer = &display_map.buffer_snapshot;
 1921        self.add_selections_state = None;
 1922        self.select_next_state = None;
 1923        self.select_prev_state = None;
 1924        self.select_larger_syntax_node_stack.clear();
 1925        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 1926        self.snippet_stack
 1927            .invalidate(&self.selections.disjoint_anchors(), buffer);
 1928        self.take_rename(false, cx);
 1929
 1930        let new_cursor_position = self.selections.newest_anchor().head();
 1931
 1932        self.push_to_nav_history(
 1933            *old_cursor_position,
 1934            Some(new_cursor_position.to_point(buffer)),
 1935            cx,
 1936        );
 1937
 1938        if local {
 1939            let new_cursor_position = self.selections.newest_anchor().head();
 1940            let mut context_menu = self.context_menu.borrow_mut();
 1941            let completion_menu = match context_menu.as_ref() {
 1942                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 1943                _ => {
 1944                    *context_menu = None;
 1945                    None
 1946                }
 1947            };
 1948
 1949            if let Some(completion_menu) = completion_menu {
 1950                let cursor_position = new_cursor_position.to_offset(buffer);
 1951                let (word_range, kind) =
 1952                    buffer.surrounding_word(completion_menu.initial_position, true);
 1953                if kind == Some(CharKind::Word)
 1954                    && word_range.to_inclusive().contains(&cursor_position)
 1955                {
 1956                    let mut completion_menu = completion_menu.clone();
 1957                    drop(context_menu);
 1958
 1959                    let query = Self::completion_query(buffer, cursor_position);
 1960                    cx.spawn(move |this, mut cx| async move {
 1961                        completion_menu
 1962                            .filter(query.as_deref(), cx.background_executor().clone())
 1963                            .await;
 1964
 1965                        this.update(&mut cx, |this, cx| {
 1966                            let mut context_menu = this.context_menu.borrow_mut();
 1967                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 1968                            else {
 1969                                return;
 1970                            };
 1971
 1972                            if menu.id > completion_menu.id {
 1973                                return;
 1974                            }
 1975
 1976                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 1977                            drop(context_menu);
 1978                            cx.notify();
 1979                        })
 1980                    })
 1981                    .detach();
 1982
 1983                    if show_completions {
 1984                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 1985                    }
 1986                } else {
 1987                    drop(context_menu);
 1988                    self.hide_context_menu(cx);
 1989                }
 1990            } else {
 1991                drop(context_menu);
 1992            }
 1993
 1994            hide_hover(self, cx);
 1995
 1996            if old_cursor_position.to_display_point(&display_map).row()
 1997                != new_cursor_position.to_display_point(&display_map).row()
 1998            {
 1999                self.available_code_actions.take();
 2000            }
 2001            self.refresh_code_actions(cx);
 2002            self.refresh_document_highlights(cx);
 2003            refresh_matching_bracket_highlights(self, cx);
 2004            self.update_visible_inline_completion(cx);
 2005            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2006            if self.git_blame_inline_enabled {
 2007                self.start_inline_blame_timer(cx);
 2008            }
 2009        }
 2010
 2011        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2012        cx.emit(EditorEvent::SelectionsChanged { local });
 2013
 2014        if self.selections.disjoint_anchors().len() == 1 {
 2015            cx.emit(SearchEvent::ActiveMatchChanged)
 2016        }
 2017        cx.notify();
 2018    }
 2019
 2020    pub fn change_selections<R>(
 2021        &mut self,
 2022        autoscroll: Option<Autoscroll>,
 2023        cx: &mut ViewContext<Self>,
 2024        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2025    ) -> R {
 2026        self.change_selections_inner(autoscroll, true, cx, change)
 2027    }
 2028
 2029    pub fn change_selections_inner<R>(
 2030        &mut self,
 2031        autoscroll: Option<Autoscroll>,
 2032        request_completions: bool,
 2033        cx: &mut ViewContext<Self>,
 2034        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2035    ) -> R {
 2036        let old_cursor_position = self.selections.newest_anchor().head();
 2037        self.push_to_selection_history();
 2038
 2039        let (changed, result) = self.selections.change_with(cx, change);
 2040
 2041        if changed {
 2042            if let Some(autoscroll) = autoscroll {
 2043                self.request_autoscroll(autoscroll, cx);
 2044            }
 2045            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2046
 2047            if self.should_open_signature_help_automatically(
 2048                &old_cursor_position,
 2049                self.signature_help_state.backspace_pressed(),
 2050                cx,
 2051            ) {
 2052                self.show_signature_help(&ShowSignatureHelp, cx);
 2053            }
 2054            self.signature_help_state.set_backspace_pressed(false);
 2055        }
 2056
 2057        result
 2058    }
 2059
 2060    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2061    where
 2062        I: IntoIterator<Item = (Range<S>, T)>,
 2063        S: ToOffset,
 2064        T: Into<Arc<str>>,
 2065    {
 2066        if self.read_only(cx) {
 2067            return;
 2068        }
 2069
 2070        self.buffer
 2071            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2072    }
 2073
 2074    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2075    where
 2076        I: IntoIterator<Item = (Range<S>, T)>,
 2077        S: ToOffset,
 2078        T: Into<Arc<str>>,
 2079    {
 2080        if self.read_only(cx) {
 2081            return;
 2082        }
 2083
 2084        self.buffer.update(cx, |buffer, cx| {
 2085            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2086        });
 2087    }
 2088
 2089    pub fn edit_with_block_indent<I, S, T>(
 2090        &mut self,
 2091        edits: I,
 2092        original_indent_columns: Vec<u32>,
 2093        cx: &mut ViewContext<Self>,
 2094    ) where
 2095        I: IntoIterator<Item = (Range<S>, T)>,
 2096        S: ToOffset,
 2097        T: Into<Arc<str>>,
 2098    {
 2099        if self.read_only(cx) {
 2100            return;
 2101        }
 2102
 2103        self.buffer.update(cx, |buffer, cx| {
 2104            buffer.edit(
 2105                edits,
 2106                Some(AutoindentMode::Block {
 2107                    original_indent_columns,
 2108                }),
 2109                cx,
 2110            )
 2111        });
 2112    }
 2113
 2114    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2115        self.hide_context_menu(cx);
 2116
 2117        match phase {
 2118            SelectPhase::Begin {
 2119                position,
 2120                add,
 2121                click_count,
 2122            } => self.begin_selection(position, add, click_count, cx),
 2123            SelectPhase::BeginColumnar {
 2124                position,
 2125                goal_column,
 2126                reset,
 2127            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2128            SelectPhase::Extend {
 2129                position,
 2130                click_count,
 2131            } => self.extend_selection(position, click_count, cx),
 2132            SelectPhase::Update {
 2133                position,
 2134                goal_column,
 2135                scroll_delta,
 2136            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2137            SelectPhase::End => self.end_selection(cx),
 2138        }
 2139    }
 2140
 2141    fn extend_selection(
 2142        &mut self,
 2143        position: DisplayPoint,
 2144        click_count: usize,
 2145        cx: &mut ViewContext<Self>,
 2146    ) {
 2147        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2148        let tail = self.selections.newest::<usize>(cx).tail();
 2149        self.begin_selection(position, false, click_count, cx);
 2150
 2151        let position = position.to_offset(&display_map, Bias::Left);
 2152        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2153
 2154        let mut pending_selection = self
 2155            .selections
 2156            .pending_anchor()
 2157            .expect("extend_selection not called with pending selection");
 2158        if position >= tail {
 2159            pending_selection.start = tail_anchor;
 2160        } else {
 2161            pending_selection.end = tail_anchor;
 2162            pending_selection.reversed = true;
 2163        }
 2164
 2165        let mut pending_mode = self.selections.pending_mode().unwrap();
 2166        match &mut pending_mode {
 2167            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2168            _ => {}
 2169        }
 2170
 2171        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2172            s.set_pending(pending_selection, pending_mode)
 2173        });
 2174    }
 2175
 2176    fn begin_selection(
 2177        &mut self,
 2178        position: DisplayPoint,
 2179        add: bool,
 2180        click_count: usize,
 2181        cx: &mut ViewContext<Self>,
 2182    ) {
 2183        if !self.focus_handle.is_focused(cx) {
 2184            self.last_focused_descendant = None;
 2185            cx.focus(&self.focus_handle);
 2186        }
 2187
 2188        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2189        let buffer = &display_map.buffer_snapshot;
 2190        let newest_selection = self.selections.newest_anchor().clone();
 2191        let position = display_map.clip_point(position, Bias::Left);
 2192
 2193        let start;
 2194        let end;
 2195        let mode;
 2196        let mut auto_scroll;
 2197        match click_count {
 2198            1 => {
 2199                start = buffer.anchor_before(position.to_point(&display_map));
 2200                end = start;
 2201                mode = SelectMode::Character;
 2202                auto_scroll = true;
 2203            }
 2204            2 => {
 2205                let range = movement::surrounding_word(&display_map, position);
 2206                start = buffer.anchor_before(range.start.to_point(&display_map));
 2207                end = buffer.anchor_before(range.end.to_point(&display_map));
 2208                mode = SelectMode::Word(start..end);
 2209                auto_scroll = true;
 2210            }
 2211            3 => {
 2212                let position = display_map
 2213                    .clip_point(position, Bias::Left)
 2214                    .to_point(&display_map);
 2215                let line_start = display_map.prev_line_boundary(position).0;
 2216                let next_line_start = buffer.clip_point(
 2217                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2218                    Bias::Left,
 2219                );
 2220                start = buffer.anchor_before(line_start);
 2221                end = buffer.anchor_before(next_line_start);
 2222                mode = SelectMode::Line(start..end);
 2223                auto_scroll = true;
 2224            }
 2225            _ => {
 2226                start = buffer.anchor_before(0);
 2227                end = buffer.anchor_before(buffer.len());
 2228                mode = SelectMode::All;
 2229                auto_scroll = false;
 2230            }
 2231        }
 2232        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2233
 2234        let point_to_delete: Option<usize> = {
 2235            let selected_points: Vec<Selection<Point>> =
 2236                self.selections.disjoint_in_range(start..end, cx);
 2237
 2238            if !add || click_count > 1 {
 2239                None
 2240            } else if !selected_points.is_empty() {
 2241                Some(selected_points[0].id)
 2242            } else {
 2243                let clicked_point_already_selected =
 2244                    self.selections.disjoint.iter().find(|selection| {
 2245                        selection.start.to_point(buffer) == start.to_point(buffer)
 2246                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2247                    });
 2248
 2249                clicked_point_already_selected.map(|selection| selection.id)
 2250            }
 2251        };
 2252
 2253        let selections_count = self.selections.count();
 2254
 2255        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2256            if let Some(point_to_delete) = point_to_delete {
 2257                s.delete(point_to_delete);
 2258
 2259                if selections_count == 1 {
 2260                    s.set_pending_anchor_range(start..end, mode);
 2261                }
 2262            } else {
 2263                if !add {
 2264                    s.clear_disjoint();
 2265                } else if click_count > 1 {
 2266                    s.delete(newest_selection.id)
 2267                }
 2268
 2269                s.set_pending_anchor_range(start..end, mode);
 2270            }
 2271        });
 2272    }
 2273
 2274    fn begin_columnar_selection(
 2275        &mut self,
 2276        position: DisplayPoint,
 2277        goal_column: u32,
 2278        reset: bool,
 2279        cx: &mut ViewContext<Self>,
 2280    ) {
 2281        if !self.focus_handle.is_focused(cx) {
 2282            self.last_focused_descendant = None;
 2283            cx.focus(&self.focus_handle);
 2284        }
 2285
 2286        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2287
 2288        if reset {
 2289            let pointer_position = display_map
 2290                .buffer_snapshot
 2291                .anchor_before(position.to_point(&display_map));
 2292
 2293            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2294                s.clear_disjoint();
 2295                s.set_pending_anchor_range(
 2296                    pointer_position..pointer_position,
 2297                    SelectMode::Character,
 2298                );
 2299            });
 2300        }
 2301
 2302        let tail = self.selections.newest::<Point>(cx).tail();
 2303        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2304
 2305        if !reset {
 2306            self.select_columns(
 2307                tail.to_display_point(&display_map),
 2308                position,
 2309                goal_column,
 2310                &display_map,
 2311                cx,
 2312            );
 2313        }
 2314    }
 2315
 2316    fn update_selection(
 2317        &mut self,
 2318        position: DisplayPoint,
 2319        goal_column: u32,
 2320        scroll_delta: gpui::Point<f32>,
 2321        cx: &mut ViewContext<Self>,
 2322    ) {
 2323        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2324
 2325        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2326            let tail = tail.to_display_point(&display_map);
 2327            self.select_columns(tail, position, goal_column, &display_map, cx);
 2328        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2329            let buffer = self.buffer.read(cx).snapshot(cx);
 2330            let head;
 2331            let tail;
 2332            let mode = self.selections.pending_mode().unwrap();
 2333            match &mode {
 2334                SelectMode::Character => {
 2335                    head = position.to_point(&display_map);
 2336                    tail = pending.tail().to_point(&buffer);
 2337                }
 2338                SelectMode::Word(original_range) => {
 2339                    let original_display_range = original_range.start.to_display_point(&display_map)
 2340                        ..original_range.end.to_display_point(&display_map);
 2341                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2342                        ..original_display_range.end.to_point(&display_map);
 2343                    if movement::is_inside_word(&display_map, position)
 2344                        || original_display_range.contains(&position)
 2345                    {
 2346                        let word_range = movement::surrounding_word(&display_map, position);
 2347                        if word_range.start < original_display_range.start {
 2348                            head = word_range.start.to_point(&display_map);
 2349                        } else {
 2350                            head = word_range.end.to_point(&display_map);
 2351                        }
 2352                    } else {
 2353                        head = position.to_point(&display_map);
 2354                    }
 2355
 2356                    if head <= original_buffer_range.start {
 2357                        tail = original_buffer_range.end;
 2358                    } else {
 2359                        tail = original_buffer_range.start;
 2360                    }
 2361                }
 2362                SelectMode::Line(original_range) => {
 2363                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2364
 2365                    let position = display_map
 2366                        .clip_point(position, Bias::Left)
 2367                        .to_point(&display_map);
 2368                    let line_start = display_map.prev_line_boundary(position).0;
 2369                    let next_line_start = buffer.clip_point(
 2370                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2371                        Bias::Left,
 2372                    );
 2373
 2374                    if line_start < original_range.start {
 2375                        head = line_start
 2376                    } else {
 2377                        head = next_line_start
 2378                    }
 2379
 2380                    if head <= original_range.start {
 2381                        tail = original_range.end;
 2382                    } else {
 2383                        tail = original_range.start;
 2384                    }
 2385                }
 2386                SelectMode::All => {
 2387                    return;
 2388                }
 2389            };
 2390
 2391            if head < tail {
 2392                pending.start = buffer.anchor_before(head);
 2393                pending.end = buffer.anchor_before(tail);
 2394                pending.reversed = true;
 2395            } else {
 2396                pending.start = buffer.anchor_before(tail);
 2397                pending.end = buffer.anchor_before(head);
 2398                pending.reversed = false;
 2399            }
 2400
 2401            self.change_selections(None, cx, |s| {
 2402                s.set_pending(pending, mode);
 2403            });
 2404        } else {
 2405            log::error!("update_selection dispatched with no pending selection");
 2406            return;
 2407        }
 2408
 2409        self.apply_scroll_delta(scroll_delta, cx);
 2410        cx.notify();
 2411    }
 2412
 2413    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2414        self.columnar_selection_tail.take();
 2415        if self.selections.pending_anchor().is_some() {
 2416            let selections = self.selections.all::<usize>(cx);
 2417            self.change_selections(None, cx, |s| {
 2418                s.select(selections);
 2419                s.clear_pending();
 2420            });
 2421        }
 2422    }
 2423
 2424    fn select_columns(
 2425        &mut self,
 2426        tail: DisplayPoint,
 2427        head: DisplayPoint,
 2428        goal_column: u32,
 2429        display_map: &DisplaySnapshot,
 2430        cx: &mut ViewContext<Self>,
 2431    ) {
 2432        let start_row = cmp::min(tail.row(), head.row());
 2433        let end_row = cmp::max(tail.row(), head.row());
 2434        let start_column = cmp::min(tail.column(), goal_column);
 2435        let end_column = cmp::max(tail.column(), goal_column);
 2436        let reversed = start_column < tail.column();
 2437
 2438        let selection_ranges = (start_row.0..=end_row.0)
 2439            .map(DisplayRow)
 2440            .filter_map(|row| {
 2441                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2442                    let start = display_map
 2443                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2444                        .to_point(display_map);
 2445                    let end = display_map
 2446                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2447                        .to_point(display_map);
 2448                    if reversed {
 2449                        Some(end..start)
 2450                    } else {
 2451                        Some(start..end)
 2452                    }
 2453                } else {
 2454                    None
 2455                }
 2456            })
 2457            .collect::<Vec<_>>();
 2458
 2459        self.change_selections(None, cx, |s| {
 2460            s.select_ranges(selection_ranges);
 2461        });
 2462        cx.notify();
 2463    }
 2464
 2465    pub fn has_pending_nonempty_selection(&self) -> bool {
 2466        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2467            Some(Selection { start, end, .. }) => start != end,
 2468            None => false,
 2469        };
 2470
 2471        pending_nonempty_selection
 2472            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2473    }
 2474
 2475    pub fn has_pending_selection(&self) -> bool {
 2476        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2477    }
 2478
 2479    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2480        self.selection_mark_mode = false;
 2481
 2482        if self.clear_expanded_diff_hunks(cx) {
 2483            cx.notify();
 2484            return;
 2485        }
 2486        if self.dismiss_menus_and_popups(true, cx) {
 2487            return;
 2488        }
 2489
 2490        if self.mode == EditorMode::Full
 2491            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 2492        {
 2493            return;
 2494        }
 2495
 2496        cx.propagate();
 2497    }
 2498
 2499    pub fn dismiss_menus_and_popups(
 2500        &mut self,
 2501        should_report_inline_completion_event: bool,
 2502        cx: &mut ViewContext<Self>,
 2503    ) -> bool {
 2504        if self.take_rename(false, cx).is_some() {
 2505            return true;
 2506        }
 2507
 2508        if hide_hover(self, cx) {
 2509            return true;
 2510        }
 2511
 2512        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2513            return true;
 2514        }
 2515
 2516        if self.hide_context_menu(cx).is_some() {
 2517            if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
 2518                self.update_visible_inline_completion(cx);
 2519            }
 2520            return true;
 2521        }
 2522
 2523        if self.mouse_context_menu.take().is_some() {
 2524            return true;
 2525        }
 2526
 2527        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2528            return true;
 2529        }
 2530
 2531        if self.snippet_stack.pop().is_some() {
 2532            return true;
 2533        }
 2534
 2535        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2536            self.dismiss_diagnostics(cx);
 2537            return true;
 2538        }
 2539
 2540        false
 2541    }
 2542
 2543    fn linked_editing_ranges_for(
 2544        &self,
 2545        selection: Range<text::Anchor>,
 2546        cx: &AppContext,
 2547    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2548        if self.linked_edit_ranges.is_empty() {
 2549            return None;
 2550        }
 2551        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2552            selection.end.buffer_id.and_then(|end_buffer_id| {
 2553                if selection.start.buffer_id != Some(end_buffer_id) {
 2554                    return None;
 2555                }
 2556                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2557                let snapshot = buffer.read(cx).snapshot();
 2558                self.linked_edit_ranges
 2559                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2560                    .map(|ranges| (ranges, snapshot, buffer))
 2561            })?;
 2562        use text::ToOffset as TO;
 2563        // find offset from the start of current range to current cursor position
 2564        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2565
 2566        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2567        let start_difference = start_offset - start_byte_offset;
 2568        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2569        let end_difference = end_offset - start_byte_offset;
 2570        // Current range has associated linked ranges.
 2571        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2572        for range in linked_ranges.iter() {
 2573            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2574            let end_offset = start_offset + end_difference;
 2575            let start_offset = start_offset + start_difference;
 2576            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2577                continue;
 2578            }
 2579            if self.selections.disjoint_anchor_ranges().any(|s| {
 2580                if s.start.buffer_id != selection.start.buffer_id
 2581                    || s.end.buffer_id != selection.end.buffer_id
 2582                {
 2583                    return false;
 2584                }
 2585                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2586                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2587            }) {
 2588                continue;
 2589            }
 2590            let start = buffer_snapshot.anchor_after(start_offset);
 2591            let end = buffer_snapshot.anchor_after(end_offset);
 2592            linked_edits
 2593                .entry(buffer.clone())
 2594                .or_default()
 2595                .push(start..end);
 2596        }
 2597        Some(linked_edits)
 2598    }
 2599
 2600    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2601        let text: Arc<str> = text.into();
 2602
 2603        if self.read_only(cx) {
 2604            return;
 2605        }
 2606
 2607        let selections = self.selections.all_adjusted(cx);
 2608        let mut bracket_inserted = false;
 2609        let mut edits = Vec::new();
 2610        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2611        let mut new_selections = Vec::with_capacity(selections.len());
 2612        let mut new_autoclose_regions = Vec::new();
 2613        let snapshot = self.buffer.read(cx).read(cx);
 2614
 2615        for (selection, autoclose_region) in
 2616            self.selections_with_autoclose_regions(selections, &snapshot)
 2617        {
 2618            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2619                // Determine if the inserted text matches the opening or closing
 2620                // bracket of any of this language's bracket pairs.
 2621                let mut bracket_pair = None;
 2622                let mut is_bracket_pair_start = false;
 2623                let mut is_bracket_pair_end = false;
 2624                if !text.is_empty() {
 2625                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2626                    //  and they are removing the character that triggered IME popup.
 2627                    for (pair, enabled) in scope.brackets() {
 2628                        if !pair.close && !pair.surround {
 2629                            continue;
 2630                        }
 2631
 2632                        if enabled && pair.start.ends_with(text.as_ref()) {
 2633                            let prefix_len = pair.start.len() - text.len();
 2634                            let preceding_text_matches_prefix = prefix_len == 0
 2635                                || (selection.start.column >= (prefix_len as u32)
 2636                                    && snapshot.contains_str_at(
 2637                                        Point::new(
 2638                                            selection.start.row,
 2639                                            selection.start.column - (prefix_len as u32),
 2640                                        ),
 2641                                        &pair.start[..prefix_len],
 2642                                    ));
 2643                            if preceding_text_matches_prefix {
 2644                                bracket_pair = Some(pair.clone());
 2645                                is_bracket_pair_start = true;
 2646                                break;
 2647                            }
 2648                        }
 2649                        if pair.end.as_str() == text.as_ref() {
 2650                            bracket_pair = Some(pair.clone());
 2651                            is_bracket_pair_end = true;
 2652                            break;
 2653                        }
 2654                    }
 2655                }
 2656
 2657                if let Some(bracket_pair) = bracket_pair {
 2658                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2659                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2660                    let auto_surround =
 2661                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2662                    if selection.is_empty() {
 2663                        if is_bracket_pair_start {
 2664                            // If the inserted text is a suffix of an opening bracket and the
 2665                            // selection is preceded by the rest of the opening bracket, then
 2666                            // insert the closing bracket.
 2667                            let following_text_allows_autoclose = snapshot
 2668                                .chars_at(selection.start)
 2669                                .next()
 2670                                .map_or(true, |c| scope.should_autoclose_before(c));
 2671
 2672                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2673                                && bracket_pair.start.len() == 1
 2674                            {
 2675                                let target = bracket_pair.start.chars().next().unwrap();
 2676                                let current_line_count = snapshot
 2677                                    .reversed_chars_at(selection.start)
 2678                                    .take_while(|&c| c != '\n')
 2679                                    .filter(|&c| c == target)
 2680                                    .count();
 2681                                current_line_count % 2 == 1
 2682                            } else {
 2683                                false
 2684                            };
 2685
 2686                            if autoclose
 2687                                && bracket_pair.close
 2688                                && following_text_allows_autoclose
 2689                                && !is_closing_quote
 2690                            {
 2691                                let anchor = snapshot.anchor_before(selection.end);
 2692                                new_selections.push((selection.map(|_| anchor), text.len()));
 2693                                new_autoclose_regions.push((
 2694                                    anchor,
 2695                                    text.len(),
 2696                                    selection.id,
 2697                                    bracket_pair.clone(),
 2698                                ));
 2699                                edits.push((
 2700                                    selection.range(),
 2701                                    format!("{}{}", text, bracket_pair.end).into(),
 2702                                ));
 2703                                bracket_inserted = true;
 2704                                continue;
 2705                            }
 2706                        }
 2707
 2708                        if let Some(region) = autoclose_region {
 2709                            // If the selection is followed by an auto-inserted closing bracket,
 2710                            // then don't insert that closing bracket again; just move the selection
 2711                            // past the closing bracket.
 2712                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2713                                && text.as_ref() == region.pair.end.as_str();
 2714                            if should_skip {
 2715                                let anchor = snapshot.anchor_after(selection.end);
 2716                                new_selections
 2717                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2718                                continue;
 2719                            }
 2720                        }
 2721
 2722                        let always_treat_brackets_as_autoclosed = snapshot
 2723                            .settings_at(selection.start, cx)
 2724                            .always_treat_brackets_as_autoclosed;
 2725                        if always_treat_brackets_as_autoclosed
 2726                            && is_bracket_pair_end
 2727                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2728                        {
 2729                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2730                            // and the inserted text is a closing bracket and the selection is followed
 2731                            // by the closing bracket then move the selection past the closing bracket.
 2732                            let anchor = snapshot.anchor_after(selection.end);
 2733                            new_selections.push((selection.map(|_| anchor), text.len()));
 2734                            continue;
 2735                        }
 2736                    }
 2737                    // If an opening bracket is 1 character long and is typed while
 2738                    // text is selected, then surround that text with the bracket pair.
 2739                    else if auto_surround
 2740                        && bracket_pair.surround
 2741                        && is_bracket_pair_start
 2742                        && bracket_pair.start.chars().count() == 1
 2743                    {
 2744                        edits.push((selection.start..selection.start, text.clone()));
 2745                        edits.push((
 2746                            selection.end..selection.end,
 2747                            bracket_pair.end.as_str().into(),
 2748                        ));
 2749                        bracket_inserted = true;
 2750                        new_selections.push((
 2751                            Selection {
 2752                                id: selection.id,
 2753                                start: snapshot.anchor_after(selection.start),
 2754                                end: snapshot.anchor_before(selection.end),
 2755                                reversed: selection.reversed,
 2756                                goal: selection.goal,
 2757                            },
 2758                            0,
 2759                        ));
 2760                        continue;
 2761                    }
 2762                }
 2763            }
 2764
 2765            if self.auto_replace_emoji_shortcode
 2766                && selection.is_empty()
 2767                && text.as_ref().ends_with(':')
 2768            {
 2769                if let Some(possible_emoji_short_code) =
 2770                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2771                {
 2772                    if !possible_emoji_short_code.is_empty() {
 2773                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2774                            let emoji_shortcode_start = Point::new(
 2775                                selection.start.row,
 2776                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2777                            );
 2778
 2779                            // Remove shortcode from buffer
 2780                            edits.push((
 2781                                emoji_shortcode_start..selection.start,
 2782                                "".to_string().into(),
 2783                            ));
 2784                            new_selections.push((
 2785                                Selection {
 2786                                    id: selection.id,
 2787                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2788                                    end: snapshot.anchor_before(selection.start),
 2789                                    reversed: selection.reversed,
 2790                                    goal: selection.goal,
 2791                                },
 2792                                0,
 2793                            ));
 2794
 2795                            // Insert emoji
 2796                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2797                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2798                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2799
 2800                            continue;
 2801                        }
 2802                    }
 2803                }
 2804            }
 2805
 2806            // If not handling any auto-close operation, then just replace the selected
 2807            // text with the given input and move the selection to the end of the
 2808            // newly inserted text.
 2809            let anchor = snapshot.anchor_after(selection.end);
 2810            if !self.linked_edit_ranges.is_empty() {
 2811                let start_anchor = snapshot.anchor_before(selection.start);
 2812
 2813                let is_word_char = text.chars().next().map_or(true, |char| {
 2814                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2815                    classifier.is_word(char)
 2816                });
 2817
 2818                if is_word_char {
 2819                    if let Some(ranges) = self
 2820                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2821                    {
 2822                        for (buffer, edits) in ranges {
 2823                            linked_edits
 2824                                .entry(buffer.clone())
 2825                                .or_default()
 2826                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2827                        }
 2828                    }
 2829                }
 2830            }
 2831
 2832            new_selections.push((selection.map(|_| anchor), 0));
 2833            edits.push((selection.start..selection.end, text.clone()));
 2834        }
 2835
 2836        drop(snapshot);
 2837
 2838        self.transact(cx, |this, cx| {
 2839            this.buffer.update(cx, |buffer, cx| {
 2840                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2841            });
 2842            for (buffer, edits) in linked_edits {
 2843                buffer.update(cx, |buffer, cx| {
 2844                    let snapshot = buffer.snapshot();
 2845                    let edits = edits
 2846                        .into_iter()
 2847                        .map(|(range, text)| {
 2848                            use text::ToPoint as TP;
 2849                            let end_point = TP::to_point(&range.end, &snapshot);
 2850                            let start_point = TP::to_point(&range.start, &snapshot);
 2851                            (start_point..end_point, text)
 2852                        })
 2853                        .sorted_by_key(|(range, _)| range.start)
 2854                        .collect::<Vec<_>>();
 2855                    buffer.edit(edits, None, cx);
 2856                })
 2857            }
 2858            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2859            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2860            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2861            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2862                .zip(new_selection_deltas)
 2863                .map(|(selection, delta)| Selection {
 2864                    id: selection.id,
 2865                    start: selection.start + delta,
 2866                    end: selection.end + delta,
 2867                    reversed: selection.reversed,
 2868                    goal: SelectionGoal::None,
 2869                })
 2870                .collect::<Vec<_>>();
 2871
 2872            let mut i = 0;
 2873            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2874                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2875                let start = map.buffer_snapshot.anchor_before(position);
 2876                let end = map.buffer_snapshot.anchor_after(position);
 2877                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2878                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2879                        Ordering::Less => i += 1,
 2880                        Ordering::Greater => break,
 2881                        Ordering::Equal => {
 2882                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2883                                Ordering::Less => i += 1,
 2884                                Ordering::Equal => break,
 2885                                Ordering::Greater => break,
 2886                            }
 2887                        }
 2888                    }
 2889                }
 2890                this.autoclose_regions.insert(
 2891                    i,
 2892                    AutocloseRegion {
 2893                        selection_id,
 2894                        range: start..end,
 2895                        pair,
 2896                    },
 2897                );
 2898            }
 2899
 2900            let had_active_inline_completion = this.has_active_inline_completion();
 2901            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 2902                s.select(new_selections)
 2903            });
 2904
 2905            if !bracket_inserted {
 2906                if let Some(on_type_format_task) =
 2907                    this.trigger_on_type_formatting(text.to_string(), cx)
 2908                {
 2909                    on_type_format_task.detach_and_log_err(cx);
 2910                }
 2911            }
 2912
 2913            let editor_settings = EditorSettings::get_global(cx);
 2914            if bracket_inserted
 2915                && (editor_settings.auto_signature_help
 2916                    || editor_settings.show_signature_help_after_edits)
 2917            {
 2918                this.show_signature_help(&ShowSignatureHelp, cx);
 2919            }
 2920
 2921            let trigger_in_words =
 2922                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 2923            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 2924            linked_editing_ranges::refresh_linked_ranges(this, cx);
 2925            this.refresh_inline_completion(true, false, cx);
 2926        });
 2927    }
 2928
 2929    fn find_possible_emoji_shortcode_at_position(
 2930        snapshot: &MultiBufferSnapshot,
 2931        position: Point,
 2932    ) -> Option<String> {
 2933        let mut chars = Vec::new();
 2934        let mut found_colon = false;
 2935        for char in snapshot.reversed_chars_at(position).take(100) {
 2936            // Found a possible emoji shortcode in the middle of the buffer
 2937            if found_colon {
 2938                if char.is_whitespace() {
 2939                    chars.reverse();
 2940                    return Some(chars.iter().collect());
 2941                }
 2942                // If the previous character is not a whitespace, we are in the middle of a word
 2943                // and we only want to complete the shortcode if the word is made up of other emojis
 2944                let mut containing_word = String::new();
 2945                for ch in snapshot
 2946                    .reversed_chars_at(position)
 2947                    .skip(chars.len() + 1)
 2948                    .take(100)
 2949                {
 2950                    if ch.is_whitespace() {
 2951                        break;
 2952                    }
 2953                    containing_word.push(ch);
 2954                }
 2955                let containing_word = containing_word.chars().rev().collect::<String>();
 2956                if util::word_consists_of_emojis(containing_word.as_str()) {
 2957                    chars.reverse();
 2958                    return Some(chars.iter().collect());
 2959                }
 2960            }
 2961
 2962            if char.is_whitespace() || !char.is_ascii() {
 2963                return None;
 2964            }
 2965            if char == ':' {
 2966                found_colon = true;
 2967            } else {
 2968                chars.push(char);
 2969            }
 2970        }
 2971        // Found a possible emoji shortcode at the beginning of the buffer
 2972        chars.reverse();
 2973        Some(chars.iter().collect())
 2974    }
 2975
 2976    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 2977        self.transact(cx, |this, cx| {
 2978            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 2979                let selections = this.selections.all::<usize>(cx);
 2980                let multi_buffer = this.buffer.read(cx);
 2981                let buffer = multi_buffer.snapshot(cx);
 2982                selections
 2983                    .iter()
 2984                    .map(|selection| {
 2985                        let start_point = selection.start.to_point(&buffer);
 2986                        let mut indent =
 2987                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 2988                        indent.len = cmp::min(indent.len, start_point.column);
 2989                        let start = selection.start;
 2990                        let end = selection.end;
 2991                        let selection_is_empty = start == end;
 2992                        let language_scope = buffer.language_scope_at(start);
 2993                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 2994                            &language_scope
 2995                        {
 2996                            let leading_whitespace_len = buffer
 2997                                .reversed_chars_at(start)
 2998                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2999                                .map(|c| c.len_utf8())
 3000                                .sum::<usize>();
 3001
 3002                            let trailing_whitespace_len = buffer
 3003                                .chars_at(end)
 3004                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3005                                .map(|c| c.len_utf8())
 3006                                .sum::<usize>();
 3007
 3008                            let insert_extra_newline =
 3009                                language.brackets().any(|(pair, enabled)| {
 3010                                    let pair_start = pair.start.trim_end();
 3011                                    let pair_end = pair.end.trim_start();
 3012
 3013                                    enabled
 3014                                        && pair.newline
 3015                                        && buffer.contains_str_at(
 3016                                            end + trailing_whitespace_len,
 3017                                            pair_end,
 3018                                        )
 3019                                        && buffer.contains_str_at(
 3020                                            (start - leading_whitespace_len)
 3021                                                .saturating_sub(pair_start.len()),
 3022                                            pair_start,
 3023                                        )
 3024                                });
 3025
 3026                            // Comment extension on newline is allowed only for cursor selections
 3027                            let comment_delimiter = maybe!({
 3028                                if !selection_is_empty {
 3029                                    return None;
 3030                                }
 3031
 3032                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3033                                    return None;
 3034                                }
 3035
 3036                                let delimiters = language.line_comment_prefixes();
 3037                                let max_len_of_delimiter =
 3038                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3039                                let (snapshot, range) =
 3040                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3041
 3042                                let mut index_of_first_non_whitespace = 0;
 3043                                let comment_candidate = snapshot
 3044                                    .chars_for_range(range)
 3045                                    .skip_while(|c| {
 3046                                        let should_skip = c.is_whitespace();
 3047                                        if should_skip {
 3048                                            index_of_first_non_whitespace += 1;
 3049                                        }
 3050                                        should_skip
 3051                                    })
 3052                                    .take(max_len_of_delimiter)
 3053                                    .collect::<String>();
 3054                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3055                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3056                                })?;
 3057                                let cursor_is_placed_after_comment_marker =
 3058                                    index_of_first_non_whitespace + comment_prefix.len()
 3059                                        <= start_point.column as usize;
 3060                                if cursor_is_placed_after_comment_marker {
 3061                                    Some(comment_prefix.clone())
 3062                                } else {
 3063                                    None
 3064                                }
 3065                            });
 3066                            (comment_delimiter, insert_extra_newline)
 3067                        } else {
 3068                            (None, false)
 3069                        };
 3070
 3071                        let capacity_for_delimiter = comment_delimiter
 3072                            .as_deref()
 3073                            .map(str::len)
 3074                            .unwrap_or_default();
 3075                        let mut new_text =
 3076                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3077                        new_text.push('\n');
 3078                        new_text.extend(indent.chars());
 3079                        if let Some(delimiter) = &comment_delimiter {
 3080                            new_text.push_str(delimiter);
 3081                        }
 3082                        if insert_extra_newline {
 3083                            new_text = new_text.repeat(2);
 3084                        }
 3085
 3086                        let anchor = buffer.anchor_after(end);
 3087                        let new_selection = selection.map(|_| anchor);
 3088                        (
 3089                            (start..end, new_text),
 3090                            (insert_extra_newline, new_selection),
 3091                        )
 3092                    })
 3093                    .unzip()
 3094            };
 3095
 3096            this.edit_with_autoindent(edits, cx);
 3097            let buffer = this.buffer.read(cx).snapshot(cx);
 3098            let new_selections = selection_fixup_info
 3099                .into_iter()
 3100                .map(|(extra_newline_inserted, new_selection)| {
 3101                    let mut cursor = new_selection.end.to_point(&buffer);
 3102                    if extra_newline_inserted {
 3103                        cursor.row -= 1;
 3104                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3105                    }
 3106                    new_selection.map(|_| cursor)
 3107                })
 3108                .collect();
 3109
 3110            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3111            this.refresh_inline_completion(true, false, cx);
 3112        });
 3113    }
 3114
 3115    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3116        let buffer = self.buffer.read(cx);
 3117        let snapshot = buffer.snapshot(cx);
 3118
 3119        let mut edits = Vec::new();
 3120        let mut rows = Vec::new();
 3121
 3122        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3123            let cursor = selection.head();
 3124            let row = cursor.row;
 3125
 3126            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3127
 3128            let newline = "\n".to_string();
 3129            edits.push((start_of_line..start_of_line, newline));
 3130
 3131            rows.push(row + rows_inserted as u32);
 3132        }
 3133
 3134        self.transact(cx, |editor, cx| {
 3135            editor.edit(edits, cx);
 3136
 3137            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3138                let mut index = 0;
 3139                s.move_cursors_with(|map, _, _| {
 3140                    let row = rows[index];
 3141                    index += 1;
 3142
 3143                    let point = Point::new(row, 0);
 3144                    let boundary = map.next_line_boundary(point).1;
 3145                    let clipped = map.clip_point(boundary, Bias::Left);
 3146
 3147                    (clipped, SelectionGoal::None)
 3148                });
 3149            });
 3150
 3151            let mut indent_edits = Vec::new();
 3152            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3153            for row in rows {
 3154                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3155                for (row, indent) in indents {
 3156                    if indent.len == 0 {
 3157                        continue;
 3158                    }
 3159
 3160                    let text = match indent.kind {
 3161                        IndentKind::Space => " ".repeat(indent.len as usize),
 3162                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3163                    };
 3164                    let point = Point::new(row.0, 0);
 3165                    indent_edits.push((point..point, text));
 3166                }
 3167            }
 3168            editor.edit(indent_edits, cx);
 3169        });
 3170    }
 3171
 3172    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3173        let buffer = self.buffer.read(cx);
 3174        let snapshot = buffer.snapshot(cx);
 3175
 3176        let mut edits = Vec::new();
 3177        let mut rows = Vec::new();
 3178        let mut rows_inserted = 0;
 3179
 3180        for selection in self.selections.all_adjusted(cx) {
 3181            let cursor = selection.head();
 3182            let row = cursor.row;
 3183
 3184            let point = Point::new(row + 1, 0);
 3185            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3186
 3187            let newline = "\n".to_string();
 3188            edits.push((start_of_line..start_of_line, newline));
 3189
 3190            rows_inserted += 1;
 3191            rows.push(row + rows_inserted);
 3192        }
 3193
 3194        self.transact(cx, |editor, cx| {
 3195            editor.edit(edits, cx);
 3196
 3197            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3198                let mut index = 0;
 3199                s.move_cursors_with(|map, _, _| {
 3200                    let row = rows[index];
 3201                    index += 1;
 3202
 3203                    let point = Point::new(row, 0);
 3204                    let boundary = map.next_line_boundary(point).1;
 3205                    let clipped = map.clip_point(boundary, Bias::Left);
 3206
 3207                    (clipped, SelectionGoal::None)
 3208                });
 3209            });
 3210
 3211            let mut indent_edits = Vec::new();
 3212            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3213            for row in rows {
 3214                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3215                for (row, indent) in indents {
 3216                    if indent.len == 0 {
 3217                        continue;
 3218                    }
 3219
 3220                    let text = match indent.kind {
 3221                        IndentKind::Space => " ".repeat(indent.len as usize),
 3222                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3223                    };
 3224                    let point = Point::new(row.0, 0);
 3225                    indent_edits.push((point..point, text));
 3226                }
 3227            }
 3228            editor.edit(indent_edits, cx);
 3229        });
 3230    }
 3231
 3232    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3233        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3234            original_indent_columns: Vec::new(),
 3235        });
 3236        self.insert_with_autoindent_mode(text, autoindent, cx);
 3237    }
 3238
 3239    fn insert_with_autoindent_mode(
 3240        &mut self,
 3241        text: &str,
 3242        autoindent_mode: Option<AutoindentMode>,
 3243        cx: &mut ViewContext<Self>,
 3244    ) {
 3245        if self.read_only(cx) {
 3246            return;
 3247        }
 3248
 3249        let text: Arc<str> = text.into();
 3250        self.transact(cx, |this, cx| {
 3251            let old_selections = this.selections.all_adjusted(cx);
 3252            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3253                let anchors = {
 3254                    let snapshot = buffer.read(cx);
 3255                    old_selections
 3256                        .iter()
 3257                        .map(|s| {
 3258                            let anchor = snapshot.anchor_after(s.head());
 3259                            s.map(|_| anchor)
 3260                        })
 3261                        .collect::<Vec<_>>()
 3262                };
 3263                buffer.edit(
 3264                    old_selections
 3265                        .iter()
 3266                        .map(|s| (s.start..s.end, text.clone())),
 3267                    autoindent_mode,
 3268                    cx,
 3269                );
 3270                anchors
 3271            });
 3272
 3273            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3274                s.select_anchors(selection_anchors);
 3275            })
 3276        });
 3277    }
 3278
 3279    fn trigger_completion_on_input(
 3280        &mut self,
 3281        text: &str,
 3282        trigger_in_words: bool,
 3283        cx: &mut ViewContext<Self>,
 3284    ) {
 3285        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3286            self.show_completions(
 3287                &ShowCompletions {
 3288                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3289                },
 3290                cx,
 3291            );
 3292        } else {
 3293            self.hide_context_menu(cx);
 3294        }
 3295    }
 3296
 3297    fn is_completion_trigger(
 3298        &self,
 3299        text: &str,
 3300        trigger_in_words: bool,
 3301        cx: &mut ViewContext<Self>,
 3302    ) -> bool {
 3303        let position = self.selections.newest_anchor().head();
 3304        let multibuffer = self.buffer.read(cx);
 3305        let Some(buffer) = position
 3306            .buffer_id
 3307            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3308        else {
 3309            return false;
 3310        };
 3311
 3312        if let Some(completion_provider) = &self.completion_provider {
 3313            completion_provider.is_completion_trigger(
 3314                &buffer,
 3315                position.text_anchor,
 3316                text,
 3317                trigger_in_words,
 3318                cx,
 3319            )
 3320        } else {
 3321            false
 3322        }
 3323    }
 3324
 3325    /// If any empty selections is touching the start of its innermost containing autoclose
 3326    /// region, expand it to select the brackets.
 3327    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3328        let selections = self.selections.all::<usize>(cx);
 3329        let buffer = self.buffer.read(cx).read(cx);
 3330        let new_selections = self
 3331            .selections_with_autoclose_regions(selections, &buffer)
 3332            .map(|(mut selection, region)| {
 3333                if !selection.is_empty() {
 3334                    return selection;
 3335                }
 3336
 3337                if let Some(region) = region {
 3338                    let mut range = region.range.to_offset(&buffer);
 3339                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3340                        range.start -= region.pair.start.len();
 3341                        if buffer.contains_str_at(range.start, &region.pair.start)
 3342                            && buffer.contains_str_at(range.end, &region.pair.end)
 3343                        {
 3344                            range.end += region.pair.end.len();
 3345                            selection.start = range.start;
 3346                            selection.end = range.end;
 3347
 3348                            return selection;
 3349                        }
 3350                    }
 3351                }
 3352
 3353                let always_treat_brackets_as_autoclosed = buffer
 3354                    .settings_at(selection.start, cx)
 3355                    .always_treat_brackets_as_autoclosed;
 3356
 3357                if !always_treat_brackets_as_autoclosed {
 3358                    return selection;
 3359                }
 3360
 3361                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3362                    for (pair, enabled) in scope.brackets() {
 3363                        if !enabled || !pair.close {
 3364                            continue;
 3365                        }
 3366
 3367                        if buffer.contains_str_at(selection.start, &pair.end) {
 3368                            let pair_start_len = pair.start.len();
 3369                            if buffer.contains_str_at(
 3370                                selection.start.saturating_sub(pair_start_len),
 3371                                &pair.start,
 3372                            ) {
 3373                                selection.start -= pair_start_len;
 3374                                selection.end += pair.end.len();
 3375
 3376                                return selection;
 3377                            }
 3378                        }
 3379                    }
 3380                }
 3381
 3382                selection
 3383            })
 3384            .collect();
 3385
 3386        drop(buffer);
 3387        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3388    }
 3389
 3390    /// Iterate the given selections, and for each one, find the smallest surrounding
 3391    /// autoclose region. This uses the ordering of the selections and the autoclose
 3392    /// regions to avoid repeated comparisons.
 3393    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3394        &'a self,
 3395        selections: impl IntoIterator<Item = Selection<D>>,
 3396        buffer: &'a MultiBufferSnapshot,
 3397    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3398        let mut i = 0;
 3399        let mut regions = self.autoclose_regions.as_slice();
 3400        selections.into_iter().map(move |selection| {
 3401            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3402
 3403            let mut enclosing = None;
 3404            while let Some(pair_state) = regions.get(i) {
 3405                if pair_state.range.end.to_offset(buffer) < range.start {
 3406                    regions = &regions[i + 1..];
 3407                    i = 0;
 3408                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3409                    break;
 3410                } else {
 3411                    if pair_state.selection_id == selection.id {
 3412                        enclosing = Some(pair_state);
 3413                    }
 3414                    i += 1;
 3415                }
 3416            }
 3417
 3418            (selection, enclosing)
 3419        })
 3420    }
 3421
 3422    /// Remove any autoclose regions that no longer contain their selection.
 3423    fn invalidate_autoclose_regions(
 3424        &mut self,
 3425        mut selections: &[Selection<Anchor>],
 3426        buffer: &MultiBufferSnapshot,
 3427    ) {
 3428        self.autoclose_regions.retain(|state| {
 3429            let mut i = 0;
 3430            while let Some(selection) = selections.get(i) {
 3431                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3432                    selections = &selections[1..];
 3433                    continue;
 3434                }
 3435                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3436                    break;
 3437                }
 3438                if selection.id == state.selection_id {
 3439                    return true;
 3440                } else {
 3441                    i += 1;
 3442                }
 3443            }
 3444            false
 3445        });
 3446    }
 3447
 3448    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3449        let offset = position.to_offset(buffer);
 3450        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3451        if offset > word_range.start && kind == Some(CharKind::Word) {
 3452            Some(
 3453                buffer
 3454                    .text_for_range(word_range.start..offset)
 3455                    .collect::<String>(),
 3456            )
 3457        } else {
 3458            None
 3459        }
 3460    }
 3461
 3462    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3463        self.refresh_inlay_hints(
 3464            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3465            cx,
 3466        );
 3467    }
 3468
 3469    pub fn inlay_hints_enabled(&self) -> bool {
 3470        self.inlay_hint_cache.enabled
 3471    }
 3472
 3473    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3474        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3475            return;
 3476        }
 3477
 3478        let reason_description = reason.description();
 3479        let ignore_debounce = matches!(
 3480            reason,
 3481            InlayHintRefreshReason::SettingsChange(_)
 3482                | InlayHintRefreshReason::Toggle(_)
 3483                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3484        );
 3485        let (invalidate_cache, required_languages) = match reason {
 3486            InlayHintRefreshReason::Toggle(enabled) => {
 3487                self.inlay_hint_cache.enabled = enabled;
 3488                if enabled {
 3489                    (InvalidationStrategy::RefreshRequested, None)
 3490                } else {
 3491                    self.inlay_hint_cache.clear();
 3492                    self.splice_inlays(
 3493                        self.visible_inlay_hints(cx)
 3494                            .iter()
 3495                            .map(|inlay| inlay.id)
 3496                            .collect(),
 3497                        Vec::new(),
 3498                        cx,
 3499                    );
 3500                    return;
 3501                }
 3502            }
 3503            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3504                match self.inlay_hint_cache.update_settings(
 3505                    &self.buffer,
 3506                    new_settings,
 3507                    self.visible_inlay_hints(cx),
 3508                    cx,
 3509                ) {
 3510                    ControlFlow::Break(Some(InlaySplice {
 3511                        to_remove,
 3512                        to_insert,
 3513                    })) => {
 3514                        self.splice_inlays(to_remove, to_insert, cx);
 3515                        return;
 3516                    }
 3517                    ControlFlow::Break(None) => return,
 3518                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3519                }
 3520            }
 3521            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3522                if let Some(InlaySplice {
 3523                    to_remove,
 3524                    to_insert,
 3525                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3526                {
 3527                    self.splice_inlays(to_remove, to_insert, cx);
 3528                }
 3529                return;
 3530            }
 3531            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3532            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3533                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3534            }
 3535            InlayHintRefreshReason::RefreshRequested => {
 3536                (InvalidationStrategy::RefreshRequested, None)
 3537            }
 3538        };
 3539
 3540        if let Some(InlaySplice {
 3541            to_remove,
 3542            to_insert,
 3543        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3544            reason_description,
 3545            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3546            invalidate_cache,
 3547            ignore_debounce,
 3548            cx,
 3549        ) {
 3550            self.splice_inlays(to_remove, to_insert, cx);
 3551        }
 3552    }
 3553
 3554    fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
 3555        self.display_map
 3556            .read(cx)
 3557            .current_inlays()
 3558            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3559            .cloned()
 3560            .collect()
 3561    }
 3562
 3563    pub fn excerpts_for_inlay_hints_query(
 3564        &self,
 3565        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3566        cx: &mut ViewContext<Editor>,
 3567    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3568        let Some(project) = self.project.as_ref() else {
 3569            return HashMap::default();
 3570        };
 3571        let project = project.read(cx);
 3572        let multi_buffer = self.buffer().read(cx);
 3573        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3574        let multi_buffer_visible_start = self
 3575            .scroll_manager
 3576            .anchor()
 3577            .anchor
 3578            .to_point(&multi_buffer_snapshot);
 3579        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3580            multi_buffer_visible_start
 3581                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3582            Bias::Left,
 3583        );
 3584        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3585        multi_buffer_snapshot
 3586            .range_to_buffer_ranges(multi_buffer_visible_range)
 3587            .into_iter()
 3588            .filter(|(_, excerpt_visible_range)| !excerpt_visible_range.is_empty())
 3589            .filter_map(|(excerpt, excerpt_visible_range)| {
 3590                let buffer_file = project::File::from_dyn(excerpt.buffer().file())?;
 3591                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3592                let worktree_entry = buffer_worktree
 3593                    .read(cx)
 3594                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3595                if worktree_entry.is_ignored {
 3596                    return None;
 3597                }
 3598
 3599                let language = excerpt.buffer().language()?;
 3600                if let Some(restrict_to_languages) = restrict_to_languages {
 3601                    if !restrict_to_languages.contains(language) {
 3602                        return None;
 3603                    }
 3604                }
 3605                Some((
 3606                    excerpt.id(),
 3607                    (
 3608                        multi_buffer.buffer(excerpt.buffer_id()).unwrap(),
 3609                        excerpt.buffer().version().clone(),
 3610                        excerpt_visible_range,
 3611                    ),
 3612                ))
 3613            })
 3614            .collect()
 3615    }
 3616
 3617    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3618        TextLayoutDetails {
 3619            text_system: cx.text_system().clone(),
 3620            editor_style: self.style.clone().unwrap(),
 3621            rem_size: cx.rem_size(),
 3622            scroll_anchor: self.scroll_manager.anchor(),
 3623            visible_rows: self.visible_line_count(),
 3624            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3625        }
 3626    }
 3627
 3628    pub fn splice_inlays(
 3629        &self,
 3630        to_remove: Vec<InlayId>,
 3631        to_insert: Vec<Inlay>,
 3632        cx: &mut ViewContext<Self>,
 3633    ) {
 3634        self.display_map.update(cx, |display_map, cx| {
 3635            display_map.splice_inlays(to_remove, to_insert, cx)
 3636        });
 3637        cx.notify();
 3638    }
 3639
 3640    fn trigger_on_type_formatting(
 3641        &self,
 3642        input: String,
 3643        cx: &mut ViewContext<Self>,
 3644    ) -> Option<Task<Result<()>>> {
 3645        if input.len() != 1 {
 3646            return None;
 3647        }
 3648
 3649        let project = self.project.as_ref()?;
 3650        let position = self.selections.newest_anchor().head();
 3651        let (buffer, buffer_position) = self
 3652            .buffer
 3653            .read(cx)
 3654            .text_anchor_for_position(position, cx)?;
 3655
 3656        let settings = language_settings::language_settings(
 3657            buffer
 3658                .read(cx)
 3659                .language_at(buffer_position)
 3660                .map(|l| l.name()),
 3661            buffer.read(cx).file(),
 3662            cx,
 3663        );
 3664        if !settings.use_on_type_format {
 3665            return None;
 3666        }
 3667
 3668        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3669        // hence we do LSP request & edit on host side only — add formats to host's history.
 3670        let push_to_lsp_host_history = true;
 3671        // If this is not the host, append its history with new edits.
 3672        let push_to_client_history = project.read(cx).is_via_collab();
 3673
 3674        let on_type_formatting = project.update(cx, |project, cx| {
 3675            project.on_type_format(
 3676                buffer.clone(),
 3677                buffer_position,
 3678                input,
 3679                push_to_lsp_host_history,
 3680                cx,
 3681            )
 3682        });
 3683        Some(cx.spawn(|editor, mut cx| async move {
 3684            if let Some(transaction) = on_type_formatting.await? {
 3685                if push_to_client_history {
 3686                    buffer
 3687                        .update(&mut cx, |buffer, _| {
 3688                            buffer.push_transaction(transaction, Instant::now());
 3689                        })
 3690                        .ok();
 3691                }
 3692                editor.update(&mut cx, |editor, cx| {
 3693                    editor.refresh_document_highlights(cx);
 3694                })?;
 3695            }
 3696            Ok(())
 3697        }))
 3698    }
 3699
 3700    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3701        if self.pending_rename.is_some() {
 3702            return;
 3703        }
 3704
 3705        let Some(provider) = self.completion_provider.as_ref() else {
 3706            return;
 3707        };
 3708
 3709        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3710            return;
 3711        }
 3712
 3713        let position = self.selections.newest_anchor().head();
 3714        let (buffer, buffer_position) =
 3715            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3716                output
 3717            } else {
 3718                return;
 3719            };
 3720        let show_completion_documentation = buffer
 3721            .read(cx)
 3722            .snapshot()
 3723            .settings_at(buffer_position, cx)
 3724            .show_completion_documentation;
 3725
 3726        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3727
 3728        let trigger_kind = match &options.trigger {
 3729            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3730                CompletionTriggerKind::TRIGGER_CHARACTER
 3731            }
 3732            _ => CompletionTriggerKind::INVOKED,
 3733        };
 3734        let completion_context = CompletionContext {
 3735            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3736                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3737                    Some(String::from(trigger))
 3738                } else {
 3739                    None
 3740                }
 3741            }),
 3742            trigger_kind,
 3743        };
 3744        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 3745        let sort_completions = provider.sort_completions();
 3746
 3747        let id = post_inc(&mut self.next_completion_id);
 3748        let task = cx.spawn(|editor, mut cx| {
 3749            async move {
 3750                editor.update(&mut cx, |this, _| {
 3751                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3752                })?;
 3753                let completions = completions.await.log_err();
 3754                let menu = if let Some(completions) = completions {
 3755                    let mut menu = CompletionsMenu::new(
 3756                        id,
 3757                        sort_completions,
 3758                        show_completion_documentation,
 3759                        position,
 3760                        buffer.clone(),
 3761                        completions.into(),
 3762                    );
 3763
 3764                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3765                        .await;
 3766
 3767                    menu.visible().then_some(menu)
 3768                } else {
 3769                    None
 3770                };
 3771
 3772                editor.update(&mut cx, |editor, cx| {
 3773                    match editor.context_menu.borrow().as_ref() {
 3774                        None => {}
 3775                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3776                            if prev_menu.id > id {
 3777                                return;
 3778                            }
 3779                        }
 3780                        _ => return,
 3781                    }
 3782
 3783                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 3784                        let mut menu = menu.unwrap();
 3785                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3786
 3787                        if editor.show_inline_completions_in_menu(cx) {
 3788                            if let Some(hint) = editor.inline_completion_menu_hint(cx) {
 3789                                menu.show_inline_completion_hint(hint);
 3790                            }
 3791                        } else {
 3792                            editor.discard_inline_completion(false, cx);
 3793                        }
 3794
 3795                        *editor.context_menu.borrow_mut() =
 3796                            Some(CodeContextMenu::Completions(menu));
 3797
 3798                        cx.notify();
 3799                    } else if editor.completion_tasks.len() <= 1 {
 3800                        // If there are no more completion tasks and the last menu was
 3801                        // empty, we should hide it.
 3802                        let was_hidden = editor.hide_context_menu(cx).is_none();
 3803                        // If it was already hidden and we don't show inline
 3804                        // completions in the menu, we should also show the
 3805                        // inline-completion when available.
 3806                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3807                            editor.update_visible_inline_completion(cx);
 3808                        }
 3809                    }
 3810                })?;
 3811
 3812                Ok::<_, anyhow::Error>(())
 3813            }
 3814            .log_err()
 3815        });
 3816
 3817        self.completion_tasks.push((id, task));
 3818    }
 3819
 3820    pub fn confirm_completion(
 3821        &mut self,
 3822        action: &ConfirmCompletion,
 3823        cx: &mut ViewContext<Self>,
 3824    ) -> Option<Task<Result<()>>> {
 3825        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 3826    }
 3827
 3828    pub fn compose_completion(
 3829        &mut self,
 3830        action: &ComposeCompletion,
 3831        cx: &mut ViewContext<Self>,
 3832    ) -> Option<Task<Result<()>>> {
 3833        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 3834    }
 3835
 3836    fn toggle_zed_predict_tos(&mut self, cx: &mut ViewContext<Self>) {
 3837        let (Some(workspace), Some(project)) = (self.workspace(), self.project.as_ref()) else {
 3838            return;
 3839        };
 3840
 3841        ZedPredictTos::toggle(workspace, project.read(cx).user_store().clone(), cx);
 3842    }
 3843
 3844    fn do_completion(
 3845        &mut self,
 3846        item_ix: Option<usize>,
 3847        intent: CompletionIntent,
 3848        cx: &mut ViewContext<Editor>,
 3849    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3850        use language::ToOffset as _;
 3851
 3852        {
 3853            let context_menu = self.context_menu.borrow();
 3854            if let CodeContextMenu::Completions(menu) = context_menu.as_ref()? {
 3855                let entries = menu.entries.borrow();
 3856                let entry = entries.get(item_ix.unwrap_or(menu.selected_item));
 3857                match entry {
 3858                    Some(CompletionEntry::InlineCompletionHint(
 3859                        InlineCompletionMenuHint::Loading,
 3860                    )) => return Some(Task::ready(Ok(()))),
 3861                    Some(CompletionEntry::InlineCompletionHint(InlineCompletionMenuHint::None)) => {
 3862                        drop(entries);
 3863                        drop(context_menu);
 3864                        self.context_menu_next(&Default::default(), cx);
 3865                        return Some(Task::ready(Ok(())));
 3866                    }
 3867                    Some(CompletionEntry::InlineCompletionHint(
 3868                        InlineCompletionMenuHint::PendingTermsAcceptance,
 3869                    )) => {
 3870                        drop(entries);
 3871                        drop(context_menu);
 3872                        self.toggle_zed_predict_tos(cx);
 3873                        return Some(Task::ready(Ok(())));
 3874                    }
 3875                    _ => {}
 3876                }
 3877            }
 3878        }
 3879
 3880        let completions_menu =
 3881            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3882                menu
 3883            } else {
 3884                return None;
 3885            };
 3886
 3887        let entries = completions_menu.entries.borrow();
 3888        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3889        let mat = match mat {
 3890            CompletionEntry::InlineCompletionHint(_) => {
 3891                self.accept_inline_completion(&AcceptInlineCompletion, cx);
 3892                cx.stop_propagation();
 3893                return Some(Task::ready(Ok(())));
 3894            }
 3895            CompletionEntry::Match(mat) => {
 3896                if self.show_inline_completions_in_menu(cx) {
 3897                    self.discard_inline_completion(true, cx);
 3898                }
 3899                mat
 3900            }
 3901        };
 3902        let candidate_id = mat.candidate_id;
 3903        drop(entries);
 3904
 3905        let buffer_handle = completions_menu.buffer;
 3906        let completion = completions_menu
 3907            .completions
 3908            .borrow()
 3909            .get(candidate_id)?
 3910            .clone();
 3911        cx.stop_propagation();
 3912
 3913        let snippet;
 3914        let text;
 3915
 3916        if completion.is_snippet() {
 3917            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3918            text = snippet.as_ref().unwrap().text.clone();
 3919        } else {
 3920            snippet = None;
 3921            text = completion.new_text.clone();
 3922        };
 3923        let selections = self.selections.all::<usize>(cx);
 3924        let buffer = buffer_handle.read(cx);
 3925        let old_range = completion.old_range.to_offset(buffer);
 3926        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3927
 3928        let newest_selection = self.selections.newest_anchor();
 3929        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3930            return None;
 3931        }
 3932
 3933        let lookbehind = newest_selection
 3934            .start
 3935            .text_anchor
 3936            .to_offset(buffer)
 3937            .saturating_sub(old_range.start);
 3938        let lookahead = old_range
 3939            .end
 3940            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3941        let mut common_prefix_len = old_text
 3942            .bytes()
 3943            .zip(text.bytes())
 3944            .take_while(|(a, b)| a == b)
 3945            .count();
 3946
 3947        let snapshot = self.buffer.read(cx).snapshot(cx);
 3948        let mut range_to_replace: Option<Range<isize>> = None;
 3949        let mut ranges = Vec::new();
 3950        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3951        for selection in &selections {
 3952            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3953                let start = selection.start.saturating_sub(lookbehind);
 3954                let end = selection.end + lookahead;
 3955                if selection.id == newest_selection.id {
 3956                    range_to_replace = Some(
 3957                        ((start + common_prefix_len) as isize - selection.start as isize)
 3958                            ..(end as isize - selection.start as isize),
 3959                    );
 3960                }
 3961                ranges.push(start + common_prefix_len..end);
 3962            } else {
 3963                common_prefix_len = 0;
 3964                ranges.clear();
 3965                ranges.extend(selections.iter().map(|s| {
 3966                    if s.id == newest_selection.id {
 3967                        range_to_replace = Some(
 3968                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3969                                - selection.start as isize
 3970                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3971                                    - selection.start as isize,
 3972                        );
 3973                        old_range.clone()
 3974                    } else {
 3975                        s.start..s.end
 3976                    }
 3977                }));
 3978                break;
 3979            }
 3980            if !self.linked_edit_ranges.is_empty() {
 3981                let start_anchor = snapshot.anchor_before(selection.head());
 3982                let end_anchor = snapshot.anchor_after(selection.tail());
 3983                if let Some(ranges) = self
 3984                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 3985                {
 3986                    for (buffer, edits) in ranges {
 3987                        linked_edits.entry(buffer.clone()).or_default().extend(
 3988                            edits
 3989                                .into_iter()
 3990                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 3991                        );
 3992                    }
 3993                }
 3994            }
 3995        }
 3996        let text = &text[common_prefix_len..];
 3997
 3998        cx.emit(EditorEvent::InputHandled {
 3999            utf16_range_to_replace: range_to_replace,
 4000            text: text.into(),
 4001        });
 4002
 4003        self.transact(cx, |this, cx| {
 4004            if let Some(mut snippet) = snippet {
 4005                snippet.text = text.to_string();
 4006                for tabstop in snippet
 4007                    .tabstops
 4008                    .iter_mut()
 4009                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4010                {
 4011                    tabstop.start -= common_prefix_len as isize;
 4012                    tabstop.end -= common_prefix_len as isize;
 4013                }
 4014
 4015                this.insert_snippet(&ranges, snippet, cx).log_err();
 4016            } else {
 4017                this.buffer.update(cx, |buffer, cx| {
 4018                    buffer.edit(
 4019                        ranges.iter().map(|range| (range.clone(), text)),
 4020                        this.autoindent_mode.clone(),
 4021                        cx,
 4022                    );
 4023                });
 4024            }
 4025            for (buffer, edits) in linked_edits {
 4026                buffer.update(cx, |buffer, cx| {
 4027                    let snapshot = buffer.snapshot();
 4028                    let edits = edits
 4029                        .into_iter()
 4030                        .map(|(range, text)| {
 4031                            use text::ToPoint as TP;
 4032                            let end_point = TP::to_point(&range.end, &snapshot);
 4033                            let start_point = TP::to_point(&range.start, &snapshot);
 4034                            (start_point..end_point, text)
 4035                        })
 4036                        .sorted_by_key(|(range, _)| range.start)
 4037                        .collect::<Vec<_>>();
 4038                    buffer.edit(edits, None, cx);
 4039                })
 4040            }
 4041
 4042            this.refresh_inline_completion(true, false, cx);
 4043        });
 4044
 4045        let show_new_completions_on_confirm = completion
 4046            .confirm
 4047            .as_ref()
 4048            .map_or(false, |confirm| confirm(intent, cx));
 4049        if show_new_completions_on_confirm {
 4050            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4051        }
 4052
 4053        let provider = self.completion_provider.as_ref()?;
 4054        drop(completion);
 4055        let apply_edits = provider.apply_additional_edits_for_completion(
 4056            buffer_handle,
 4057            completions_menu.completions.clone(),
 4058            candidate_id,
 4059            true,
 4060            cx,
 4061        );
 4062
 4063        let editor_settings = EditorSettings::get_global(cx);
 4064        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4065            // After the code completion is finished, users often want to know what signatures are needed.
 4066            // so we should automatically call signature_help
 4067            self.show_signature_help(&ShowSignatureHelp, cx);
 4068        }
 4069
 4070        Some(cx.foreground_executor().spawn(async move {
 4071            apply_edits.await?;
 4072            Ok(())
 4073        }))
 4074    }
 4075
 4076    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4077        let mut context_menu = self.context_menu.borrow_mut();
 4078        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4079            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4080                // Toggle if we're selecting the same one
 4081                *context_menu = None;
 4082                cx.notify();
 4083                return;
 4084            } else {
 4085                // Otherwise, clear it and start a new one
 4086                *context_menu = None;
 4087                cx.notify();
 4088            }
 4089        }
 4090        drop(context_menu);
 4091        let snapshot = self.snapshot(cx);
 4092        let deployed_from_indicator = action.deployed_from_indicator;
 4093        let mut task = self.code_actions_task.take();
 4094        let action = action.clone();
 4095        cx.spawn(|editor, mut cx| async move {
 4096            while let Some(prev_task) = task {
 4097                prev_task.await.log_err();
 4098                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4099            }
 4100
 4101            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4102                if editor.focus_handle.is_focused(cx) {
 4103                    let multibuffer_point = action
 4104                        .deployed_from_indicator
 4105                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4106                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4107                    let (buffer, buffer_row) = snapshot
 4108                        .buffer_snapshot
 4109                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4110                        .and_then(|(buffer_snapshot, range)| {
 4111                            editor
 4112                                .buffer
 4113                                .read(cx)
 4114                                .buffer(buffer_snapshot.remote_id())
 4115                                .map(|buffer| (buffer, range.start.row))
 4116                        })?;
 4117                    let (_, code_actions) = editor
 4118                        .available_code_actions
 4119                        .clone()
 4120                        .and_then(|(location, code_actions)| {
 4121                            let snapshot = location.buffer.read(cx).snapshot();
 4122                            let point_range = location.range.to_point(&snapshot);
 4123                            let point_range = point_range.start.row..=point_range.end.row;
 4124                            if point_range.contains(&buffer_row) {
 4125                                Some((location, code_actions))
 4126                            } else {
 4127                                None
 4128                            }
 4129                        })
 4130                        .unzip();
 4131                    let buffer_id = buffer.read(cx).remote_id();
 4132                    let tasks = editor
 4133                        .tasks
 4134                        .get(&(buffer_id, buffer_row))
 4135                        .map(|t| Arc::new(t.to_owned()));
 4136                    if tasks.is_none() && code_actions.is_none() {
 4137                        return None;
 4138                    }
 4139
 4140                    editor.completion_tasks.clear();
 4141                    editor.discard_inline_completion(false, cx);
 4142                    let task_context =
 4143                        tasks
 4144                            .as_ref()
 4145                            .zip(editor.project.clone())
 4146                            .map(|(tasks, project)| {
 4147                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4148                            });
 4149
 4150                    Some(cx.spawn(|editor, mut cx| async move {
 4151                        let task_context = match task_context {
 4152                            Some(task_context) => task_context.await,
 4153                            None => None,
 4154                        };
 4155                        let resolved_tasks =
 4156                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4157                                Rc::new(ResolvedTasks {
 4158                                    templates: tasks.resolve(&task_context).collect(),
 4159                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4160                                        multibuffer_point.row,
 4161                                        tasks.column,
 4162                                    )),
 4163                                })
 4164                            });
 4165                        let spawn_straight_away = resolved_tasks
 4166                            .as_ref()
 4167                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4168                            && code_actions
 4169                                .as_ref()
 4170                                .map_or(true, |actions| actions.is_empty());
 4171                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4172                            *editor.context_menu.borrow_mut() =
 4173                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4174                                    buffer,
 4175                                    actions: CodeActionContents {
 4176                                        tasks: resolved_tasks,
 4177                                        actions: code_actions,
 4178                                    },
 4179                                    selected_item: Default::default(),
 4180                                    scroll_handle: UniformListScrollHandle::default(),
 4181                                    deployed_from_indicator,
 4182                                }));
 4183                            if spawn_straight_away {
 4184                                if let Some(task) = editor.confirm_code_action(
 4185                                    &ConfirmCodeAction { item_ix: Some(0) },
 4186                                    cx,
 4187                                ) {
 4188                                    cx.notify();
 4189                                    return task;
 4190                                }
 4191                            }
 4192                            cx.notify();
 4193                            Task::ready(Ok(()))
 4194                        }) {
 4195                            task.await
 4196                        } else {
 4197                            Ok(())
 4198                        }
 4199                    }))
 4200                } else {
 4201                    Some(Task::ready(Ok(())))
 4202                }
 4203            })?;
 4204            if let Some(task) = spawned_test_task {
 4205                task.await?;
 4206            }
 4207
 4208            Ok::<_, anyhow::Error>(())
 4209        })
 4210        .detach_and_log_err(cx);
 4211    }
 4212
 4213    pub fn confirm_code_action(
 4214        &mut self,
 4215        action: &ConfirmCodeAction,
 4216        cx: &mut ViewContext<Self>,
 4217    ) -> Option<Task<Result<()>>> {
 4218        let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4219            menu
 4220        } else {
 4221            return None;
 4222        };
 4223        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4224        let action = actions_menu.actions.get(action_ix)?;
 4225        let title = action.label();
 4226        let buffer = actions_menu.buffer;
 4227        let workspace = self.workspace()?;
 4228
 4229        match action {
 4230            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4231                workspace.update(cx, |workspace, cx| {
 4232                    workspace::tasks::schedule_resolved_task(
 4233                        workspace,
 4234                        task_source_kind,
 4235                        resolved_task,
 4236                        false,
 4237                        cx,
 4238                    );
 4239
 4240                    Some(Task::ready(Ok(())))
 4241                })
 4242            }
 4243            CodeActionsItem::CodeAction {
 4244                excerpt_id,
 4245                action,
 4246                provider,
 4247            } => {
 4248                let apply_code_action =
 4249                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4250                let workspace = workspace.downgrade();
 4251                Some(cx.spawn(|editor, cx| async move {
 4252                    let project_transaction = apply_code_action.await?;
 4253                    Self::open_project_transaction(
 4254                        &editor,
 4255                        workspace,
 4256                        project_transaction,
 4257                        title,
 4258                        cx,
 4259                    )
 4260                    .await
 4261                }))
 4262            }
 4263        }
 4264    }
 4265
 4266    pub async fn open_project_transaction(
 4267        this: &WeakView<Editor>,
 4268        workspace: WeakView<Workspace>,
 4269        transaction: ProjectTransaction,
 4270        title: String,
 4271        mut cx: AsyncWindowContext,
 4272    ) -> Result<()> {
 4273        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4274        cx.update(|cx| {
 4275            entries.sort_unstable_by_key(|(buffer, _)| {
 4276                buffer.read(cx).file().map(|f| f.path().clone())
 4277            });
 4278        })?;
 4279
 4280        // If the project transaction's edits are all contained within this editor, then
 4281        // avoid opening a new editor to display them.
 4282
 4283        if let Some((buffer, transaction)) = entries.first() {
 4284            if entries.len() == 1 {
 4285                let excerpt = this.update(&mut cx, |editor, cx| {
 4286                    editor
 4287                        .buffer()
 4288                        .read(cx)
 4289                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4290                })?;
 4291                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4292                    if excerpted_buffer == *buffer {
 4293                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4294                            let excerpt_range = excerpt_range.to_offset(buffer);
 4295                            buffer
 4296                                .edited_ranges_for_transaction::<usize>(transaction)
 4297                                .all(|range| {
 4298                                    excerpt_range.start <= range.start
 4299                                        && excerpt_range.end >= range.end
 4300                                })
 4301                        })?;
 4302
 4303                        if all_edits_within_excerpt {
 4304                            return Ok(());
 4305                        }
 4306                    }
 4307                }
 4308            }
 4309        } else {
 4310            return Ok(());
 4311        }
 4312
 4313        let mut ranges_to_highlight = Vec::new();
 4314        let excerpt_buffer = cx.new_model(|cx| {
 4315            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4316            for (buffer_handle, transaction) in &entries {
 4317                let buffer = buffer_handle.read(cx);
 4318                ranges_to_highlight.extend(
 4319                    multibuffer.push_excerpts_with_context_lines(
 4320                        buffer_handle.clone(),
 4321                        buffer
 4322                            .edited_ranges_for_transaction::<usize>(transaction)
 4323                            .collect(),
 4324                        DEFAULT_MULTIBUFFER_CONTEXT,
 4325                        cx,
 4326                    ),
 4327                );
 4328            }
 4329            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4330            multibuffer
 4331        })?;
 4332
 4333        workspace.update(&mut cx, |workspace, cx| {
 4334            let project = workspace.project().clone();
 4335            let editor =
 4336                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4337            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4338            editor.update(cx, |editor, cx| {
 4339                editor.highlight_background::<Self>(
 4340                    &ranges_to_highlight,
 4341                    |theme| theme.editor_highlighted_line_background,
 4342                    cx,
 4343                );
 4344            });
 4345        })?;
 4346
 4347        Ok(())
 4348    }
 4349
 4350    pub fn clear_code_action_providers(&mut self) {
 4351        self.code_action_providers.clear();
 4352        self.available_code_actions.take();
 4353    }
 4354
 4355    pub fn add_code_action_provider(
 4356        &mut self,
 4357        provider: Rc<dyn CodeActionProvider>,
 4358        cx: &mut ViewContext<Self>,
 4359    ) {
 4360        if self
 4361            .code_action_providers
 4362            .iter()
 4363            .any(|existing_provider| existing_provider.id() == provider.id())
 4364        {
 4365            return;
 4366        }
 4367
 4368        self.code_action_providers.push(provider);
 4369        self.refresh_code_actions(cx);
 4370    }
 4371
 4372    pub fn remove_code_action_provider(&mut self, id: Arc<str>, cx: &mut ViewContext<Self>) {
 4373        self.code_action_providers
 4374            .retain(|provider| provider.id() != id);
 4375        self.refresh_code_actions(cx);
 4376    }
 4377
 4378    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4379        let buffer = self.buffer.read(cx);
 4380        let newest_selection = self.selections.newest_anchor().clone();
 4381        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4382        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4383        if start_buffer != end_buffer {
 4384            return None;
 4385        }
 4386
 4387        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4388            cx.background_executor()
 4389                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4390                .await;
 4391
 4392            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4393                let providers = this.code_action_providers.clone();
 4394                let tasks = this
 4395                    .code_action_providers
 4396                    .iter()
 4397                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4398                    .collect::<Vec<_>>();
 4399                (providers, tasks)
 4400            })?;
 4401
 4402            let mut actions = Vec::new();
 4403            for (provider, provider_actions) in
 4404                providers.into_iter().zip(future::join_all(tasks).await)
 4405            {
 4406                if let Some(provider_actions) = provider_actions.log_err() {
 4407                    actions.extend(provider_actions.into_iter().map(|action| {
 4408                        AvailableCodeAction {
 4409                            excerpt_id: newest_selection.start.excerpt_id,
 4410                            action,
 4411                            provider: provider.clone(),
 4412                        }
 4413                    }));
 4414                }
 4415            }
 4416
 4417            this.update(&mut cx, |this, cx| {
 4418                this.available_code_actions = if actions.is_empty() {
 4419                    None
 4420                } else {
 4421                    Some((
 4422                        Location {
 4423                            buffer: start_buffer,
 4424                            range: start..end,
 4425                        },
 4426                        actions.into(),
 4427                    ))
 4428                };
 4429                cx.notify();
 4430            })
 4431        }));
 4432        None
 4433    }
 4434
 4435    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4436        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4437            self.show_git_blame_inline = false;
 4438
 4439            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4440                cx.background_executor().timer(delay).await;
 4441
 4442                this.update(&mut cx, |this, cx| {
 4443                    this.show_git_blame_inline = true;
 4444                    cx.notify();
 4445                })
 4446                .log_err();
 4447            }));
 4448        }
 4449    }
 4450
 4451    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4452        if self.pending_rename.is_some() {
 4453            return None;
 4454        }
 4455
 4456        let provider = self.semantics_provider.clone()?;
 4457        let buffer = self.buffer.read(cx);
 4458        let newest_selection = self.selections.newest_anchor().clone();
 4459        let cursor_position = newest_selection.head();
 4460        let (cursor_buffer, cursor_buffer_position) =
 4461            buffer.text_anchor_for_position(cursor_position, cx)?;
 4462        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4463        if cursor_buffer != tail_buffer {
 4464            return None;
 4465        }
 4466        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4467        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4468            cx.background_executor()
 4469                .timer(Duration::from_millis(debounce))
 4470                .await;
 4471
 4472            let highlights = if let Some(highlights) = cx
 4473                .update(|cx| {
 4474                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4475                })
 4476                .ok()
 4477                .flatten()
 4478            {
 4479                highlights.await.log_err()
 4480            } else {
 4481                None
 4482            };
 4483
 4484            if let Some(highlights) = highlights {
 4485                this.update(&mut cx, |this, cx| {
 4486                    if this.pending_rename.is_some() {
 4487                        return;
 4488                    }
 4489
 4490                    let buffer_id = cursor_position.buffer_id;
 4491                    let buffer = this.buffer.read(cx);
 4492                    if !buffer
 4493                        .text_anchor_for_position(cursor_position, cx)
 4494                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4495                    {
 4496                        return;
 4497                    }
 4498
 4499                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4500                    let mut write_ranges = Vec::new();
 4501                    let mut read_ranges = Vec::new();
 4502                    for highlight in highlights {
 4503                        for (excerpt_id, excerpt_range) in
 4504                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4505                        {
 4506                            let start = highlight
 4507                                .range
 4508                                .start
 4509                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4510                            let end = highlight
 4511                                .range
 4512                                .end
 4513                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4514                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4515                                continue;
 4516                            }
 4517
 4518                            let range = Anchor {
 4519                                buffer_id,
 4520                                excerpt_id,
 4521                                text_anchor: start,
 4522                            }..Anchor {
 4523                                buffer_id,
 4524                                excerpt_id,
 4525                                text_anchor: end,
 4526                            };
 4527                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4528                                write_ranges.push(range);
 4529                            } else {
 4530                                read_ranges.push(range);
 4531                            }
 4532                        }
 4533                    }
 4534
 4535                    this.highlight_background::<DocumentHighlightRead>(
 4536                        &read_ranges,
 4537                        |theme| theme.editor_document_highlight_read_background,
 4538                        cx,
 4539                    );
 4540                    this.highlight_background::<DocumentHighlightWrite>(
 4541                        &write_ranges,
 4542                        |theme| theme.editor_document_highlight_write_background,
 4543                        cx,
 4544                    );
 4545                    cx.notify();
 4546                })
 4547                .log_err();
 4548            }
 4549        }));
 4550        None
 4551    }
 4552
 4553    pub fn refresh_inline_completion(
 4554        &mut self,
 4555        debounce: bool,
 4556        user_requested: bool,
 4557        cx: &mut ViewContext<Self>,
 4558    ) -> Option<()> {
 4559        let provider = self.inline_completion_provider()?;
 4560        let cursor = self.selections.newest_anchor().head();
 4561        let (buffer, cursor_buffer_position) =
 4562            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4563
 4564        if !user_requested
 4565            && (!self.enable_inline_completions
 4566                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4567                || !self.is_focused(cx)
 4568                || buffer.read(cx).is_empty())
 4569        {
 4570            self.discard_inline_completion(false, cx);
 4571            return None;
 4572        }
 4573
 4574        self.update_visible_inline_completion(cx);
 4575        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4576        Some(())
 4577    }
 4578
 4579    fn cycle_inline_completion(
 4580        &mut self,
 4581        direction: Direction,
 4582        cx: &mut ViewContext<Self>,
 4583    ) -> Option<()> {
 4584        let provider = self.inline_completion_provider()?;
 4585        let cursor = self.selections.newest_anchor().head();
 4586        let (buffer, cursor_buffer_position) =
 4587            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4588        if !self.enable_inline_completions
 4589            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4590        {
 4591            return None;
 4592        }
 4593
 4594        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4595        self.update_visible_inline_completion(cx);
 4596
 4597        Some(())
 4598    }
 4599
 4600    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4601        if !self.has_active_inline_completion() {
 4602            self.refresh_inline_completion(false, true, cx);
 4603            return;
 4604        }
 4605
 4606        self.update_visible_inline_completion(cx);
 4607    }
 4608
 4609    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4610        self.show_cursor_names(cx);
 4611    }
 4612
 4613    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4614        self.show_cursor_names = true;
 4615        cx.notify();
 4616        cx.spawn(|this, mut cx| async move {
 4617            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4618            this.update(&mut cx, |this, cx| {
 4619                this.show_cursor_names = false;
 4620                cx.notify()
 4621            })
 4622            .ok()
 4623        })
 4624        .detach();
 4625    }
 4626
 4627    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4628        if self.has_active_inline_completion() {
 4629            self.cycle_inline_completion(Direction::Next, cx);
 4630        } else {
 4631            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4632            if is_copilot_disabled {
 4633                cx.propagate();
 4634            }
 4635        }
 4636    }
 4637
 4638    pub fn previous_inline_completion(
 4639        &mut self,
 4640        _: &PreviousInlineCompletion,
 4641        cx: &mut ViewContext<Self>,
 4642    ) {
 4643        if self.has_active_inline_completion() {
 4644            self.cycle_inline_completion(Direction::Prev, cx);
 4645        } else {
 4646            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4647            if is_copilot_disabled {
 4648                cx.propagate();
 4649            }
 4650        }
 4651    }
 4652
 4653    pub fn accept_inline_completion(
 4654        &mut self,
 4655        _: &AcceptInlineCompletion,
 4656        cx: &mut ViewContext<Self>,
 4657    ) {
 4658        let buffer = self.buffer.read(cx);
 4659        let snapshot = buffer.snapshot(cx);
 4660        let selection = self.selections.newest_adjusted(cx);
 4661        let cursor = selection.head();
 4662        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4663        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4664        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4665        {
 4666            if cursor.column < suggested_indent.len
 4667                && cursor.column <= current_indent.len
 4668                && current_indent.len <= suggested_indent.len
 4669            {
 4670                self.tab(&Default::default(), cx);
 4671                return;
 4672            }
 4673        }
 4674
 4675        if self.show_inline_completions_in_menu(cx) {
 4676            self.hide_context_menu(cx);
 4677        }
 4678
 4679        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4680            return;
 4681        };
 4682
 4683        self.report_inline_completion_event(true, cx);
 4684
 4685        match &active_inline_completion.completion {
 4686            InlineCompletion::Move(position) => {
 4687                let position = *position;
 4688                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4689                    selections.select_anchor_ranges([position..position]);
 4690                });
 4691            }
 4692            InlineCompletion::Edit {
 4693                edits,
 4694                single_line: _,
 4695            } => {
 4696                if let Some(provider) = self.inline_completion_provider() {
 4697                    provider.accept(cx);
 4698                }
 4699
 4700                let snapshot = self.buffer.read(cx).snapshot(cx);
 4701                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4702
 4703                self.buffer.update(cx, |buffer, cx| {
 4704                    buffer.edit(edits.iter().cloned(), None, cx)
 4705                });
 4706
 4707                self.change_selections(None, cx, |s| {
 4708                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4709                });
 4710
 4711                self.update_visible_inline_completion(cx);
 4712                if self.active_inline_completion.is_none() {
 4713                    self.refresh_inline_completion(true, true, cx);
 4714                }
 4715
 4716                cx.notify();
 4717            }
 4718        }
 4719    }
 4720
 4721    pub fn accept_partial_inline_completion(
 4722        &mut self,
 4723        _: &AcceptPartialInlineCompletion,
 4724        cx: &mut ViewContext<Self>,
 4725    ) {
 4726        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4727            return;
 4728        };
 4729        if self.selections.count() != 1 {
 4730            return;
 4731        }
 4732
 4733        self.report_inline_completion_event(true, cx);
 4734
 4735        match &active_inline_completion.completion {
 4736            InlineCompletion::Move(position) => {
 4737                let position = *position;
 4738                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4739                    selections.select_anchor_ranges([position..position]);
 4740                });
 4741            }
 4742            InlineCompletion::Edit {
 4743                edits,
 4744                single_line: _,
 4745            } => {
 4746                // Find an insertion that starts at the cursor position.
 4747                let snapshot = self.buffer.read(cx).snapshot(cx);
 4748                let cursor_offset = self.selections.newest::<usize>(cx).head();
 4749                let insertion = edits.iter().find_map(|(range, text)| {
 4750                    let range = range.to_offset(&snapshot);
 4751                    if range.is_empty() && range.start == cursor_offset {
 4752                        Some(text)
 4753                    } else {
 4754                        None
 4755                    }
 4756                });
 4757
 4758                if let Some(text) = insertion {
 4759                    let mut partial_completion = text
 4760                        .chars()
 4761                        .by_ref()
 4762                        .take_while(|c| c.is_alphabetic())
 4763                        .collect::<String>();
 4764                    if partial_completion.is_empty() {
 4765                        partial_completion = text
 4766                            .chars()
 4767                            .by_ref()
 4768                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4769                            .collect::<String>();
 4770                    }
 4771
 4772                    cx.emit(EditorEvent::InputHandled {
 4773                        utf16_range_to_replace: None,
 4774                        text: partial_completion.clone().into(),
 4775                    });
 4776
 4777                    self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4778
 4779                    self.refresh_inline_completion(true, true, cx);
 4780                    cx.notify();
 4781                } else {
 4782                    self.accept_inline_completion(&Default::default(), cx);
 4783                }
 4784            }
 4785        }
 4786    }
 4787
 4788    fn discard_inline_completion(
 4789        &mut self,
 4790        should_report_inline_completion_event: bool,
 4791        cx: &mut ViewContext<Self>,
 4792    ) -> bool {
 4793        if should_report_inline_completion_event {
 4794            self.report_inline_completion_event(false, cx);
 4795        }
 4796
 4797        if let Some(provider) = self.inline_completion_provider() {
 4798            provider.discard(cx);
 4799        }
 4800
 4801        self.take_active_inline_completion(cx).is_some()
 4802    }
 4803
 4804    fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
 4805        let Some(provider) = self.inline_completion_provider() else {
 4806            return;
 4807        };
 4808
 4809        let Some((_, buffer, _)) = self
 4810            .buffer
 4811            .read(cx)
 4812            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4813        else {
 4814            return;
 4815        };
 4816
 4817        let extension = buffer
 4818            .read(cx)
 4819            .file()
 4820            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4821
 4822        let event_type = match accepted {
 4823            true => "Inline Completion Accepted",
 4824            false => "Inline Completion Discarded",
 4825        };
 4826        telemetry::event!(
 4827            event_type,
 4828            provider = provider.name(),
 4829            suggestion_accepted = accepted,
 4830            file_extension = extension,
 4831        );
 4832    }
 4833
 4834    pub fn has_active_inline_completion(&self) -> bool {
 4835        self.active_inline_completion.is_some()
 4836    }
 4837
 4838    fn take_active_inline_completion(
 4839        &mut self,
 4840        cx: &mut ViewContext<Self>,
 4841    ) -> Option<InlineCompletion> {
 4842        let active_inline_completion = self.active_inline_completion.take()?;
 4843        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 4844        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4845        Some(active_inline_completion.completion)
 4846    }
 4847
 4848    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4849        let selection = self.selections.newest_anchor();
 4850        let cursor = selection.head();
 4851        let multibuffer = self.buffer.read(cx).snapshot(cx);
 4852        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 4853        let excerpt_id = cursor.excerpt_id;
 4854
 4855        let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
 4856            && (self.context_menu.borrow().is_some()
 4857                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 4858        if completions_menu_has_precedence
 4859            || !offset_selection.is_empty()
 4860            || !self.enable_inline_completions
 4861            || self
 4862                .active_inline_completion
 4863                .as_ref()
 4864                .map_or(false, |completion| {
 4865                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 4866                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 4867                    !invalidation_range.contains(&offset_selection.head())
 4868                })
 4869        {
 4870            self.discard_inline_completion(false, cx);
 4871            return None;
 4872        }
 4873
 4874        self.take_active_inline_completion(cx);
 4875        let provider = self.inline_completion_provider()?;
 4876
 4877        let (buffer, cursor_buffer_position) =
 4878            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4879
 4880        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 4881        let edits = completion
 4882            .edits
 4883            .into_iter()
 4884            .flat_map(|(range, new_text)| {
 4885                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 4886                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 4887                Some((start..end, new_text))
 4888            })
 4889            .collect::<Vec<_>>();
 4890        if edits.is_empty() {
 4891            return None;
 4892        }
 4893
 4894        let first_edit_start = edits.first().unwrap().0.start;
 4895        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 4896        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 4897
 4898        let last_edit_end = edits.last().unwrap().0.end;
 4899        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 4900        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 4901
 4902        let cursor_row = cursor.to_point(&multibuffer).row;
 4903
 4904        let mut inlay_ids = Vec::new();
 4905        let invalidation_row_range;
 4906        let completion;
 4907        if cursor_row < edit_start_row {
 4908            invalidation_row_range = cursor_row..edit_end_row;
 4909            completion = InlineCompletion::Move(first_edit_start);
 4910        } else if cursor_row > edit_end_row {
 4911            invalidation_row_range = edit_start_row..cursor_row;
 4912            completion = InlineCompletion::Move(first_edit_start);
 4913        } else {
 4914            if edits
 4915                .iter()
 4916                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 4917            {
 4918                let mut inlays = Vec::new();
 4919                for (range, new_text) in &edits {
 4920                    let inlay = Inlay::inline_completion(
 4921                        post_inc(&mut self.next_inlay_id),
 4922                        range.start,
 4923                        new_text.as_str(),
 4924                    );
 4925                    inlay_ids.push(inlay.id);
 4926                    inlays.push(inlay);
 4927                }
 4928
 4929                self.splice_inlays(vec![], inlays, cx);
 4930            } else {
 4931                let background_color = cx.theme().status().deleted_background;
 4932                self.highlight_text::<InlineCompletionHighlight>(
 4933                    edits.iter().map(|(range, _)| range.clone()).collect(),
 4934                    HighlightStyle {
 4935                        background_color: Some(background_color),
 4936                        ..Default::default()
 4937                    },
 4938                    cx,
 4939                );
 4940            }
 4941
 4942            invalidation_row_range = edit_start_row..edit_end_row;
 4943
 4944            let single_line = first_edit_start_point.row == last_edit_end_point.row
 4945                && !edits.iter().any(|(_, edit)| edit.contains('\n'));
 4946
 4947            completion = InlineCompletion::Edit { edits, single_line };
 4948        };
 4949
 4950        let invalidation_range = multibuffer
 4951            .anchor_before(Point::new(invalidation_row_range.start, 0))
 4952            ..multibuffer.anchor_after(Point::new(
 4953                invalidation_row_range.end,
 4954                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 4955            ));
 4956
 4957        self.active_inline_completion = Some(InlineCompletionState {
 4958            inlay_ids,
 4959            completion,
 4960            invalidation_range,
 4961        });
 4962
 4963        if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
 4964            if let Some(hint) = self.inline_completion_menu_hint(cx) {
 4965                match self.context_menu.borrow_mut().as_mut() {
 4966                    Some(CodeContextMenu::Completions(menu)) => {
 4967                        menu.show_inline_completion_hint(hint);
 4968                    }
 4969                    _ => {}
 4970                }
 4971            }
 4972        }
 4973
 4974        cx.notify();
 4975
 4976        Some(())
 4977    }
 4978
 4979    fn inline_completion_menu_hint(
 4980        &mut self,
 4981        cx: &mut ViewContext<Self>,
 4982    ) -> Option<InlineCompletionMenuHint> {
 4983        let provider = self.inline_completion_provider()?;
 4984        if self.has_active_inline_completion() {
 4985            let editor_snapshot = self.snapshot(cx);
 4986
 4987            let text = match &self.active_inline_completion.as_ref()?.completion {
 4988                InlineCompletion::Edit {
 4989                    edits,
 4990                    single_line: _,
 4991                } => inline_completion_edit_text(&editor_snapshot, edits, true, cx),
 4992                InlineCompletion::Move(target) => {
 4993                    let target_point =
 4994                        target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
 4995                    let target_line = target_point.row + 1;
 4996                    InlineCompletionText::Move(
 4997                        format!("Jump to edit in line {}", target_line).into(),
 4998                    )
 4999                }
 5000            };
 5001
 5002            Some(InlineCompletionMenuHint::Loaded { text })
 5003        } else if provider.is_refreshing(cx) {
 5004            Some(InlineCompletionMenuHint::Loading)
 5005        } else if provider.needs_terms_acceptance(cx) {
 5006            Some(InlineCompletionMenuHint::PendingTermsAcceptance)
 5007        } else {
 5008            Some(InlineCompletionMenuHint::None)
 5009        }
 5010    }
 5011
 5012    pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5013        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5014    }
 5015
 5016    fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
 5017        EditorSettings::get_global(cx).show_inline_completions_in_menu
 5018            && self
 5019                .inline_completion_provider()
 5020                .map_or(false, |provider| provider.show_completions_in_menu())
 5021    }
 5022
 5023    fn render_code_actions_indicator(
 5024        &self,
 5025        _style: &EditorStyle,
 5026        row: DisplayRow,
 5027        is_active: bool,
 5028        cx: &mut ViewContext<Self>,
 5029    ) -> Option<IconButton> {
 5030        if self.available_code_actions.is_some() {
 5031            Some(
 5032                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5033                    .shape(ui::IconButtonShape::Square)
 5034                    .icon_size(IconSize::XSmall)
 5035                    .icon_color(Color::Muted)
 5036                    .toggle_state(is_active)
 5037                    .tooltip({
 5038                        let focus_handle = self.focus_handle.clone();
 5039                        move |cx| {
 5040                            Tooltip::for_action_in(
 5041                                "Toggle Code Actions",
 5042                                &ToggleCodeActions {
 5043                                    deployed_from_indicator: None,
 5044                                },
 5045                                &focus_handle,
 5046                                cx,
 5047                            )
 5048                        }
 5049                    })
 5050                    .on_click(cx.listener(move |editor, _e, cx| {
 5051                        editor.focus(cx);
 5052                        editor.toggle_code_actions(
 5053                            &ToggleCodeActions {
 5054                                deployed_from_indicator: Some(row),
 5055                            },
 5056                            cx,
 5057                        );
 5058                    })),
 5059            )
 5060        } else {
 5061            None
 5062        }
 5063    }
 5064
 5065    fn clear_tasks(&mut self) {
 5066        self.tasks.clear()
 5067    }
 5068
 5069    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5070        if self.tasks.insert(key, value).is_some() {
 5071            // This case should hopefully be rare, but just in case...
 5072            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5073        }
 5074    }
 5075
 5076    fn build_tasks_context(
 5077        project: &Model<Project>,
 5078        buffer: &Model<Buffer>,
 5079        buffer_row: u32,
 5080        tasks: &Arc<RunnableTasks>,
 5081        cx: &mut ViewContext<Self>,
 5082    ) -> Task<Option<task::TaskContext>> {
 5083        let position = Point::new(buffer_row, tasks.column);
 5084        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5085        let location = Location {
 5086            buffer: buffer.clone(),
 5087            range: range_start..range_start,
 5088        };
 5089        // Fill in the environmental variables from the tree-sitter captures
 5090        let mut captured_task_variables = TaskVariables::default();
 5091        for (capture_name, value) in tasks.extra_variables.clone() {
 5092            captured_task_variables.insert(
 5093                task::VariableName::Custom(capture_name.into()),
 5094                value.clone(),
 5095            );
 5096        }
 5097        project.update(cx, |project, cx| {
 5098            project.task_store().update(cx, |task_store, cx| {
 5099                task_store.task_context_for_location(captured_task_variables, location, cx)
 5100            })
 5101        })
 5102    }
 5103
 5104    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5105        let Some((workspace, _)) = self.workspace.clone() else {
 5106            return;
 5107        };
 5108        let Some(project) = self.project.clone() else {
 5109            return;
 5110        };
 5111
 5112        // Try to find a closest, enclosing node using tree-sitter that has a
 5113        // task
 5114        let Some((buffer, buffer_row, tasks)) = self
 5115            .find_enclosing_node_task(cx)
 5116            // Or find the task that's closest in row-distance.
 5117            .or_else(|| self.find_closest_task(cx))
 5118        else {
 5119            return;
 5120        };
 5121
 5122        let reveal_strategy = action.reveal;
 5123        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5124        cx.spawn(|_, mut cx| async move {
 5125            let context = task_context.await?;
 5126            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5127
 5128            let resolved = resolved_task.resolved.as_mut()?;
 5129            resolved.reveal = reveal_strategy;
 5130
 5131            workspace
 5132                .update(&mut cx, |workspace, cx| {
 5133                    workspace::tasks::schedule_resolved_task(
 5134                        workspace,
 5135                        task_source_kind,
 5136                        resolved_task,
 5137                        false,
 5138                        cx,
 5139                    );
 5140                })
 5141                .ok()
 5142        })
 5143        .detach();
 5144    }
 5145
 5146    fn find_closest_task(
 5147        &mut self,
 5148        cx: &mut ViewContext<Self>,
 5149    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5150        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5151
 5152        let ((buffer_id, row), tasks) = self
 5153            .tasks
 5154            .iter()
 5155            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5156
 5157        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5158        let tasks = Arc::new(tasks.to_owned());
 5159        Some((buffer, *row, tasks))
 5160    }
 5161
 5162    fn find_enclosing_node_task(
 5163        &mut self,
 5164        cx: &mut ViewContext<Self>,
 5165    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5166        let snapshot = self.buffer.read(cx).snapshot(cx);
 5167        let offset = self.selections.newest::<usize>(cx).head();
 5168        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5169        let buffer_id = excerpt.buffer().remote_id();
 5170
 5171        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5172        let mut cursor = layer.node().walk();
 5173
 5174        while cursor.goto_first_child_for_byte(offset).is_some() {
 5175            if cursor.node().end_byte() == offset {
 5176                cursor.goto_next_sibling();
 5177            }
 5178        }
 5179
 5180        // Ascend to the smallest ancestor that contains the range and has a task.
 5181        loop {
 5182            let node = cursor.node();
 5183            let node_range = node.byte_range();
 5184            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5185
 5186            // Check if this node contains our offset
 5187            if node_range.start <= offset && node_range.end >= offset {
 5188                // If it contains offset, check for task
 5189                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5190                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5191                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5192                }
 5193            }
 5194
 5195            if !cursor.goto_parent() {
 5196                break;
 5197            }
 5198        }
 5199        None
 5200    }
 5201
 5202    fn render_run_indicator(
 5203        &self,
 5204        _style: &EditorStyle,
 5205        is_active: bool,
 5206        row: DisplayRow,
 5207        cx: &mut ViewContext<Self>,
 5208    ) -> IconButton {
 5209        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5210            .shape(ui::IconButtonShape::Square)
 5211            .icon_size(IconSize::XSmall)
 5212            .icon_color(Color::Muted)
 5213            .toggle_state(is_active)
 5214            .on_click(cx.listener(move |editor, _e, cx| {
 5215                editor.focus(cx);
 5216                editor.toggle_code_actions(
 5217                    &ToggleCodeActions {
 5218                        deployed_from_indicator: Some(row),
 5219                    },
 5220                    cx,
 5221                );
 5222            }))
 5223    }
 5224
 5225    #[cfg(any(feature = "test-support", test))]
 5226    pub fn context_menu_visible(&self) -> bool {
 5227        self.context_menu
 5228            .borrow()
 5229            .as_ref()
 5230            .map_or(false, |menu| menu.visible())
 5231    }
 5232
 5233    #[cfg(feature = "test-support")]
 5234    pub fn context_menu_contains_inline_completion(&self) -> bool {
 5235        self.context_menu
 5236            .borrow()
 5237            .as_ref()
 5238            .map_or(false, |menu| match menu {
 5239                CodeContextMenu::Completions(menu) => {
 5240                    menu.entries.borrow().first().map_or(false, |entry| {
 5241                        matches!(entry, CompletionEntry::InlineCompletionHint(_))
 5242                    })
 5243                }
 5244                CodeContextMenu::CodeActions(_) => false,
 5245            })
 5246    }
 5247
 5248    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5249        self.context_menu
 5250            .borrow()
 5251            .as_ref()
 5252            .map(|menu| menu.origin(cursor_position))
 5253    }
 5254
 5255    fn render_context_menu(
 5256        &self,
 5257        style: &EditorStyle,
 5258        max_height_in_lines: u32,
 5259        y_flipped: bool,
 5260        cx: &mut ViewContext<Editor>,
 5261    ) -> Option<AnyElement> {
 5262        self.context_menu.borrow().as_ref().and_then(|menu| {
 5263            if menu.visible() {
 5264                Some(menu.render(style, max_height_in_lines, y_flipped, cx))
 5265            } else {
 5266                None
 5267            }
 5268        })
 5269    }
 5270
 5271    fn render_context_menu_aside(
 5272        &self,
 5273        style: &EditorStyle,
 5274        max_size: Size<Pixels>,
 5275        cx: &mut ViewContext<Editor>,
 5276    ) -> Option<AnyElement> {
 5277        self.context_menu.borrow().as_ref().and_then(|menu| {
 5278            if menu.visible() {
 5279                menu.render_aside(
 5280                    style,
 5281                    max_size,
 5282                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5283                    cx,
 5284                )
 5285            } else {
 5286                None
 5287            }
 5288        })
 5289    }
 5290
 5291    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
 5292        cx.notify();
 5293        self.completion_tasks.clear();
 5294        let context_menu = self.context_menu.borrow_mut().take();
 5295        if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
 5296            self.update_visible_inline_completion(cx);
 5297        }
 5298        context_menu
 5299    }
 5300
 5301    fn show_snippet_choices(
 5302        &mut self,
 5303        choices: &Vec<String>,
 5304        selection: Range<Anchor>,
 5305        cx: &mut ViewContext<Self>,
 5306    ) {
 5307        if selection.start.buffer_id.is_none() {
 5308            return;
 5309        }
 5310        let buffer_id = selection.start.buffer_id.unwrap();
 5311        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5312        let id = post_inc(&mut self.next_completion_id);
 5313
 5314        if let Some(buffer) = buffer {
 5315            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5316                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5317            ));
 5318        }
 5319    }
 5320
 5321    pub fn insert_snippet(
 5322        &mut self,
 5323        insertion_ranges: &[Range<usize>],
 5324        snippet: Snippet,
 5325        cx: &mut ViewContext<Self>,
 5326    ) -> Result<()> {
 5327        struct Tabstop<T> {
 5328            is_end_tabstop: bool,
 5329            ranges: Vec<Range<T>>,
 5330            choices: Option<Vec<String>>,
 5331        }
 5332
 5333        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5334            let snippet_text: Arc<str> = snippet.text.clone().into();
 5335            buffer.edit(
 5336                insertion_ranges
 5337                    .iter()
 5338                    .cloned()
 5339                    .map(|range| (range, snippet_text.clone())),
 5340                Some(AutoindentMode::EachLine),
 5341                cx,
 5342            );
 5343
 5344            let snapshot = &*buffer.read(cx);
 5345            let snippet = &snippet;
 5346            snippet
 5347                .tabstops
 5348                .iter()
 5349                .map(|tabstop| {
 5350                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5351                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5352                    });
 5353                    let mut tabstop_ranges = tabstop
 5354                        .ranges
 5355                        .iter()
 5356                        .flat_map(|tabstop_range| {
 5357                            let mut delta = 0_isize;
 5358                            insertion_ranges.iter().map(move |insertion_range| {
 5359                                let insertion_start = insertion_range.start as isize + delta;
 5360                                delta +=
 5361                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5362
 5363                                let start = ((insertion_start + tabstop_range.start) as usize)
 5364                                    .min(snapshot.len());
 5365                                let end = ((insertion_start + tabstop_range.end) as usize)
 5366                                    .min(snapshot.len());
 5367                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5368                            })
 5369                        })
 5370                        .collect::<Vec<_>>();
 5371                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5372
 5373                    Tabstop {
 5374                        is_end_tabstop,
 5375                        ranges: tabstop_ranges,
 5376                        choices: tabstop.choices.clone(),
 5377                    }
 5378                })
 5379                .collect::<Vec<_>>()
 5380        });
 5381        if let Some(tabstop) = tabstops.first() {
 5382            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5383                s.select_ranges(tabstop.ranges.iter().cloned());
 5384            });
 5385
 5386            if let Some(choices) = &tabstop.choices {
 5387                if let Some(selection) = tabstop.ranges.first() {
 5388                    self.show_snippet_choices(choices, selection.clone(), cx)
 5389                }
 5390            }
 5391
 5392            // If we're already at the last tabstop and it's at the end of the snippet,
 5393            // we're done, we don't need to keep the state around.
 5394            if !tabstop.is_end_tabstop {
 5395                let choices = tabstops
 5396                    .iter()
 5397                    .map(|tabstop| tabstop.choices.clone())
 5398                    .collect();
 5399
 5400                let ranges = tabstops
 5401                    .into_iter()
 5402                    .map(|tabstop| tabstop.ranges)
 5403                    .collect::<Vec<_>>();
 5404
 5405                self.snippet_stack.push(SnippetState {
 5406                    active_index: 0,
 5407                    ranges,
 5408                    choices,
 5409                });
 5410            }
 5411
 5412            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5413            if self.autoclose_regions.is_empty() {
 5414                let snapshot = self.buffer.read(cx).snapshot(cx);
 5415                for selection in &mut self.selections.all::<Point>(cx) {
 5416                    let selection_head = selection.head();
 5417                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5418                        continue;
 5419                    };
 5420
 5421                    let mut bracket_pair = None;
 5422                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5423                    let prev_chars = snapshot
 5424                        .reversed_chars_at(selection_head)
 5425                        .collect::<String>();
 5426                    for (pair, enabled) in scope.brackets() {
 5427                        if enabled
 5428                            && pair.close
 5429                            && prev_chars.starts_with(pair.start.as_str())
 5430                            && next_chars.starts_with(pair.end.as_str())
 5431                        {
 5432                            bracket_pair = Some(pair.clone());
 5433                            break;
 5434                        }
 5435                    }
 5436                    if let Some(pair) = bracket_pair {
 5437                        let start = snapshot.anchor_after(selection_head);
 5438                        let end = snapshot.anchor_after(selection_head);
 5439                        self.autoclose_regions.push(AutocloseRegion {
 5440                            selection_id: selection.id,
 5441                            range: start..end,
 5442                            pair,
 5443                        });
 5444                    }
 5445                }
 5446            }
 5447        }
 5448        Ok(())
 5449    }
 5450
 5451    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5452        self.move_to_snippet_tabstop(Bias::Right, cx)
 5453    }
 5454
 5455    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5456        self.move_to_snippet_tabstop(Bias::Left, cx)
 5457    }
 5458
 5459    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5460        if let Some(mut snippet) = self.snippet_stack.pop() {
 5461            match bias {
 5462                Bias::Left => {
 5463                    if snippet.active_index > 0 {
 5464                        snippet.active_index -= 1;
 5465                    } else {
 5466                        self.snippet_stack.push(snippet);
 5467                        return false;
 5468                    }
 5469                }
 5470                Bias::Right => {
 5471                    if snippet.active_index + 1 < snippet.ranges.len() {
 5472                        snippet.active_index += 1;
 5473                    } else {
 5474                        self.snippet_stack.push(snippet);
 5475                        return false;
 5476                    }
 5477                }
 5478            }
 5479            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5480                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5481                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5482                });
 5483
 5484                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5485                    if let Some(selection) = current_ranges.first() {
 5486                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5487                    }
 5488                }
 5489
 5490                // If snippet state is not at the last tabstop, push it back on the stack
 5491                if snippet.active_index + 1 < snippet.ranges.len() {
 5492                    self.snippet_stack.push(snippet);
 5493                }
 5494                return true;
 5495            }
 5496        }
 5497
 5498        false
 5499    }
 5500
 5501    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5502        self.transact(cx, |this, cx| {
 5503            this.select_all(&SelectAll, cx);
 5504            this.insert("", cx);
 5505        });
 5506    }
 5507
 5508    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5509        self.transact(cx, |this, cx| {
 5510            this.select_autoclose_pair(cx);
 5511            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5512            if !this.linked_edit_ranges.is_empty() {
 5513                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5514                let snapshot = this.buffer.read(cx).snapshot(cx);
 5515
 5516                for selection in selections.iter() {
 5517                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5518                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5519                    if selection_start.buffer_id != selection_end.buffer_id {
 5520                        continue;
 5521                    }
 5522                    if let Some(ranges) =
 5523                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5524                    {
 5525                        for (buffer, entries) in ranges {
 5526                            linked_ranges.entry(buffer).or_default().extend(entries);
 5527                        }
 5528                    }
 5529                }
 5530            }
 5531
 5532            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5533            if !this.selections.line_mode {
 5534                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5535                for selection in &mut selections {
 5536                    if selection.is_empty() {
 5537                        let old_head = selection.head();
 5538                        let mut new_head =
 5539                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5540                                .to_point(&display_map);
 5541                        if let Some((buffer, line_buffer_range)) = display_map
 5542                            .buffer_snapshot
 5543                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5544                        {
 5545                            let indent_size =
 5546                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5547                            let indent_len = match indent_size.kind {
 5548                                IndentKind::Space => {
 5549                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5550                                }
 5551                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5552                            };
 5553                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5554                                let indent_len = indent_len.get();
 5555                                new_head = cmp::min(
 5556                                    new_head,
 5557                                    MultiBufferPoint::new(
 5558                                        old_head.row,
 5559                                        ((old_head.column - 1) / indent_len) * indent_len,
 5560                                    ),
 5561                                );
 5562                            }
 5563                        }
 5564
 5565                        selection.set_head(new_head, SelectionGoal::None);
 5566                    }
 5567                }
 5568            }
 5569
 5570            this.signature_help_state.set_backspace_pressed(true);
 5571            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5572            this.insert("", cx);
 5573            let empty_str: Arc<str> = Arc::from("");
 5574            for (buffer, edits) in linked_ranges {
 5575                let snapshot = buffer.read(cx).snapshot();
 5576                use text::ToPoint as TP;
 5577
 5578                let edits = edits
 5579                    .into_iter()
 5580                    .map(|range| {
 5581                        let end_point = TP::to_point(&range.end, &snapshot);
 5582                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5583
 5584                        if end_point == start_point {
 5585                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5586                                .saturating_sub(1);
 5587                            start_point =
 5588                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5589                        };
 5590
 5591                        (start_point..end_point, empty_str.clone())
 5592                    })
 5593                    .sorted_by_key(|(range, _)| range.start)
 5594                    .collect::<Vec<_>>();
 5595                buffer.update(cx, |this, cx| {
 5596                    this.edit(edits, None, cx);
 5597                })
 5598            }
 5599            this.refresh_inline_completion(true, false, cx);
 5600            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5601        });
 5602    }
 5603
 5604    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5605        self.transact(cx, |this, cx| {
 5606            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5607                let line_mode = s.line_mode;
 5608                s.move_with(|map, selection| {
 5609                    if selection.is_empty() && !line_mode {
 5610                        let cursor = movement::right(map, selection.head());
 5611                        selection.end = cursor;
 5612                        selection.reversed = true;
 5613                        selection.goal = SelectionGoal::None;
 5614                    }
 5615                })
 5616            });
 5617            this.insert("", cx);
 5618            this.refresh_inline_completion(true, false, cx);
 5619        });
 5620    }
 5621
 5622    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5623        if self.move_to_prev_snippet_tabstop(cx) {
 5624            return;
 5625        }
 5626
 5627        self.outdent(&Outdent, cx);
 5628    }
 5629
 5630    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5631        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5632            return;
 5633        }
 5634
 5635        let mut selections = self.selections.all_adjusted(cx);
 5636        let buffer = self.buffer.read(cx);
 5637        let snapshot = buffer.snapshot(cx);
 5638        let rows_iter = selections.iter().map(|s| s.head().row);
 5639        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5640
 5641        let mut edits = Vec::new();
 5642        let mut prev_edited_row = 0;
 5643        let mut row_delta = 0;
 5644        for selection in &mut selections {
 5645            if selection.start.row != prev_edited_row {
 5646                row_delta = 0;
 5647            }
 5648            prev_edited_row = selection.end.row;
 5649
 5650            // If the selection is non-empty, then increase the indentation of the selected lines.
 5651            if !selection.is_empty() {
 5652                row_delta =
 5653                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5654                continue;
 5655            }
 5656
 5657            // If the selection is empty and the cursor is in the leading whitespace before the
 5658            // suggested indentation, then auto-indent the line.
 5659            let cursor = selection.head();
 5660            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5661            if let Some(suggested_indent) =
 5662                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5663            {
 5664                if cursor.column < suggested_indent.len
 5665                    && cursor.column <= current_indent.len
 5666                    && current_indent.len <= suggested_indent.len
 5667                {
 5668                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5669                    selection.end = selection.start;
 5670                    if row_delta == 0 {
 5671                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5672                            cursor.row,
 5673                            current_indent,
 5674                            suggested_indent,
 5675                        ));
 5676                        row_delta = suggested_indent.len - current_indent.len;
 5677                    }
 5678                    continue;
 5679                }
 5680            }
 5681
 5682            // Otherwise, insert a hard or soft tab.
 5683            let settings = buffer.settings_at(cursor, cx);
 5684            let tab_size = if settings.hard_tabs {
 5685                IndentSize::tab()
 5686            } else {
 5687                let tab_size = settings.tab_size.get();
 5688                let char_column = snapshot
 5689                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5690                    .flat_map(str::chars)
 5691                    .count()
 5692                    + row_delta as usize;
 5693                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5694                IndentSize::spaces(chars_to_next_tab_stop)
 5695            };
 5696            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5697            selection.end = selection.start;
 5698            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5699            row_delta += tab_size.len;
 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            this.refresh_inline_completion(true, false, cx);
 5706        });
 5707    }
 5708
 5709    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5710        if self.read_only(cx) {
 5711            return;
 5712        }
 5713        let mut selections = self.selections.all::<Point>(cx);
 5714        let mut prev_edited_row = 0;
 5715        let mut row_delta = 0;
 5716        let mut edits = Vec::new();
 5717        let buffer = self.buffer.read(cx);
 5718        let snapshot = buffer.snapshot(cx);
 5719        for selection in &mut selections {
 5720            if selection.start.row != prev_edited_row {
 5721                row_delta = 0;
 5722            }
 5723            prev_edited_row = selection.end.row;
 5724
 5725            row_delta =
 5726                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5727        }
 5728
 5729        self.transact(cx, |this, cx| {
 5730            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5731            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5732        });
 5733    }
 5734
 5735    fn indent_selection(
 5736        buffer: &MultiBuffer,
 5737        snapshot: &MultiBufferSnapshot,
 5738        selection: &mut Selection<Point>,
 5739        edits: &mut Vec<(Range<Point>, String)>,
 5740        delta_for_start_row: u32,
 5741        cx: &AppContext,
 5742    ) -> u32 {
 5743        let settings = buffer.settings_at(selection.start, cx);
 5744        let tab_size = settings.tab_size.get();
 5745        let indent_kind = if settings.hard_tabs {
 5746            IndentKind::Tab
 5747        } else {
 5748            IndentKind::Space
 5749        };
 5750        let mut start_row = selection.start.row;
 5751        let mut end_row = selection.end.row + 1;
 5752
 5753        // If a selection ends at the beginning of a line, don't indent
 5754        // that last line.
 5755        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5756            end_row -= 1;
 5757        }
 5758
 5759        // Avoid re-indenting a row that has already been indented by a
 5760        // previous selection, but still update this selection's column
 5761        // to reflect that indentation.
 5762        if delta_for_start_row > 0 {
 5763            start_row += 1;
 5764            selection.start.column += delta_for_start_row;
 5765            if selection.end.row == selection.start.row {
 5766                selection.end.column += delta_for_start_row;
 5767            }
 5768        }
 5769
 5770        let mut delta_for_end_row = 0;
 5771        let has_multiple_rows = start_row + 1 != end_row;
 5772        for row in start_row..end_row {
 5773            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5774            let indent_delta = match (current_indent.kind, indent_kind) {
 5775                (IndentKind::Space, IndentKind::Space) => {
 5776                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5777                    IndentSize::spaces(columns_to_next_tab_stop)
 5778                }
 5779                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5780                (_, IndentKind::Tab) => IndentSize::tab(),
 5781            };
 5782
 5783            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5784                0
 5785            } else {
 5786                selection.start.column
 5787            };
 5788            let row_start = Point::new(row, start);
 5789            edits.push((
 5790                row_start..row_start,
 5791                indent_delta.chars().collect::<String>(),
 5792            ));
 5793
 5794            // Update this selection's endpoints to reflect the indentation.
 5795            if row == selection.start.row {
 5796                selection.start.column += indent_delta.len;
 5797            }
 5798            if row == selection.end.row {
 5799                selection.end.column += indent_delta.len;
 5800                delta_for_end_row = indent_delta.len;
 5801            }
 5802        }
 5803
 5804        if selection.start.row == selection.end.row {
 5805            delta_for_start_row + delta_for_end_row
 5806        } else {
 5807            delta_for_end_row
 5808        }
 5809    }
 5810
 5811    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5812        if self.read_only(cx) {
 5813            return;
 5814        }
 5815        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5816        let selections = self.selections.all::<Point>(cx);
 5817        let mut deletion_ranges = Vec::new();
 5818        let mut last_outdent = None;
 5819        {
 5820            let buffer = self.buffer.read(cx);
 5821            let snapshot = buffer.snapshot(cx);
 5822            for selection in &selections {
 5823                let settings = buffer.settings_at(selection.start, cx);
 5824                let tab_size = settings.tab_size.get();
 5825                let mut rows = selection.spanned_rows(false, &display_map);
 5826
 5827                // Avoid re-outdenting a row that has already been outdented by a
 5828                // previous selection.
 5829                if let Some(last_row) = last_outdent {
 5830                    if last_row == rows.start {
 5831                        rows.start = rows.start.next_row();
 5832                    }
 5833                }
 5834                let has_multiple_rows = rows.len() > 1;
 5835                for row in rows.iter_rows() {
 5836                    let indent_size = snapshot.indent_size_for_line(row);
 5837                    if indent_size.len > 0 {
 5838                        let deletion_len = match indent_size.kind {
 5839                            IndentKind::Space => {
 5840                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5841                                if columns_to_prev_tab_stop == 0 {
 5842                                    tab_size
 5843                                } else {
 5844                                    columns_to_prev_tab_stop
 5845                                }
 5846                            }
 5847                            IndentKind::Tab => 1,
 5848                        };
 5849                        let start = if has_multiple_rows
 5850                            || deletion_len > selection.start.column
 5851                            || indent_size.len < selection.start.column
 5852                        {
 5853                            0
 5854                        } else {
 5855                            selection.start.column - deletion_len
 5856                        };
 5857                        deletion_ranges.push(
 5858                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5859                        );
 5860                        last_outdent = Some(row);
 5861                    }
 5862                }
 5863            }
 5864        }
 5865
 5866        self.transact(cx, |this, cx| {
 5867            this.buffer.update(cx, |buffer, cx| {
 5868                let empty_str: Arc<str> = Arc::default();
 5869                buffer.edit(
 5870                    deletion_ranges
 5871                        .into_iter()
 5872                        .map(|range| (range, empty_str.clone())),
 5873                    None,
 5874                    cx,
 5875                );
 5876            });
 5877            let selections = this.selections.all::<usize>(cx);
 5878            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5879        });
 5880    }
 5881
 5882    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 5883        if self.read_only(cx) {
 5884            return;
 5885        }
 5886        let selections = self
 5887            .selections
 5888            .all::<usize>(cx)
 5889            .into_iter()
 5890            .map(|s| s.range());
 5891
 5892        self.transact(cx, |this, cx| {
 5893            this.buffer.update(cx, |buffer, cx| {
 5894                buffer.autoindent_ranges(selections, cx);
 5895            });
 5896            let selections = this.selections.all::<usize>(cx);
 5897            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5898        });
 5899    }
 5900
 5901    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5902        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5903        let selections = self.selections.all::<Point>(cx);
 5904
 5905        let mut new_cursors = Vec::new();
 5906        let mut edit_ranges = Vec::new();
 5907        let mut selections = selections.iter().peekable();
 5908        while let Some(selection) = selections.next() {
 5909            let mut rows = selection.spanned_rows(false, &display_map);
 5910            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5911
 5912            // Accumulate contiguous regions of rows that we want to delete.
 5913            while let Some(next_selection) = selections.peek() {
 5914                let next_rows = next_selection.spanned_rows(false, &display_map);
 5915                if next_rows.start <= rows.end {
 5916                    rows.end = next_rows.end;
 5917                    selections.next().unwrap();
 5918                } else {
 5919                    break;
 5920                }
 5921            }
 5922
 5923            let buffer = &display_map.buffer_snapshot;
 5924            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5925            let edit_end;
 5926            let cursor_buffer_row;
 5927            if buffer.max_point().row >= rows.end.0 {
 5928                // If there's a line after the range, delete the \n from the end of the row range
 5929                // and position the cursor on the next line.
 5930                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5931                cursor_buffer_row = rows.end;
 5932            } else {
 5933                // If there isn't a line after the range, delete the \n from the line before the
 5934                // start of the row range and position the cursor there.
 5935                edit_start = edit_start.saturating_sub(1);
 5936                edit_end = buffer.len();
 5937                cursor_buffer_row = rows.start.previous_row();
 5938            }
 5939
 5940            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5941            *cursor.column_mut() =
 5942                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5943
 5944            new_cursors.push((
 5945                selection.id,
 5946                buffer.anchor_after(cursor.to_point(&display_map)),
 5947            ));
 5948            edit_ranges.push(edit_start..edit_end);
 5949        }
 5950
 5951        self.transact(cx, |this, cx| {
 5952            let buffer = this.buffer.update(cx, |buffer, cx| {
 5953                let empty_str: Arc<str> = Arc::default();
 5954                buffer.edit(
 5955                    edit_ranges
 5956                        .into_iter()
 5957                        .map(|range| (range, empty_str.clone())),
 5958                    None,
 5959                    cx,
 5960                );
 5961                buffer.snapshot(cx)
 5962            });
 5963            let new_selections = new_cursors
 5964                .into_iter()
 5965                .map(|(id, cursor)| {
 5966                    let cursor = cursor.to_point(&buffer);
 5967                    Selection {
 5968                        id,
 5969                        start: cursor,
 5970                        end: cursor,
 5971                        reversed: false,
 5972                        goal: SelectionGoal::None,
 5973                    }
 5974                })
 5975                .collect();
 5976
 5977            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5978                s.select(new_selections);
 5979            });
 5980        });
 5981    }
 5982
 5983    pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
 5984        if self.read_only(cx) {
 5985            return;
 5986        }
 5987        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5988        for selection in self.selections.all::<Point>(cx) {
 5989            let start = MultiBufferRow(selection.start.row);
 5990            // Treat single line selections as if they include the next line. Otherwise this action
 5991            // would do nothing for single line selections individual cursors.
 5992            let end = if selection.start.row == selection.end.row {
 5993                MultiBufferRow(selection.start.row + 1)
 5994            } else {
 5995                MultiBufferRow(selection.end.row)
 5996            };
 5997
 5998            if let Some(last_row_range) = row_ranges.last_mut() {
 5999                if start <= last_row_range.end {
 6000                    last_row_range.end = end;
 6001                    continue;
 6002                }
 6003            }
 6004            row_ranges.push(start..end);
 6005        }
 6006
 6007        let snapshot = self.buffer.read(cx).snapshot(cx);
 6008        let mut cursor_positions = Vec::new();
 6009        for row_range in &row_ranges {
 6010            let anchor = snapshot.anchor_before(Point::new(
 6011                row_range.end.previous_row().0,
 6012                snapshot.line_len(row_range.end.previous_row()),
 6013            ));
 6014            cursor_positions.push(anchor..anchor);
 6015        }
 6016
 6017        self.transact(cx, |this, cx| {
 6018            for row_range in row_ranges.into_iter().rev() {
 6019                for row in row_range.iter_rows().rev() {
 6020                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6021                    let next_line_row = row.next_row();
 6022                    let indent = snapshot.indent_size_for_line(next_line_row);
 6023                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6024
 6025                    let replace =
 6026                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6027                            " "
 6028                        } else {
 6029                            ""
 6030                        };
 6031
 6032                    this.buffer.update(cx, |buffer, cx| {
 6033                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6034                    });
 6035                }
 6036            }
 6037
 6038            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6039                s.select_anchor_ranges(cursor_positions)
 6040            });
 6041        });
 6042    }
 6043
 6044    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6045        self.join_lines_impl(true, cx);
 6046    }
 6047
 6048    pub fn sort_lines_case_sensitive(
 6049        &mut self,
 6050        _: &SortLinesCaseSensitive,
 6051        cx: &mut ViewContext<Self>,
 6052    ) {
 6053        self.manipulate_lines(cx, |lines| lines.sort())
 6054    }
 6055
 6056    pub fn sort_lines_case_insensitive(
 6057        &mut self,
 6058        _: &SortLinesCaseInsensitive,
 6059        cx: &mut ViewContext<Self>,
 6060    ) {
 6061        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6062    }
 6063
 6064    pub fn unique_lines_case_insensitive(
 6065        &mut self,
 6066        _: &UniqueLinesCaseInsensitive,
 6067        cx: &mut ViewContext<Self>,
 6068    ) {
 6069        self.manipulate_lines(cx, |lines| {
 6070            let mut seen = HashSet::default();
 6071            lines.retain(|line| seen.insert(line.to_lowercase()));
 6072        })
 6073    }
 6074
 6075    pub fn unique_lines_case_sensitive(
 6076        &mut self,
 6077        _: &UniqueLinesCaseSensitive,
 6078        cx: &mut ViewContext<Self>,
 6079    ) {
 6080        self.manipulate_lines(cx, |lines| {
 6081            let mut seen = HashSet::default();
 6082            lines.retain(|line| seen.insert(*line));
 6083        })
 6084    }
 6085
 6086    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6087        let mut revert_changes = HashMap::default();
 6088        let snapshot = self.snapshot(cx);
 6089        for hunk in hunks_for_ranges(
 6090            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 6091            &snapshot,
 6092        ) {
 6093            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6094        }
 6095        if !revert_changes.is_empty() {
 6096            self.transact(cx, |editor, cx| {
 6097                editor.revert(revert_changes, cx);
 6098            });
 6099        }
 6100    }
 6101
 6102    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6103        let Some(project) = self.project.clone() else {
 6104            return;
 6105        };
 6106        self.reload(project, cx).detach_and_notify_err(cx);
 6107    }
 6108
 6109    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6110        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 6111        if !revert_changes.is_empty() {
 6112            self.transact(cx, |editor, cx| {
 6113                editor.revert(revert_changes, cx);
 6114            });
 6115        }
 6116    }
 6117
 6118    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 6119        let snapshot = self.buffer.read(cx).read(cx);
 6120        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 6121            drop(snapshot);
 6122            let mut revert_changes = HashMap::default();
 6123            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6124            if !revert_changes.is_empty() {
 6125                self.revert(revert_changes, cx)
 6126            }
 6127        }
 6128    }
 6129
 6130    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6131        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6132            let project_path = buffer.read(cx).project_path(cx)?;
 6133            let project = self.project.as_ref()?.read(cx);
 6134            let entry = project.entry_for_path(&project_path, cx)?;
 6135            let parent = match &entry.canonical_path {
 6136                Some(canonical_path) => canonical_path.to_path_buf(),
 6137                None => project.absolute_path(&project_path, cx)?,
 6138            }
 6139            .parent()?
 6140            .to_path_buf();
 6141            Some(parent)
 6142        }) {
 6143            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6144        }
 6145    }
 6146
 6147    fn gather_revert_changes(
 6148        &mut self,
 6149        selections: &[Selection<Point>],
 6150        cx: &mut ViewContext<Editor>,
 6151    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6152        let mut revert_changes = HashMap::default();
 6153        let snapshot = self.snapshot(cx);
 6154        for hunk in hunks_for_selections(&snapshot, selections) {
 6155            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6156        }
 6157        revert_changes
 6158    }
 6159
 6160    pub fn prepare_revert_change(
 6161        &mut self,
 6162        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6163        hunk: &MultiBufferDiffHunk,
 6164        cx: &AppContext,
 6165    ) -> Option<()> {
 6166        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 6167        let buffer = buffer.read(cx);
 6168        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 6169        let original_text = change_set
 6170            .read(cx)
 6171            .base_text
 6172            .as_ref()?
 6173            .read(cx)
 6174            .as_rope()
 6175            .slice(hunk.diff_base_byte_range.clone());
 6176        let buffer_snapshot = buffer.snapshot();
 6177        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6178        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6179            probe
 6180                .0
 6181                .start
 6182                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6183                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6184        }) {
 6185            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6186            Some(())
 6187        } else {
 6188            None
 6189        }
 6190    }
 6191
 6192    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6193        self.manipulate_lines(cx, |lines| lines.reverse())
 6194    }
 6195
 6196    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6197        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6198    }
 6199
 6200    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6201    where
 6202        Fn: FnMut(&mut Vec<&str>),
 6203    {
 6204        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6205        let buffer = self.buffer.read(cx).snapshot(cx);
 6206
 6207        let mut edits = Vec::new();
 6208
 6209        let selections = self.selections.all::<Point>(cx);
 6210        let mut selections = selections.iter().peekable();
 6211        let mut contiguous_row_selections = Vec::new();
 6212        let mut new_selections = Vec::new();
 6213        let mut added_lines = 0;
 6214        let mut removed_lines = 0;
 6215
 6216        while let Some(selection) = selections.next() {
 6217            let (start_row, end_row) = consume_contiguous_rows(
 6218                &mut contiguous_row_selections,
 6219                selection,
 6220                &display_map,
 6221                &mut selections,
 6222            );
 6223
 6224            let start_point = Point::new(start_row.0, 0);
 6225            let end_point = Point::new(
 6226                end_row.previous_row().0,
 6227                buffer.line_len(end_row.previous_row()),
 6228            );
 6229            let text = buffer
 6230                .text_for_range(start_point..end_point)
 6231                .collect::<String>();
 6232
 6233            let mut lines = text.split('\n').collect_vec();
 6234
 6235            let lines_before = lines.len();
 6236            callback(&mut lines);
 6237            let lines_after = lines.len();
 6238
 6239            edits.push((start_point..end_point, lines.join("\n")));
 6240
 6241            // Selections must change based on added and removed line count
 6242            let start_row =
 6243                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6244            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6245            new_selections.push(Selection {
 6246                id: selection.id,
 6247                start: start_row,
 6248                end: end_row,
 6249                goal: SelectionGoal::None,
 6250                reversed: selection.reversed,
 6251            });
 6252
 6253            if lines_after > lines_before {
 6254                added_lines += lines_after - lines_before;
 6255            } else if lines_before > lines_after {
 6256                removed_lines += lines_before - lines_after;
 6257            }
 6258        }
 6259
 6260        self.transact(cx, |this, cx| {
 6261            let buffer = this.buffer.update(cx, |buffer, cx| {
 6262                buffer.edit(edits, None, cx);
 6263                buffer.snapshot(cx)
 6264            });
 6265
 6266            // Recalculate offsets on newly edited buffer
 6267            let new_selections = new_selections
 6268                .iter()
 6269                .map(|s| {
 6270                    let start_point = Point::new(s.start.0, 0);
 6271                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6272                    Selection {
 6273                        id: s.id,
 6274                        start: buffer.point_to_offset(start_point),
 6275                        end: buffer.point_to_offset(end_point),
 6276                        goal: s.goal,
 6277                        reversed: s.reversed,
 6278                    }
 6279                })
 6280                .collect();
 6281
 6282            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6283                s.select(new_selections);
 6284            });
 6285
 6286            this.request_autoscroll(Autoscroll::fit(), cx);
 6287        });
 6288    }
 6289
 6290    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6291        self.manipulate_text(cx, |text| text.to_uppercase())
 6292    }
 6293
 6294    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6295        self.manipulate_text(cx, |text| text.to_lowercase())
 6296    }
 6297
 6298    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6299        self.manipulate_text(cx, |text| {
 6300            text.split('\n')
 6301                .map(|line| line.to_case(Case::Title))
 6302                .join("\n")
 6303        })
 6304    }
 6305
 6306    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6307        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6308    }
 6309
 6310    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6311        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6312    }
 6313
 6314    pub fn convert_to_upper_camel_case(
 6315        &mut self,
 6316        _: &ConvertToUpperCamelCase,
 6317        cx: &mut ViewContext<Self>,
 6318    ) {
 6319        self.manipulate_text(cx, |text| {
 6320            text.split('\n')
 6321                .map(|line| line.to_case(Case::UpperCamel))
 6322                .join("\n")
 6323        })
 6324    }
 6325
 6326    pub fn convert_to_lower_camel_case(
 6327        &mut self,
 6328        _: &ConvertToLowerCamelCase,
 6329        cx: &mut ViewContext<Self>,
 6330    ) {
 6331        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6332    }
 6333
 6334    pub fn convert_to_opposite_case(
 6335        &mut self,
 6336        _: &ConvertToOppositeCase,
 6337        cx: &mut ViewContext<Self>,
 6338    ) {
 6339        self.manipulate_text(cx, |text| {
 6340            text.chars()
 6341                .fold(String::with_capacity(text.len()), |mut t, c| {
 6342                    if c.is_uppercase() {
 6343                        t.extend(c.to_lowercase());
 6344                    } else {
 6345                        t.extend(c.to_uppercase());
 6346                    }
 6347                    t
 6348                })
 6349        })
 6350    }
 6351
 6352    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6353    where
 6354        Fn: FnMut(&str) -> String,
 6355    {
 6356        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6357        let buffer = self.buffer.read(cx).snapshot(cx);
 6358
 6359        let mut new_selections = Vec::new();
 6360        let mut edits = Vec::new();
 6361        let mut selection_adjustment = 0i32;
 6362
 6363        for selection in self.selections.all::<usize>(cx) {
 6364            let selection_is_empty = selection.is_empty();
 6365
 6366            let (start, end) = if selection_is_empty {
 6367                let word_range = movement::surrounding_word(
 6368                    &display_map,
 6369                    selection.start.to_display_point(&display_map),
 6370                );
 6371                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6372                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6373                (start, end)
 6374            } else {
 6375                (selection.start, selection.end)
 6376            };
 6377
 6378            let text = buffer.text_for_range(start..end).collect::<String>();
 6379            let old_length = text.len() as i32;
 6380            let text = callback(&text);
 6381
 6382            new_selections.push(Selection {
 6383                start: (start as i32 - selection_adjustment) as usize,
 6384                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6385                goal: SelectionGoal::None,
 6386                ..selection
 6387            });
 6388
 6389            selection_adjustment += old_length - text.len() as i32;
 6390
 6391            edits.push((start..end, text));
 6392        }
 6393
 6394        self.transact(cx, |this, cx| {
 6395            this.buffer.update(cx, |buffer, cx| {
 6396                buffer.edit(edits, None, cx);
 6397            });
 6398
 6399            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6400                s.select(new_selections);
 6401            });
 6402
 6403            this.request_autoscroll(Autoscroll::fit(), cx);
 6404        });
 6405    }
 6406
 6407    pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
 6408        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6409        let buffer = &display_map.buffer_snapshot;
 6410        let selections = self.selections.all::<Point>(cx);
 6411
 6412        let mut edits = Vec::new();
 6413        let mut selections_iter = selections.iter().peekable();
 6414        while let Some(selection) = selections_iter.next() {
 6415            let mut rows = selection.spanned_rows(false, &display_map);
 6416            // duplicate line-wise
 6417            if whole_lines || selection.start == selection.end {
 6418                // Avoid duplicating the same lines twice.
 6419                while let Some(next_selection) = selections_iter.peek() {
 6420                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6421                    if next_rows.start < rows.end {
 6422                        rows.end = next_rows.end;
 6423                        selections_iter.next().unwrap();
 6424                    } else {
 6425                        break;
 6426                    }
 6427                }
 6428
 6429                // Copy the text from the selected row region and splice it either at the start
 6430                // or end of the region.
 6431                let start = Point::new(rows.start.0, 0);
 6432                let end = Point::new(
 6433                    rows.end.previous_row().0,
 6434                    buffer.line_len(rows.end.previous_row()),
 6435                );
 6436                let text = buffer
 6437                    .text_for_range(start..end)
 6438                    .chain(Some("\n"))
 6439                    .collect::<String>();
 6440                let insert_location = if upwards {
 6441                    Point::new(rows.end.0, 0)
 6442                } else {
 6443                    start
 6444                };
 6445                edits.push((insert_location..insert_location, text));
 6446            } else {
 6447                // duplicate character-wise
 6448                let start = selection.start;
 6449                let end = selection.end;
 6450                let text = buffer.text_for_range(start..end).collect::<String>();
 6451                edits.push((selection.end..selection.end, text));
 6452            }
 6453        }
 6454
 6455        self.transact(cx, |this, cx| {
 6456            this.buffer.update(cx, |buffer, cx| {
 6457                buffer.edit(edits, None, cx);
 6458            });
 6459
 6460            this.request_autoscroll(Autoscroll::fit(), cx);
 6461        });
 6462    }
 6463
 6464    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6465        self.duplicate(true, true, cx);
 6466    }
 6467
 6468    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6469        self.duplicate(false, true, cx);
 6470    }
 6471
 6472    pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
 6473        self.duplicate(false, false, cx);
 6474    }
 6475
 6476    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6477        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6478        let buffer = self.buffer.read(cx).snapshot(cx);
 6479
 6480        let mut edits = Vec::new();
 6481        let mut unfold_ranges = Vec::new();
 6482        let mut refold_creases = Vec::new();
 6483
 6484        let selections = self.selections.all::<Point>(cx);
 6485        let mut selections = selections.iter().peekable();
 6486        let mut contiguous_row_selections = Vec::new();
 6487        let mut new_selections = Vec::new();
 6488
 6489        while let Some(selection) = selections.next() {
 6490            // Find all the selections that span a contiguous row range
 6491            let (start_row, end_row) = consume_contiguous_rows(
 6492                &mut contiguous_row_selections,
 6493                selection,
 6494                &display_map,
 6495                &mut selections,
 6496            );
 6497
 6498            // Move the text spanned by the row range to be before the line preceding the row range
 6499            if start_row.0 > 0 {
 6500                let range_to_move = Point::new(
 6501                    start_row.previous_row().0,
 6502                    buffer.line_len(start_row.previous_row()),
 6503                )
 6504                    ..Point::new(
 6505                        end_row.previous_row().0,
 6506                        buffer.line_len(end_row.previous_row()),
 6507                    );
 6508                let insertion_point = display_map
 6509                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6510                    .0;
 6511
 6512                // Don't move lines across excerpts
 6513                if buffer
 6514                    .excerpt_boundaries_in_range((
 6515                        Bound::Excluded(insertion_point),
 6516                        Bound::Included(range_to_move.end),
 6517                    ))
 6518                    .next()
 6519                    .is_none()
 6520                {
 6521                    let text = buffer
 6522                        .text_for_range(range_to_move.clone())
 6523                        .flat_map(|s| s.chars())
 6524                        .skip(1)
 6525                        .chain(['\n'])
 6526                        .collect::<String>();
 6527
 6528                    edits.push((
 6529                        buffer.anchor_after(range_to_move.start)
 6530                            ..buffer.anchor_before(range_to_move.end),
 6531                        String::new(),
 6532                    ));
 6533                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6534                    edits.push((insertion_anchor..insertion_anchor, text));
 6535
 6536                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6537
 6538                    // Move selections up
 6539                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6540                        |mut selection| {
 6541                            selection.start.row -= row_delta;
 6542                            selection.end.row -= row_delta;
 6543                            selection
 6544                        },
 6545                    ));
 6546
 6547                    // Move folds up
 6548                    unfold_ranges.push(range_to_move.clone());
 6549                    for fold in display_map.folds_in_range(
 6550                        buffer.anchor_before(range_to_move.start)
 6551                            ..buffer.anchor_after(range_to_move.end),
 6552                    ) {
 6553                        let mut start = fold.range.start.to_point(&buffer);
 6554                        let mut end = fold.range.end.to_point(&buffer);
 6555                        start.row -= row_delta;
 6556                        end.row -= row_delta;
 6557                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6558                    }
 6559                }
 6560            }
 6561
 6562            // If we didn't move line(s), preserve the existing selections
 6563            new_selections.append(&mut contiguous_row_selections);
 6564        }
 6565
 6566        self.transact(cx, |this, cx| {
 6567            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6568            this.buffer.update(cx, |buffer, cx| {
 6569                for (range, text) in edits {
 6570                    buffer.edit([(range, text)], None, cx);
 6571                }
 6572            });
 6573            this.fold_creases(refold_creases, true, cx);
 6574            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6575                s.select(new_selections);
 6576            })
 6577        });
 6578    }
 6579
 6580    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6581        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6582        let buffer = self.buffer.read(cx).snapshot(cx);
 6583
 6584        let mut edits = Vec::new();
 6585        let mut unfold_ranges = Vec::new();
 6586        let mut refold_creases = Vec::new();
 6587
 6588        let selections = self.selections.all::<Point>(cx);
 6589        let mut selections = selections.iter().peekable();
 6590        let mut contiguous_row_selections = Vec::new();
 6591        let mut new_selections = Vec::new();
 6592
 6593        while let Some(selection) = selections.next() {
 6594            // Find all the selections that span a contiguous row range
 6595            let (start_row, end_row) = consume_contiguous_rows(
 6596                &mut contiguous_row_selections,
 6597                selection,
 6598                &display_map,
 6599                &mut selections,
 6600            );
 6601
 6602            // Move the text spanned by the row range to be after the last line of the row range
 6603            if end_row.0 <= buffer.max_point().row {
 6604                let range_to_move =
 6605                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6606                let insertion_point = display_map
 6607                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6608                    .0;
 6609
 6610                // Don't move lines across excerpt boundaries
 6611                if buffer
 6612                    .excerpt_boundaries_in_range((
 6613                        Bound::Excluded(range_to_move.start),
 6614                        Bound::Included(insertion_point),
 6615                    ))
 6616                    .next()
 6617                    .is_none()
 6618                {
 6619                    let mut text = String::from("\n");
 6620                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6621                    text.pop(); // Drop trailing newline
 6622                    edits.push((
 6623                        buffer.anchor_after(range_to_move.start)
 6624                            ..buffer.anchor_before(range_to_move.end),
 6625                        String::new(),
 6626                    ));
 6627                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6628                    edits.push((insertion_anchor..insertion_anchor, text));
 6629
 6630                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6631
 6632                    // Move selections down
 6633                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6634                        |mut selection| {
 6635                            selection.start.row += row_delta;
 6636                            selection.end.row += row_delta;
 6637                            selection
 6638                        },
 6639                    ));
 6640
 6641                    // Move folds down
 6642                    unfold_ranges.push(range_to_move.clone());
 6643                    for fold in display_map.folds_in_range(
 6644                        buffer.anchor_before(range_to_move.start)
 6645                            ..buffer.anchor_after(range_to_move.end),
 6646                    ) {
 6647                        let mut start = fold.range.start.to_point(&buffer);
 6648                        let mut end = fold.range.end.to_point(&buffer);
 6649                        start.row += row_delta;
 6650                        end.row += row_delta;
 6651                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6652                    }
 6653                }
 6654            }
 6655
 6656            // If we didn't move line(s), preserve the existing selections
 6657            new_selections.append(&mut contiguous_row_selections);
 6658        }
 6659
 6660        self.transact(cx, |this, cx| {
 6661            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6662            this.buffer.update(cx, |buffer, cx| {
 6663                for (range, text) in edits {
 6664                    buffer.edit([(range, text)], None, cx);
 6665                }
 6666            });
 6667            this.fold_creases(refold_creases, true, cx);
 6668            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6669        });
 6670    }
 6671
 6672    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6673        let text_layout_details = &self.text_layout_details(cx);
 6674        self.transact(cx, |this, cx| {
 6675            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6676                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6677                let line_mode = s.line_mode;
 6678                s.move_with(|display_map, selection| {
 6679                    if !selection.is_empty() || line_mode {
 6680                        return;
 6681                    }
 6682
 6683                    let mut head = selection.head();
 6684                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6685                    if head.column() == display_map.line_len(head.row()) {
 6686                        transpose_offset = display_map
 6687                            .buffer_snapshot
 6688                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6689                    }
 6690
 6691                    if transpose_offset == 0 {
 6692                        return;
 6693                    }
 6694
 6695                    *head.column_mut() += 1;
 6696                    head = display_map.clip_point(head, Bias::Right);
 6697                    let goal = SelectionGoal::HorizontalPosition(
 6698                        display_map
 6699                            .x_for_display_point(head, text_layout_details)
 6700                            .into(),
 6701                    );
 6702                    selection.collapse_to(head, goal);
 6703
 6704                    let transpose_start = display_map
 6705                        .buffer_snapshot
 6706                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6707                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6708                        let transpose_end = display_map
 6709                            .buffer_snapshot
 6710                            .clip_offset(transpose_offset + 1, Bias::Right);
 6711                        if let Some(ch) =
 6712                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6713                        {
 6714                            edits.push((transpose_start..transpose_offset, String::new()));
 6715                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6716                        }
 6717                    }
 6718                });
 6719                edits
 6720            });
 6721            this.buffer
 6722                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6723            let selections = this.selections.all::<usize>(cx);
 6724            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6725                s.select(selections);
 6726            });
 6727        });
 6728    }
 6729
 6730    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6731        self.rewrap_impl(IsVimMode::No, cx)
 6732    }
 6733
 6734    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 6735        let buffer = self.buffer.read(cx).snapshot(cx);
 6736        let selections = self.selections.all::<Point>(cx);
 6737        let mut selections = selections.iter().peekable();
 6738
 6739        let mut edits = Vec::new();
 6740        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6741
 6742        while let Some(selection) = selections.next() {
 6743            let mut start_row = selection.start.row;
 6744            let mut end_row = selection.end.row;
 6745
 6746            // Skip selections that overlap with a range that has already been rewrapped.
 6747            let selection_range = start_row..end_row;
 6748            if rewrapped_row_ranges
 6749                .iter()
 6750                .any(|range| range.overlaps(&selection_range))
 6751            {
 6752                continue;
 6753            }
 6754
 6755            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 6756
 6757            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6758                match language_scope.language_name().0.as_ref() {
 6759                    "Markdown" | "Plain Text" => {
 6760                        should_rewrap = true;
 6761                    }
 6762                    _ => {}
 6763                }
 6764            }
 6765
 6766            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 6767
 6768            // Since not all lines in the selection may be at the same indent
 6769            // level, choose the indent size that is the most common between all
 6770            // of the lines.
 6771            //
 6772            // If there is a tie, we use the deepest indent.
 6773            let (indent_size, indent_end) = {
 6774                let mut indent_size_occurrences = HashMap::default();
 6775                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6776
 6777                for row in start_row..=end_row {
 6778                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6779                    rows_by_indent_size.entry(indent).or_default().push(row);
 6780                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6781                }
 6782
 6783                let indent_size = indent_size_occurrences
 6784                    .into_iter()
 6785                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 6786                    .map(|(indent, _)| indent)
 6787                    .unwrap_or_default();
 6788                let row = rows_by_indent_size[&indent_size][0];
 6789                let indent_end = Point::new(row, indent_size.len);
 6790
 6791                (indent_size, indent_end)
 6792            };
 6793
 6794            let mut line_prefix = indent_size.chars().collect::<String>();
 6795
 6796            if let Some(comment_prefix) =
 6797                buffer
 6798                    .language_scope_at(selection.head())
 6799                    .and_then(|language| {
 6800                        language
 6801                            .line_comment_prefixes()
 6802                            .iter()
 6803                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6804                            .cloned()
 6805                    })
 6806            {
 6807                line_prefix.push_str(&comment_prefix);
 6808                should_rewrap = true;
 6809            }
 6810
 6811            if !should_rewrap {
 6812                continue;
 6813            }
 6814
 6815            if selection.is_empty() {
 6816                'expand_upwards: while start_row > 0 {
 6817                    let prev_row = start_row - 1;
 6818                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6819                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6820                    {
 6821                        start_row = prev_row;
 6822                    } else {
 6823                        break 'expand_upwards;
 6824                    }
 6825                }
 6826
 6827                'expand_downwards: while end_row < buffer.max_point().row {
 6828                    let next_row = end_row + 1;
 6829                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6830                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6831                    {
 6832                        end_row = next_row;
 6833                    } else {
 6834                        break 'expand_downwards;
 6835                    }
 6836                }
 6837            }
 6838
 6839            let start = Point::new(start_row, 0);
 6840            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6841            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6842            let Some(lines_without_prefixes) = selection_text
 6843                .lines()
 6844                .map(|line| {
 6845                    line.strip_prefix(&line_prefix)
 6846                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6847                        .ok_or_else(|| {
 6848                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6849                        })
 6850                })
 6851                .collect::<Result<Vec<_>, _>>()
 6852                .log_err()
 6853            else {
 6854                continue;
 6855            };
 6856
 6857            let wrap_column = buffer
 6858                .settings_at(Point::new(start_row, 0), cx)
 6859                .preferred_line_length as usize;
 6860            let wrapped_text = wrap_with_prefix(
 6861                line_prefix,
 6862                lines_without_prefixes.join(" "),
 6863                wrap_column,
 6864                tab_size,
 6865            );
 6866
 6867            // TODO: should always use char-based diff while still supporting cursor behavior that
 6868            // matches vim.
 6869            let diff = match is_vim_mode {
 6870                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 6871                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 6872            };
 6873            let mut offset = start.to_offset(&buffer);
 6874            let mut moved_since_edit = true;
 6875
 6876            for change in diff.iter_all_changes() {
 6877                let value = change.value();
 6878                match change.tag() {
 6879                    ChangeTag::Equal => {
 6880                        offset += value.len();
 6881                        moved_since_edit = true;
 6882                    }
 6883                    ChangeTag::Delete => {
 6884                        let start = buffer.anchor_after(offset);
 6885                        let end = buffer.anchor_before(offset + value.len());
 6886
 6887                        if moved_since_edit {
 6888                            edits.push((start..end, String::new()));
 6889                        } else {
 6890                            edits.last_mut().unwrap().0.end = end;
 6891                        }
 6892
 6893                        offset += value.len();
 6894                        moved_since_edit = false;
 6895                    }
 6896                    ChangeTag::Insert => {
 6897                        if moved_since_edit {
 6898                            let anchor = buffer.anchor_after(offset);
 6899                            edits.push((anchor..anchor, value.to_string()));
 6900                        } else {
 6901                            edits.last_mut().unwrap().1.push_str(value);
 6902                        }
 6903
 6904                        moved_since_edit = false;
 6905                    }
 6906                }
 6907            }
 6908
 6909            rewrapped_row_ranges.push(start_row..=end_row);
 6910        }
 6911
 6912        self.buffer
 6913            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6914    }
 6915
 6916    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 6917        let mut text = String::new();
 6918        let buffer = self.buffer.read(cx).snapshot(cx);
 6919        let mut selections = self.selections.all::<Point>(cx);
 6920        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6921        {
 6922            let max_point = buffer.max_point();
 6923            let mut is_first = true;
 6924            for selection in &mut selections {
 6925                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6926                if is_entire_line {
 6927                    selection.start = Point::new(selection.start.row, 0);
 6928                    if !selection.is_empty() && selection.end.column == 0 {
 6929                        selection.end = cmp::min(max_point, selection.end);
 6930                    } else {
 6931                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6932                    }
 6933                    selection.goal = SelectionGoal::None;
 6934                }
 6935                if is_first {
 6936                    is_first = false;
 6937                } else {
 6938                    text += "\n";
 6939                }
 6940                let mut len = 0;
 6941                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6942                    text.push_str(chunk);
 6943                    len += chunk.len();
 6944                }
 6945                clipboard_selections.push(ClipboardSelection {
 6946                    len,
 6947                    is_entire_line,
 6948                    first_line_indent: buffer
 6949                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6950                        .len,
 6951                });
 6952            }
 6953        }
 6954
 6955        self.transact(cx, |this, cx| {
 6956            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6957                s.select(selections);
 6958            });
 6959            this.insert("", cx);
 6960        });
 6961        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 6962    }
 6963
 6964    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6965        let item = self.cut_common(cx);
 6966        cx.write_to_clipboard(item);
 6967    }
 6968
 6969    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 6970        self.change_selections(None, cx, |s| {
 6971            s.move_with(|snapshot, sel| {
 6972                if sel.is_empty() {
 6973                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 6974                }
 6975            });
 6976        });
 6977        let item = self.cut_common(cx);
 6978        cx.set_global(KillRing(item))
 6979    }
 6980
 6981    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 6982        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 6983            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 6984                (kill_ring.text().to_string(), kill_ring.metadata_json())
 6985            } else {
 6986                return;
 6987            }
 6988        } else {
 6989            return;
 6990        };
 6991        self.do_paste(&text, metadata, false, cx);
 6992    }
 6993
 6994    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6995        let selections = self.selections.all::<Point>(cx);
 6996        let buffer = self.buffer.read(cx).read(cx);
 6997        let mut text = String::new();
 6998
 6999        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7000        {
 7001            let max_point = buffer.max_point();
 7002            let mut is_first = true;
 7003            for selection in selections.iter() {
 7004                let mut start = selection.start;
 7005                let mut end = selection.end;
 7006                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7007                if is_entire_line {
 7008                    start = Point::new(start.row, 0);
 7009                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7010                }
 7011                if is_first {
 7012                    is_first = false;
 7013                } else {
 7014                    text += "\n";
 7015                }
 7016                let mut len = 0;
 7017                for chunk in buffer.text_for_range(start..end) {
 7018                    text.push_str(chunk);
 7019                    len += chunk.len();
 7020                }
 7021                clipboard_selections.push(ClipboardSelection {
 7022                    len,
 7023                    is_entire_line,
 7024                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7025                });
 7026            }
 7027        }
 7028
 7029        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7030            text,
 7031            clipboard_selections,
 7032        ));
 7033    }
 7034
 7035    pub fn do_paste(
 7036        &mut self,
 7037        text: &String,
 7038        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7039        handle_entire_lines: bool,
 7040        cx: &mut ViewContext<Self>,
 7041    ) {
 7042        if self.read_only(cx) {
 7043            return;
 7044        }
 7045
 7046        let clipboard_text = Cow::Borrowed(text);
 7047
 7048        self.transact(cx, |this, cx| {
 7049            if let Some(mut clipboard_selections) = clipboard_selections {
 7050                let old_selections = this.selections.all::<usize>(cx);
 7051                let all_selections_were_entire_line =
 7052                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7053                let first_selection_indent_column =
 7054                    clipboard_selections.first().map(|s| s.first_line_indent);
 7055                if clipboard_selections.len() != old_selections.len() {
 7056                    clipboard_selections.drain(..);
 7057                }
 7058                let cursor_offset = this.selections.last::<usize>(cx).head();
 7059                let mut auto_indent_on_paste = true;
 7060
 7061                this.buffer.update(cx, |buffer, cx| {
 7062                    let snapshot = buffer.read(cx);
 7063                    auto_indent_on_paste =
 7064                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7065
 7066                    let mut start_offset = 0;
 7067                    let mut edits = Vec::new();
 7068                    let mut original_indent_columns = Vec::new();
 7069                    for (ix, selection) in old_selections.iter().enumerate() {
 7070                        let to_insert;
 7071                        let entire_line;
 7072                        let original_indent_column;
 7073                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7074                            let end_offset = start_offset + clipboard_selection.len;
 7075                            to_insert = &clipboard_text[start_offset..end_offset];
 7076                            entire_line = clipboard_selection.is_entire_line;
 7077                            start_offset = end_offset + 1;
 7078                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7079                        } else {
 7080                            to_insert = clipboard_text.as_str();
 7081                            entire_line = all_selections_were_entire_line;
 7082                            original_indent_column = first_selection_indent_column
 7083                        }
 7084
 7085                        // If the corresponding selection was empty when this slice of the
 7086                        // clipboard text was written, then the entire line containing the
 7087                        // selection was copied. If this selection is also currently empty,
 7088                        // then paste the line before the current line of the buffer.
 7089                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7090                            let column = selection.start.to_point(&snapshot).column as usize;
 7091                            let line_start = selection.start - column;
 7092                            line_start..line_start
 7093                        } else {
 7094                            selection.range()
 7095                        };
 7096
 7097                        edits.push((range, to_insert));
 7098                        original_indent_columns.extend(original_indent_column);
 7099                    }
 7100                    drop(snapshot);
 7101
 7102                    buffer.edit(
 7103                        edits,
 7104                        if auto_indent_on_paste {
 7105                            Some(AutoindentMode::Block {
 7106                                original_indent_columns,
 7107                            })
 7108                        } else {
 7109                            None
 7110                        },
 7111                        cx,
 7112                    );
 7113                });
 7114
 7115                let selections = this.selections.all::<usize>(cx);
 7116                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7117            } else {
 7118                this.insert(&clipboard_text, cx);
 7119            }
 7120        });
 7121    }
 7122
 7123    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7124        if let Some(item) = cx.read_from_clipboard() {
 7125            let entries = item.entries();
 7126
 7127            match entries.first() {
 7128                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7129                // of all the pasted entries.
 7130                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7131                    .do_paste(
 7132                        clipboard_string.text(),
 7133                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7134                        true,
 7135                        cx,
 7136                    ),
 7137                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7138            }
 7139        }
 7140    }
 7141
 7142    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7143        if self.read_only(cx) {
 7144            return;
 7145        }
 7146
 7147        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7148            if let Some((selections, _)) =
 7149                self.selection_history.transaction(transaction_id).cloned()
 7150            {
 7151                self.change_selections(None, cx, |s| {
 7152                    s.select_anchors(selections.to_vec());
 7153                });
 7154            }
 7155            self.request_autoscroll(Autoscroll::fit(), cx);
 7156            self.unmark_text(cx);
 7157            self.refresh_inline_completion(true, false, cx);
 7158            cx.emit(EditorEvent::Edited { transaction_id });
 7159            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7160        }
 7161    }
 7162
 7163    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7164        if self.read_only(cx) {
 7165            return;
 7166        }
 7167
 7168        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7169            if let Some((_, Some(selections))) =
 7170                self.selection_history.transaction(transaction_id).cloned()
 7171            {
 7172                self.change_selections(None, cx, |s| {
 7173                    s.select_anchors(selections.to_vec());
 7174                });
 7175            }
 7176            self.request_autoscroll(Autoscroll::fit(), cx);
 7177            self.unmark_text(cx);
 7178            self.refresh_inline_completion(true, false, cx);
 7179            cx.emit(EditorEvent::Edited { transaction_id });
 7180        }
 7181    }
 7182
 7183    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7184        self.buffer
 7185            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7186    }
 7187
 7188    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7189        self.buffer
 7190            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7191    }
 7192
 7193    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7194        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7195            let line_mode = s.line_mode;
 7196            s.move_with(|map, selection| {
 7197                let cursor = if selection.is_empty() && !line_mode {
 7198                    movement::left(map, selection.start)
 7199                } else {
 7200                    selection.start
 7201                };
 7202                selection.collapse_to(cursor, SelectionGoal::None);
 7203            });
 7204        })
 7205    }
 7206
 7207    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7208        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7209            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7210        })
 7211    }
 7212
 7213    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7214        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7215            let line_mode = s.line_mode;
 7216            s.move_with(|map, selection| {
 7217                let cursor = if selection.is_empty() && !line_mode {
 7218                    movement::right(map, selection.end)
 7219                } else {
 7220                    selection.end
 7221                };
 7222                selection.collapse_to(cursor, SelectionGoal::None)
 7223            });
 7224        })
 7225    }
 7226
 7227    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7228        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7229            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7230        })
 7231    }
 7232
 7233    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7234        if self.take_rename(true, cx).is_some() {
 7235            return;
 7236        }
 7237
 7238        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7239            cx.propagate();
 7240            return;
 7241        }
 7242
 7243        let text_layout_details = &self.text_layout_details(cx);
 7244        let selection_count = self.selections.count();
 7245        let first_selection = self.selections.first_anchor();
 7246
 7247        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7248            let line_mode = s.line_mode;
 7249            s.move_with(|map, selection| {
 7250                if !selection.is_empty() && !line_mode {
 7251                    selection.goal = SelectionGoal::None;
 7252                }
 7253                let (cursor, goal) = movement::up(
 7254                    map,
 7255                    selection.start,
 7256                    selection.goal,
 7257                    false,
 7258                    text_layout_details,
 7259                );
 7260                selection.collapse_to(cursor, goal);
 7261            });
 7262        });
 7263
 7264        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7265        {
 7266            cx.propagate();
 7267        }
 7268    }
 7269
 7270    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7271        if self.take_rename(true, cx).is_some() {
 7272            return;
 7273        }
 7274
 7275        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7276            cx.propagate();
 7277            return;
 7278        }
 7279
 7280        let text_layout_details = &self.text_layout_details(cx);
 7281
 7282        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7283            let line_mode = s.line_mode;
 7284            s.move_with(|map, selection| {
 7285                if !selection.is_empty() && !line_mode {
 7286                    selection.goal = SelectionGoal::None;
 7287                }
 7288                let (cursor, goal) = movement::up_by_rows(
 7289                    map,
 7290                    selection.start,
 7291                    action.lines,
 7292                    selection.goal,
 7293                    false,
 7294                    text_layout_details,
 7295                );
 7296                selection.collapse_to(cursor, goal);
 7297            });
 7298        })
 7299    }
 7300
 7301    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7302        if self.take_rename(true, cx).is_some() {
 7303            return;
 7304        }
 7305
 7306        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7307            cx.propagate();
 7308            return;
 7309        }
 7310
 7311        let text_layout_details = &self.text_layout_details(cx);
 7312
 7313        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7314            let line_mode = s.line_mode;
 7315            s.move_with(|map, selection| {
 7316                if !selection.is_empty() && !line_mode {
 7317                    selection.goal = SelectionGoal::None;
 7318                }
 7319                let (cursor, goal) = movement::down_by_rows(
 7320                    map,
 7321                    selection.start,
 7322                    action.lines,
 7323                    selection.goal,
 7324                    false,
 7325                    text_layout_details,
 7326                );
 7327                selection.collapse_to(cursor, goal);
 7328            });
 7329        })
 7330    }
 7331
 7332    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7333        let text_layout_details = &self.text_layout_details(cx);
 7334        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7335            s.move_heads_with(|map, head, goal| {
 7336                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7337            })
 7338        })
 7339    }
 7340
 7341    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7342        let text_layout_details = &self.text_layout_details(cx);
 7343        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7344            s.move_heads_with(|map, head, goal| {
 7345                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7346            })
 7347        })
 7348    }
 7349
 7350    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7351        let Some(row_count) = self.visible_row_count() else {
 7352            return;
 7353        };
 7354
 7355        let text_layout_details = &self.text_layout_details(cx);
 7356
 7357        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7358            s.move_heads_with(|map, head, goal| {
 7359                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7360            })
 7361        })
 7362    }
 7363
 7364    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7365        if self.take_rename(true, cx).is_some() {
 7366            return;
 7367        }
 7368
 7369        if self
 7370            .context_menu
 7371            .borrow_mut()
 7372            .as_mut()
 7373            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7374            .unwrap_or(false)
 7375        {
 7376            return;
 7377        }
 7378
 7379        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7380            cx.propagate();
 7381            return;
 7382        }
 7383
 7384        let Some(row_count) = self.visible_row_count() else {
 7385            return;
 7386        };
 7387
 7388        let autoscroll = if action.center_cursor {
 7389            Autoscroll::center()
 7390        } else {
 7391            Autoscroll::fit()
 7392        };
 7393
 7394        let text_layout_details = &self.text_layout_details(cx);
 7395
 7396        self.change_selections(Some(autoscroll), cx, |s| {
 7397            let line_mode = s.line_mode;
 7398            s.move_with(|map, selection| {
 7399                if !selection.is_empty() && !line_mode {
 7400                    selection.goal = SelectionGoal::None;
 7401                }
 7402                let (cursor, goal) = movement::up_by_rows(
 7403                    map,
 7404                    selection.end,
 7405                    row_count,
 7406                    selection.goal,
 7407                    false,
 7408                    text_layout_details,
 7409                );
 7410                selection.collapse_to(cursor, goal);
 7411            });
 7412        });
 7413    }
 7414
 7415    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7416        let text_layout_details = &self.text_layout_details(cx);
 7417        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7418            s.move_heads_with(|map, head, goal| {
 7419                movement::up(map, head, goal, false, text_layout_details)
 7420            })
 7421        })
 7422    }
 7423
 7424    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7425        self.take_rename(true, cx);
 7426
 7427        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7428            cx.propagate();
 7429            return;
 7430        }
 7431
 7432        let text_layout_details = &self.text_layout_details(cx);
 7433        let selection_count = self.selections.count();
 7434        let first_selection = self.selections.first_anchor();
 7435
 7436        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7437            let line_mode = s.line_mode;
 7438            s.move_with(|map, selection| {
 7439                if !selection.is_empty() && !line_mode {
 7440                    selection.goal = SelectionGoal::None;
 7441                }
 7442                let (cursor, goal) = movement::down(
 7443                    map,
 7444                    selection.end,
 7445                    selection.goal,
 7446                    false,
 7447                    text_layout_details,
 7448                );
 7449                selection.collapse_to(cursor, goal);
 7450            });
 7451        });
 7452
 7453        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7454        {
 7455            cx.propagate();
 7456        }
 7457    }
 7458
 7459    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7460        let Some(row_count) = self.visible_row_count() else {
 7461            return;
 7462        };
 7463
 7464        let text_layout_details = &self.text_layout_details(cx);
 7465
 7466        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7467            s.move_heads_with(|map, head, goal| {
 7468                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7469            })
 7470        })
 7471    }
 7472
 7473    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7474        if self.take_rename(true, cx).is_some() {
 7475            return;
 7476        }
 7477
 7478        if self
 7479            .context_menu
 7480            .borrow_mut()
 7481            .as_mut()
 7482            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7483            .unwrap_or(false)
 7484        {
 7485            return;
 7486        }
 7487
 7488        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7489            cx.propagate();
 7490            return;
 7491        }
 7492
 7493        let Some(row_count) = self.visible_row_count() else {
 7494            return;
 7495        };
 7496
 7497        let autoscroll = if action.center_cursor {
 7498            Autoscroll::center()
 7499        } else {
 7500            Autoscroll::fit()
 7501        };
 7502
 7503        let text_layout_details = &self.text_layout_details(cx);
 7504        self.change_selections(Some(autoscroll), cx, |s| {
 7505            let line_mode = s.line_mode;
 7506            s.move_with(|map, selection| {
 7507                if !selection.is_empty() && !line_mode {
 7508                    selection.goal = SelectionGoal::None;
 7509                }
 7510                let (cursor, goal) = movement::down_by_rows(
 7511                    map,
 7512                    selection.end,
 7513                    row_count,
 7514                    selection.goal,
 7515                    false,
 7516                    text_layout_details,
 7517                );
 7518                selection.collapse_to(cursor, goal);
 7519            });
 7520        });
 7521    }
 7522
 7523    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7524        let text_layout_details = &self.text_layout_details(cx);
 7525        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7526            s.move_heads_with(|map, head, goal| {
 7527                movement::down(map, head, goal, false, text_layout_details)
 7528            })
 7529        });
 7530    }
 7531
 7532    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7533        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7534            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7535        }
 7536    }
 7537
 7538    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7539        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7540            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7541        }
 7542    }
 7543
 7544    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7545        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7546            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7547        }
 7548    }
 7549
 7550    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7551        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7552            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7553        }
 7554    }
 7555
 7556    pub fn move_to_previous_word_start(
 7557        &mut self,
 7558        _: &MoveToPreviousWordStart,
 7559        cx: &mut ViewContext<Self>,
 7560    ) {
 7561        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7562            s.move_cursors_with(|map, head, _| {
 7563                (
 7564                    movement::previous_word_start(map, head),
 7565                    SelectionGoal::None,
 7566                )
 7567            });
 7568        })
 7569    }
 7570
 7571    pub fn move_to_previous_subword_start(
 7572        &mut self,
 7573        _: &MoveToPreviousSubwordStart,
 7574        cx: &mut ViewContext<Self>,
 7575    ) {
 7576        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7577            s.move_cursors_with(|map, head, _| {
 7578                (
 7579                    movement::previous_subword_start(map, head),
 7580                    SelectionGoal::None,
 7581                )
 7582            });
 7583        })
 7584    }
 7585
 7586    pub fn select_to_previous_word_start(
 7587        &mut self,
 7588        _: &SelectToPreviousWordStart,
 7589        cx: &mut ViewContext<Self>,
 7590    ) {
 7591        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7592            s.move_heads_with(|map, head, _| {
 7593                (
 7594                    movement::previous_word_start(map, head),
 7595                    SelectionGoal::None,
 7596                )
 7597            });
 7598        })
 7599    }
 7600
 7601    pub fn select_to_previous_subword_start(
 7602        &mut self,
 7603        _: &SelectToPreviousSubwordStart,
 7604        cx: &mut ViewContext<Self>,
 7605    ) {
 7606        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7607            s.move_heads_with(|map, head, _| {
 7608                (
 7609                    movement::previous_subword_start(map, head),
 7610                    SelectionGoal::None,
 7611                )
 7612            });
 7613        })
 7614    }
 7615
 7616    pub fn delete_to_previous_word_start(
 7617        &mut self,
 7618        action: &DeleteToPreviousWordStart,
 7619        cx: &mut ViewContext<Self>,
 7620    ) {
 7621        self.transact(cx, |this, cx| {
 7622            this.select_autoclose_pair(cx);
 7623            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7624                let line_mode = s.line_mode;
 7625                s.move_with(|map, selection| {
 7626                    if selection.is_empty() && !line_mode {
 7627                        let cursor = if action.ignore_newlines {
 7628                            movement::previous_word_start(map, selection.head())
 7629                        } else {
 7630                            movement::previous_word_start_or_newline(map, selection.head())
 7631                        };
 7632                        selection.set_head(cursor, SelectionGoal::None);
 7633                    }
 7634                });
 7635            });
 7636            this.insert("", cx);
 7637        });
 7638    }
 7639
 7640    pub fn delete_to_previous_subword_start(
 7641        &mut self,
 7642        _: &DeleteToPreviousSubwordStart,
 7643        cx: &mut ViewContext<Self>,
 7644    ) {
 7645        self.transact(cx, |this, cx| {
 7646            this.select_autoclose_pair(cx);
 7647            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7648                let line_mode = s.line_mode;
 7649                s.move_with(|map, selection| {
 7650                    if selection.is_empty() && !line_mode {
 7651                        let cursor = movement::previous_subword_start(map, selection.head());
 7652                        selection.set_head(cursor, SelectionGoal::None);
 7653                    }
 7654                });
 7655            });
 7656            this.insert("", cx);
 7657        });
 7658    }
 7659
 7660    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7661        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7662            s.move_cursors_with(|map, head, _| {
 7663                (movement::next_word_end(map, head), SelectionGoal::None)
 7664            });
 7665        })
 7666    }
 7667
 7668    pub fn move_to_next_subword_end(
 7669        &mut self,
 7670        _: &MoveToNextSubwordEnd,
 7671        cx: &mut ViewContext<Self>,
 7672    ) {
 7673        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7674            s.move_cursors_with(|map, head, _| {
 7675                (movement::next_subword_end(map, head), SelectionGoal::None)
 7676            });
 7677        })
 7678    }
 7679
 7680    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7681        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7682            s.move_heads_with(|map, head, _| {
 7683                (movement::next_word_end(map, head), SelectionGoal::None)
 7684            });
 7685        })
 7686    }
 7687
 7688    pub fn select_to_next_subword_end(
 7689        &mut self,
 7690        _: &SelectToNextSubwordEnd,
 7691        cx: &mut ViewContext<Self>,
 7692    ) {
 7693        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7694            s.move_heads_with(|map, head, _| {
 7695                (movement::next_subword_end(map, head), SelectionGoal::None)
 7696            });
 7697        })
 7698    }
 7699
 7700    pub fn delete_to_next_word_end(
 7701        &mut self,
 7702        action: &DeleteToNextWordEnd,
 7703        cx: &mut ViewContext<Self>,
 7704    ) {
 7705        self.transact(cx, |this, cx| {
 7706            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7707                let line_mode = s.line_mode;
 7708                s.move_with(|map, selection| {
 7709                    if selection.is_empty() && !line_mode {
 7710                        let cursor = if action.ignore_newlines {
 7711                            movement::next_word_end(map, selection.head())
 7712                        } else {
 7713                            movement::next_word_end_or_newline(map, selection.head())
 7714                        };
 7715                        selection.set_head(cursor, SelectionGoal::None);
 7716                    }
 7717                });
 7718            });
 7719            this.insert("", cx);
 7720        });
 7721    }
 7722
 7723    pub fn delete_to_next_subword_end(
 7724        &mut self,
 7725        _: &DeleteToNextSubwordEnd,
 7726        cx: &mut ViewContext<Self>,
 7727    ) {
 7728        self.transact(cx, |this, cx| {
 7729            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7730                s.move_with(|map, selection| {
 7731                    if selection.is_empty() {
 7732                        let cursor = movement::next_subword_end(map, selection.head());
 7733                        selection.set_head(cursor, SelectionGoal::None);
 7734                    }
 7735                });
 7736            });
 7737            this.insert("", cx);
 7738        });
 7739    }
 7740
 7741    pub fn move_to_beginning_of_line(
 7742        &mut self,
 7743        action: &MoveToBeginningOfLine,
 7744        cx: &mut ViewContext<Self>,
 7745    ) {
 7746        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7747            s.move_cursors_with(|map, head, _| {
 7748                (
 7749                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7750                    SelectionGoal::None,
 7751                )
 7752            });
 7753        })
 7754    }
 7755
 7756    pub fn select_to_beginning_of_line(
 7757        &mut self,
 7758        action: &SelectToBeginningOfLine,
 7759        cx: &mut ViewContext<Self>,
 7760    ) {
 7761        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7762            s.move_heads_with(|map, head, _| {
 7763                (
 7764                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7765                    SelectionGoal::None,
 7766                )
 7767            });
 7768        });
 7769    }
 7770
 7771    pub fn delete_to_beginning_of_line(
 7772        &mut self,
 7773        _: &DeleteToBeginningOfLine,
 7774        cx: &mut ViewContext<Self>,
 7775    ) {
 7776        self.transact(cx, |this, cx| {
 7777            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7778                s.move_with(|_, selection| {
 7779                    selection.reversed = true;
 7780                });
 7781            });
 7782
 7783            this.select_to_beginning_of_line(
 7784                &SelectToBeginningOfLine {
 7785                    stop_at_soft_wraps: false,
 7786                },
 7787                cx,
 7788            );
 7789            this.backspace(&Backspace, cx);
 7790        });
 7791    }
 7792
 7793    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7794        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7795            s.move_cursors_with(|map, head, _| {
 7796                (
 7797                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7798                    SelectionGoal::None,
 7799                )
 7800            });
 7801        })
 7802    }
 7803
 7804    pub fn select_to_end_of_line(
 7805        &mut self,
 7806        action: &SelectToEndOfLine,
 7807        cx: &mut ViewContext<Self>,
 7808    ) {
 7809        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7810            s.move_heads_with(|map, head, _| {
 7811                (
 7812                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7813                    SelectionGoal::None,
 7814                )
 7815            });
 7816        })
 7817    }
 7818
 7819    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7820        self.transact(cx, |this, cx| {
 7821            this.select_to_end_of_line(
 7822                &SelectToEndOfLine {
 7823                    stop_at_soft_wraps: false,
 7824                },
 7825                cx,
 7826            );
 7827            this.delete(&Delete, cx);
 7828        });
 7829    }
 7830
 7831    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7832        self.transact(cx, |this, cx| {
 7833            this.select_to_end_of_line(
 7834                &SelectToEndOfLine {
 7835                    stop_at_soft_wraps: false,
 7836                },
 7837                cx,
 7838            );
 7839            this.cut(&Cut, cx);
 7840        });
 7841    }
 7842
 7843    pub fn move_to_start_of_paragraph(
 7844        &mut self,
 7845        _: &MoveToStartOfParagraph,
 7846        cx: &mut ViewContext<Self>,
 7847    ) {
 7848        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7849            cx.propagate();
 7850            return;
 7851        }
 7852
 7853        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7854            s.move_with(|map, selection| {
 7855                selection.collapse_to(
 7856                    movement::start_of_paragraph(map, selection.head(), 1),
 7857                    SelectionGoal::None,
 7858                )
 7859            });
 7860        })
 7861    }
 7862
 7863    pub fn move_to_end_of_paragraph(
 7864        &mut self,
 7865        _: &MoveToEndOfParagraph,
 7866        cx: &mut ViewContext<Self>,
 7867    ) {
 7868        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7869            cx.propagate();
 7870            return;
 7871        }
 7872
 7873        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7874            s.move_with(|map, selection| {
 7875                selection.collapse_to(
 7876                    movement::end_of_paragraph(map, selection.head(), 1),
 7877                    SelectionGoal::None,
 7878                )
 7879            });
 7880        })
 7881    }
 7882
 7883    pub fn select_to_start_of_paragraph(
 7884        &mut self,
 7885        _: &SelectToStartOfParagraph,
 7886        cx: &mut ViewContext<Self>,
 7887    ) {
 7888        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7889            cx.propagate();
 7890            return;
 7891        }
 7892
 7893        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7894            s.move_heads_with(|map, head, _| {
 7895                (
 7896                    movement::start_of_paragraph(map, head, 1),
 7897                    SelectionGoal::None,
 7898                )
 7899            });
 7900        })
 7901    }
 7902
 7903    pub fn select_to_end_of_paragraph(
 7904        &mut self,
 7905        _: &SelectToEndOfParagraph,
 7906        cx: &mut ViewContext<Self>,
 7907    ) {
 7908        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7909            cx.propagate();
 7910            return;
 7911        }
 7912
 7913        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7914            s.move_heads_with(|map, head, _| {
 7915                (
 7916                    movement::end_of_paragraph(map, head, 1),
 7917                    SelectionGoal::None,
 7918                )
 7919            });
 7920        })
 7921    }
 7922
 7923    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7924        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7925            cx.propagate();
 7926            return;
 7927        }
 7928
 7929        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7930            s.select_ranges(vec![0..0]);
 7931        });
 7932    }
 7933
 7934    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7935        let mut selection = self.selections.last::<Point>(cx);
 7936        selection.set_head(Point::zero(), SelectionGoal::None);
 7937
 7938        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7939            s.select(vec![selection]);
 7940        });
 7941    }
 7942
 7943    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7944        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7945            cx.propagate();
 7946            return;
 7947        }
 7948
 7949        let cursor = self.buffer.read(cx).read(cx).len();
 7950        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7951            s.select_ranges(vec![cursor..cursor])
 7952        });
 7953    }
 7954
 7955    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7956        self.nav_history = nav_history;
 7957    }
 7958
 7959    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7960        self.nav_history.as_ref()
 7961    }
 7962
 7963    fn push_to_nav_history(
 7964        &mut self,
 7965        cursor_anchor: Anchor,
 7966        new_position: Option<Point>,
 7967        cx: &mut ViewContext<Self>,
 7968    ) {
 7969        if let Some(nav_history) = self.nav_history.as_mut() {
 7970            let buffer = self.buffer.read(cx).read(cx);
 7971            let cursor_position = cursor_anchor.to_point(&buffer);
 7972            let scroll_state = self.scroll_manager.anchor();
 7973            let scroll_top_row = scroll_state.top_row(&buffer);
 7974            drop(buffer);
 7975
 7976            if let Some(new_position) = new_position {
 7977                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7978                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7979                    return;
 7980                }
 7981            }
 7982
 7983            nav_history.push(
 7984                Some(NavigationData {
 7985                    cursor_anchor,
 7986                    cursor_position,
 7987                    scroll_anchor: scroll_state,
 7988                    scroll_top_row,
 7989                }),
 7990                cx,
 7991            );
 7992        }
 7993    }
 7994
 7995    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7996        let buffer = self.buffer.read(cx).snapshot(cx);
 7997        let mut selection = self.selections.first::<usize>(cx);
 7998        selection.set_head(buffer.len(), SelectionGoal::None);
 7999        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8000            s.select(vec![selection]);
 8001        });
 8002    }
 8003
 8004    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8005        let end = self.buffer.read(cx).read(cx).len();
 8006        self.change_selections(None, cx, |s| {
 8007            s.select_ranges(vec![0..end]);
 8008        });
 8009    }
 8010
 8011    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8012        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8013        let mut selections = self.selections.all::<Point>(cx);
 8014        let max_point = display_map.buffer_snapshot.max_point();
 8015        for selection in &mut selections {
 8016            let rows = selection.spanned_rows(true, &display_map);
 8017            selection.start = Point::new(rows.start.0, 0);
 8018            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8019            selection.reversed = false;
 8020        }
 8021        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8022            s.select(selections);
 8023        });
 8024    }
 8025
 8026    pub fn split_selection_into_lines(
 8027        &mut self,
 8028        _: &SplitSelectionIntoLines,
 8029        cx: &mut ViewContext<Self>,
 8030    ) {
 8031        let mut to_unfold = Vec::new();
 8032        let mut new_selection_ranges = Vec::new();
 8033        {
 8034            let selections = self.selections.all::<Point>(cx);
 8035            let buffer = self.buffer.read(cx).read(cx);
 8036            for selection in selections {
 8037                for row in selection.start.row..selection.end.row {
 8038                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8039                    new_selection_ranges.push(cursor..cursor);
 8040                }
 8041                new_selection_ranges.push(selection.end..selection.end);
 8042                to_unfold.push(selection.start..selection.end);
 8043            }
 8044        }
 8045        self.unfold_ranges(&to_unfold, true, true, cx);
 8046        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8047            s.select_ranges(new_selection_ranges);
 8048        });
 8049    }
 8050
 8051    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8052        self.add_selection(true, cx);
 8053    }
 8054
 8055    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8056        self.add_selection(false, cx);
 8057    }
 8058
 8059    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8060        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8061        let mut selections = self.selections.all::<Point>(cx);
 8062        let text_layout_details = self.text_layout_details(cx);
 8063        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8064            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8065            let range = oldest_selection.display_range(&display_map).sorted();
 8066
 8067            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8068            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8069            let positions = start_x.min(end_x)..start_x.max(end_x);
 8070
 8071            selections.clear();
 8072            let mut stack = Vec::new();
 8073            for row in range.start.row().0..=range.end.row().0 {
 8074                if let Some(selection) = self.selections.build_columnar_selection(
 8075                    &display_map,
 8076                    DisplayRow(row),
 8077                    &positions,
 8078                    oldest_selection.reversed,
 8079                    &text_layout_details,
 8080                ) {
 8081                    stack.push(selection.id);
 8082                    selections.push(selection);
 8083                }
 8084            }
 8085
 8086            if above {
 8087                stack.reverse();
 8088            }
 8089
 8090            AddSelectionsState { above, stack }
 8091        });
 8092
 8093        let last_added_selection = *state.stack.last().unwrap();
 8094        let mut new_selections = Vec::new();
 8095        if above == state.above {
 8096            let end_row = if above {
 8097                DisplayRow(0)
 8098            } else {
 8099                display_map.max_point().row()
 8100            };
 8101
 8102            'outer: for selection in selections {
 8103                if selection.id == last_added_selection {
 8104                    let range = selection.display_range(&display_map).sorted();
 8105                    debug_assert_eq!(range.start.row(), range.end.row());
 8106                    let mut row = range.start.row();
 8107                    let positions =
 8108                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8109                            px(start)..px(end)
 8110                        } else {
 8111                            let start_x =
 8112                                display_map.x_for_display_point(range.start, &text_layout_details);
 8113                            let end_x =
 8114                                display_map.x_for_display_point(range.end, &text_layout_details);
 8115                            start_x.min(end_x)..start_x.max(end_x)
 8116                        };
 8117
 8118                    while row != end_row {
 8119                        if above {
 8120                            row.0 -= 1;
 8121                        } else {
 8122                            row.0 += 1;
 8123                        }
 8124
 8125                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8126                            &display_map,
 8127                            row,
 8128                            &positions,
 8129                            selection.reversed,
 8130                            &text_layout_details,
 8131                        ) {
 8132                            state.stack.push(new_selection.id);
 8133                            if above {
 8134                                new_selections.push(new_selection);
 8135                                new_selections.push(selection);
 8136                            } else {
 8137                                new_selections.push(selection);
 8138                                new_selections.push(new_selection);
 8139                            }
 8140
 8141                            continue 'outer;
 8142                        }
 8143                    }
 8144                }
 8145
 8146                new_selections.push(selection);
 8147            }
 8148        } else {
 8149            new_selections = selections;
 8150            new_selections.retain(|s| s.id != last_added_selection);
 8151            state.stack.pop();
 8152        }
 8153
 8154        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8155            s.select(new_selections);
 8156        });
 8157        if state.stack.len() > 1 {
 8158            self.add_selections_state = Some(state);
 8159        }
 8160    }
 8161
 8162    pub fn select_next_match_internal(
 8163        &mut self,
 8164        display_map: &DisplaySnapshot,
 8165        replace_newest: bool,
 8166        autoscroll: Option<Autoscroll>,
 8167        cx: &mut ViewContext<Self>,
 8168    ) -> Result<()> {
 8169        fn select_next_match_ranges(
 8170            this: &mut Editor,
 8171            range: Range<usize>,
 8172            replace_newest: bool,
 8173            auto_scroll: Option<Autoscroll>,
 8174            cx: &mut ViewContext<Editor>,
 8175        ) {
 8176            this.unfold_ranges(&[range.clone()], false, true, cx);
 8177            this.change_selections(auto_scroll, cx, |s| {
 8178                if replace_newest {
 8179                    s.delete(s.newest_anchor().id);
 8180                }
 8181                s.insert_range(range.clone());
 8182            });
 8183        }
 8184
 8185        let buffer = &display_map.buffer_snapshot;
 8186        let mut selections = self.selections.all::<usize>(cx);
 8187        if let Some(mut select_next_state) = self.select_next_state.take() {
 8188            let query = &select_next_state.query;
 8189            if !select_next_state.done {
 8190                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8191                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8192                let mut next_selected_range = None;
 8193
 8194                let bytes_after_last_selection =
 8195                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8196                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8197                let query_matches = query
 8198                    .stream_find_iter(bytes_after_last_selection)
 8199                    .map(|result| (last_selection.end, result))
 8200                    .chain(
 8201                        query
 8202                            .stream_find_iter(bytes_before_first_selection)
 8203                            .map(|result| (0, result)),
 8204                    );
 8205
 8206                for (start_offset, query_match) in query_matches {
 8207                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8208                    let offset_range =
 8209                        start_offset + query_match.start()..start_offset + query_match.end();
 8210                    let display_range = offset_range.start.to_display_point(display_map)
 8211                        ..offset_range.end.to_display_point(display_map);
 8212
 8213                    if !select_next_state.wordwise
 8214                        || (!movement::is_inside_word(display_map, display_range.start)
 8215                            && !movement::is_inside_word(display_map, display_range.end))
 8216                    {
 8217                        // TODO: This is n^2, because we might check all the selections
 8218                        if !selections
 8219                            .iter()
 8220                            .any(|selection| selection.range().overlaps(&offset_range))
 8221                        {
 8222                            next_selected_range = Some(offset_range);
 8223                            break;
 8224                        }
 8225                    }
 8226                }
 8227
 8228                if let Some(next_selected_range) = next_selected_range {
 8229                    select_next_match_ranges(
 8230                        self,
 8231                        next_selected_range,
 8232                        replace_newest,
 8233                        autoscroll,
 8234                        cx,
 8235                    );
 8236                } else {
 8237                    select_next_state.done = true;
 8238                }
 8239            }
 8240
 8241            self.select_next_state = Some(select_next_state);
 8242        } else {
 8243            let mut only_carets = true;
 8244            let mut same_text_selected = true;
 8245            let mut selected_text = None;
 8246
 8247            let mut selections_iter = selections.iter().peekable();
 8248            while let Some(selection) = selections_iter.next() {
 8249                if selection.start != selection.end {
 8250                    only_carets = false;
 8251                }
 8252
 8253                if same_text_selected {
 8254                    if selected_text.is_none() {
 8255                        selected_text =
 8256                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8257                    }
 8258
 8259                    if let Some(next_selection) = selections_iter.peek() {
 8260                        if next_selection.range().len() == selection.range().len() {
 8261                            let next_selected_text = buffer
 8262                                .text_for_range(next_selection.range())
 8263                                .collect::<String>();
 8264                            if Some(next_selected_text) != selected_text {
 8265                                same_text_selected = false;
 8266                                selected_text = None;
 8267                            }
 8268                        } else {
 8269                            same_text_selected = false;
 8270                            selected_text = None;
 8271                        }
 8272                    }
 8273                }
 8274            }
 8275
 8276            if only_carets {
 8277                for selection in &mut selections {
 8278                    let word_range = movement::surrounding_word(
 8279                        display_map,
 8280                        selection.start.to_display_point(display_map),
 8281                    );
 8282                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8283                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8284                    selection.goal = SelectionGoal::None;
 8285                    selection.reversed = false;
 8286                    select_next_match_ranges(
 8287                        self,
 8288                        selection.start..selection.end,
 8289                        replace_newest,
 8290                        autoscroll,
 8291                        cx,
 8292                    );
 8293                }
 8294
 8295                if selections.len() == 1 {
 8296                    let selection = selections
 8297                        .last()
 8298                        .expect("ensured that there's only one selection");
 8299                    let query = buffer
 8300                        .text_for_range(selection.start..selection.end)
 8301                        .collect::<String>();
 8302                    let is_empty = query.is_empty();
 8303                    let select_state = SelectNextState {
 8304                        query: AhoCorasick::new(&[query])?,
 8305                        wordwise: true,
 8306                        done: is_empty,
 8307                    };
 8308                    self.select_next_state = Some(select_state);
 8309                } else {
 8310                    self.select_next_state = None;
 8311                }
 8312            } else if let Some(selected_text) = selected_text {
 8313                self.select_next_state = Some(SelectNextState {
 8314                    query: AhoCorasick::new(&[selected_text])?,
 8315                    wordwise: false,
 8316                    done: false,
 8317                });
 8318                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8319            }
 8320        }
 8321        Ok(())
 8322    }
 8323
 8324    pub fn select_all_matches(
 8325        &mut self,
 8326        _action: &SelectAllMatches,
 8327        cx: &mut ViewContext<Self>,
 8328    ) -> Result<()> {
 8329        self.push_to_selection_history();
 8330        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8331
 8332        self.select_next_match_internal(&display_map, false, None, cx)?;
 8333        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8334            return Ok(());
 8335        };
 8336        if select_next_state.done {
 8337            return Ok(());
 8338        }
 8339
 8340        let mut new_selections = self.selections.all::<usize>(cx);
 8341
 8342        let buffer = &display_map.buffer_snapshot;
 8343        let query_matches = select_next_state
 8344            .query
 8345            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8346
 8347        for query_match in query_matches {
 8348            let query_match = query_match.unwrap(); // can only fail due to I/O
 8349            let offset_range = query_match.start()..query_match.end();
 8350            let display_range = offset_range.start.to_display_point(&display_map)
 8351                ..offset_range.end.to_display_point(&display_map);
 8352
 8353            if !select_next_state.wordwise
 8354                || (!movement::is_inside_word(&display_map, display_range.start)
 8355                    && !movement::is_inside_word(&display_map, display_range.end))
 8356            {
 8357                self.selections.change_with(cx, |selections| {
 8358                    new_selections.push(Selection {
 8359                        id: selections.new_selection_id(),
 8360                        start: offset_range.start,
 8361                        end: offset_range.end,
 8362                        reversed: false,
 8363                        goal: SelectionGoal::None,
 8364                    });
 8365                });
 8366            }
 8367        }
 8368
 8369        new_selections.sort_by_key(|selection| selection.start);
 8370        let mut ix = 0;
 8371        while ix + 1 < new_selections.len() {
 8372            let current_selection = &new_selections[ix];
 8373            let next_selection = &new_selections[ix + 1];
 8374            if current_selection.range().overlaps(&next_selection.range()) {
 8375                if current_selection.id < next_selection.id {
 8376                    new_selections.remove(ix + 1);
 8377                } else {
 8378                    new_selections.remove(ix);
 8379                }
 8380            } else {
 8381                ix += 1;
 8382            }
 8383        }
 8384
 8385        select_next_state.done = true;
 8386        self.unfold_ranges(
 8387            &new_selections
 8388                .iter()
 8389                .map(|selection| selection.range())
 8390                .collect::<Vec<_>>(),
 8391            false,
 8392            false,
 8393            cx,
 8394        );
 8395        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8396            selections.select(new_selections)
 8397        });
 8398
 8399        Ok(())
 8400    }
 8401
 8402    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8403        self.push_to_selection_history();
 8404        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8405        self.select_next_match_internal(
 8406            &display_map,
 8407            action.replace_newest,
 8408            Some(Autoscroll::newest()),
 8409            cx,
 8410        )?;
 8411        Ok(())
 8412    }
 8413
 8414    pub fn select_previous(
 8415        &mut self,
 8416        action: &SelectPrevious,
 8417        cx: &mut ViewContext<Self>,
 8418    ) -> Result<()> {
 8419        self.push_to_selection_history();
 8420        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8421        let buffer = &display_map.buffer_snapshot;
 8422        let mut selections = self.selections.all::<usize>(cx);
 8423        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8424            let query = &select_prev_state.query;
 8425            if !select_prev_state.done {
 8426                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8427                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8428                let mut next_selected_range = None;
 8429                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8430                let bytes_before_last_selection =
 8431                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8432                let bytes_after_first_selection =
 8433                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8434                let query_matches = query
 8435                    .stream_find_iter(bytes_before_last_selection)
 8436                    .map(|result| (last_selection.start, result))
 8437                    .chain(
 8438                        query
 8439                            .stream_find_iter(bytes_after_first_selection)
 8440                            .map(|result| (buffer.len(), result)),
 8441                    );
 8442                for (end_offset, query_match) in query_matches {
 8443                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8444                    let offset_range =
 8445                        end_offset - query_match.end()..end_offset - query_match.start();
 8446                    let display_range = offset_range.start.to_display_point(&display_map)
 8447                        ..offset_range.end.to_display_point(&display_map);
 8448
 8449                    if !select_prev_state.wordwise
 8450                        || (!movement::is_inside_word(&display_map, display_range.start)
 8451                            && !movement::is_inside_word(&display_map, display_range.end))
 8452                    {
 8453                        next_selected_range = Some(offset_range);
 8454                        break;
 8455                    }
 8456                }
 8457
 8458                if let Some(next_selected_range) = next_selected_range {
 8459                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8460                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8461                        if action.replace_newest {
 8462                            s.delete(s.newest_anchor().id);
 8463                        }
 8464                        s.insert_range(next_selected_range);
 8465                    });
 8466                } else {
 8467                    select_prev_state.done = true;
 8468                }
 8469            }
 8470
 8471            self.select_prev_state = Some(select_prev_state);
 8472        } else {
 8473            let mut only_carets = true;
 8474            let mut same_text_selected = true;
 8475            let mut selected_text = None;
 8476
 8477            let mut selections_iter = selections.iter().peekable();
 8478            while let Some(selection) = selections_iter.next() {
 8479                if selection.start != selection.end {
 8480                    only_carets = false;
 8481                }
 8482
 8483                if same_text_selected {
 8484                    if selected_text.is_none() {
 8485                        selected_text =
 8486                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8487                    }
 8488
 8489                    if let Some(next_selection) = selections_iter.peek() {
 8490                        if next_selection.range().len() == selection.range().len() {
 8491                            let next_selected_text = buffer
 8492                                .text_for_range(next_selection.range())
 8493                                .collect::<String>();
 8494                            if Some(next_selected_text) != selected_text {
 8495                                same_text_selected = false;
 8496                                selected_text = None;
 8497                            }
 8498                        } else {
 8499                            same_text_selected = false;
 8500                            selected_text = None;
 8501                        }
 8502                    }
 8503                }
 8504            }
 8505
 8506            if only_carets {
 8507                for selection in &mut selections {
 8508                    let word_range = movement::surrounding_word(
 8509                        &display_map,
 8510                        selection.start.to_display_point(&display_map),
 8511                    );
 8512                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8513                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8514                    selection.goal = SelectionGoal::None;
 8515                    selection.reversed = false;
 8516                }
 8517                if selections.len() == 1 {
 8518                    let selection = selections
 8519                        .last()
 8520                        .expect("ensured that there's only one selection");
 8521                    let query = buffer
 8522                        .text_for_range(selection.start..selection.end)
 8523                        .collect::<String>();
 8524                    let is_empty = query.is_empty();
 8525                    let select_state = SelectNextState {
 8526                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8527                        wordwise: true,
 8528                        done: is_empty,
 8529                    };
 8530                    self.select_prev_state = Some(select_state);
 8531                } else {
 8532                    self.select_prev_state = None;
 8533                }
 8534
 8535                self.unfold_ranges(
 8536                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8537                    false,
 8538                    true,
 8539                    cx,
 8540                );
 8541                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8542                    s.select(selections);
 8543                });
 8544            } else if let Some(selected_text) = selected_text {
 8545                self.select_prev_state = Some(SelectNextState {
 8546                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8547                    wordwise: false,
 8548                    done: false,
 8549                });
 8550                self.select_previous(action, cx)?;
 8551            }
 8552        }
 8553        Ok(())
 8554    }
 8555
 8556    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8557        if self.read_only(cx) {
 8558            return;
 8559        }
 8560        let text_layout_details = &self.text_layout_details(cx);
 8561        self.transact(cx, |this, cx| {
 8562            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8563            let mut edits = Vec::new();
 8564            let mut selection_edit_ranges = Vec::new();
 8565            let mut last_toggled_row = None;
 8566            let snapshot = this.buffer.read(cx).read(cx);
 8567            let empty_str: Arc<str> = Arc::default();
 8568            let mut suffixes_inserted = Vec::new();
 8569            let ignore_indent = action.ignore_indent;
 8570
 8571            fn comment_prefix_range(
 8572                snapshot: &MultiBufferSnapshot,
 8573                row: MultiBufferRow,
 8574                comment_prefix: &str,
 8575                comment_prefix_whitespace: &str,
 8576                ignore_indent: bool,
 8577            ) -> Range<Point> {
 8578                let indent_size = if ignore_indent {
 8579                    0
 8580                } else {
 8581                    snapshot.indent_size_for_line(row).len
 8582                };
 8583
 8584                let start = Point::new(row.0, indent_size);
 8585
 8586                let mut line_bytes = snapshot
 8587                    .bytes_in_range(start..snapshot.max_point())
 8588                    .flatten()
 8589                    .copied();
 8590
 8591                // If this line currently begins with the line comment prefix, then record
 8592                // the range containing the prefix.
 8593                if line_bytes
 8594                    .by_ref()
 8595                    .take(comment_prefix.len())
 8596                    .eq(comment_prefix.bytes())
 8597                {
 8598                    // Include any whitespace that matches the comment prefix.
 8599                    let matching_whitespace_len = line_bytes
 8600                        .zip(comment_prefix_whitespace.bytes())
 8601                        .take_while(|(a, b)| a == b)
 8602                        .count() as u32;
 8603                    let end = Point::new(
 8604                        start.row,
 8605                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8606                    );
 8607                    start..end
 8608                } else {
 8609                    start..start
 8610                }
 8611            }
 8612
 8613            fn comment_suffix_range(
 8614                snapshot: &MultiBufferSnapshot,
 8615                row: MultiBufferRow,
 8616                comment_suffix: &str,
 8617                comment_suffix_has_leading_space: bool,
 8618            ) -> Range<Point> {
 8619                let end = Point::new(row.0, snapshot.line_len(row));
 8620                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8621
 8622                let mut line_end_bytes = snapshot
 8623                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8624                    .flatten()
 8625                    .copied();
 8626
 8627                let leading_space_len = if suffix_start_column > 0
 8628                    && line_end_bytes.next() == Some(b' ')
 8629                    && comment_suffix_has_leading_space
 8630                {
 8631                    1
 8632                } else {
 8633                    0
 8634                };
 8635
 8636                // If this line currently begins with the line comment prefix, then record
 8637                // the range containing the prefix.
 8638                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8639                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8640                    start..end
 8641                } else {
 8642                    end..end
 8643                }
 8644            }
 8645
 8646            // TODO: Handle selections that cross excerpts
 8647            for selection in &mut selections {
 8648                let start_column = snapshot
 8649                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8650                    .len;
 8651                let language = if let Some(language) =
 8652                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8653                {
 8654                    language
 8655                } else {
 8656                    continue;
 8657                };
 8658
 8659                selection_edit_ranges.clear();
 8660
 8661                // If multiple selections contain a given row, avoid processing that
 8662                // row more than once.
 8663                let mut start_row = MultiBufferRow(selection.start.row);
 8664                if last_toggled_row == Some(start_row) {
 8665                    start_row = start_row.next_row();
 8666                }
 8667                let end_row =
 8668                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8669                        MultiBufferRow(selection.end.row - 1)
 8670                    } else {
 8671                        MultiBufferRow(selection.end.row)
 8672                    };
 8673                last_toggled_row = Some(end_row);
 8674
 8675                if start_row > end_row {
 8676                    continue;
 8677                }
 8678
 8679                // If the language has line comments, toggle those.
 8680                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8681
 8682                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8683                if ignore_indent {
 8684                    full_comment_prefixes = full_comment_prefixes
 8685                        .into_iter()
 8686                        .map(|s| Arc::from(s.trim_end()))
 8687                        .collect();
 8688                }
 8689
 8690                if !full_comment_prefixes.is_empty() {
 8691                    let first_prefix = full_comment_prefixes
 8692                        .first()
 8693                        .expect("prefixes is non-empty");
 8694                    let prefix_trimmed_lengths = full_comment_prefixes
 8695                        .iter()
 8696                        .map(|p| p.trim_end_matches(' ').len())
 8697                        .collect::<SmallVec<[usize; 4]>>();
 8698
 8699                    let mut all_selection_lines_are_comments = true;
 8700
 8701                    for row in start_row.0..=end_row.0 {
 8702                        let row = MultiBufferRow(row);
 8703                        if start_row < end_row && snapshot.is_line_blank(row) {
 8704                            continue;
 8705                        }
 8706
 8707                        let prefix_range = full_comment_prefixes
 8708                            .iter()
 8709                            .zip(prefix_trimmed_lengths.iter().copied())
 8710                            .map(|(prefix, trimmed_prefix_len)| {
 8711                                comment_prefix_range(
 8712                                    snapshot.deref(),
 8713                                    row,
 8714                                    &prefix[..trimmed_prefix_len],
 8715                                    &prefix[trimmed_prefix_len..],
 8716                                    ignore_indent,
 8717                                )
 8718                            })
 8719                            .max_by_key(|range| range.end.column - range.start.column)
 8720                            .expect("prefixes is non-empty");
 8721
 8722                        if prefix_range.is_empty() {
 8723                            all_selection_lines_are_comments = false;
 8724                        }
 8725
 8726                        selection_edit_ranges.push(prefix_range);
 8727                    }
 8728
 8729                    if all_selection_lines_are_comments {
 8730                        edits.extend(
 8731                            selection_edit_ranges
 8732                                .iter()
 8733                                .cloned()
 8734                                .map(|range| (range, empty_str.clone())),
 8735                        );
 8736                    } else {
 8737                        let min_column = selection_edit_ranges
 8738                            .iter()
 8739                            .map(|range| range.start.column)
 8740                            .min()
 8741                            .unwrap_or(0);
 8742                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8743                            let position = Point::new(range.start.row, min_column);
 8744                            (position..position, first_prefix.clone())
 8745                        }));
 8746                    }
 8747                } else if let Some((full_comment_prefix, comment_suffix)) =
 8748                    language.block_comment_delimiters()
 8749                {
 8750                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8751                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8752                    let prefix_range = comment_prefix_range(
 8753                        snapshot.deref(),
 8754                        start_row,
 8755                        comment_prefix,
 8756                        comment_prefix_whitespace,
 8757                        ignore_indent,
 8758                    );
 8759                    let suffix_range = comment_suffix_range(
 8760                        snapshot.deref(),
 8761                        end_row,
 8762                        comment_suffix.trim_start_matches(' '),
 8763                        comment_suffix.starts_with(' '),
 8764                    );
 8765
 8766                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8767                        edits.push((
 8768                            prefix_range.start..prefix_range.start,
 8769                            full_comment_prefix.clone(),
 8770                        ));
 8771                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8772                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8773                    } else {
 8774                        edits.push((prefix_range, empty_str.clone()));
 8775                        edits.push((suffix_range, empty_str.clone()));
 8776                    }
 8777                } else {
 8778                    continue;
 8779                }
 8780            }
 8781
 8782            drop(snapshot);
 8783            this.buffer.update(cx, |buffer, cx| {
 8784                buffer.edit(edits, None, cx);
 8785            });
 8786
 8787            // Adjust selections so that they end before any comment suffixes that
 8788            // were inserted.
 8789            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8790            let mut selections = this.selections.all::<Point>(cx);
 8791            let snapshot = this.buffer.read(cx).read(cx);
 8792            for selection in &mut selections {
 8793                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8794                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8795                        Ordering::Less => {
 8796                            suffixes_inserted.next();
 8797                            continue;
 8798                        }
 8799                        Ordering::Greater => break,
 8800                        Ordering::Equal => {
 8801                            if selection.end.column == snapshot.line_len(row) {
 8802                                if selection.is_empty() {
 8803                                    selection.start.column -= suffix_len as u32;
 8804                                }
 8805                                selection.end.column -= suffix_len as u32;
 8806                            }
 8807                            break;
 8808                        }
 8809                    }
 8810                }
 8811            }
 8812
 8813            drop(snapshot);
 8814            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8815
 8816            let selections = this.selections.all::<Point>(cx);
 8817            let selections_on_single_row = selections.windows(2).all(|selections| {
 8818                selections[0].start.row == selections[1].start.row
 8819                    && selections[0].end.row == selections[1].end.row
 8820                    && selections[0].start.row == selections[0].end.row
 8821            });
 8822            let selections_selecting = selections
 8823                .iter()
 8824                .any(|selection| selection.start != selection.end);
 8825            let advance_downwards = action.advance_downwards
 8826                && selections_on_single_row
 8827                && !selections_selecting
 8828                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8829
 8830            if advance_downwards {
 8831                let snapshot = this.buffer.read(cx).snapshot(cx);
 8832
 8833                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8834                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8835                        let mut point = display_point.to_point(display_snapshot);
 8836                        point.row += 1;
 8837                        point = snapshot.clip_point(point, Bias::Left);
 8838                        let display_point = point.to_display_point(display_snapshot);
 8839                        let goal = SelectionGoal::HorizontalPosition(
 8840                            display_snapshot
 8841                                .x_for_display_point(display_point, text_layout_details)
 8842                                .into(),
 8843                        );
 8844                        (display_point, goal)
 8845                    })
 8846                });
 8847            }
 8848        });
 8849    }
 8850
 8851    pub fn select_enclosing_symbol(
 8852        &mut self,
 8853        _: &SelectEnclosingSymbol,
 8854        cx: &mut ViewContext<Self>,
 8855    ) {
 8856        let buffer = self.buffer.read(cx).snapshot(cx);
 8857        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8858
 8859        fn update_selection(
 8860            selection: &Selection<usize>,
 8861            buffer_snap: &MultiBufferSnapshot,
 8862        ) -> Option<Selection<usize>> {
 8863            let cursor = selection.head();
 8864            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8865            for symbol in symbols.iter().rev() {
 8866                let start = symbol.range.start.to_offset(buffer_snap);
 8867                let end = symbol.range.end.to_offset(buffer_snap);
 8868                let new_range = start..end;
 8869                if start < selection.start || end > selection.end {
 8870                    return Some(Selection {
 8871                        id: selection.id,
 8872                        start: new_range.start,
 8873                        end: new_range.end,
 8874                        goal: SelectionGoal::None,
 8875                        reversed: selection.reversed,
 8876                    });
 8877                }
 8878            }
 8879            None
 8880        }
 8881
 8882        let mut selected_larger_symbol = false;
 8883        let new_selections = old_selections
 8884            .iter()
 8885            .map(|selection| match update_selection(selection, &buffer) {
 8886                Some(new_selection) => {
 8887                    if new_selection.range() != selection.range() {
 8888                        selected_larger_symbol = true;
 8889                    }
 8890                    new_selection
 8891                }
 8892                None => selection.clone(),
 8893            })
 8894            .collect::<Vec<_>>();
 8895
 8896        if selected_larger_symbol {
 8897            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8898                s.select(new_selections);
 8899            });
 8900        }
 8901    }
 8902
 8903    pub fn select_larger_syntax_node(
 8904        &mut self,
 8905        _: &SelectLargerSyntaxNode,
 8906        cx: &mut ViewContext<Self>,
 8907    ) {
 8908        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8909        let buffer = self.buffer.read(cx).snapshot(cx);
 8910        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8911
 8912        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8913        let mut selected_larger_node = false;
 8914        let new_selections = old_selections
 8915            .iter()
 8916            .map(|selection| {
 8917                let old_range = selection.start..selection.end;
 8918                let mut new_range = old_range.clone();
 8919                let mut new_node = None;
 8920                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 8921                {
 8922                    new_node = Some(node);
 8923                    new_range = containing_range;
 8924                    if !display_map.intersects_fold(new_range.start)
 8925                        && !display_map.intersects_fold(new_range.end)
 8926                    {
 8927                        break;
 8928                    }
 8929                }
 8930
 8931                if let Some(node) = new_node {
 8932                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 8933                    // nodes. Parent and grandparent are also logged because this operation will not
 8934                    // visit nodes that have the same range as their parent.
 8935                    log::info!("Node: {node:?}");
 8936                    let parent = node.parent();
 8937                    log::info!("Parent: {parent:?}");
 8938                    let grandparent = parent.and_then(|x| x.parent());
 8939                    log::info!("Grandparent: {grandparent:?}");
 8940                }
 8941
 8942                selected_larger_node |= new_range != old_range;
 8943                Selection {
 8944                    id: selection.id,
 8945                    start: new_range.start,
 8946                    end: new_range.end,
 8947                    goal: SelectionGoal::None,
 8948                    reversed: selection.reversed,
 8949                }
 8950            })
 8951            .collect::<Vec<_>>();
 8952
 8953        if selected_larger_node {
 8954            stack.push(old_selections);
 8955            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8956                s.select(new_selections);
 8957            });
 8958        }
 8959        self.select_larger_syntax_node_stack = stack;
 8960    }
 8961
 8962    pub fn select_smaller_syntax_node(
 8963        &mut self,
 8964        _: &SelectSmallerSyntaxNode,
 8965        cx: &mut ViewContext<Self>,
 8966    ) {
 8967        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8968        if let Some(selections) = stack.pop() {
 8969            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8970                s.select(selections.to_vec());
 8971            });
 8972        }
 8973        self.select_larger_syntax_node_stack = stack;
 8974    }
 8975
 8976    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8977        if !EditorSettings::get_global(cx).gutter.runnables {
 8978            self.clear_tasks();
 8979            return Task::ready(());
 8980        }
 8981        let project = self.project.as_ref().map(Model::downgrade);
 8982        cx.spawn(|this, mut cx| async move {
 8983            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 8984            let Some(project) = project.and_then(|p| p.upgrade()) else {
 8985                return;
 8986            };
 8987            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8988                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8989            }) else {
 8990                return;
 8991            };
 8992
 8993            let hide_runnables = project
 8994                .update(&mut cx, |project, cx| {
 8995                    // Do not display any test indicators in non-dev server remote projects.
 8996                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8997                })
 8998                .unwrap_or(true);
 8999            if hide_runnables {
 9000                return;
 9001            }
 9002            let new_rows =
 9003                cx.background_executor()
 9004                    .spawn({
 9005                        let snapshot = display_snapshot.clone();
 9006                        async move {
 9007                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9008                        }
 9009                    })
 9010                    .await;
 9011            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9012
 9013            this.update(&mut cx, |this, _| {
 9014                this.clear_tasks();
 9015                for (key, value) in rows {
 9016                    this.insert_tasks(key, value);
 9017                }
 9018            })
 9019            .ok();
 9020        })
 9021    }
 9022    fn fetch_runnable_ranges(
 9023        snapshot: &DisplaySnapshot,
 9024        range: Range<Anchor>,
 9025    ) -> Vec<language::RunnableRange> {
 9026        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9027    }
 9028
 9029    fn runnable_rows(
 9030        project: Model<Project>,
 9031        snapshot: DisplaySnapshot,
 9032        runnable_ranges: Vec<RunnableRange>,
 9033        mut cx: AsyncWindowContext,
 9034    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9035        runnable_ranges
 9036            .into_iter()
 9037            .filter_map(|mut runnable| {
 9038                let tasks = cx
 9039                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9040                    .ok()?;
 9041                if tasks.is_empty() {
 9042                    return None;
 9043                }
 9044
 9045                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9046
 9047                let row = snapshot
 9048                    .buffer_snapshot
 9049                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9050                    .1
 9051                    .start
 9052                    .row;
 9053
 9054                let context_range =
 9055                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9056                Some((
 9057                    (runnable.buffer_id, row),
 9058                    RunnableTasks {
 9059                        templates: tasks,
 9060                        offset: MultiBufferOffset(runnable.run_range.start),
 9061                        context_range,
 9062                        column: point.column,
 9063                        extra_variables: runnable.extra_captures,
 9064                    },
 9065                ))
 9066            })
 9067            .collect()
 9068    }
 9069
 9070    fn templates_with_tags(
 9071        project: &Model<Project>,
 9072        runnable: &mut Runnable,
 9073        cx: &WindowContext,
 9074    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9075        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9076            let (worktree_id, file) = project
 9077                .buffer_for_id(runnable.buffer, cx)
 9078                .and_then(|buffer| buffer.read(cx).file())
 9079                .map(|file| (file.worktree_id(cx), file.clone()))
 9080                .unzip();
 9081
 9082            (
 9083                project.task_store().read(cx).task_inventory().cloned(),
 9084                worktree_id,
 9085                file,
 9086            )
 9087        });
 9088
 9089        let tags = mem::take(&mut runnable.tags);
 9090        let mut tags: Vec<_> = tags
 9091            .into_iter()
 9092            .flat_map(|tag| {
 9093                let tag = tag.0.clone();
 9094                inventory
 9095                    .as_ref()
 9096                    .into_iter()
 9097                    .flat_map(|inventory| {
 9098                        inventory.read(cx).list_tasks(
 9099                            file.clone(),
 9100                            Some(runnable.language.clone()),
 9101                            worktree_id,
 9102                            cx,
 9103                        )
 9104                    })
 9105                    .filter(move |(_, template)| {
 9106                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9107                    })
 9108            })
 9109            .sorted_by_key(|(kind, _)| kind.to_owned())
 9110            .collect();
 9111        if let Some((leading_tag_source, _)) = tags.first() {
 9112            // Strongest source wins; if we have worktree tag binding, prefer that to
 9113            // global and language bindings;
 9114            // if we have a global binding, prefer that to language binding.
 9115            let first_mismatch = tags
 9116                .iter()
 9117                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9118            if let Some(index) = first_mismatch {
 9119                tags.truncate(index);
 9120            }
 9121        }
 9122
 9123        tags
 9124    }
 9125
 9126    pub fn move_to_enclosing_bracket(
 9127        &mut self,
 9128        _: &MoveToEnclosingBracket,
 9129        cx: &mut ViewContext<Self>,
 9130    ) {
 9131        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9132            s.move_offsets_with(|snapshot, selection| {
 9133                let Some(enclosing_bracket_ranges) =
 9134                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9135                else {
 9136                    return;
 9137                };
 9138
 9139                let mut best_length = usize::MAX;
 9140                let mut best_inside = false;
 9141                let mut best_in_bracket_range = false;
 9142                let mut best_destination = None;
 9143                for (open, close) in enclosing_bracket_ranges {
 9144                    let close = close.to_inclusive();
 9145                    let length = close.end() - open.start;
 9146                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9147                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9148                        || close.contains(&selection.head());
 9149
 9150                    // If best is next to a bracket and current isn't, skip
 9151                    if !in_bracket_range && best_in_bracket_range {
 9152                        continue;
 9153                    }
 9154
 9155                    // Prefer smaller lengths unless best is inside and current isn't
 9156                    if length > best_length && (best_inside || !inside) {
 9157                        continue;
 9158                    }
 9159
 9160                    best_length = length;
 9161                    best_inside = inside;
 9162                    best_in_bracket_range = in_bracket_range;
 9163                    best_destination = Some(
 9164                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9165                            if inside {
 9166                                open.end
 9167                            } else {
 9168                                open.start
 9169                            }
 9170                        } else if inside {
 9171                            *close.start()
 9172                        } else {
 9173                            *close.end()
 9174                        },
 9175                    );
 9176                }
 9177
 9178                if let Some(destination) = best_destination {
 9179                    selection.collapse_to(destination, SelectionGoal::None);
 9180                }
 9181            })
 9182        });
 9183    }
 9184
 9185    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9186        self.end_selection(cx);
 9187        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9188        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9189            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9190            self.select_next_state = entry.select_next_state;
 9191            self.select_prev_state = entry.select_prev_state;
 9192            self.add_selections_state = entry.add_selections_state;
 9193            self.request_autoscroll(Autoscroll::newest(), cx);
 9194        }
 9195        self.selection_history.mode = SelectionHistoryMode::Normal;
 9196    }
 9197
 9198    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9199        self.end_selection(cx);
 9200        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9201        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9202            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9203            self.select_next_state = entry.select_next_state;
 9204            self.select_prev_state = entry.select_prev_state;
 9205            self.add_selections_state = entry.add_selections_state;
 9206            self.request_autoscroll(Autoscroll::newest(), cx);
 9207        }
 9208        self.selection_history.mode = SelectionHistoryMode::Normal;
 9209    }
 9210
 9211    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9212        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9213    }
 9214
 9215    pub fn expand_excerpts_down(
 9216        &mut self,
 9217        action: &ExpandExcerptsDown,
 9218        cx: &mut ViewContext<Self>,
 9219    ) {
 9220        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9221    }
 9222
 9223    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9224        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9225    }
 9226
 9227    pub fn expand_excerpts_for_direction(
 9228        &mut self,
 9229        lines: u32,
 9230        direction: ExpandExcerptDirection,
 9231        cx: &mut ViewContext<Self>,
 9232    ) {
 9233        let selections = self.selections.disjoint_anchors();
 9234
 9235        let lines = if lines == 0 {
 9236            EditorSettings::get_global(cx).expand_excerpt_lines
 9237        } else {
 9238            lines
 9239        };
 9240
 9241        self.buffer.update(cx, |buffer, cx| {
 9242            let snapshot = buffer.snapshot(cx);
 9243            let mut excerpt_ids = selections
 9244                .iter()
 9245                .flat_map(|selection| {
 9246                    snapshot
 9247                        .excerpts_for_range(selection.range())
 9248                        .map(|excerpt| excerpt.id())
 9249                })
 9250                .collect::<Vec<_>>();
 9251            excerpt_ids.sort();
 9252            excerpt_ids.dedup();
 9253            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
 9254        })
 9255    }
 9256
 9257    pub fn expand_excerpt(
 9258        &mut self,
 9259        excerpt: ExcerptId,
 9260        direction: ExpandExcerptDirection,
 9261        cx: &mut ViewContext<Self>,
 9262    ) {
 9263        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9264        self.buffer.update(cx, |buffer, cx| {
 9265            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9266        })
 9267    }
 9268
 9269    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9270        self.go_to_diagnostic_impl(Direction::Next, cx)
 9271    }
 9272
 9273    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9274        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9275    }
 9276
 9277    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9278        let buffer = self.buffer.read(cx).snapshot(cx);
 9279        let selection = self.selections.newest::<usize>(cx);
 9280
 9281        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9282        if direction == Direction::Next {
 9283            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9284                self.activate_diagnostics(popover.group_id(), cx);
 9285                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
 9286                    let primary_range_start = active_diagnostics.primary_range.start;
 9287                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9288                        let mut new_selection = s.newest_anchor().clone();
 9289                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
 9290                        s.select_anchors(vec![new_selection.clone()]);
 9291                    });
 9292                    self.refresh_inline_completion(false, true, cx);
 9293                }
 9294                return;
 9295            }
 9296        }
 9297
 9298        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9299            active_diagnostics
 9300                .primary_range
 9301                .to_offset(&buffer)
 9302                .to_inclusive()
 9303        });
 9304        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9305            if active_primary_range.contains(&selection.head()) {
 9306                *active_primary_range.start()
 9307            } else {
 9308                selection.head()
 9309            }
 9310        } else {
 9311            selection.head()
 9312        };
 9313        let snapshot = self.snapshot(cx);
 9314        loop {
 9315            let diagnostics = if direction == Direction::Prev {
 9316                buffer.diagnostics_in_range(0..search_start, true)
 9317            } else {
 9318                buffer.diagnostics_in_range(search_start..buffer.len(), false)
 9319            }
 9320            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9321            let search_start_anchor = buffer.anchor_after(search_start);
 9322            let group = diagnostics
 9323                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9324                // be sorted in a stable way
 9325                // skip until we are at current active diagnostic, if it exists
 9326                .skip_while(|entry| {
 9327                    let is_in_range = match direction {
 9328                        Direction::Prev => {
 9329                            entry.range.start.cmp(&search_start_anchor, &buffer).is_ge()
 9330                        }
 9331                        Direction::Next => {
 9332                            entry.range.start.cmp(&search_start_anchor, &buffer).is_le()
 9333                        }
 9334                    };
 9335                    is_in_range
 9336                        && self
 9337                            .active_diagnostics
 9338                            .as_ref()
 9339                            .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9340                })
 9341                .find_map(|entry| {
 9342                    if entry.diagnostic.is_primary
 9343                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9344                        && !(entry.range.start == entry.range.end)
 9345                        // if we match with the active diagnostic, skip it
 9346                        && Some(entry.diagnostic.group_id)
 9347                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9348                    {
 9349                        Some((entry.range, entry.diagnostic.group_id))
 9350                    } else {
 9351                        None
 9352                    }
 9353                });
 9354
 9355            if let Some((primary_range, group_id)) = group {
 9356                self.activate_diagnostics(group_id, cx);
 9357                let primary_range = primary_range.to_offset(&buffer);
 9358                if self.active_diagnostics.is_some() {
 9359                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9360                        s.select(vec![Selection {
 9361                            id: selection.id,
 9362                            start: primary_range.start,
 9363                            end: primary_range.start,
 9364                            reversed: false,
 9365                            goal: SelectionGoal::None,
 9366                        }]);
 9367                    });
 9368                    self.refresh_inline_completion(false, true, cx);
 9369                }
 9370                break;
 9371            } else {
 9372                // Cycle around to the start of the buffer, potentially moving back to the start of
 9373                // the currently active diagnostic.
 9374                active_primary_range.take();
 9375                if direction == Direction::Prev {
 9376                    if search_start == buffer.len() {
 9377                        break;
 9378                    } else {
 9379                        search_start = buffer.len();
 9380                    }
 9381                } else if search_start == 0 {
 9382                    break;
 9383                } else {
 9384                    search_start = 0;
 9385                }
 9386            }
 9387        }
 9388    }
 9389
 9390    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9391        let snapshot = self.snapshot(cx);
 9392        let selection = self.selections.newest::<Point>(cx);
 9393        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9394    }
 9395
 9396    fn go_to_hunk_after_position(
 9397        &mut self,
 9398        snapshot: &EditorSnapshot,
 9399        position: Point,
 9400        cx: &mut ViewContext<Editor>,
 9401    ) -> Option<MultiBufferDiffHunk> {
 9402        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9403            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9404                snapshot,
 9405                position,
 9406                ix > 0,
 9407                snapshot.diff_map.diff_hunks_in_range(
 9408                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9409                    &snapshot.buffer_snapshot,
 9410                ),
 9411                cx,
 9412            ) {
 9413                return Some(hunk);
 9414            }
 9415        }
 9416        None
 9417    }
 9418
 9419    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9420        let snapshot = self.snapshot(cx);
 9421        let selection = self.selections.newest::<Point>(cx);
 9422        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9423    }
 9424
 9425    fn go_to_hunk_before_position(
 9426        &mut self,
 9427        snapshot: &EditorSnapshot,
 9428        position: Point,
 9429        cx: &mut ViewContext<Editor>,
 9430    ) -> Option<MultiBufferDiffHunk> {
 9431        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9432            .into_iter()
 9433            .enumerate()
 9434        {
 9435            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9436                snapshot,
 9437                position,
 9438                ix > 0,
 9439                snapshot
 9440                    .diff_map
 9441                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9442                cx,
 9443            ) {
 9444                return Some(hunk);
 9445            }
 9446        }
 9447        None
 9448    }
 9449
 9450    fn go_to_next_hunk_in_direction(
 9451        &mut self,
 9452        snapshot: &DisplaySnapshot,
 9453        initial_point: Point,
 9454        is_wrapped: bool,
 9455        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9456        cx: &mut ViewContext<Editor>,
 9457    ) -> Option<MultiBufferDiffHunk> {
 9458        let display_point = initial_point.to_display_point(snapshot);
 9459        let mut hunks = hunks
 9460            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9461            .filter(|(display_hunk, _)| {
 9462                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9463            })
 9464            .dedup();
 9465
 9466        if let Some((display_hunk, hunk)) = hunks.next() {
 9467            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9468                let row = display_hunk.start_display_row();
 9469                let point = DisplayPoint::new(row, 0);
 9470                s.select_display_ranges([point..point]);
 9471            });
 9472
 9473            Some(hunk)
 9474        } else {
 9475            None
 9476        }
 9477    }
 9478
 9479    pub fn go_to_definition(
 9480        &mut self,
 9481        _: &GoToDefinition,
 9482        cx: &mut ViewContext<Self>,
 9483    ) -> Task<Result<Navigated>> {
 9484        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9485        cx.spawn(|editor, mut cx| async move {
 9486            if definition.await? == Navigated::Yes {
 9487                return Ok(Navigated::Yes);
 9488            }
 9489            match editor.update(&mut cx, |editor, cx| {
 9490                editor.find_all_references(&FindAllReferences, cx)
 9491            })? {
 9492                Some(references) => references.await,
 9493                None => Ok(Navigated::No),
 9494            }
 9495        })
 9496    }
 9497
 9498    pub fn go_to_declaration(
 9499        &mut self,
 9500        _: &GoToDeclaration,
 9501        cx: &mut ViewContext<Self>,
 9502    ) -> Task<Result<Navigated>> {
 9503        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9504    }
 9505
 9506    pub fn go_to_declaration_split(
 9507        &mut self,
 9508        _: &GoToDeclaration,
 9509        cx: &mut ViewContext<Self>,
 9510    ) -> Task<Result<Navigated>> {
 9511        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9512    }
 9513
 9514    pub fn go_to_implementation(
 9515        &mut self,
 9516        _: &GoToImplementation,
 9517        cx: &mut ViewContext<Self>,
 9518    ) -> Task<Result<Navigated>> {
 9519        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9520    }
 9521
 9522    pub fn go_to_implementation_split(
 9523        &mut self,
 9524        _: &GoToImplementationSplit,
 9525        cx: &mut ViewContext<Self>,
 9526    ) -> Task<Result<Navigated>> {
 9527        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9528    }
 9529
 9530    pub fn go_to_type_definition(
 9531        &mut self,
 9532        _: &GoToTypeDefinition,
 9533        cx: &mut ViewContext<Self>,
 9534    ) -> Task<Result<Navigated>> {
 9535        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9536    }
 9537
 9538    pub fn go_to_definition_split(
 9539        &mut self,
 9540        _: &GoToDefinitionSplit,
 9541        cx: &mut ViewContext<Self>,
 9542    ) -> Task<Result<Navigated>> {
 9543        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9544    }
 9545
 9546    pub fn go_to_type_definition_split(
 9547        &mut self,
 9548        _: &GoToTypeDefinitionSplit,
 9549        cx: &mut ViewContext<Self>,
 9550    ) -> Task<Result<Navigated>> {
 9551        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9552    }
 9553
 9554    fn go_to_definition_of_kind(
 9555        &mut self,
 9556        kind: GotoDefinitionKind,
 9557        split: bool,
 9558        cx: &mut ViewContext<Self>,
 9559    ) -> Task<Result<Navigated>> {
 9560        let Some(provider) = self.semantics_provider.clone() else {
 9561            return Task::ready(Ok(Navigated::No));
 9562        };
 9563        let head = self.selections.newest::<usize>(cx).head();
 9564        let buffer = self.buffer.read(cx);
 9565        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9566            text_anchor
 9567        } else {
 9568            return Task::ready(Ok(Navigated::No));
 9569        };
 9570
 9571        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9572            return Task::ready(Ok(Navigated::No));
 9573        };
 9574
 9575        cx.spawn(|editor, mut cx| async move {
 9576            let definitions = definitions.await?;
 9577            let navigated = editor
 9578                .update(&mut cx, |editor, cx| {
 9579                    editor.navigate_to_hover_links(
 9580                        Some(kind),
 9581                        definitions
 9582                            .into_iter()
 9583                            .filter(|location| {
 9584                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9585                            })
 9586                            .map(HoverLink::Text)
 9587                            .collect::<Vec<_>>(),
 9588                        split,
 9589                        cx,
 9590                    )
 9591                })?
 9592                .await?;
 9593            anyhow::Ok(navigated)
 9594        })
 9595    }
 9596
 9597    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9598        let selection = self.selections.newest_anchor();
 9599        let head = selection.head();
 9600        let tail = selection.tail();
 9601
 9602        let Some((buffer, start_position)) =
 9603            self.buffer.read(cx).text_anchor_for_position(head, cx)
 9604        else {
 9605            return;
 9606        };
 9607
 9608        let end_position = if head != tail {
 9609            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
 9610                return;
 9611            };
 9612            Some(pos)
 9613        } else {
 9614            None
 9615        };
 9616
 9617        let url_finder = cx.spawn(|editor, mut cx| async move {
 9618            let url = if let Some(end_pos) = end_position {
 9619                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
 9620            } else {
 9621                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
 9622            };
 9623
 9624            if let Some(url) = url {
 9625                editor.update(&mut cx, |_, cx| {
 9626                    cx.open_url(&url);
 9627                })
 9628            } else {
 9629                Ok(())
 9630            }
 9631        });
 9632
 9633        url_finder.detach();
 9634    }
 9635
 9636    pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
 9637        let Some(workspace) = self.workspace() else {
 9638            return;
 9639        };
 9640
 9641        let position = self.selections.newest_anchor().head();
 9642
 9643        let Some((buffer, buffer_position)) =
 9644            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9645        else {
 9646            return;
 9647        };
 9648
 9649        let project = self.project.clone();
 9650
 9651        cx.spawn(|_, mut cx| async move {
 9652            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9653
 9654            if let Some((_, path)) = result {
 9655                workspace
 9656                    .update(&mut cx, |workspace, cx| {
 9657                        workspace.open_resolved_path(path, cx)
 9658                    })?
 9659                    .await?;
 9660            }
 9661            anyhow::Ok(())
 9662        })
 9663        .detach();
 9664    }
 9665
 9666    pub(crate) fn navigate_to_hover_links(
 9667        &mut self,
 9668        kind: Option<GotoDefinitionKind>,
 9669        mut definitions: Vec<HoverLink>,
 9670        split: bool,
 9671        cx: &mut ViewContext<Editor>,
 9672    ) -> Task<Result<Navigated>> {
 9673        // If there is one definition, just open it directly
 9674        if definitions.len() == 1 {
 9675            let definition = definitions.pop().unwrap();
 9676
 9677            enum TargetTaskResult {
 9678                Location(Option<Location>),
 9679                AlreadyNavigated,
 9680            }
 9681
 9682            let target_task = match definition {
 9683                HoverLink::Text(link) => {
 9684                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9685                }
 9686                HoverLink::InlayHint(lsp_location, server_id) => {
 9687                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9688                    cx.background_executor().spawn(async move {
 9689                        let location = computation.await?;
 9690                        Ok(TargetTaskResult::Location(location))
 9691                    })
 9692                }
 9693                HoverLink::Url(url) => {
 9694                    cx.open_url(&url);
 9695                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9696                }
 9697                HoverLink::File(path) => {
 9698                    if let Some(workspace) = self.workspace() {
 9699                        cx.spawn(|_, mut cx| async move {
 9700                            workspace
 9701                                .update(&mut cx, |workspace, cx| {
 9702                                    workspace.open_resolved_path(path, cx)
 9703                                })?
 9704                                .await
 9705                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9706                        })
 9707                    } else {
 9708                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9709                    }
 9710                }
 9711            };
 9712            cx.spawn(|editor, mut cx| async move {
 9713                let target = match target_task.await.context("target resolution task")? {
 9714                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9715                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9716                    TargetTaskResult::Location(Some(target)) => target,
 9717                };
 9718
 9719                editor.update(&mut cx, |editor, cx| {
 9720                    let Some(workspace) = editor.workspace() else {
 9721                        return Navigated::No;
 9722                    };
 9723                    let pane = workspace.read(cx).active_pane().clone();
 9724
 9725                    let range = target.range.to_offset(target.buffer.read(cx));
 9726                    let range = editor.range_for_match(&range);
 9727
 9728                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9729                        let buffer = target.buffer.read(cx);
 9730                        let range = check_multiline_range(buffer, range);
 9731                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9732                            s.select_ranges([range]);
 9733                        });
 9734                    } else {
 9735                        cx.window_context().defer(move |cx| {
 9736                            let target_editor: View<Self> =
 9737                                workspace.update(cx, |workspace, cx| {
 9738                                    let pane = if split {
 9739                                        workspace.adjacent_pane(cx)
 9740                                    } else {
 9741                                        workspace.active_pane().clone()
 9742                                    };
 9743
 9744                                    workspace.open_project_item(
 9745                                        pane,
 9746                                        target.buffer.clone(),
 9747                                        true,
 9748                                        true,
 9749                                        cx,
 9750                                    )
 9751                                });
 9752                            target_editor.update(cx, |target_editor, cx| {
 9753                                // When selecting a definition in a different buffer, disable the nav history
 9754                                // to avoid creating a history entry at the previous cursor location.
 9755                                pane.update(cx, |pane, _| pane.disable_history());
 9756                                let buffer = target.buffer.read(cx);
 9757                                let range = check_multiline_range(buffer, range);
 9758                                target_editor.change_selections(
 9759                                    Some(Autoscroll::focused()),
 9760                                    cx,
 9761                                    |s| {
 9762                                        s.select_ranges([range]);
 9763                                    },
 9764                                );
 9765                                pane.update(cx, |pane, _| pane.enable_history());
 9766                            });
 9767                        });
 9768                    }
 9769                    Navigated::Yes
 9770                })
 9771            })
 9772        } else if !definitions.is_empty() {
 9773            cx.spawn(|editor, mut cx| async move {
 9774                let (title, location_tasks, workspace) = editor
 9775                    .update(&mut cx, |editor, cx| {
 9776                        let tab_kind = match kind {
 9777                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9778                            _ => "Definitions",
 9779                        };
 9780                        let title = definitions
 9781                            .iter()
 9782                            .find_map(|definition| match definition {
 9783                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9784                                    let buffer = origin.buffer.read(cx);
 9785                                    format!(
 9786                                        "{} for {}",
 9787                                        tab_kind,
 9788                                        buffer
 9789                                            .text_for_range(origin.range.clone())
 9790                                            .collect::<String>()
 9791                                    )
 9792                                }),
 9793                                HoverLink::InlayHint(_, _) => None,
 9794                                HoverLink::Url(_) => None,
 9795                                HoverLink::File(_) => None,
 9796                            })
 9797                            .unwrap_or(tab_kind.to_string());
 9798                        let location_tasks = definitions
 9799                            .into_iter()
 9800                            .map(|definition| match definition {
 9801                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
 9802                                HoverLink::InlayHint(lsp_location, server_id) => {
 9803                                    editor.compute_target_location(lsp_location, server_id, cx)
 9804                                }
 9805                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9806                                HoverLink::File(_) => Task::ready(Ok(None)),
 9807                            })
 9808                            .collect::<Vec<_>>();
 9809                        (title, location_tasks, editor.workspace().clone())
 9810                    })
 9811                    .context("location tasks preparation")?;
 9812
 9813                let locations = future::join_all(location_tasks)
 9814                    .await
 9815                    .into_iter()
 9816                    .filter_map(|location| location.transpose())
 9817                    .collect::<Result<_>>()
 9818                    .context("location tasks")?;
 9819
 9820                let Some(workspace) = workspace else {
 9821                    return Ok(Navigated::No);
 9822                };
 9823                let opened = workspace
 9824                    .update(&mut cx, |workspace, cx| {
 9825                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9826                    })
 9827                    .ok();
 9828
 9829                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9830            })
 9831        } else {
 9832            Task::ready(Ok(Navigated::No))
 9833        }
 9834    }
 9835
 9836    fn compute_target_location(
 9837        &self,
 9838        lsp_location: lsp::Location,
 9839        server_id: LanguageServerId,
 9840        cx: &mut ViewContext<Self>,
 9841    ) -> Task<anyhow::Result<Option<Location>>> {
 9842        let Some(project) = self.project.clone() else {
 9843            return Task::ready(Ok(None));
 9844        };
 9845
 9846        cx.spawn(move |editor, mut cx| async move {
 9847            let location_task = editor.update(&mut cx, |_, cx| {
 9848                project.update(cx, |project, cx| {
 9849                    let language_server_name = project
 9850                        .language_server_statuses(cx)
 9851                        .find(|(id, _)| server_id == *id)
 9852                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9853                    language_server_name.map(|language_server_name| {
 9854                        project.open_local_buffer_via_lsp(
 9855                            lsp_location.uri.clone(),
 9856                            server_id,
 9857                            language_server_name,
 9858                            cx,
 9859                        )
 9860                    })
 9861                })
 9862            })?;
 9863            let location = match location_task {
 9864                Some(task) => Some({
 9865                    let target_buffer_handle = task.await.context("open local buffer")?;
 9866                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9867                        let target_start = target_buffer
 9868                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9869                        let target_end = target_buffer
 9870                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9871                        target_buffer.anchor_after(target_start)
 9872                            ..target_buffer.anchor_before(target_end)
 9873                    })?;
 9874                    Location {
 9875                        buffer: target_buffer_handle,
 9876                        range,
 9877                    }
 9878                }),
 9879                None => None,
 9880            };
 9881            Ok(location)
 9882        })
 9883    }
 9884
 9885    pub fn find_all_references(
 9886        &mut self,
 9887        _: &FindAllReferences,
 9888        cx: &mut ViewContext<Self>,
 9889    ) -> Option<Task<Result<Navigated>>> {
 9890        let selection = self.selections.newest::<usize>(cx);
 9891        let multi_buffer = self.buffer.read(cx);
 9892        let head = selection.head();
 9893
 9894        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9895        let head_anchor = multi_buffer_snapshot.anchor_at(
 9896            head,
 9897            if head < selection.tail() {
 9898                Bias::Right
 9899            } else {
 9900                Bias::Left
 9901            },
 9902        );
 9903
 9904        match self
 9905            .find_all_references_task_sources
 9906            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9907        {
 9908            Ok(_) => {
 9909                log::info!(
 9910                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9911                );
 9912                return None;
 9913            }
 9914            Err(i) => {
 9915                self.find_all_references_task_sources.insert(i, head_anchor);
 9916            }
 9917        }
 9918
 9919        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9920        let workspace = self.workspace()?;
 9921        let project = workspace.read(cx).project().clone();
 9922        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9923        Some(cx.spawn(|editor, mut cx| async move {
 9924            let _cleanup = defer({
 9925                let mut cx = cx.clone();
 9926                move || {
 9927                    let _ = editor.update(&mut cx, |editor, _| {
 9928                        if let Ok(i) =
 9929                            editor
 9930                                .find_all_references_task_sources
 9931                                .binary_search_by(|anchor| {
 9932                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9933                                })
 9934                        {
 9935                            editor.find_all_references_task_sources.remove(i);
 9936                        }
 9937                    });
 9938                }
 9939            });
 9940
 9941            let locations = references.await?;
 9942            if locations.is_empty() {
 9943                return anyhow::Ok(Navigated::No);
 9944            }
 9945
 9946            workspace.update(&mut cx, |workspace, cx| {
 9947                let title = locations
 9948                    .first()
 9949                    .as_ref()
 9950                    .map(|location| {
 9951                        let buffer = location.buffer.read(cx);
 9952                        format!(
 9953                            "References to `{}`",
 9954                            buffer
 9955                                .text_for_range(location.range.clone())
 9956                                .collect::<String>()
 9957                        )
 9958                    })
 9959                    .unwrap();
 9960                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9961                Navigated::Yes
 9962            })
 9963        }))
 9964    }
 9965
 9966    /// Opens a multibuffer with the given project locations in it
 9967    pub fn open_locations_in_multibuffer(
 9968        workspace: &mut Workspace,
 9969        mut locations: Vec<Location>,
 9970        title: String,
 9971        split: bool,
 9972        cx: &mut ViewContext<Workspace>,
 9973    ) {
 9974        // If there are multiple definitions, open them in a multibuffer
 9975        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9976        let mut locations = locations.into_iter().peekable();
 9977        let mut ranges_to_highlight = Vec::new();
 9978        let capability = workspace.project().read(cx).capability();
 9979
 9980        let excerpt_buffer = cx.new_model(|cx| {
 9981            let mut multibuffer = MultiBuffer::new(capability);
 9982            while let Some(location) = locations.next() {
 9983                let buffer = location.buffer.read(cx);
 9984                let mut ranges_for_buffer = Vec::new();
 9985                let range = location.range.to_offset(buffer);
 9986                ranges_for_buffer.push(range.clone());
 9987
 9988                while let Some(next_location) = locations.peek() {
 9989                    if next_location.buffer == location.buffer {
 9990                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9991                        locations.next();
 9992                    } else {
 9993                        break;
 9994                    }
 9995                }
 9996
 9997                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9998                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9999                    location.buffer.clone(),
10000                    ranges_for_buffer,
10001                    DEFAULT_MULTIBUFFER_CONTEXT,
10002                    cx,
10003                ))
10004            }
10005
10006            multibuffer.with_title(title)
10007        });
10008
10009        let editor = cx.new_view(|cx| {
10010            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10011        });
10012        editor.update(cx, |editor, cx| {
10013            if let Some(first_range) = ranges_to_highlight.first() {
10014                editor.change_selections(None, cx, |selections| {
10015                    selections.clear_disjoint();
10016                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10017                });
10018            }
10019            editor.highlight_background::<Self>(
10020                &ranges_to_highlight,
10021                |theme| theme.editor_highlighted_line_background,
10022                cx,
10023            );
10024            editor.register_buffers_with_language_servers(cx);
10025        });
10026
10027        let item = Box::new(editor);
10028        let item_id = item.item_id();
10029
10030        if split {
10031            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10032        } else {
10033            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10034                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10035                    pane.close_current_preview_item(cx)
10036                } else {
10037                    None
10038                }
10039            });
10040            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10041        }
10042        workspace.active_pane().update(cx, |pane, cx| {
10043            pane.set_preview_item_id(Some(item_id), cx);
10044        });
10045    }
10046
10047    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10048        use language::ToOffset as _;
10049
10050        let provider = self.semantics_provider.clone()?;
10051        let selection = self.selections.newest_anchor().clone();
10052        let (cursor_buffer, cursor_buffer_position) = self
10053            .buffer
10054            .read(cx)
10055            .text_anchor_for_position(selection.head(), cx)?;
10056        let (tail_buffer, cursor_buffer_position_end) = self
10057            .buffer
10058            .read(cx)
10059            .text_anchor_for_position(selection.tail(), cx)?;
10060        if tail_buffer != cursor_buffer {
10061            return None;
10062        }
10063
10064        let snapshot = cursor_buffer.read(cx).snapshot();
10065        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10066        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10067        let prepare_rename = provider
10068            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10069            .unwrap_or_else(|| Task::ready(Ok(None)));
10070        drop(snapshot);
10071
10072        Some(cx.spawn(|this, mut cx| async move {
10073            let rename_range = if let Some(range) = prepare_rename.await? {
10074                Some(range)
10075            } else {
10076                this.update(&mut cx, |this, cx| {
10077                    let buffer = this.buffer.read(cx).snapshot(cx);
10078                    let mut buffer_highlights = this
10079                        .document_highlights_for_position(selection.head(), &buffer)
10080                        .filter(|highlight| {
10081                            highlight.start.excerpt_id == selection.head().excerpt_id
10082                                && highlight.end.excerpt_id == selection.head().excerpt_id
10083                        });
10084                    buffer_highlights
10085                        .next()
10086                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10087                })?
10088            };
10089            if let Some(rename_range) = rename_range {
10090                this.update(&mut cx, |this, cx| {
10091                    let snapshot = cursor_buffer.read(cx).snapshot();
10092                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10093                    let cursor_offset_in_rename_range =
10094                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10095                    let cursor_offset_in_rename_range_end =
10096                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10097
10098                    this.take_rename(false, cx);
10099                    let buffer = this.buffer.read(cx).read(cx);
10100                    let cursor_offset = selection.head().to_offset(&buffer);
10101                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10102                    let rename_end = rename_start + rename_buffer_range.len();
10103                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10104                    let mut old_highlight_id = None;
10105                    let old_name: Arc<str> = buffer
10106                        .chunks(rename_start..rename_end, true)
10107                        .map(|chunk| {
10108                            if old_highlight_id.is_none() {
10109                                old_highlight_id = chunk.syntax_highlight_id;
10110                            }
10111                            chunk.text
10112                        })
10113                        .collect::<String>()
10114                        .into();
10115
10116                    drop(buffer);
10117
10118                    // Position the selection in the rename editor so that it matches the current selection.
10119                    this.show_local_selections = false;
10120                    let rename_editor = cx.new_view(|cx| {
10121                        let mut editor = Editor::single_line(cx);
10122                        editor.buffer.update(cx, |buffer, cx| {
10123                            buffer.edit([(0..0, old_name.clone())], None, cx)
10124                        });
10125                        let rename_selection_range = match cursor_offset_in_rename_range
10126                            .cmp(&cursor_offset_in_rename_range_end)
10127                        {
10128                            Ordering::Equal => {
10129                                editor.select_all(&SelectAll, cx);
10130                                return editor;
10131                            }
10132                            Ordering::Less => {
10133                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10134                            }
10135                            Ordering::Greater => {
10136                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10137                            }
10138                        };
10139                        if rename_selection_range.end > old_name.len() {
10140                            editor.select_all(&SelectAll, cx);
10141                        } else {
10142                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10143                                s.select_ranges([rename_selection_range]);
10144                            });
10145                        }
10146                        editor
10147                    });
10148                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10149                        if e == &EditorEvent::Focused {
10150                            cx.emit(EditorEvent::FocusedIn)
10151                        }
10152                    })
10153                    .detach();
10154
10155                    let write_highlights =
10156                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10157                    let read_highlights =
10158                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10159                    let ranges = write_highlights
10160                        .iter()
10161                        .flat_map(|(_, ranges)| ranges.iter())
10162                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10163                        .cloned()
10164                        .collect();
10165
10166                    this.highlight_text::<Rename>(
10167                        ranges,
10168                        HighlightStyle {
10169                            fade_out: Some(0.6),
10170                            ..Default::default()
10171                        },
10172                        cx,
10173                    );
10174                    let rename_focus_handle = rename_editor.focus_handle(cx);
10175                    cx.focus(&rename_focus_handle);
10176                    let block_id = this.insert_blocks(
10177                        [BlockProperties {
10178                            style: BlockStyle::Flex,
10179                            placement: BlockPlacement::Below(range.start),
10180                            height: 1,
10181                            render: Arc::new({
10182                                let rename_editor = rename_editor.clone();
10183                                move |cx: &mut BlockContext| {
10184                                    let mut text_style = cx.editor_style.text.clone();
10185                                    if let Some(highlight_style) = old_highlight_id
10186                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10187                                    {
10188                                        text_style = text_style.highlight(highlight_style);
10189                                    }
10190                                    div()
10191                                        .block_mouse_down()
10192                                        .pl(cx.anchor_x)
10193                                        .child(EditorElement::new(
10194                                            &rename_editor,
10195                                            EditorStyle {
10196                                                background: cx.theme().system().transparent,
10197                                                local_player: cx.editor_style.local_player,
10198                                                text: text_style,
10199                                                scrollbar_width: cx.editor_style.scrollbar_width,
10200                                                syntax: cx.editor_style.syntax.clone(),
10201                                                status: cx.editor_style.status.clone(),
10202                                                inlay_hints_style: HighlightStyle {
10203                                                    font_weight: Some(FontWeight::BOLD),
10204                                                    ..make_inlay_hints_style(cx)
10205                                                },
10206                                                inline_completion_styles: make_suggestion_styles(
10207                                                    cx,
10208                                                ),
10209                                                ..EditorStyle::default()
10210                                            },
10211                                        ))
10212                                        .into_any_element()
10213                                }
10214                            }),
10215                            priority: 0,
10216                        }],
10217                        Some(Autoscroll::fit()),
10218                        cx,
10219                    )[0];
10220                    this.pending_rename = Some(RenameState {
10221                        range,
10222                        old_name,
10223                        editor: rename_editor,
10224                        block_id,
10225                    });
10226                })?;
10227            }
10228
10229            Ok(())
10230        }))
10231    }
10232
10233    pub fn confirm_rename(
10234        &mut self,
10235        _: &ConfirmRename,
10236        cx: &mut ViewContext<Self>,
10237    ) -> Option<Task<Result<()>>> {
10238        let rename = self.take_rename(false, cx)?;
10239        let workspace = self.workspace()?.downgrade();
10240        let (buffer, start) = self
10241            .buffer
10242            .read(cx)
10243            .text_anchor_for_position(rename.range.start, cx)?;
10244        let (end_buffer, _) = self
10245            .buffer
10246            .read(cx)
10247            .text_anchor_for_position(rename.range.end, cx)?;
10248        if buffer != end_buffer {
10249            return None;
10250        }
10251
10252        let old_name = rename.old_name;
10253        let new_name = rename.editor.read(cx).text(cx);
10254
10255        let rename = self.semantics_provider.as_ref()?.perform_rename(
10256            &buffer,
10257            start,
10258            new_name.clone(),
10259            cx,
10260        )?;
10261
10262        Some(cx.spawn(|editor, mut cx| async move {
10263            let project_transaction = rename.await?;
10264            Self::open_project_transaction(
10265                &editor,
10266                workspace,
10267                project_transaction,
10268                format!("Rename: {}{}", old_name, new_name),
10269                cx.clone(),
10270            )
10271            .await?;
10272
10273            editor.update(&mut cx, |editor, cx| {
10274                editor.refresh_document_highlights(cx);
10275            })?;
10276            Ok(())
10277        }))
10278    }
10279
10280    fn take_rename(
10281        &mut self,
10282        moving_cursor: bool,
10283        cx: &mut ViewContext<Self>,
10284    ) -> Option<RenameState> {
10285        let rename = self.pending_rename.take()?;
10286        if rename.editor.focus_handle(cx).is_focused(cx) {
10287            cx.focus(&self.focus_handle);
10288        }
10289
10290        self.remove_blocks(
10291            [rename.block_id].into_iter().collect(),
10292            Some(Autoscroll::fit()),
10293            cx,
10294        );
10295        self.clear_highlights::<Rename>(cx);
10296        self.show_local_selections = true;
10297
10298        if moving_cursor {
10299            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10300                editor.selections.newest::<usize>(cx).head()
10301            });
10302
10303            // Update the selection to match the position of the selection inside
10304            // the rename editor.
10305            let snapshot = self.buffer.read(cx).read(cx);
10306            let rename_range = rename.range.to_offset(&snapshot);
10307            let cursor_in_editor = snapshot
10308                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10309                .min(rename_range.end);
10310            drop(snapshot);
10311
10312            self.change_selections(None, cx, |s| {
10313                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10314            });
10315        } else {
10316            self.refresh_document_highlights(cx);
10317        }
10318
10319        Some(rename)
10320    }
10321
10322    pub fn pending_rename(&self) -> Option<&RenameState> {
10323        self.pending_rename.as_ref()
10324    }
10325
10326    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10327        let project = match &self.project {
10328            Some(project) => project.clone(),
10329            None => return None,
10330        };
10331
10332        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffers, cx))
10333    }
10334
10335    fn format_selections(
10336        &mut self,
10337        _: &FormatSelections,
10338        cx: &mut ViewContext<Self>,
10339    ) -> Option<Task<Result<()>>> {
10340        let project = match &self.project {
10341            Some(project) => project.clone(),
10342            None => return None,
10343        };
10344
10345        let ranges = self
10346            .selections
10347            .all_adjusted(cx)
10348            .into_iter()
10349            .map(|selection| selection.range())
10350            .collect_vec();
10351
10352        Some(self.perform_format(
10353            project,
10354            FormatTrigger::Manual,
10355            FormatTarget::Ranges(ranges),
10356            cx,
10357        ))
10358    }
10359
10360    fn perform_format(
10361        &mut self,
10362        project: Model<Project>,
10363        trigger: FormatTrigger,
10364        target: FormatTarget,
10365        cx: &mut ViewContext<Self>,
10366    ) -> Task<Result<()>> {
10367        let buffer = self.buffer.clone();
10368        let (buffers, target) = match target {
10369            FormatTarget::Buffers => {
10370                let mut buffers = buffer.read(cx).all_buffers();
10371                if trigger == FormatTrigger::Save {
10372                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
10373                }
10374                (buffers, LspFormatTarget::Buffers)
10375            }
10376            FormatTarget::Ranges(selection_ranges) => {
10377                let multi_buffer = buffer.read(cx);
10378                let snapshot = multi_buffer.read(cx);
10379                let mut buffers = HashSet::default();
10380                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10381                    BTreeMap::new();
10382                for selection_range in selection_ranges {
10383                    for (excerpt, buffer_range) in snapshot.range_to_buffer_ranges(selection_range)
10384                    {
10385                        let buffer_id = excerpt.buffer_id();
10386                        let start = excerpt.buffer().anchor_before(buffer_range.start);
10387                        let end = excerpt.buffer().anchor_after(buffer_range.end);
10388                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10389                        buffer_id_to_ranges
10390                            .entry(buffer_id)
10391                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10392                            .or_insert_with(|| vec![start..end]);
10393                    }
10394                }
10395                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10396            }
10397        };
10398
10399        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10400        let format = project.update(cx, |project, cx| {
10401            project.format(buffers, target, true, trigger, cx)
10402        });
10403
10404        cx.spawn(|_, mut cx| async move {
10405            let transaction = futures::select_biased! {
10406                () = timeout => {
10407                    log::warn!("timed out waiting for formatting");
10408                    None
10409                }
10410                transaction = format.log_err().fuse() => transaction,
10411            };
10412
10413            buffer
10414                .update(&mut cx, |buffer, cx| {
10415                    if let Some(transaction) = transaction {
10416                        if !buffer.is_singleton() {
10417                            buffer.push_transaction(&transaction.0, cx);
10418                        }
10419                    }
10420
10421                    cx.notify();
10422                })
10423                .ok();
10424
10425            Ok(())
10426        })
10427    }
10428
10429    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10430        if let Some(project) = self.project.clone() {
10431            self.buffer.update(cx, |multi_buffer, cx| {
10432                project.update(cx, |project, cx| {
10433                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10434                });
10435            })
10436        }
10437    }
10438
10439    fn cancel_language_server_work(
10440        &mut self,
10441        _: &actions::CancelLanguageServerWork,
10442        cx: &mut ViewContext<Self>,
10443    ) {
10444        if let Some(project) = self.project.clone() {
10445            self.buffer.update(cx, |multi_buffer, cx| {
10446                project.update(cx, |project, cx| {
10447                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10448                });
10449            })
10450        }
10451    }
10452
10453    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10454        cx.show_character_palette();
10455    }
10456
10457    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10458        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10459            let buffer = self.buffer.read(cx).snapshot(cx);
10460            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10461            let is_valid = buffer
10462                .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10463                .any(|entry| {
10464                    let range = entry.range.to_offset(&buffer);
10465                    entry.diagnostic.is_primary
10466                        && !range.is_empty()
10467                        && range.start == primary_range_start
10468                        && entry.diagnostic.message == active_diagnostics.primary_message
10469                });
10470
10471            if is_valid != active_diagnostics.is_valid {
10472                active_diagnostics.is_valid = is_valid;
10473                let mut new_styles = HashMap::default();
10474                for (block_id, diagnostic) in &active_diagnostics.blocks {
10475                    new_styles.insert(
10476                        *block_id,
10477                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10478                    );
10479                }
10480                self.display_map.update(cx, |display_map, _cx| {
10481                    display_map.replace_blocks(new_styles)
10482                });
10483            }
10484        }
10485    }
10486
10487    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10488        self.dismiss_diagnostics(cx);
10489        let snapshot = self.snapshot(cx);
10490        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10491            let buffer = self.buffer.read(cx).snapshot(cx);
10492
10493            let mut primary_range = None;
10494            let mut primary_message = None;
10495            let mut group_end = Point::zero();
10496            let diagnostic_group = buffer
10497                .diagnostic_group(group_id)
10498                .filter_map(|entry| {
10499                    let start = entry.range.start.to_point(&buffer);
10500                    let end = entry.range.end.to_point(&buffer);
10501                    if snapshot.is_line_folded(MultiBufferRow(start.row))
10502                        && (start.row == end.row
10503                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
10504                    {
10505                        return None;
10506                    }
10507                    if end > group_end {
10508                        group_end = end;
10509                    }
10510                    if entry.diagnostic.is_primary {
10511                        primary_range = Some(entry.range.clone());
10512                        primary_message = Some(entry.diagnostic.message.clone());
10513                    }
10514                    Some(entry)
10515                })
10516                .collect::<Vec<_>>();
10517            let primary_range = primary_range?;
10518            let primary_message = primary_message?;
10519
10520            let blocks = display_map
10521                .insert_blocks(
10522                    diagnostic_group.iter().map(|entry| {
10523                        let diagnostic = entry.diagnostic.clone();
10524                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10525                        BlockProperties {
10526                            style: BlockStyle::Fixed,
10527                            placement: BlockPlacement::Below(
10528                                buffer.anchor_after(entry.range.start),
10529                            ),
10530                            height: message_height,
10531                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10532                            priority: 0,
10533                        }
10534                    }),
10535                    cx,
10536                )
10537                .into_iter()
10538                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10539                .collect();
10540
10541            Some(ActiveDiagnosticGroup {
10542                primary_range,
10543                primary_message,
10544                group_id,
10545                blocks,
10546                is_valid: true,
10547            })
10548        });
10549    }
10550
10551    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10552        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10553            self.display_map.update(cx, |display_map, cx| {
10554                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10555            });
10556            cx.notify();
10557        }
10558    }
10559
10560    pub fn set_selections_from_remote(
10561        &mut self,
10562        selections: Vec<Selection<Anchor>>,
10563        pending_selection: Option<Selection<Anchor>>,
10564        cx: &mut ViewContext<Self>,
10565    ) {
10566        let old_cursor_position = self.selections.newest_anchor().head();
10567        self.selections.change_with(cx, |s| {
10568            s.select_anchors(selections);
10569            if let Some(pending_selection) = pending_selection {
10570                s.set_pending(pending_selection, SelectMode::Character);
10571            } else {
10572                s.clear_pending();
10573            }
10574        });
10575        self.selections_did_change(false, &old_cursor_position, true, cx);
10576    }
10577
10578    fn push_to_selection_history(&mut self) {
10579        self.selection_history.push(SelectionHistoryEntry {
10580            selections: self.selections.disjoint_anchors(),
10581            select_next_state: self.select_next_state.clone(),
10582            select_prev_state: self.select_prev_state.clone(),
10583            add_selections_state: self.add_selections_state.clone(),
10584        });
10585    }
10586
10587    pub fn transact(
10588        &mut self,
10589        cx: &mut ViewContext<Self>,
10590        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10591    ) -> Option<TransactionId> {
10592        self.start_transaction_at(Instant::now(), cx);
10593        update(self, cx);
10594        self.end_transaction_at(Instant::now(), cx)
10595    }
10596
10597    pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10598        self.end_selection(cx);
10599        if let Some(tx_id) = self
10600            .buffer
10601            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10602        {
10603            self.selection_history
10604                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10605            cx.emit(EditorEvent::TransactionBegun {
10606                transaction_id: tx_id,
10607            })
10608        }
10609    }
10610
10611    pub fn end_transaction_at(
10612        &mut self,
10613        now: Instant,
10614        cx: &mut ViewContext<Self>,
10615    ) -> Option<TransactionId> {
10616        if let Some(transaction_id) = self
10617            .buffer
10618            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10619        {
10620            if let Some((_, end_selections)) =
10621                self.selection_history.transaction_mut(transaction_id)
10622            {
10623                *end_selections = Some(self.selections.disjoint_anchors());
10624            } else {
10625                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10626            }
10627
10628            cx.emit(EditorEvent::Edited { transaction_id });
10629            Some(transaction_id)
10630        } else {
10631            None
10632        }
10633    }
10634
10635    pub fn set_mark(&mut self, _: &actions::SetMark, cx: &mut ViewContext<Self>) {
10636        if self.selection_mark_mode {
10637            self.change_selections(None, cx, |s| {
10638                s.move_with(|_, sel| {
10639                    sel.collapse_to(sel.head(), SelectionGoal::None);
10640                });
10641            })
10642        }
10643        self.selection_mark_mode = true;
10644        cx.notify();
10645    }
10646
10647    pub fn swap_selection_ends(
10648        &mut self,
10649        _: &actions::SwapSelectionEnds,
10650        cx: &mut ViewContext<Self>,
10651    ) {
10652        self.change_selections(None, cx, |s| {
10653            s.move_with(|_, sel| {
10654                if sel.start != sel.end {
10655                    sel.reversed = !sel.reversed
10656                }
10657            });
10658        });
10659        cx.notify();
10660    }
10661
10662    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10663        if self.is_singleton(cx) {
10664            let selection = self.selections.newest::<Point>(cx);
10665
10666            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10667            let range = if selection.is_empty() {
10668                let point = selection.head().to_display_point(&display_map);
10669                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10670                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10671                    .to_point(&display_map);
10672                start..end
10673            } else {
10674                selection.range()
10675            };
10676            if display_map.folds_in_range(range).next().is_some() {
10677                self.unfold_lines(&Default::default(), cx)
10678            } else {
10679                self.fold(&Default::default(), cx)
10680            }
10681        } else {
10682            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10683            let mut toggled_buffers = HashSet::default();
10684            for (_, buffer_snapshot, _) in
10685                multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10686            {
10687                let buffer_id = buffer_snapshot.remote_id();
10688                if toggled_buffers.insert(buffer_id) {
10689                    if self.buffer_folded(buffer_id, cx) {
10690                        self.unfold_buffer(buffer_id, cx);
10691                    } else {
10692                        self.fold_buffer(buffer_id, cx);
10693                    }
10694                }
10695            }
10696        }
10697    }
10698
10699    pub fn toggle_fold_recursive(
10700        &mut self,
10701        _: &actions::ToggleFoldRecursive,
10702        cx: &mut ViewContext<Self>,
10703    ) {
10704        let selection = self.selections.newest::<Point>(cx);
10705
10706        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10707        let range = if selection.is_empty() {
10708            let point = selection.head().to_display_point(&display_map);
10709            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10710            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10711                .to_point(&display_map);
10712            start..end
10713        } else {
10714            selection.range()
10715        };
10716        if display_map.folds_in_range(range).next().is_some() {
10717            self.unfold_recursive(&Default::default(), cx)
10718        } else {
10719            self.fold_recursive(&Default::default(), cx)
10720        }
10721    }
10722
10723    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10724        if self.is_singleton(cx) {
10725            let mut to_fold = Vec::new();
10726            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10727            let selections = self.selections.all_adjusted(cx);
10728
10729            for selection in selections {
10730                let range = selection.range().sorted();
10731                let buffer_start_row = range.start.row;
10732
10733                if range.start.row != range.end.row {
10734                    let mut found = false;
10735                    let mut row = range.start.row;
10736                    while row <= range.end.row {
10737                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10738                        {
10739                            found = true;
10740                            row = crease.range().end.row + 1;
10741                            to_fold.push(crease);
10742                        } else {
10743                            row += 1
10744                        }
10745                    }
10746                    if found {
10747                        continue;
10748                    }
10749                }
10750
10751                for row in (0..=range.start.row).rev() {
10752                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10753                        if crease.range().end.row >= buffer_start_row {
10754                            to_fold.push(crease);
10755                            if row <= range.start.row {
10756                                break;
10757                            }
10758                        }
10759                    }
10760                }
10761            }
10762
10763            self.fold_creases(to_fold, true, cx);
10764        } else {
10765            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10766            let mut folded_buffers = HashSet::default();
10767            for (_, buffer_snapshot, _) in
10768                multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10769            {
10770                let buffer_id = buffer_snapshot.remote_id();
10771                if folded_buffers.insert(buffer_id) {
10772                    self.fold_buffer(buffer_id, cx);
10773                }
10774            }
10775        }
10776    }
10777
10778    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10779        if !self.buffer.read(cx).is_singleton() {
10780            return;
10781        }
10782
10783        let fold_at_level = fold_at.level;
10784        let snapshot = self.buffer.read(cx).snapshot(cx);
10785        let mut to_fold = Vec::new();
10786        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10787
10788        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10789            while start_row < end_row {
10790                match self
10791                    .snapshot(cx)
10792                    .crease_for_buffer_row(MultiBufferRow(start_row))
10793                {
10794                    Some(crease) => {
10795                        let nested_start_row = crease.range().start.row + 1;
10796                        let nested_end_row = crease.range().end.row;
10797
10798                        if current_level < fold_at_level {
10799                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10800                        } else if current_level == fold_at_level {
10801                            to_fold.push(crease);
10802                        }
10803
10804                        start_row = nested_end_row + 1;
10805                    }
10806                    None => start_row += 1,
10807                }
10808            }
10809        }
10810
10811        self.fold_creases(to_fold, true, cx);
10812    }
10813
10814    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10815        if self.buffer.read(cx).is_singleton() {
10816            let mut fold_ranges = Vec::new();
10817            let snapshot = self.buffer.read(cx).snapshot(cx);
10818
10819            for row in 0..snapshot.max_row().0 {
10820                if let Some(foldable_range) =
10821                    self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10822                {
10823                    fold_ranges.push(foldable_range);
10824                }
10825            }
10826
10827            self.fold_creases(fold_ranges, true, cx);
10828        } else {
10829            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10830                editor
10831                    .update(&mut cx, |editor, cx| {
10832                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10833                            editor.fold_buffer(buffer_id, cx);
10834                        }
10835                    })
10836                    .ok();
10837            });
10838        }
10839    }
10840
10841    pub fn fold_function_bodies(
10842        &mut self,
10843        _: &actions::FoldFunctionBodies,
10844        cx: &mut ViewContext<Self>,
10845    ) {
10846        let snapshot = self.buffer.read(cx).snapshot(cx);
10847        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10848            return;
10849        };
10850        let creases = buffer
10851            .function_body_fold_ranges(0..buffer.len())
10852            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10853            .collect();
10854
10855        self.fold_creases(creases, true, cx);
10856    }
10857
10858    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10859        let mut to_fold = Vec::new();
10860        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10861        let selections = self.selections.all_adjusted(cx);
10862
10863        for selection in selections {
10864            let range = selection.range().sorted();
10865            let buffer_start_row = range.start.row;
10866
10867            if range.start.row != range.end.row {
10868                let mut found = false;
10869                for row in range.start.row..=range.end.row {
10870                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10871                        found = true;
10872                        to_fold.push(crease);
10873                    }
10874                }
10875                if found {
10876                    continue;
10877                }
10878            }
10879
10880            for row in (0..=range.start.row).rev() {
10881                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10882                    if crease.range().end.row >= buffer_start_row {
10883                        to_fold.push(crease);
10884                    } else {
10885                        break;
10886                    }
10887                }
10888            }
10889        }
10890
10891        self.fold_creases(to_fold, true, cx);
10892    }
10893
10894    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10895        let buffer_row = fold_at.buffer_row;
10896        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10897
10898        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10899            let autoscroll = self
10900                .selections
10901                .all::<Point>(cx)
10902                .iter()
10903                .any(|selection| crease.range().overlaps(&selection.range()));
10904
10905            self.fold_creases(vec![crease], autoscroll, cx);
10906        }
10907    }
10908
10909    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10910        if self.is_singleton(cx) {
10911            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10912            let buffer = &display_map.buffer_snapshot;
10913            let selections = self.selections.all::<Point>(cx);
10914            let ranges = selections
10915                .iter()
10916                .map(|s| {
10917                    let range = s.display_range(&display_map).sorted();
10918                    let mut start = range.start.to_point(&display_map);
10919                    let mut end = range.end.to_point(&display_map);
10920                    start.column = 0;
10921                    end.column = buffer.line_len(MultiBufferRow(end.row));
10922                    start..end
10923                })
10924                .collect::<Vec<_>>();
10925
10926            self.unfold_ranges(&ranges, true, true, cx);
10927        } else {
10928            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10929            let mut unfolded_buffers = HashSet::default();
10930            for (_, buffer_snapshot, _) in
10931                multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10932            {
10933                let buffer_id = buffer_snapshot.remote_id();
10934                if unfolded_buffers.insert(buffer_id) {
10935                    self.unfold_buffer(buffer_id, cx);
10936                }
10937            }
10938        }
10939    }
10940
10941    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10942        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10943        let selections = self.selections.all::<Point>(cx);
10944        let ranges = selections
10945            .iter()
10946            .map(|s| {
10947                let mut range = s.display_range(&display_map).sorted();
10948                *range.start.column_mut() = 0;
10949                *range.end.column_mut() = display_map.line_len(range.end.row());
10950                let start = range.start.to_point(&display_map);
10951                let end = range.end.to_point(&display_map);
10952                start..end
10953            })
10954            .collect::<Vec<_>>();
10955
10956        self.unfold_ranges(&ranges, true, true, cx);
10957    }
10958
10959    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10960        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10961
10962        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10963            ..Point::new(
10964                unfold_at.buffer_row.0,
10965                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10966            );
10967
10968        let autoscroll = self
10969            .selections
10970            .all::<Point>(cx)
10971            .iter()
10972            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10973
10974        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10975    }
10976
10977    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10978        if self.buffer.read(cx).is_singleton() {
10979            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10980            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10981        } else {
10982            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10983                editor
10984                    .update(&mut cx, |editor, cx| {
10985                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10986                            editor.unfold_buffer(buffer_id, cx);
10987                        }
10988                    })
10989                    .ok();
10990            });
10991        }
10992    }
10993
10994    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10995        let selections = self.selections.all::<Point>(cx);
10996        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10997        let line_mode = self.selections.line_mode;
10998        let ranges = selections
10999            .into_iter()
11000            .map(|s| {
11001                if line_mode {
11002                    let start = Point::new(s.start.row, 0);
11003                    let end = Point::new(
11004                        s.end.row,
11005                        display_map
11006                            .buffer_snapshot
11007                            .line_len(MultiBufferRow(s.end.row)),
11008                    );
11009                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11010                } else {
11011                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11012                }
11013            })
11014            .collect::<Vec<_>>();
11015        self.fold_creases(ranges, true, cx);
11016    }
11017
11018    pub fn fold_ranges<T: ToOffset + Clone>(
11019        &mut self,
11020        ranges: Vec<Range<T>>,
11021        auto_scroll: bool,
11022        cx: &mut ViewContext<Self>,
11023    ) {
11024        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11025        let ranges = ranges
11026            .into_iter()
11027            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
11028            .collect::<Vec<_>>();
11029        self.fold_creases(ranges, auto_scroll, cx);
11030    }
11031
11032    pub fn fold_creases<T: ToOffset + Clone>(
11033        &mut self,
11034        creases: Vec<Crease<T>>,
11035        auto_scroll: bool,
11036        cx: &mut ViewContext<Self>,
11037    ) {
11038        if creases.is_empty() {
11039            return;
11040        }
11041
11042        let mut buffers_affected = HashSet::default();
11043        let multi_buffer = self.buffer().read(cx);
11044        for crease in &creases {
11045            if let Some((_, buffer, _)) =
11046                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11047            {
11048                buffers_affected.insert(buffer.read(cx).remote_id());
11049            };
11050        }
11051
11052        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11053
11054        if auto_scroll {
11055            self.request_autoscroll(Autoscroll::fit(), cx);
11056        }
11057
11058        for buffer_id in buffers_affected {
11059            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11060        }
11061
11062        cx.notify();
11063
11064        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11065            // Clear diagnostics block when folding a range that contains it.
11066            let snapshot = self.snapshot(cx);
11067            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11068                drop(snapshot);
11069                self.active_diagnostics = Some(active_diagnostics);
11070                self.dismiss_diagnostics(cx);
11071            } else {
11072                self.active_diagnostics = Some(active_diagnostics);
11073            }
11074        }
11075
11076        self.scrollbar_marker_state.dirty = true;
11077    }
11078
11079    /// Removes any folds whose ranges intersect any of the given ranges.
11080    pub fn unfold_ranges<T: ToOffset + Clone>(
11081        &mut self,
11082        ranges: &[Range<T>],
11083        inclusive: bool,
11084        auto_scroll: bool,
11085        cx: &mut ViewContext<Self>,
11086    ) {
11087        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11088            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11089        });
11090    }
11091
11092    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11093        if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
11094            return;
11095        }
11096        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11097            return;
11098        };
11099        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11100        self.display_map
11101            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11102        cx.emit(EditorEvent::BufferFoldToggled {
11103            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11104            folded: true,
11105        });
11106        cx.notify();
11107    }
11108
11109    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11110        if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
11111            return;
11112        }
11113        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11114            return;
11115        };
11116        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11117        self.display_map.update(cx, |display_map, cx| {
11118            display_map.unfold_buffer(buffer_id, cx);
11119        });
11120        cx.emit(EditorEvent::BufferFoldToggled {
11121            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11122            folded: false,
11123        });
11124        cx.notify();
11125    }
11126
11127    pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
11128        self.display_map.read(cx).buffer_folded(buffer)
11129    }
11130
11131    /// Removes any folds with the given ranges.
11132    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11133        &mut self,
11134        ranges: &[Range<T>],
11135        type_id: TypeId,
11136        auto_scroll: bool,
11137        cx: &mut ViewContext<Self>,
11138    ) {
11139        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11140            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11141        });
11142    }
11143
11144    fn remove_folds_with<T: ToOffset + Clone>(
11145        &mut self,
11146        ranges: &[Range<T>],
11147        auto_scroll: bool,
11148        cx: &mut ViewContext<Self>,
11149        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11150    ) {
11151        if ranges.is_empty() {
11152            return;
11153        }
11154
11155        let mut buffers_affected = HashSet::default();
11156        let multi_buffer = self.buffer().read(cx);
11157        for range in ranges {
11158            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11159                buffers_affected.insert(buffer.read(cx).remote_id());
11160            };
11161        }
11162
11163        self.display_map.update(cx, update);
11164
11165        if auto_scroll {
11166            self.request_autoscroll(Autoscroll::fit(), cx);
11167        }
11168
11169        for buffer_id in buffers_affected {
11170            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11171        }
11172
11173        cx.notify();
11174        self.scrollbar_marker_state.dirty = true;
11175        self.active_indent_guides_state.dirty = true;
11176    }
11177
11178    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11179        self.display_map.read(cx).fold_placeholder.clone()
11180    }
11181
11182    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11183        if hovered != self.gutter_hovered {
11184            self.gutter_hovered = hovered;
11185            cx.notify();
11186        }
11187    }
11188
11189    pub fn insert_blocks(
11190        &mut self,
11191        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11192        autoscroll: Option<Autoscroll>,
11193        cx: &mut ViewContext<Self>,
11194    ) -> Vec<CustomBlockId> {
11195        let blocks = self
11196            .display_map
11197            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11198        if let Some(autoscroll) = autoscroll {
11199            self.request_autoscroll(autoscroll, cx);
11200        }
11201        cx.notify();
11202        blocks
11203    }
11204
11205    pub fn resize_blocks(
11206        &mut self,
11207        heights: HashMap<CustomBlockId, u32>,
11208        autoscroll: Option<Autoscroll>,
11209        cx: &mut ViewContext<Self>,
11210    ) {
11211        self.display_map
11212            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11213        if let Some(autoscroll) = autoscroll {
11214            self.request_autoscroll(autoscroll, cx);
11215        }
11216        cx.notify();
11217    }
11218
11219    pub fn replace_blocks(
11220        &mut self,
11221        renderers: HashMap<CustomBlockId, RenderBlock>,
11222        autoscroll: Option<Autoscroll>,
11223        cx: &mut ViewContext<Self>,
11224    ) {
11225        self.display_map
11226            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11227        if let Some(autoscroll) = autoscroll {
11228            self.request_autoscroll(autoscroll, cx);
11229        }
11230        cx.notify();
11231    }
11232
11233    pub fn remove_blocks(
11234        &mut self,
11235        block_ids: HashSet<CustomBlockId>,
11236        autoscroll: Option<Autoscroll>,
11237        cx: &mut ViewContext<Self>,
11238    ) {
11239        self.display_map.update(cx, |display_map, cx| {
11240            display_map.remove_blocks(block_ids, cx)
11241        });
11242        if let Some(autoscroll) = autoscroll {
11243            self.request_autoscroll(autoscroll, cx);
11244        }
11245        cx.notify();
11246    }
11247
11248    pub fn row_for_block(
11249        &self,
11250        block_id: CustomBlockId,
11251        cx: &mut ViewContext<Self>,
11252    ) -> Option<DisplayRow> {
11253        self.display_map
11254            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11255    }
11256
11257    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11258        self.focused_block = Some(focused_block);
11259    }
11260
11261    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11262        self.focused_block.take()
11263    }
11264
11265    pub fn insert_creases(
11266        &mut self,
11267        creases: impl IntoIterator<Item = Crease<Anchor>>,
11268        cx: &mut ViewContext<Self>,
11269    ) -> Vec<CreaseId> {
11270        self.display_map
11271            .update(cx, |map, cx| map.insert_creases(creases, cx))
11272    }
11273
11274    pub fn remove_creases(
11275        &mut self,
11276        ids: impl IntoIterator<Item = CreaseId>,
11277        cx: &mut ViewContext<Self>,
11278    ) {
11279        self.display_map
11280            .update(cx, |map, cx| map.remove_creases(ids, cx));
11281    }
11282
11283    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11284        self.display_map
11285            .update(cx, |map, cx| map.snapshot(cx))
11286            .longest_row()
11287    }
11288
11289    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11290        self.display_map
11291            .update(cx, |map, cx| map.snapshot(cx))
11292            .max_point()
11293    }
11294
11295    pub fn text(&self, cx: &AppContext) -> String {
11296        self.buffer.read(cx).read(cx).text()
11297    }
11298
11299    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11300        let text = self.text(cx);
11301        let text = text.trim();
11302
11303        if text.is_empty() {
11304            return None;
11305        }
11306
11307        Some(text.to_string())
11308    }
11309
11310    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11311        self.transact(cx, |this, cx| {
11312            this.buffer
11313                .read(cx)
11314                .as_singleton()
11315                .expect("you can only call set_text on editors for singleton buffers")
11316                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11317        });
11318    }
11319
11320    pub fn display_text(&self, cx: &mut AppContext) -> String {
11321        self.display_map
11322            .update(cx, |map, cx| map.snapshot(cx))
11323            .text()
11324    }
11325
11326    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11327        let mut wrap_guides = smallvec::smallvec![];
11328
11329        if self.show_wrap_guides == Some(false) {
11330            return wrap_guides;
11331        }
11332
11333        let settings = self.buffer.read(cx).settings_at(0, cx);
11334        if settings.show_wrap_guides {
11335            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11336                wrap_guides.push((soft_wrap as usize, true));
11337            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11338                wrap_guides.push((soft_wrap as usize, true));
11339            }
11340            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11341        }
11342
11343        wrap_guides
11344    }
11345
11346    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11347        let settings = self.buffer.read(cx).settings_at(0, cx);
11348        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11349        match mode {
11350            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11351                SoftWrap::None
11352            }
11353            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11354            language_settings::SoftWrap::PreferredLineLength => {
11355                SoftWrap::Column(settings.preferred_line_length)
11356            }
11357            language_settings::SoftWrap::Bounded => {
11358                SoftWrap::Bounded(settings.preferred_line_length)
11359            }
11360        }
11361    }
11362
11363    pub fn set_soft_wrap_mode(
11364        &mut self,
11365        mode: language_settings::SoftWrap,
11366        cx: &mut ViewContext<Self>,
11367    ) {
11368        self.soft_wrap_mode_override = Some(mode);
11369        cx.notify();
11370    }
11371
11372    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11373        self.text_style_refinement = Some(style);
11374    }
11375
11376    /// called by the Element so we know what style we were most recently rendered with.
11377    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11378        let rem_size = cx.rem_size();
11379        self.display_map.update(cx, |map, cx| {
11380            map.set_font(
11381                style.text.font(),
11382                style.text.font_size.to_pixels(rem_size),
11383                cx,
11384            )
11385        });
11386        self.style = Some(style);
11387    }
11388
11389    pub fn style(&self) -> Option<&EditorStyle> {
11390        self.style.as_ref()
11391    }
11392
11393    // Called by the element. This method is not designed to be called outside of the editor
11394    // element's layout code because it does not notify when rewrapping is computed synchronously.
11395    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11396        self.display_map
11397            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11398    }
11399
11400    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11401        if self.soft_wrap_mode_override.is_some() {
11402            self.soft_wrap_mode_override.take();
11403        } else {
11404            let soft_wrap = match self.soft_wrap_mode(cx) {
11405                SoftWrap::GitDiff => return,
11406                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11407                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11408                    language_settings::SoftWrap::None
11409                }
11410            };
11411            self.soft_wrap_mode_override = Some(soft_wrap);
11412        }
11413        cx.notify();
11414    }
11415
11416    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11417        let Some(workspace) = self.workspace() else {
11418            return;
11419        };
11420        let fs = workspace.read(cx).app_state().fs.clone();
11421        let current_show = TabBarSettings::get_global(cx).show;
11422        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11423            setting.show = Some(!current_show);
11424        });
11425    }
11426
11427    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11428        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11429            self.buffer
11430                .read(cx)
11431                .settings_at(0, cx)
11432                .indent_guides
11433                .enabled
11434        });
11435        self.show_indent_guides = Some(!currently_enabled);
11436        cx.notify();
11437    }
11438
11439    fn should_show_indent_guides(&self) -> Option<bool> {
11440        self.show_indent_guides
11441    }
11442
11443    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11444        let mut editor_settings = EditorSettings::get_global(cx).clone();
11445        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11446        EditorSettings::override_global(editor_settings, cx);
11447    }
11448
11449    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11450        self.use_relative_line_numbers
11451            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11452    }
11453
11454    pub fn toggle_relative_line_numbers(
11455        &mut self,
11456        _: &ToggleRelativeLineNumbers,
11457        cx: &mut ViewContext<Self>,
11458    ) {
11459        let is_relative = self.should_use_relative_line_numbers(cx);
11460        self.set_relative_line_number(Some(!is_relative), cx)
11461    }
11462
11463    pub fn set_relative_line_number(
11464        &mut self,
11465        is_relative: Option<bool>,
11466        cx: &mut ViewContext<Self>,
11467    ) {
11468        self.use_relative_line_numbers = is_relative;
11469        cx.notify();
11470    }
11471
11472    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11473        self.show_gutter = show_gutter;
11474        cx.notify();
11475    }
11476
11477    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11478        self.show_scrollbars = show_scrollbars;
11479        cx.notify();
11480    }
11481
11482    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11483        self.show_line_numbers = Some(show_line_numbers);
11484        cx.notify();
11485    }
11486
11487    pub fn set_show_git_diff_gutter(
11488        &mut self,
11489        show_git_diff_gutter: bool,
11490        cx: &mut ViewContext<Self>,
11491    ) {
11492        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11493        cx.notify();
11494    }
11495
11496    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11497        self.show_code_actions = Some(show_code_actions);
11498        cx.notify();
11499    }
11500
11501    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11502        self.show_runnables = Some(show_runnables);
11503        cx.notify();
11504    }
11505
11506    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11507        if self.display_map.read(cx).masked != masked {
11508            self.display_map.update(cx, |map, _| map.masked = masked);
11509        }
11510        cx.notify()
11511    }
11512
11513    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11514        self.show_wrap_guides = Some(show_wrap_guides);
11515        cx.notify();
11516    }
11517
11518    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11519        self.show_indent_guides = Some(show_indent_guides);
11520        cx.notify();
11521    }
11522
11523    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11524        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11525            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11526                if let Some(dir) = file.abs_path(cx).parent() {
11527                    return Some(dir.to_owned());
11528                }
11529            }
11530
11531            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11532                return Some(project_path.path.to_path_buf());
11533            }
11534        }
11535
11536        None
11537    }
11538
11539    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11540        self.active_excerpt(cx)?
11541            .1
11542            .read(cx)
11543            .file()
11544            .and_then(|f| f.as_local())
11545    }
11546
11547    fn target_file_abs_path(&self, cx: &mut ViewContext<Self>) -> Option<PathBuf> {
11548        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
11549            let project_path = buffer.read(cx).project_path(cx)?;
11550            let project = self.project.as_ref()?.read(cx);
11551            project.absolute_path(&project_path, cx)
11552        })
11553    }
11554
11555    fn target_file_path(&self, cx: &mut ViewContext<Self>) -> Option<PathBuf> {
11556        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
11557            let project_path = buffer.read(cx).project_path(cx)?;
11558            let project = self.project.as_ref()?.read(cx);
11559            let entry = project.entry_for_path(&project_path, cx)?;
11560            let path = entry.path.to_path_buf();
11561            Some(path)
11562        })
11563    }
11564
11565    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11566        if let Some(target) = self.target_file(cx) {
11567            cx.reveal_path(&target.abs_path(cx));
11568        }
11569    }
11570
11571    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11572        if let Some(path) = self.target_file_abs_path(cx) {
11573            if let Some(path) = path.to_str() {
11574                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11575            }
11576        }
11577    }
11578
11579    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11580        if let Some(path) = self.target_file_path(cx) {
11581            if let Some(path) = path.to_str() {
11582                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11583            }
11584        }
11585    }
11586
11587    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11588        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11589
11590        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11591            self.start_git_blame(true, cx);
11592        }
11593
11594        cx.notify();
11595    }
11596
11597    pub fn toggle_git_blame_inline(
11598        &mut self,
11599        _: &ToggleGitBlameInline,
11600        cx: &mut ViewContext<Self>,
11601    ) {
11602        self.toggle_git_blame_inline_internal(true, cx);
11603        cx.notify();
11604    }
11605
11606    pub fn git_blame_inline_enabled(&self) -> bool {
11607        self.git_blame_inline_enabled
11608    }
11609
11610    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11611        self.show_selection_menu = self
11612            .show_selection_menu
11613            .map(|show_selections_menu| !show_selections_menu)
11614            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11615
11616        cx.notify();
11617    }
11618
11619    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11620        self.show_selection_menu
11621            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11622    }
11623
11624    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11625        if let Some(project) = self.project.as_ref() {
11626            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11627                return;
11628            };
11629
11630            if buffer.read(cx).file().is_none() {
11631                return;
11632            }
11633
11634            let focused = self.focus_handle(cx).contains_focused(cx);
11635
11636            let project = project.clone();
11637            let blame =
11638                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11639            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11640            self.blame = Some(blame);
11641        }
11642    }
11643
11644    fn toggle_git_blame_inline_internal(
11645        &mut self,
11646        user_triggered: bool,
11647        cx: &mut ViewContext<Self>,
11648    ) {
11649        if self.git_blame_inline_enabled {
11650            self.git_blame_inline_enabled = false;
11651            self.show_git_blame_inline = false;
11652            self.show_git_blame_inline_delay_task.take();
11653        } else {
11654            self.git_blame_inline_enabled = true;
11655            self.start_git_blame_inline(user_triggered, cx);
11656        }
11657
11658        cx.notify();
11659    }
11660
11661    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11662        self.start_git_blame(user_triggered, cx);
11663
11664        if ProjectSettings::get_global(cx)
11665            .git
11666            .inline_blame_delay()
11667            .is_some()
11668        {
11669            self.start_inline_blame_timer(cx);
11670        } else {
11671            self.show_git_blame_inline = true
11672        }
11673    }
11674
11675    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11676        self.blame.as_ref()
11677    }
11678
11679    pub fn show_git_blame_gutter(&self) -> bool {
11680        self.show_git_blame_gutter
11681    }
11682
11683    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11684        self.show_git_blame_gutter && self.has_blame_entries(cx)
11685    }
11686
11687    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11688        self.show_git_blame_inline
11689            && self.focus_handle.is_focused(cx)
11690            && !self.newest_selection_head_on_empty_line(cx)
11691            && self.has_blame_entries(cx)
11692    }
11693
11694    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11695        self.blame()
11696            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11697    }
11698
11699    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11700        let cursor_anchor = self.selections.newest_anchor().head();
11701
11702        let snapshot = self.buffer.read(cx).snapshot(cx);
11703        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11704
11705        snapshot.line_len(buffer_row) == 0
11706    }
11707
11708    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11709        let buffer_and_selection = maybe!({
11710            let selection = self.selections.newest::<Point>(cx);
11711            let selection_range = selection.range();
11712
11713            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11714                (buffer, selection_range.start.row..selection_range.end.row)
11715            } else {
11716                let multi_buffer = self.buffer().read(cx);
11717                let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11718                let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11719
11720                let (excerpt, range) = if selection.reversed {
11721                    buffer_ranges.first()
11722                } else {
11723                    buffer_ranges.last()
11724                }?;
11725
11726                let snapshot = excerpt.buffer();
11727                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11728                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11729                (
11730                    multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11731                    selection,
11732                )
11733            };
11734
11735            Some((buffer, selection))
11736        });
11737
11738        let Some((buffer, selection)) = buffer_and_selection else {
11739            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11740        };
11741
11742        let Some(project) = self.project.as_ref() else {
11743            return Task::ready(Err(anyhow!("editor does not have project")));
11744        };
11745
11746        project.update(cx, |project, cx| {
11747            project.get_permalink_to_line(&buffer, selection, cx)
11748        })
11749    }
11750
11751    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11752        let permalink_task = self.get_permalink_to_line(cx);
11753        let workspace = self.workspace();
11754
11755        cx.spawn(|_, mut cx| async move {
11756            match permalink_task.await {
11757                Ok(permalink) => {
11758                    cx.update(|cx| {
11759                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11760                    })
11761                    .ok();
11762                }
11763                Err(err) => {
11764                    let message = format!("Failed to copy permalink: {err}");
11765
11766                    Err::<(), anyhow::Error>(err).log_err();
11767
11768                    if let Some(workspace) = workspace {
11769                        workspace
11770                            .update(&mut cx, |workspace, cx| {
11771                                struct CopyPermalinkToLine;
11772
11773                                workspace.show_toast(
11774                                    Toast::new(
11775                                        NotificationId::unique::<CopyPermalinkToLine>(),
11776                                        message,
11777                                    ),
11778                                    cx,
11779                                )
11780                            })
11781                            .ok();
11782                    }
11783                }
11784            }
11785        })
11786        .detach();
11787    }
11788
11789    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11790        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11791        if let Some(file) = self.target_file(cx) {
11792            if let Some(path) = file.path().to_str() {
11793                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11794            }
11795        }
11796    }
11797
11798    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11799        let permalink_task = self.get_permalink_to_line(cx);
11800        let workspace = self.workspace();
11801
11802        cx.spawn(|_, mut cx| async move {
11803            match permalink_task.await {
11804                Ok(permalink) => {
11805                    cx.update(|cx| {
11806                        cx.open_url(permalink.as_ref());
11807                    })
11808                    .ok();
11809                }
11810                Err(err) => {
11811                    let message = format!("Failed to open permalink: {err}");
11812
11813                    Err::<(), anyhow::Error>(err).log_err();
11814
11815                    if let Some(workspace) = workspace {
11816                        workspace
11817                            .update(&mut cx, |workspace, cx| {
11818                                struct OpenPermalinkToLine;
11819
11820                                workspace.show_toast(
11821                                    Toast::new(
11822                                        NotificationId::unique::<OpenPermalinkToLine>(),
11823                                        message,
11824                                    ),
11825                                    cx,
11826                                )
11827                            })
11828                            .ok();
11829                    }
11830                }
11831            }
11832        })
11833        .detach();
11834    }
11835
11836    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11837        self.insert_uuid(UuidVersion::V4, cx);
11838    }
11839
11840    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11841        self.insert_uuid(UuidVersion::V7, cx);
11842    }
11843
11844    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11845        self.transact(cx, |this, cx| {
11846            let edits = this
11847                .selections
11848                .all::<Point>(cx)
11849                .into_iter()
11850                .map(|selection| {
11851                    let uuid = match version {
11852                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11853                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11854                    };
11855
11856                    (selection.range(), uuid.to_string())
11857                });
11858            this.edit(edits, cx);
11859            this.refresh_inline_completion(true, false, cx);
11860        });
11861    }
11862
11863    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11864    /// last highlight added will be used.
11865    ///
11866    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11867    pub fn highlight_rows<T: 'static>(
11868        &mut self,
11869        range: Range<Anchor>,
11870        color: Hsla,
11871        should_autoscroll: bool,
11872        cx: &mut ViewContext<Self>,
11873    ) {
11874        let snapshot = self.buffer().read(cx).snapshot(cx);
11875        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11876        let ix = row_highlights.binary_search_by(|highlight| {
11877            Ordering::Equal
11878                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11879                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11880        });
11881
11882        if let Err(mut ix) = ix {
11883            let index = post_inc(&mut self.highlight_order);
11884
11885            // If this range intersects with the preceding highlight, then merge it with
11886            // the preceding highlight. Otherwise insert a new highlight.
11887            let mut merged = false;
11888            if ix > 0 {
11889                let prev_highlight = &mut row_highlights[ix - 1];
11890                if prev_highlight
11891                    .range
11892                    .end
11893                    .cmp(&range.start, &snapshot)
11894                    .is_ge()
11895                {
11896                    ix -= 1;
11897                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11898                        prev_highlight.range.end = range.end;
11899                    }
11900                    merged = true;
11901                    prev_highlight.index = index;
11902                    prev_highlight.color = color;
11903                    prev_highlight.should_autoscroll = should_autoscroll;
11904                }
11905            }
11906
11907            if !merged {
11908                row_highlights.insert(
11909                    ix,
11910                    RowHighlight {
11911                        range: range.clone(),
11912                        index,
11913                        color,
11914                        should_autoscroll,
11915                    },
11916                );
11917            }
11918
11919            // If any of the following highlights intersect with this one, merge them.
11920            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11921                let highlight = &row_highlights[ix];
11922                if next_highlight
11923                    .range
11924                    .start
11925                    .cmp(&highlight.range.end, &snapshot)
11926                    .is_le()
11927                {
11928                    if next_highlight
11929                        .range
11930                        .end
11931                        .cmp(&highlight.range.end, &snapshot)
11932                        .is_gt()
11933                    {
11934                        row_highlights[ix].range.end = next_highlight.range.end;
11935                    }
11936                    row_highlights.remove(ix + 1);
11937                } else {
11938                    break;
11939                }
11940            }
11941        }
11942    }
11943
11944    /// Remove any highlighted row ranges of the given type that intersect the
11945    /// given ranges.
11946    pub fn remove_highlighted_rows<T: 'static>(
11947        &mut self,
11948        ranges_to_remove: Vec<Range<Anchor>>,
11949        cx: &mut ViewContext<Self>,
11950    ) {
11951        let snapshot = self.buffer().read(cx).snapshot(cx);
11952        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11953        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11954        row_highlights.retain(|highlight| {
11955            while let Some(range_to_remove) = ranges_to_remove.peek() {
11956                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11957                    Ordering::Less | Ordering::Equal => {
11958                        ranges_to_remove.next();
11959                    }
11960                    Ordering::Greater => {
11961                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11962                            Ordering::Less | Ordering::Equal => {
11963                                return false;
11964                            }
11965                            Ordering::Greater => break,
11966                        }
11967                    }
11968                }
11969            }
11970
11971            true
11972        })
11973    }
11974
11975    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11976    pub fn clear_row_highlights<T: 'static>(&mut self) {
11977        self.highlighted_rows.remove(&TypeId::of::<T>());
11978    }
11979
11980    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11981    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11982        self.highlighted_rows
11983            .get(&TypeId::of::<T>())
11984            .map_or(&[] as &[_], |vec| vec.as_slice())
11985            .iter()
11986            .map(|highlight| (highlight.range.clone(), highlight.color))
11987    }
11988
11989    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11990    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11991    /// Allows to ignore certain kinds of highlights.
11992    pub fn highlighted_display_rows(
11993        &mut self,
11994        cx: &mut WindowContext,
11995    ) -> BTreeMap<DisplayRow, Hsla> {
11996        let snapshot = self.snapshot(cx);
11997        let mut used_highlight_orders = HashMap::default();
11998        self.highlighted_rows
11999            .iter()
12000            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12001            .fold(
12002                BTreeMap::<DisplayRow, Hsla>::new(),
12003                |mut unique_rows, highlight| {
12004                    let start = highlight.range.start.to_display_point(&snapshot);
12005                    let end = highlight.range.end.to_display_point(&snapshot);
12006                    let start_row = start.row().0;
12007                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12008                        && end.column() == 0
12009                    {
12010                        end.row().0.saturating_sub(1)
12011                    } else {
12012                        end.row().0
12013                    };
12014                    for row in start_row..=end_row {
12015                        let used_index =
12016                            used_highlight_orders.entry(row).or_insert(highlight.index);
12017                        if highlight.index >= *used_index {
12018                            *used_index = highlight.index;
12019                            unique_rows.insert(DisplayRow(row), highlight.color);
12020                        }
12021                    }
12022                    unique_rows
12023                },
12024            )
12025    }
12026
12027    pub fn highlighted_display_row_for_autoscroll(
12028        &self,
12029        snapshot: &DisplaySnapshot,
12030    ) -> Option<DisplayRow> {
12031        self.highlighted_rows
12032            .values()
12033            .flat_map(|highlighted_rows| highlighted_rows.iter())
12034            .filter_map(|highlight| {
12035                if highlight.should_autoscroll {
12036                    Some(highlight.range.start.to_display_point(snapshot).row())
12037                } else {
12038                    None
12039                }
12040            })
12041            .min()
12042    }
12043
12044    pub fn set_search_within_ranges(
12045        &mut self,
12046        ranges: &[Range<Anchor>],
12047        cx: &mut ViewContext<Self>,
12048    ) {
12049        self.highlight_background::<SearchWithinRange>(
12050            ranges,
12051            |colors| colors.editor_document_highlight_read_background,
12052            cx,
12053        )
12054    }
12055
12056    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12057        self.breadcrumb_header = Some(new_header);
12058    }
12059
12060    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12061        self.clear_background_highlights::<SearchWithinRange>(cx);
12062    }
12063
12064    pub fn highlight_background<T: 'static>(
12065        &mut self,
12066        ranges: &[Range<Anchor>],
12067        color_fetcher: fn(&ThemeColors) -> Hsla,
12068        cx: &mut ViewContext<Self>,
12069    ) {
12070        self.background_highlights
12071            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12072        self.scrollbar_marker_state.dirty = true;
12073        cx.notify();
12074    }
12075
12076    pub fn clear_background_highlights<T: 'static>(
12077        &mut self,
12078        cx: &mut ViewContext<Self>,
12079    ) -> Option<BackgroundHighlight> {
12080        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12081        if !text_highlights.1.is_empty() {
12082            self.scrollbar_marker_state.dirty = true;
12083            cx.notify();
12084        }
12085        Some(text_highlights)
12086    }
12087
12088    pub fn highlight_gutter<T: 'static>(
12089        &mut self,
12090        ranges: &[Range<Anchor>],
12091        color_fetcher: fn(&AppContext) -> Hsla,
12092        cx: &mut ViewContext<Self>,
12093    ) {
12094        self.gutter_highlights
12095            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12096        cx.notify();
12097    }
12098
12099    pub fn clear_gutter_highlights<T: 'static>(
12100        &mut self,
12101        cx: &mut ViewContext<Self>,
12102    ) -> Option<GutterHighlight> {
12103        cx.notify();
12104        self.gutter_highlights.remove(&TypeId::of::<T>())
12105    }
12106
12107    #[cfg(feature = "test-support")]
12108    pub fn all_text_background_highlights(
12109        &mut self,
12110        cx: &mut ViewContext<Self>,
12111    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12112        let snapshot = self.snapshot(cx);
12113        let buffer = &snapshot.buffer_snapshot;
12114        let start = buffer.anchor_before(0);
12115        let end = buffer.anchor_after(buffer.len());
12116        let theme = cx.theme().colors();
12117        self.background_highlights_in_range(start..end, &snapshot, theme)
12118    }
12119
12120    #[cfg(feature = "test-support")]
12121    pub fn search_background_highlights(
12122        &mut self,
12123        cx: &mut ViewContext<Self>,
12124    ) -> Vec<Range<Point>> {
12125        let snapshot = self.buffer().read(cx).snapshot(cx);
12126
12127        let highlights = self
12128            .background_highlights
12129            .get(&TypeId::of::<items::BufferSearchHighlights>());
12130
12131        if let Some((_color, ranges)) = highlights {
12132            ranges
12133                .iter()
12134                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12135                .collect_vec()
12136        } else {
12137            vec![]
12138        }
12139    }
12140
12141    fn document_highlights_for_position<'a>(
12142        &'a self,
12143        position: Anchor,
12144        buffer: &'a MultiBufferSnapshot,
12145    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12146        let read_highlights = self
12147            .background_highlights
12148            .get(&TypeId::of::<DocumentHighlightRead>())
12149            .map(|h| &h.1);
12150        let write_highlights = self
12151            .background_highlights
12152            .get(&TypeId::of::<DocumentHighlightWrite>())
12153            .map(|h| &h.1);
12154        let left_position = position.bias_left(buffer);
12155        let right_position = position.bias_right(buffer);
12156        read_highlights
12157            .into_iter()
12158            .chain(write_highlights)
12159            .flat_map(move |ranges| {
12160                let start_ix = match ranges.binary_search_by(|probe| {
12161                    let cmp = probe.end.cmp(&left_position, buffer);
12162                    if cmp.is_ge() {
12163                        Ordering::Greater
12164                    } else {
12165                        Ordering::Less
12166                    }
12167                }) {
12168                    Ok(i) | Err(i) => i,
12169                };
12170
12171                ranges[start_ix..]
12172                    .iter()
12173                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12174            })
12175    }
12176
12177    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12178        self.background_highlights
12179            .get(&TypeId::of::<T>())
12180            .map_or(false, |(_, highlights)| !highlights.is_empty())
12181    }
12182
12183    pub fn background_highlights_in_range(
12184        &self,
12185        search_range: Range<Anchor>,
12186        display_snapshot: &DisplaySnapshot,
12187        theme: &ThemeColors,
12188    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12189        let mut results = Vec::new();
12190        for (color_fetcher, ranges) in self.background_highlights.values() {
12191            let color = color_fetcher(theme);
12192            let start_ix = match ranges.binary_search_by(|probe| {
12193                let cmp = probe
12194                    .end
12195                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12196                if cmp.is_gt() {
12197                    Ordering::Greater
12198                } else {
12199                    Ordering::Less
12200                }
12201            }) {
12202                Ok(i) | Err(i) => i,
12203            };
12204            for range in &ranges[start_ix..] {
12205                if range
12206                    .start
12207                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12208                    .is_ge()
12209                {
12210                    break;
12211                }
12212
12213                let start = range.start.to_display_point(display_snapshot);
12214                let end = range.end.to_display_point(display_snapshot);
12215                results.push((start..end, color))
12216            }
12217        }
12218        results
12219    }
12220
12221    pub fn background_highlight_row_ranges<T: 'static>(
12222        &self,
12223        search_range: Range<Anchor>,
12224        display_snapshot: &DisplaySnapshot,
12225        count: usize,
12226    ) -> Vec<RangeInclusive<DisplayPoint>> {
12227        let mut results = Vec::new();
12228        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12229            return vec![];
12230        };
12231
12232        let start_ix = match ranges.binary_search_by(|probe| {
12233            let cmp = probe
12234                .end
12235                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12236            if cmp.is_gt() {
12237                Ordering::Greater
12238            } else {
12239                Ordering::Less
12240            }
12241        }) {
12242            Ok(i) | Err(i) => i,
12243        };
12244        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12245            if let (Some(start_display), Some(end_display)) = (start, end) {
12246                results.push(
12247                    start_display.to_display_point(display_snapshot)
12248                        ..=end_display.to_display_point(display_snapshot),
12249                );
12250            }
12251        };
12252        let mut start_row: Option<Point> = None;
12253        let mut end_row: Option<Point> = None;
12254        if ranges.len() > count {
12255            return Vec::new();
12256        }
12257        for range in &ranges[start_ix..] {
12258            if range
12259                .start
12260                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12261                .is_ge()
12262            {
12263                break;
12264            }
12265            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12266            if let Some(current_row) = &end_row {
12267                if end.row == current_row.row {
12268                    continue;
12269                }
12270            }
12271            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12272            if start_row.is_none() {
12273                assert_eq!(end_row, None);
12274                start_row = Some(start);
12275                end_row = Some(end);
12276                continue;
12277            }
12278            if let Some(current_end) = end_row.as_mut() {
12279                if start.row > current_end.row + 1 {
12280                    push_region(start_row, end_row);
12281                    start_row = Some(start);
12282                    end_row = Some(end);
12283                } else {
12284                    // Merge two hunks.
12285                    *current_end = end;
12286                }
12287            } else {
12288                unreachable!();
12289            }
12290        }
12291        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12292        push_region(start_row, end_row);
12293        results
12294    }
12295
12296    pub fn gutter_highlights_in_range(
12297        &self,
12298        search_range: Range<Anchor>,
12299        display_snapshot: &DisplaySnapshot,
12300        cx: &AppContext,
12301    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12302        let mut results = Vec::new();
12303        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12304            let color = color_fetcher(cx);
12305            let start_ix = match ranges.binary_search_by(|probe| {
12306                let cmp = probe
12307                    .end
12308                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12309                if cmp.is_gt() {
12310                    Ordering::Greater
12311                } else {
12312                    Ordering::Less
12313                }
12314            }) {
12315                Ok(i) | Err(i) => i,
12316            };
12317            for range in &ranges[start_ix..] {
12318                if range
12319                    .start
12320                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12321                    .is_ge()
12322                {
12323                    break;
12324                }
12325
12326                let start = range.start.to_display_point(display_snapshot);
12327                let end = range.end.to_display_point(display_snapshot);
12328                results.push((start..end, color))
12329            }
12330        }
12331        results
12332    }
12333
12334    /// Get the text ranges corresponding to the redaction query
12335    pub fn redacted_ranges(
12336        &self,
12337        search_range: Range<Anchor>,
12338        display_snapshot: &DisplaySnapshot,
12339        cx: &WindowContext,
12340    ) -> Vec<Range<DisplayPoint>> {
12341        display_snapshot
12342            .buffer_snapshot
12343            .redacted_ranges(search_range, |file| {
12344                if let Some(file) = file {
12345                    file.is_private()
12346                        && EditorSettings::get(
12347                            Some(SettingsLocation {
12348                                worktree_id: file.worktree_id(cx),
12349                                path: file.path().as_ref(),
12350                            }),
12351                            cx,
12352                        )
12353                        .redact_private_values
12354                } else {
12355                    false
12356                }
12357            })
12358            .map(|range| {
12359                range.start.to_display_point(display_snapshot)
12360                    ..range.end.to_display_point(display_snapshot)
12361            })
12362            .collect()
12363    }
12364
12365    pub fn highlight_text<T: 'static>(
12366        &mut self,
12367        ranges: Vec<Range<Anchor>>,
12368        style: HighlightStyle,
12369        cx: &mut ViewContext<Self>,
12370    ) {
12371        self.display_map.update(cx, |map, _| {
12372            map.highlight_text(TypeId::of::<T>(), ranges, style)
12373        });
12374        cx.notify();
12375    }
12376
12377    pub(crate) fn highlight_inlays<T: 'static>(
12378        &mut self,
12379        highlights: Vec<InlayHighlight>,
12380        style: HighlightStyle,
12381        cx: &mut ViewContext<Self>,
12382    ) {
12383        self.display_map.update(cx, |map, _| {
12384            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12385        });
12386        cx.notify();
12387    }
12388
12389    pub fn text_highlights<'a, T: 'static>(
12390        &'a self,
12391        cx: &'a AppContext,
12392    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12393        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12394    }
12395
12396    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12397        let cleared = self
12398            .display_map
12399            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12400        if cleared {
12401            cx.notify();
12402        }
12403    }
12404
12405    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12406        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12407            && self.focus_handle.is_focused(cx)
12408    }
12409
12410    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12411        self.show_cursor_when_unfocused = is_enabled;
12412        cx.notify();
12413    }
12414
12415    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12416        self.project
12417            .as_ref()
12418            .map(|project| project.read(cx).lsp_store())
12419    }
12420
12421    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12422        cx.notify();
12423    }
12424
12425    fn on_buffer_event(
12426        &mut self,
12427        multibuffer: Model<MultiBuffer>,
12428        event: &multi_buffer::Event,
12429        cx: &mut ViewContext<Self>,
12430    ) {
12431        match event {
12432            multi_buffer::Event::Edited {
12433                singleton_buffer_edited,
12434                edited_buffer: buffer_edited,
12435            } => {
12436                self.scrollbar_marker_state.dirty = true;
12437                self.active_indent_guides_state.dirty = true;
12438                self.refresh_active_diagnostics(cx);
12439                self.refresh_code_actions(cx);
12440                if self.has_active_inline_completion() {
12441                    self.update_visible_inline_completion(cx);
12442                }
12443                if let Some(buffer) = buffer_edited {
12444                    let buffer_id = buffer.read(cx).remote_id();
12445                    if !self.registered_buffers.contains_key(&buffer_id) {
12446                        if let Some(lsp_store) = self.lsp_store(cx) {
12447                            lsp_store.update(cx, |lsp_store, cx| {
12448                                self.registered_buffers.insert(
12449                                    buffer_id,
12450                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
12451                                );
12452                            })
12453                        }
12454                    }
12455                }
12456                cx.emit(EditorEvent::BufferEdited);
12457                cx.emit(SearchEvent::MatchesInvalidated);
12458                if *singleton_buffer_edited {
12459                    if let Some(project) = &self.project {
12460                        let project = project.read(cx);
12461                        #[allow(clippy::mutable_key_type)]
12462                        let languages_affected = multibuffer
12463                            .read(cx)
12464                            .all_buffers()
12465                            .into_iter()
12466                            .filter_map(|buffer| {
12467                                let buffer = buffer.read(cx);
12468                                let language = buffer.language()?;
12469                                if project.is_local()
12470                                    && project
12471                                        .language_servers_for_local_buffer(buffer, cx)
12472                                        .count()
12473                                        == 0
12474                                {
12475                                    None
12476                                } else {
12477                                    Some(language)
12478                                }
12479                            })
12480                            .cloned()
12481                            .collect::<HashSet<_>>();
12482                        if !languages_affected.is_empty() {
12483                            self.refresh_inlay_hints(
12484                                InlayHintRefreshReason::BufferEdited(languages_affected),
12485                                cx,
12486                            );
12487                        }
12488                    }
12489                }
12490
12491                let Some(project) = &self.project else { return };
12492                let (telemetry, is_via_ssh) = {
12493                    let project = project.read(cx);
12494                    let telemetry = project.client().telemetry().clone();
12495                    let is_via_ssh = project.is_via_ssh();
12496                    (telemetry, is_via_ssh)
12497                };
12498                refresh_linked_ranges(self, cx);
12499                telemetry.log_edit_event("editor", is_via_ssh);
12500            }
12501            multi_buffer::Event::ExcerptsAdded {
12502                buffer,
12503                predecessor,
12504                excerpts,
12505            } => {
12506                self.tasks_update_task = Some(self.refresh_runnables(cx));
12507                let buffer_id = buffer.read(cx).remote_id();
12508                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12509                    if let Some(project) = &self.project {
12510                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12511                    }
12512                }
12513                cx.emit(EditorEvent::ExcerptsAdded {
12514                    buffer: buffer.clone(),
12515                    predecessor: *predecessor,
12516                    excerpts: excerpts.clone(),
12517                });
12518                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12519            }
12520            multi_buffer::Event::ExcerptsRemoved { ids } => {
12521                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12522                let buffer = self.buffer.read(cx);
12523                self.registered_buffers
12524                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12525                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12526            }
12527            multi_buffer::Event::ExcerptsEdited { ids } => {
12528                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12529            }
12530            multi_buffer::Event::ExcerptsExpanded { ids } => {
12531                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12532                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12533            }
12534            multi_buffer::Event::Reparsed(buffer_id) => {
12535                self.tasks_update_task = Some(self.refresh_runnables(cx));
12536
12537                cx.emit(EditorEvent::Reparsed(*buffer_id));
12538            }
12539            multi_buffer::Event::LanguageChanged(buffer_id) => {
12540                linked_editing_ranges::refresh_linked_ranges(self, cx);
12541                cx.emit(EditorEvent::Reparsed(*buffer_id));
12542                cx.notify();
12543            }
12544            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12545            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12546            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12547                cx.emit(EditorEvent::TitleChanged)
12548            }
12549            // multi_buffer::Event::DiffBaseChanged => {
12550            //     self.scrollbar_marker_state.dirty = true;
12551            //     cx.emit(EditorEvent::DiffBaseChanged);
12552            //     cx.notify();
12553            // }
12554            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12555            multi_buffer::Event::DiagnosticsUpdated => {
12556                self.refresh_active_diagnostics(cx);
12557                self.scrollbar_marker_state.dirty = true;
12558                cx.notify();
12559            }
12560            _ => {}
12561        };
12562    }
12563
12564    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12565        cx.notify();
12566    }
12567
12568    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12569        self.tasks_update_task = Some(self.refresh_runnables(cx));
12570        self.refresh_inline_completion(true, false, cx);
12571        self.refresh_inlay_hints(
12572            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12573                self.selections.newest_anchor().head(),
12574                &self.buffer.read(cx).snapshot(cx),
12575                cx,
12576            )),
12577            cx,
12578        );
12579
12580        let old_cursor_shape = self.cursor_shape;
12581
12582        {
12583            let editor_settings = EditorSettings::get_global(cx);
12584            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12585            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12586            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12587        }
12588
12589        if old_cursor_shape != self.cursor_shape {
12590            cx.emit(EditorEvent::CursorShapeChanged);
12591        }
12592
12593        let project_settings = ProjectSettings::get_global(cx);
12594        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12595
12596        if self.mode == EditorMode::Full {
12597            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12598            if self.git_blame_inline_enabled != inline_blame_enabled {
12599                self.toggle_git_blame_inline_internal(false, cx);
12600            }
12601        }
12602
12603        cx.notify();
12604    }
12605
12606    pub fn set_searchable(&mut self, searchable: bool) {
12607        self.searchable = searchable;
12608    }
12609
12610    pub fn searchable(&self) -> bool {
12611        self.searchable
12612    }
12613
12614    fn open_proposed_changes_editor(
12615        &mut self,
12616        _: &OpenProposedChangesEditor,
12617        cx: &mut ViewContext<Self>,
12618    ) {
12619        let Some(workspace) = self.workspace() else {
12620            cx.propagate();
12621            return;
12622        };
12623
12624        let selections = self.selections.all::<usize>(cx);
12625        let multi_buffer = self.buffer.read(cx);
12626        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12627        let mut new_selections_by_buffer = HashMap::default();
12628        for selection in selections {
12629            for (excerpt, range) in
12630                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12631            {
12632                let mut range = range.to_point(excerpt.buffer());
12633                range.start.column = 0;
12634                range.end.column = excerpt.buffer().line_len(range.end.row);
12635                new_selections_by_buffer
12636                    .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12637                    .or_insert(Vec::new())
12638                    .push(range)
12639            }
12640        }
12641
12642        let proposed_changes_buffers = new_selections_by_buffer
12643            .into_iter()
12644            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12645            .collect::<Vec<_>>();
12646        let proposed_changes_editor = cx.new_view(|cx| {
12647            ProposedChangesEditor::new(
12648                "Proposed changes",
12649                proposed_changes_buffers,
12650                self.project.clone(),
12651                cx,
12652            )
12653        });
12654
12655        cx.window_context().defer(move |cx| {
12656            workspace.update(cx, |workspace, cx| {
12657                workspace.active_pane().update(cx, |pane, cx| {
12658                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12659                });
12660            });
12661        });
12662    }
12663
12664    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12665        self.open_excerpts_common(None, true, cx)
12666    }
12667
12668    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12669        self.open_excerpts_common(None, false, cx)
12670    }
12671
12672    fn open_excerpts_common(
12673        &mut self,
12674        jump_data: Option<JumpData>,
12675        split: bool,
12676        cx: &mut ViewContext<Self>,
12677    ) {
12678        let Some(workspace) = self.workspace() else {
12679            cx.propagate();
12680            return;
12681        };
12682
12683        if self.buffer.read(cx).is_singleton() {
12684            cx.propagate();
12685            return;
12686        }
12687
12688        let mut new_selections_by_buffer = HashMap::default();
12689        match &jump_data {
12690            Some(JumpData::MultiBufferPoint {
12691                excerpt_id,
12692                position,
12693                anchor,
12694                line_offset_from_top,
12695            }) => {
12696                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12697                if let Some(buffer) = multi_buffer_snapshot
12698                    .buffer_id_for_excerpt(*excerpt_id)
12699                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12700                {
12701                    let buffer_snapshot = buffer.read(cx).snapshot();
12702                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12703                        language::ToPoint::to_point(anchor, &buffer_snapshot)
12704                    } else {
12705                        buffer_snapshot.clip_point(*position, Bias::Left)
12706                    };
12707                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12708                    new_selections_by_buffer.insert(
12709                        buffer,
12710                        (
12711                            vec![jump_to_offset..jump_to_offset],
12712                            Some(*line_offset_from_top),
12713                        ),
12714                    );
12715                }
12716            }
12717            Some(JumpData::MultiBufferRow {
12718                row,
12719                line_offset_from_top,
12720            }) => {
12721                let point = MultiBufferPoint::new(row.0, 0);
12722                if let Some((buffer, buffer_point, _)) =
12723                    self.buffer.read(cx).point_to_buffer_point(point, cx)
12724                {
12725                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12726                    new_selections_by_buffer
12727                        .entry(buffer)
12728                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
12729                        .0
12730                        .push(buffer_offset..buffer_offset)
12731                }
12732            }
12733            None => {
12734                let selections = self.selections.all::<usize>(cx);
12735                let multi_buffer = self.buffer.read(cx);
12736                for selection in selections {
12737                    for (excerpt, mut range) in multi_buffer
12738                        .snapshot(cx)
12739                        .range_to_buffer_ranges(selection.range())
12740                    {
12741                        // When editing branch buffers, jump to the corresponding location
12742                        // in their base buffer.
12743                        let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12744                        let buffer = buffer_handle.read(cx);
12745                        if let Some(base_buffer) = buffer.base_buffer() {
12746                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12747                            buffer_handle = base_buffer;
12748                        }
12749
12750                        if selection.reversed {
12751                            mem::swap(&mut range.start, &mut range.end);
12752                        }
12753                        new_selections_by_buffer
12754                            .entry(buffer_handle)
12755                            .or_insert((Vec::new(), None))
12756                            .0
12757                            .push(range)
12758                    }
12759                }
12760            }
12761        }
12762
12763        if new_selections_by_buffer.is_empty() {
12764            return;
12765        }
12766
12767        // We defer the pane interaction because we ourselves are a workspace item
12768        // and activating a new item causes the pane to call a method on us reentrantly,
12769        // which panics if we're on the stack.
12770        cx.window_context().defer(move |cx| {
12771            workspace.update(cx, |workspace, cx| {
12772                let pane = if split {
12773                    workspace.adjacent_pane(cx)
12774                } else {
12775                    workspace.active_pane().clone()
12776                };
12777
12778                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12779                    let editor = buffer
12780                        .read(cx)
12781                        .file()
12782                        .is_none()
12783                        .then(|| {
12784                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12785                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12786                            // Instead, we try to activate the existing editor in the pane first.
12787                            let (editor, pane_item_index) =
12788                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12789                                    let editor = item.downcast::<Editor>()?;
12790                                    let singleton_buffer =
12791                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12792                                    if singleton_buffer == buffer {
12793                                        Some((editor, i))
12794                                    } else {
12795                                        None
12796                                    }
12797                                })?;
12798                            pane.update(cx, |pane, cx| {
12799                                pane.activate_item(pane_item_index, true, true, cx)
12800                            });
12801                            Some(editor)
12802                        })
12803                        .flatten()
12804                        .unwrap_or_else(|| {
12805                            workspace.open_project_item::<Self>(
12806                                pane.clone(),
12807                                buffer,
12808                                true,
12809                                true,
12810                                cx,
12811                            )
12812                        });
12813
12814                    editor.update(cx, |editor, cx| {
12815                        let autoscroll = match scroll_offset {
12816                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12817                            None => Autoscroll::newest(),
12818                        };
12819                        let nav_history = editor.nav_history.take();
12820                        editor.change_selections(Some(autoscroll), cx, |s| {
12821                            s.select_ranges(ranges);
12822                        });
12823                        editor.nav_history = nav_history;
12824                    });
12825                }
12826            })
12827        });
12828    }
12829
12830    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12831        let snapshot = self.buffer.read(cx).read(cx);
12832        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12833        Some(
12834            ranges
12835                .iter()
12836                .map(move |range| {
12837                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12838                })
12839                .collect(),
12840        )
12841    }
12842
12843    fn selection_replacement_ranges(
12844        &self,
12845        range: Range<OffsetUtf16>,
12846        cx: &mut AppContext,
12847    ) -> Vec<Range<OffsetUtf16>> {
12848        let selections = self.selections.all::<OffsetUtf16>(cx);
12849        let newest_selection = selections
12850            .iter()
12851            .max_by_key(|selection| selection.id)
12852            .unwrap();
12853        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12854        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12855        let snapshot = self.buffer.read(cx).read(cx);
12856        selections
12857            .into_iter()
12858            .map(|mut selection| {
12859                selection.start.0 =
12860                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12861                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12862                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12863                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12864            })
12865            .collect()
12866    }
12867
12868    fn report_editor_event(
12869        &self,
12870        event_type: &'static str,
12871        file_extension: Option<String>,
12872        cx: &AppContext,
12873    ) {
12874        if cfg!(any(test, feature = "test-support")) {
12875            return;
12876        }
12877
12878        let Some(project) = &self.project else { return };
12879
12880        // If None, we are in a file without an extension
12881        let file = self
12882            .buffer
12883            .read(cx)
12884            .as_singleton()
12885            .and_then(|b| b.read(cx).file());
12886        let file_extension = file_extension.or(file
12887            .as_ref()
12888            .and_then(|file| Path::new(file.file_name(cx)).extension())
12889            .and_then(|e| e.to_str())
12890            .map(|a| a.to_string()));
12891
12892        let vim_mode = cx
12893            .global::<SettingsStore>()
12894            .raw_user_settings()
12895            .get("vim_mode")
12896            == Some(&serde_json::Value::Bool(true));
12897
12898        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12899            == language::language_settings::InlineCompletionProvider::Copilot;
12900        let copilot_enabled_for_language = self
12901            .buffer
12902            .read(cx)
12903            .settings_at(0, cx)
12904            .show_inline_completions;
12905
12906        let project = project.read(cx);
12907        telemetry::event!(
12908            event_type,
12909            file_extension,
12910            vim_mode,
12911            copilot_enabled,
12912            copilot_enabled_for_language,
12913            is_via_ssh = project.is_via_ssh(),
12914        );
12915    }
12916
12917    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12918    /// with each line being an array of {text, highlight} objects.
12919    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12920        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12921            return;
12922        };
12923
12924        #[derive(Serialize)]
12925        struct Chunk<'a> {
12926            text: String,
12927            highlight: Option<&'a str>,
12928        }
12929
12930        let snapshot = buffer.read(cx).snapshot();
12931        let range = self
12932            .selected_text_range(false, cx)
12933            .and_then(|selection| {
12934                if selection.range.is_empty() {
12935                    None
12936                } else {
12937                    Some(selection.range)
12938                }
12939            })
12940            .unwrap_or_else(|| 0..snapshot.len());
12941
12942        let chunks = snapshot.chunks(range, true);
12943        let mut lines = Vec::new();
12944        let mut line: VecDeque<Chunk> = VecDeque::new();
12945
12946        let Some(style) = self.style.as_ref() else {
12947            return;
12948        };
12949
12950        for chunk in chunks {
12951            let highlight = chunk
12952                .syntax_highlight_id
12953                .and_then(|id| id.name(&style.syntax));
12954            let mut chunk_lines = chunk.text.split('\n').peekable();
12955            while let Some(text) = chunk_lines.next() {
12956                let mut merged_with_last_token = false;
12957                if let Some(last_token) = line.back_mut() {
12958                    if last_token.highlight == highlight {
12959                        last_token.text.push_str(text);
12960                        merged_with_last_token = true;
12961                    }
12962                }
12963
12964                if !merged_with_last_token {
12965                    line.push_back(Chunk {
12966                        text: text.into(),
12967                        highlight,
12968                    });
12969                }
12970
12971                if chunk_lines.peek().is_some() {
12972                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12973                        line.pop_front();
12974                    }
12975                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12976                        line.pop_back();
12977                    }
12978
12979                    lines.push(mem::take(&mut line));
12980                }
12981            }
12982        }
12983
12984        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12985            return;
12986        };
12987        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12988    }
12989
12990    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12991        self.request_autoscroll(Autoscroll::newest(), cx);
12992        let position = self.selections.newest_display(cx).start;
12993        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12994    }
12995
12996    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12997        &self.inlay_hint_cache
12998    }
12999
13000    pub fn replay_insert_event(
13001        &mut self,
13002        text: &str,
13003        relative_utf16_range: Option<Range<isize>>,
13004        cx: &mut ViewContext<Self>,
13005    ) {
13006        if !self.input_enabled {
13007            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13008            return;
13009        }
13010        if let Some(relative_utf16_range) = relative_utf16_range {
13011            let selections = self.selections.all::<OffsetUtf16>(cx);
13012            self.change_selections(None, cx, |s| {
13013                let new_ranges = selections.into_iter().map(|range| {
13014                    let start = OffsetUtf16(
13015                        range
13016                            .head()
13017                            .0
13018                            .saturating_add_signed(relative_utf16_range.start),
13019                    );
13020                    let end = OffsetUtf16(
13021                        range
13022                            .head()
13023                            .0
13024                            .saturating_add_signed(relative_utf16_range.end),
13025                    );
13026                    start..end
13027                });
13028                s.select_ranges(new_ranges);
13029            });
13030        }
13031
13032        self.handle_input(text, cx);
13033    }
13034
13035    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13036        let Some(provider) = self.semantics_provider.as_ref() else {
13037            return false;
13038        };
13039
13040        let mut supports = false;
13041        self.buffer().read(cx).for_each_buffer(|buffer| {
13042            supports |= provider.supports_inlay_hints(buffer, cx);
13043        });
13044        supports
13045    }
13046
13047    pub fn focus(&self, cx: &mut WindowContext) {
13048        cx.focus(&self.focus_handle)
13049    }
13050
13051    pub fn is_focused(&self, cx: &WindowContext) -> bool {
13052        self.focus_handle.is_focused(cx)
13053    }
13054
13055    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13056        cx.emit(EditorEvent::Focused);
13057
13058        if let Some(descendant) = self
13059            .last_focused_descendant
13060            .take()
13061            .and_then(|descendant| descendant.upgrade())
13062        {
13063            cx.focus(&descendant);
13064        } else {
13065            if let Some(blame) = self.blame.as_ref() {
13066                blame.update(cx, GitBlame::focus)
13067            }
13068
13069            self.blink_manager.update(cx, BlinkManager::enable);
13070            self.show_cursor_names(cx);
13071            self.buffer.update(cx, |buffer, cx| {
13072                buffer.finalize_last_transaction(cx);
13073                if self.leader_peer_id.is_none() {
13074                    buffer.set_active_selections(
13075                        &self.selections.disjoint_anchors(),
13076                        self.selections.line_mode,
13077                        self.cursor_shape,
13078                        cx,
13079                    );
13080                }
13081            });
13082        }
13083    }
13084
13085    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13086        cx.emit(EditorEvent::FocusedIn)
13087    }
13088
13089    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13090        if event.blurred != self.focus_handle {
13091            self.last_focused_descendant = Some(event.blurred);
13092        }
13093    }
13094
13095    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13096        self.blink_manager.update(cx, BlinkManager::disable);
13097        self.buffer
13098            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13099
13100        if let Some(blame) = self.blame.as_ref() {
13101            blame.update(cx, GitBlame::blur)
13102        }
13103        if !self.hover_state.focused(cx) {
13104            hide_hover(self, cx);
13105        }
13106
13107        self.hide_context_menu(cx);
13108        cx.emit(EditorEvent::Blurred);
13109        cx.notify();
13110    }
13111
13112    pub fn register_action<A: Action>(
13113        &mut self,
13114        listener: impl Fn(&A, &mut WindowContext) + 'static,
13115    ) -> Subscription {
13116        let id = self.next_editor_action_id.post_inc();
13117        let listener = Arc::new(listener);
13118        self.editor_actions.borrow_mut().insert(
13119            id,
13120            Box::new(move |cx| {
13121                let cx = cx.window_context();
13122                let listener = listener.clone();
13123                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13124                    let action = action.downcast_ref().unwrap();
13125                    if phase == DispatchPhase::Bubble {
13126                        listener(action, cx)
13127                    }
13128                })
13129            }),
13130        );
13131
13132        let editor_actions = self.editor_actions.clone();
13133        Subscription::new(move || {
13134            editor_actions.borrow_mut().remove(&id);
13135        })
13136    }
13137
13138    pub fn file_header_size(&self) -> u32 {
13139        FILE_HEADER_HEIGHT
13140    }
13141
13142    pub fn revert(
13143        &mut self,
13144        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13145        cx: &mut ViewContext<Self>,
13146    ) {
13147        self.buffer().update(cx, |multi_buffer, cx| {
13148            for (buffer_id, changes) in revert_changes {
13149                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13150                    buffer.update(cx, |buffer, cx| {
13151                        buffer.edit(
13152                            changes.into_iter().map(|(range, text)| {
13153                                (range, text.to_string().map(Arc::<str>::from))
13154                            }),
13155                            None,
13156                            cx,
13157                        );
13158                    });
13159                }
13160            }
13161        });
13162        self.change_selections(None, cx, |selections| selections.refresh());
13163    }
13164
13165    pub fn to_pixel_point(
13166        &mut self,
13167        source: multi_buffer::Anchor,
13168        editor_snapshot: &EditorSnapshot,
13169        cx: &mut ViewContext<Self>,
13170    ) -> Option<gpui::Point<Pixels>> {
13171        let source_point = source.to_display_point(editor_snapshot);
13172        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13173    }
13174
13175    pub fn display_to_pixel_point(
13176        &self,
13177        source: DisplayPoint,
13178        editor_snapshot: &EditorSnapshot,
13179        cx: &WindowContext,
13180    ) -> Option<gpui::Point<Pixels>> {
13181        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13182        let text_layout_details = self.text_layout_details(cx);
13183        let scroll_top = text_layout_details
13184            .scroll_anchor
13185            .scroll_position(editor_snapshot)
13186            .y;
13187
13188        if source.row().as_f32() < scroll_top.floor() {
13189            return None;
13190        }
13191        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13192        let source_y = line_height * (source.row().as_f32() - scroll_top);
13193        Some(gpui::Point::new(source_x, source_y))
13194    }
13195
13196    pub fn has_active_completions_menu(&self) -> bool {
13197        self.context_menu.borrow().as_ref().map_or(false, |menu| {
13198            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13199        })
13200    }
13201
13202    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13203        self.addons
13204            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13205    }
13206
13207    pub fn unregister_addon<T: Addon>(&mut self) {
13208        self.addons.remove(&std::any::TypeId::of::<T>());
13209    }
13210
13211    pub fn addon<T: Addon>(&self) -> Option<&T> {
13212        let type_id = std::any::TypeId::of::<T>();
13213        self.addons
13214            .get(&type_id)
13215            .and_then(|item| item.to_any().downcast_ref::<T>())
13216    }
13217
13218    pub fn add_change_set(
13219        &mut self,
13220        change_set: Model<BufferChangeSet>,
13221        cx: &mut ViewContext<Self>,
13222    ) {
13223        self.diff_map.add_change_set(change_set, cx);
13224    }
13225
13226    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13227        let text_layout_details = self.text_layout_details(cx);
13228        let style = &text_layout_details.editor_style;
13229        let font_id = cx.text_system().resolve_font(&style.text.font());
13230        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13231        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13232
13233        let em_width = cx
13234            .text_system()
13235            .typographic_bounds(font_id, font_size, 'm')
13236            .unwrap()
13237            .size
13238            .width;
13239
13240        gpui::Point::new(em_width, line_height)
13241    }
13242}
13243
13244fn get_unstaged_changes_for_buffers(
13245    project: &Model<Project>,
13246    buffers: impl IntoIterator<Item = Model<Buffer>>,
13247    cx: &mut ViewContext<Editor>,
13248) {
13249    let mut tasks = Vec::new();
13250    project.update(cx, |project, cx| {
13251        for buffer in buffers {
13252            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13253        }
13254    });
13255    cx.spawn(|this, mut cx| async move {
13256        let change_sets = futures::future::join_all(tasks).await;
13257        this.update(&mut cx, |this, cx| {
13258            for change_set in change_sets {
13259                if let Some(change_set) = change_set.log_err() {
13260                    this.diff_map.add_change_set(change_set, cx);
13261                }
13262            }
13263        })
13264        .ok();
13265    })
13266    .detach();
13267}
13268
13269fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13270    let tab_size = tab_size.get() as usize;
13271    let mut width = offset;
13272
13273    for ch in text.chars() {
13274        width += if ch == '\t' {
13275            tab_size - (width % tab_size)
13276        } else {
13277            1
13278        };
13279    }
13280
13281    width - offset
13282}
13283
13284#[cfg(test)]
13285mod tests {
13286    use super::*;
13287
13288    #[test]
13289    fn test_string_size_with_expanded_tabs() {
13290        let nz = |val| NonZeroU32::new(val).unwrap();
13291        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13292        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13293        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13294        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13295        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13296        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13297        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13298        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13299    }
13300}
13301
13302/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13303struct WordBreakingTokenizer<'a> {
13304    input: &'a str,
13305}
13306
13307impl<'a> WordBreakingTokenizer<'a> {
13308    fn new(input: &'a str) -> Self {
13309        Self { input }
13310    }
13311}
13312
13313fn is_char_ideographic(ch: char) -> bool {
13314    use unicode_script::Script::*;
13315    use unicode_script::UnicodeScript;
13316    matches!(ch.script(), Han | Tangut | Yi)
13317}
13318
13319fn is_grapheme_ideographic(text: &str) -> bool {
13320    text.chars().any(is_char_ideographic)
13321}
13322
13323fn is_grapheme_whitespace(text: &str) -> bool {
13324    text.chars().any(|x| x.is_whitespace())
13325}
13326
13327fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13328    text.chars().next().map_or(false, |ch| {
13329        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13330    })
13331}
13332
13333#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13334struct WordBreakToken<'a> {
13335    token: &'a str,
13336    grapheme_len: usize,
13337    is_whitespace: bool,
13338}
13339
13340impl<'a> Iterator for WordBreakingTokenizer<'a> {
13341    /// Yields a span, the count of graphemes in the token, and whether it was
13342    /// whitespace. Note that it also breaks at word boundaries.
13343    type Item = WordBreakToken<'a>;
13344
13345    fn next(&mut self) -> Option<Self::Item> {
13346        use unicode_segmentation::UnicodeSegmentation;
13347        if self.input.is_empty() {
13348            return None;
13349        }
13350
13351        let mut iter = self.input.graphemes(true).peekable();
13352        let mut offset = 0;
13353        let mut graphemes = 0;
13354        if let Some(first_grapheme) = iter.next() {
13355            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13356            offset += first_grapheme.len();
13357            graphemes += 1;
13358            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13359                if let Some(grapheme) = iter.peek().copied() {
13360                    if should_stay_with_preceding_ideograph(grapheme) {
13361                        offset += grapheme.len();
13362                        graphemes += 1;
13363                    }
13364                }
13365            } else {
13366                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13367                let mut next_word_bound = words.peek().copied();
13368                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13369                    next_word_bound = words.next();
13370                }
13371                while let Some(grapheme) = iter.peek().copied() {
13372                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13373                        break;
13374                    };
13375                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13376                        break;
13377                    };
13378                    offset += grapheme.len();
13379                    graphemes += 1;
13380                    iter.next();
13381                }
13382            }
13383            let token = &self.input[..offset];
13384            self.input = &self.input[offset..];
13385            if is_whitespace {
13386                Some(WordBreakToken {
13387                    token: " ",
13388                    grapheme_len: 1,
13389                    is_whitespace: true,
13390                })
13391            } else {
13392                Some(WordBreakToken {
13393                    token,
13394                    grapheme_len: graphemes,
13395                    is_whitespace: false,
13396                })
13397            }
13398        } else {
13399            None
13400        }
13401    }
13402}
13403
13404#[test]
13405fn test_word_breaking_tokenizer() {
13406    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13407        ("", &[]),
13408        ("  ", &[(" ", 1, true)]),
13409        ("Ʒ", &[("Ʒ", 1, false)]),
13410        ("Ǽ", &[("Ǽ", 1, false)]),
13411        ("", &[("", 1, false)]),
13412        ("⋑⋑", &[("⋑⋑", 2, false)]),
13413        (
13414            "原理,进而",
13415            &[
13416                ("", 1, false),
13417                ("理,", 2, false),
13418                ("", 1, false),
13419                ("", 1, false),
13420            ],
13421        ),
13422        (
13423            "hello world",
13424            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13425        ),
13426        (
13427            "hello, world",
13428            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13429        ),
13430        (
13431            "  hello world",
13432            &[
13433                (" ", 1, true),
13434                ("hello", 5, false),
13435                (" ", 1, true),
13436                ("world", 5, false),
13437            ],
13438        ),
13439        (
13440            "这是什么 \n 钢笔",
13441            &[
13442                ("", 1, false),
13443                ("", 1, false),
13444                ("", 1, false),
13445                ("", 1, false),
13446                (" ", 1, true),
13447                ("", 1, false),
13448                ("", 1, false),
13449            ],
13450        ),
13451        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13452    ];
13453
13454    for (input, result) in tests {
13455        assert_eq!(
13456            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13457            result
13458                .iter()
13459                .copied()
13460                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13461                    token,
13462                    grapheme_len,
13463                    is_whitespace,
13464                })
13465                .collect::<Vec<_>>()
13466        );
13467    }
13468}
13469
13470fn wrap_with_prefix(
13471    line_prefix: String,
13472    unwrapped_text: String,
13473    wrap_column: usize,
13474    tab_size: NonZeroU32,
13475) -> String {
13476    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13477    let mut wrapped_text = String::new();
13478    let mut current_line = line_prefix.clone();
13479
13480    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13481    let mut current_line_len = line_prefix_len;
13482    for WordBreakToken {
13483        token,
13484        grapheme_len,
13485        is_whitespace,
13486    } in tokenizer
13487    {
13488        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13489            wrapped_text.push_str(current_line.trim_end());
13490            wrapped_text.push('\n');
13491            current_line.truncate(line_prefix.len());
13492            current_line_len = line_prefix_len;
13493            if !is_whitespace {
13494                current_line.push_str(token);
13495                current_line_len += grapheme_len;
13496            }
13497        } else if !is_whitespace {
13498            current_line.push_str(token);
13499            current_line_len += grapheme_len;
13500        } else if current_line_len != line_prefix_len {
13501            current_line.push(' ');
13502            current_line_len += 1;
13503        }
13504    }
13505
13506    if !current_line.is_empty() {
13507        wrapped_text.push_str(&current_line);
13508    }
13509    wrapped_text
13510}
13511
13512#[test]
13513fn test_wrap_with_prefix() {
13514    assert_eq!(
13515        wrap_with_prefix(
13516            "# ".to_string(),
13517            "abcdefg".to_string(),
13518            4,
13519            NonZeroU32::new(4).unwrap()
13520        ),
13521        "# abcdefg"
13522    );
13523    assert_eq!(
13524        wrap_with_prefix(
13525            "".to_string(),
13526            "\thello world".to_string(),
13527            8,
13528            NonZeroU32::new(4).unwrap()
13529        ),
13530        "hello\nworld"
13531    );
13532    assert_eq!(
13533        wrap_with_prefix(
13534            "// ".to_string(),
13535            "xx \nyy zz aa bb cc".to_string(),
13536            12,
13537            NonZeroU32::new(4).unwrap()
13538        ),
13539        "// xx yy zz\n// aa bb cc"
13540    );
13541    assert_eq!(
13542        wrap_with_prefix(
13543            String::new(),
13544            "这是什么 \n 钢笔".to_string(),
13545            3,
13546            NonZeroU32::new(4).unwrap()
13547        ),
13548        "这是什\n么 钢\n"
13549    );
13550}
13551
13552fn hunks_for_selections(
13553    snapshot: &EditorSnapshot,
13554    selections: &[Selection<Point>],
13555) -> Vec<MultiBufferDiffHunk> {
13556    hunks_for_ranges(
13557        selections.iter().map(|selection| selection.range()),
13558        snapshot,
13559    )
13560}
13561
13562pub fn hunks_for_ranges(
13563    ranges: impl Iterator<Item = Range<Point>>,
13564    snapshot: &EditorSnapshot,
13565) -> Vec<MultiBufferDiffHunk> {
13566    let mut hunks = Vec::new();
13567    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13568        HashMap::default();
13569    for query_range in ranges {
13570        let query_rows =
13571            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13572        for hunk in snapshot.diff_map.diff_hunks_in_range(
13573            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13574            &snapshot.buffer_snapshot,
13575        ) {
13576            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13577            // when the caret is just above or just below the deleted hunk.
13578            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13579            let related_to_selection = if allow_adjacent {
13580                hunk.row_range.overlaps(&query_rows)
13581                    || hunk.row_range.start == query_rows.end
13582                    || hunk.row_range.end == query_rows.start
13583            } else {
13584                hunk.row_range.overlaps(&query_rows)
13585            };
13586            if related_to_selection {
13587                if !processed_buffer_rows
13588                    .entry(hunk.buffer_id)
13589                    .or_default()
13590                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13591                {
13592                    continue;
13593                }
13594                hunks.push(hunk);
13595            }
13596        }
13597    }
13598
13599    hunks
13600}
13601
13602pub trait CollaborationHub {
13603    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13604    fn user_participant_indices<'a>(
13605        &self,
13606        cx: &'a AppContext,
13607    ) -> &'a HashMap<u64, ParticipantIndex>;
13608    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13609}
13610
13611impl CollaborationHub for Model<Project> {
13612    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13613        self.read(cx).collaborators()
13614    }
13615
13616    fn user_participant_indices<'a>(
13617        &self,
13618        cx: &'a AppContext,
13619    ) -> &'a HashMap<u64, ParticipantIndex> {
13620        self.read(cx).user_store().read(cx).participant_indices()
13621    }
13622
13623    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13624        let this = self.read(cx);
13625        let user_ids = this.collaborators().values().map(|c| c.user_id);
13626        this.user_store().read_with(cx, |user_store, cx| {
13627            user_store.participant_names(user_ids, cx)
13628        })
13629    }
13630}
13631
13632pub trait SemanticsProvider {
13633    fn hover(
13634        &self,
13635        buffer: &Model<Buffer>,
13636        position: text::Anchor,
13637        cx: &mut AppContext,
13638    ) -> Option<Task<Vec<project::Hover>>>;
13639
13640    fn inlay_hints(
13641        &self,
13642        buffer_handle: Model<Buffer>,
13643        range: Range<text::Anchor>,
13644        cx: &mut AppContext,
13645    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13646
13647    fn resolve_inlay_hint(
13648        &self,
13649        hint: InlayHint,
13650        buffer_handle: Model<Buffer>,
13651        server_id: LanguageServerId,
13652        cx: &mut AppContext,
13653    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13654
13655    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13656
13657    fn document_highlights(
13658        &self,
13659        buffer: &Model<Buffer>,
13660        position: text::Anchor,
13661        cx: &mut AppContext,
13662    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13663
13664    fn definitions(
13665        &self,
13666        buffer: &Model<Buffer>,
13667        position: text::Anchor,
13668        kind: GotoDefinitionKind,
13669        cx: &mut AppContext,
13670    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13671
13672    fn range_for_rename(
13673        &self,
13674        buffer: &Model<Buffer>,
13675        position: text::Anchor,
13676        cx: &mut AppContext,
13677    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13678
13679    fn perform_rename(
13680        &self,
13681        buffer: &Model<Buffer>,
13682        position: text::Anchor,
13683        new_name: String,
13684        cx: &mut AppContext,
13685    ) -> Option<Task<Result<ProjectTransaction>>>;
13686}
13687
13688pub trait CompletionProvider {
13689    fn completions(
13690        &self,
13691        buffer: &Model<Buffer>,
13692        buffer_position: text::Anchor,
13693        trigger: CompletionContext,
13694        cx: &mut ViewContext<Editor>,
13695    ) -> Task<Result<Vec<Completion>>>;
13696
13697    fn resolve_completions(
13698        &self,
13699        buffer: Model<Buffer>,
13700        completion_indices: Vec<usize>,
13701        completions: Rc<RefCell<Box<[Completion]>>>,
13702        cx: &mut ViewContext<Editor>,
13703    ) -> Task<Result<bool>>;
13704
13705    fn apply_additional_edits_for_completion(
13706        &self,
13707        _buffer: Model<Buffer>,
13708        _completions: Rc<RefCell<Box<[Completion]>>>,
13709        _completion_index: usize,
13710        _push_to_history: bool,
13711        _cx: &mut ViewContext<Editor>,
13712    ) -> Task<Result<Option<language::Transaction>>> {
13713        Task::ready(Ok(None))
13714    }
13715
13716    fn is_completion_trigger(
13717        &self,
13718        buffer: &Model<Buffer>,
13719        position: language::Anchor,
13720        text: &str,
13721        trigger_in_words: bool,
13722        cx: &mut ViewContext<Editor>,
13723    ) -> bool;
13724
13725    fn sort_completions(&self) -> bool {
13726        true
13727    }
13728}
13729
13730pub trait CodeActionProvider {
13731    fn id(&self) -> Arc<str>;
13732
13733    fn code_actions(
13734        &self,
13735        buffer: &Model<Buffer>,
13736        range: Range<text::Anchor>,
13737        cx: &mut WindowContext,
13738    ) -> Task<Result<Vec<CodeAction>>>;
13739
13740    fn apply_code_action(
13741        &self,
13742        buffer_handle: Model<Buffer>,
13743        action: CodeAction,
13744        excerpt_id: ExcerptId,
13745        push_to_history: bool,
13746        cx: &mut WindowContext,
13747    ) -> Task<Result<ProjectTransaction>>;
13748}
13749
13750impl CodeActionProvider for Model<Project> {
13751    fn id(&self) -> Arc<str> {
13752        "project".into()
13753    }
13754
13755    fn code_actions(
13756        &self,
13757        buffer: &Model<Buffer>,
13758        range: Range<text::Anchor>,
13759        cx: &mut WindowContext,
13760    ) -> Task<Result<Vec<CodeAction>>> {
13761        self.update(cx, |project, cx| {
13762            project.code_actions(buffer, range, None, cx)
13763        })
13764    }
13765
13766    fn apply_code_action(
13767        &self,
13768        buffer_handle: Model<Buffer>,
13769        action: CodeAction,
13770        _excerpt_id: ExcerptId,
13771        push_to_history: bool,
13772        cx: &mut WindowContext,
13773    ) -> Task<Result<ProjectTransaction>> {
13774        self.update(cx, |project, cx| {
13775            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13776        })
13777    }
13778}
13779
13780fn snippet_completions(
13781    project: &Project,
13782    buffer: &Model<Buffer>,
13783    buffer_position: text::Anchor,
13784    cx: &mut AppContext,
13785) -> Task<Result<Vec<Completion>>> {
13786    let language = buffer.read(cx).language_at(buffer_position);
13787    let language_name = language.as_ref().map(|language| language.lsp_id());
13788    let snippet_store = project.snippets().read(cx);
13789    let snippets = snippet_store.snippets_for(language_name, cx);
13790
13791    if snippets.is_empty() {
13792        return Task::ready(Ok(vec![]));
13793    }
13794    let snapshot = buffer.read(cx).text_snapshot();
13795    let chars: String = snapshot
13796        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13797        .collect();
13798
13799    let scope = language.map(|language| language.default_scope());
13800    let executor = cx.background_executor().clone();
13801
13802    cx.background_executor().spawn(async move {
13803        let classifier = CharClassifier::new(scope).for_completion(true);
13804        let mut last_word = chars
13805            .chars()
13806            .take_while(|c| classifier.is_word(*c))
13807            .collect::<String>();
13808        last_word = last_word.chars().rev().collect();
13809
13810        if last_word.is_empty() {
13811            return Ok(vec![]);
13812        }
13813
13814        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13815        let to_lsp = |point: &text::Anchor| {
13816            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13817            point_to_lsp(end)
13818        };
13819        let lsp_end = to_lsp(&buffer_position);
13820
13821        let candidates = snippets
13822            .iter()
13823            .enumerate()
13824            .flat_map(|(ix, snippet)| {
13825                snippet
13826                    .prefix
13827                    .iter()
13828                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13829            })
13830            .collect::<Vec<StringMatchCandidate>>();
13831
13832        let mut matches = fuzzy::match_strings(
13833            &candidates,
13834            &last_word,
13835            last_word.chars().any(|c| c.is_uppercase()),
13836            100,
13837            &Default::default(),
13838            executor,
13839        )
13840        .await;
13841
13842        // Remove all candidates where the query's start does not match the start of any word in the candidate
13843        if let Some(query_start) = last_word.chars().next() {
13844            matches.retain(|string_match| {
13845                split_words(&string_match.string).any(|word| {
13846                    // Check that the first codepoint of the word as lowercase matches the first
13847                    // codepoint of the query as lowercase
13848                    word.chars()
13849                        .flat_map(|codepoint| codepoint.to_lowercase())
13850                        .zip(query_start.to_lowercase())
13851                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13852                })
13853            });
13854        }
13855
13856        let matched_strings = matches
13857            .into_iter()
13858            .map(|m| m.string)
13859            .collect::<HashSet<_>>();
13860
13861        let result: Vec<Completion> = snippets
13862            .into_iter()
13863            .filter_map(|snippet| {
13864                let matching_prefix = snippet
13865                    .prefix
13866                    .iter()
13867                    .find(|prefix| matched_strings.contains(*prefix))?;
13868                let start = as_offset - last_word.len();
13869                let start = snapshot.anchor_before(start);
13870                let range = start..buffer_position;
13871                let lsp_start = to_lsp(&start);
13872                let lsp_range = lsp::Range {
13873                    start: lsp_start,
13874                    end: lsp_end,
13875                };
13876                Some(Completion {
13877                    old_range: range,
13878                    new_text: snippet.body.clone(),
13879                    resolved: false,
13880                    label: CodeLabel {
13881                        text: matching_prefix.clone(),
13882                        runs: vec![],
13883                        filter_range: 0..matching_prefix.len(),
13884                    },
13885                    server_id: LanguageServerId(usize::MAX),
13886                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13887                    lsp_completion: lsp::CompletionItem {
13888                        label: snippet.prefix.first().unwrap().clone(),
13889                        kind: Some(CompletionItemKind::SNIPPET),
13890                        label_details: snippet.description.as_ref().map(|description| {
13891                            lsp::CompletionItemLabelDetails {
13892                                detail: Some(description.clone()),
13893                                description: None,
13894                            }
13895                        }),
13896                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13897                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13898                            lsp::InsertReplaceEdit {
13899                                new_text: snippet.body.clone(),
13900                                insert: lsp_range,
13901                                replace: lsp_range,
13902                            },
13903                        )),
13904                        filter_text: Some(snippet.body.clone()),
13905                        sort_text: Some(char::MAX.to_string()),
13906                        ..Default::default()
13907                    },
13908                    confirm: None,
13909                })
13910            })
13911            .collect();
13912
13913        Ok(result)
13914    })
13915}
13916
13917impl CompletionProvider for Model<Project> {
13918    fn completions(
13919        &self,
13920        buffer: &Model<Buffer>,
13921        buffer_position: text::Anchor,
13922        options: CompletionContext,
13923        cx: &mut ViewContext<Editor>,
13924    ) -> Task<Result<Vec<Completion>>> {
13925        self.update(cx, |project, cx| {
13926            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13927            let project_completions = project.completions(buffer, buffer_position, options, cx);
13928            cx.background_executor().spawn(async move {
13929                let mut completions = project_completions.await?;
13930                let snippets_completions = snippets.await?;
13931                completions.extend(snippets_completions);
13932                Ok(completions)
13933            })
13934        })
13935    }
13936
13937    fn resolve_completions(
13938        &self,
13939        buffer: Model<Buffer>,
13940        completion_indices: Vec<usize>,
13941        completions: Rc<RefCell<Box<[Completion]>>>,
13942        cx: &mut ViewContext<Editor>,
13943    ) -> Task<Result<bool>> {
13944        self.update(cx, |project, cx| {
13945            project.lsp_store().update(cx, |lsp_store, cx| {
13946                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13947            })
13948        })
13949    }
13950
13951    fn apply_additional_edits_for_completion(
13952        &self,
13953        buffer: Model<Buffer>,
13954        completions: Rc<RefCell<Box<[Completion]>>>,
13955        completion_index: usize,
13956        push_to_history: bool,
13957        cx: &mut ViewContext<Editor>,
13958    ) -> Task<Result<Option<language::Transaction>>> {
13959        self.update(cx, |project, cx| {
13960            project.lsp_store().update(cx, |lsp_store, cx| {
13961                lsp_store.apply_additional_edits_for_completion(
13962                    buffer,
13963                    completions,
13964                    completion_index,
13965                    push_to_history,
13966                    cx,
13967                )
13968            })
13969        })
13970    }
13971
13972    fn is_completion_trigger(
13973        &self,
13974        buffer: &Model<Buffer>,
13975        position: language::Anchor,
13976        text: &str,
13977        trigger_in_words: bool,
13978        cx: &mut ViewContext<Editor>,
13979    ) -> bool {
13980        let mut chars = text.chars();
13981        let char = if let Some(char) = chars.next() {
13982            char
13983        } else {
13984            return false;
13985        };
13986        if chars.next().is_some() {
13987            return false;
13988        }
13989
13990        let buffer = buffer.read(cx);
13991        let snapshot = buffer.snapshot();
13992        if !snapshot.settings_at(position, cx).show_completions_on_input {
13993            return false;
13994        }
13995        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13996        if trigger_in_words && classifier.is_word(char) {
13997            return true;
13998        }
13999
14000        buffer.completion_triggers().contains(text)
14001    }
14002}
14003
14004impl SemanticsProvider for Model<Project> {
14005    fn hover(
14006        &self,
14007        buffer: &Model<Buffer>,
14008        position: text::Anchor,
14009        cx: &mut AppContext,
14010    ) -> Option<Task<Vec<project::Hover>>> {
14011        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
14012    }
14013
14014    fn document_highlights(
14015        &self,
14016        buffer: &Model<Buffer>,
14017        position: text::Anchor,
14018        cx: &mut AppContext,
14019    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14020        Some(self.update(cx, |project, cx| {
14021            project.document_highlights(buffer, position, cx)
14022        }))
14023    }
14024
14025    fn definitions(
14026        &self,
14027        buffer: &Model<Buffer>,
14028        position: text::Anchor,
14029        kind: GotoDefinitionKind,
14030        cx: &mut AppContext,
14031    ) -> Option<Task<Result<Vec<LocationLink>>>> {
14032        Some(self.update(cx, |project, cx| match kind {
14033            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14034            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14035            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14036            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14037        }))
14038    }
14039
14040    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
14041        // TODO: make this work for remote projects
14042        self.read(cx)
14043            .language_servers_for_local_buffer(buffer.read(cx), cx)
14044            .any(
14045                |(_, server)| match server.capabilities().inlay_hint_provider {
14046                    Some(lsp::OneOf::Left(enabled)) => enabled,
14047                    Some(lsp::OneOf::Right(_)) => true,
14048                    None => false,
14049                },
14050            )
14051    }
14052
14053    fn inlay_hints(
14054        &self,
14055        buffer_handle: Model<Buffer>,
14056        range: Range<text::Anchor>,
14057        cx: &mut AppContext,
14058    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14059        Some(self.update(cx, |project, cx| {
14060            project.inlay_hints(buffer_handle, range, cx)
14061        }))
14062    }
14063
14064    fn resolve_inlay_hint(
14065        &self,
14066        hint: InlayHint,
14067        buffer_handle: Model<Buffer>,
14068        server_id: LanguageServerId,
14069        cx: &mut AppContext,
14070    ) -> Option<Task<anyhow::Result<InlayHint>>> {
14071        Some(self.update(cx, |project, cx| {
14072            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14073        }))
14074    }
14075
14076    fn range_for_rename(
14077        &self,
14078        buffer: &Model<Buffer>,
14079        position: text::Anchor,
14080        cx: &mut AppContext,
14081    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14082        Some(self.update(cx, |project, cx| {
14083            let buffer = buffer.clone();
14084            let task = project.prepare_rename(buffer.clone(), position, cx);
14085            cx.spawn(|_, mut cx| async move {
14086                Ok(match task.await? {
14087                    PrepareRenameResponse::Success(range) => Some(range),
14088                    PrepareRenameResponse::InvalidPosition => None,
14089                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
14090                        // Fallback on using TreeSitter info to determine identifier range
14091                        buffer.update(&mut cx, |buffer, _| {
14092                            let snapshot = buffer.snapshot();
14093                            let (range, kind) = snapshot.surrounding_word(position);
14094                            if kind != Some(CharKind::Word) {
14095                                return None;
14096                            }
14097                            Some(
14098                                snapshot.anchor_before(range.start)
14099                                    ..snapshot.anchor_after(range.end),
14100                            )
14101                        })?
14102                    }
14103                })
14104            })
14105        }))
14106    }
14107
14108    fn perform_rename(
14109        &self,
14110        buffer: &Model<Buffer>,
14111        position: text::Anchor,
14112        new_name: String,
14113        cx: &mut AppContext,
14114    ) -> Option<Task<Result<ProjectTransaction>>> {
14115        Some(self.update(cx, |project, cx| {
14116            project.perform_rename(buffer.clone(), position, new_name, cx)
14117        }))
14118    }
14119}
14120
14121fn inlay_hint_settings(
14122    location: Anchor,
14123    snapshot: &MultiBufferSnapshot,
14124    cx: &mut ViewContext<Editor>,
14125) -> InlayHintSettings {
14126    let file = snapshot.file_at(location);
14127    let language = snapshot.language_at(location).map(|l| l.name());
14128    language_settings(language, file, cx).inlay_hints
14129}
14130
14131fn consume_contiguous_rows(
14132    contiguous_row_selections: &mut Vec<Selection<Point>>,
14133    selection: &Selection<Point>,
14134    display_map: &DisplaySnapshot,
14135    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14136) -> (MultiBufferRow, MultiBufferRow) {
14137    contiguous_row_selections.push(selection.clone());
14138    let start_row = MultiBufferRow(selection.start.row);
14139    let mut end_row = ending_row(selection, display_map);
14140
14141    while let Some(next_selection) = selections.peek() {
14142        if next_selection.start.row <= end_row.0 {
14143            end_row = ending_row(next_selection, display_map);
14144            contiguous_row_selections.push(selections.next().unwrap().clone());
14145        } else {
14146            break;
14147        }
14148    }
14149    (start_row, end_row)
14150}
14151
14152fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14153    if next_selection.end.column > 0 || next_selection.is_empty() {
14154        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14155    } else {
14156        MultiBufferRow(next_selection.end.row)
14157    }
14158}
14159
14160impl EditorSnapshot {
14161    pub fn remote_selections_in_range<'a>(
14162        &'a self,
14163        range: &'a Range<Anchor>,
14164        collaboration_hub: &dyn CollaborationHub,
14165        cx: &'a AppContext,
14166    ) -> impl 'a + Iterator<Item = RemoteSelection> {
14167        let participant_names = collaboration_hub.user_names(cx);
14168        let participant_indices = collaboration_hub.user_participant_indices(cx);
14169        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14170        let collaborators_by_replica_id = collaborators_by_peer_id
14171            .iter()
14172            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14173            .collect::<HashMap<_, _>>();
14174        self.buffer_snapshot
14175            .selections_in_range(range, false)
14176            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14177                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14178                let participant_index = participant_indices.get(&collaborator.user_id).copied();
14179                let user_name = participant_names.get(&collaborator.user_id).cloned();
14180                Some(RemoteSelection {
14181                    replica_id,
14182                    selection,
14183                    cursor_shape,
14184                    line_mode,
14185                    participant_index,
14186                    peer_id: collaborator.peer_id,
14187                    user_name,
14188                })
14189            })
14190    }
14191
14192    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14193        self.display_snapshot.buffer_snapshot.language_at(position)
14194    }
14195
14196    pub fn is_focused(&self) -> bool {
14197        self.is_focused
14198    }
14199
14200    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14201        self.placeholder_text.as_ref()
14202    }
14203
14204    pub fn scroll_position(&self) -> gpui::Point<f32> {
14205        self.scroll_anchor.scroll_position(&self.display_snapshot)
14206    }
14207
14208    fn gutter_dimensions(
14209        &self,
14210        font_id: FontId,
14211        font_size: Pixels,
14212        em_width: Pixels,
14213        em_advance: Pixels,
14214        max_line_number_width: Pixels,
14215        cx: &AppContext,
14216    ) -> GutterDimensions {
14217        if !self.show_gutter {
14218            return GutterDimensions::default();
14219        }
14220        let descent = cx.text_system().descent(font_id, font_size);
14221
14222        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14223            matches!(
14224                ProjectSettings::get_global(cx).git.git_gutter,
14225                Some(GitGutterSetting::TrackedFiles)
14226            )
14227        });
14228        let gutter_settings = EditorSettings::get_global(cx).gutter;
14229        let show_line_numbers = self
14230            .show_line_numbers
14231            .unwrap_or(gutter_settings.line_numbers);
14232        let line_gutter_width = if show_line_numbers {
14233            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14234            let min_width_for_number_on_gutter = em_advance * 4.0;
14235            max_line_number_width.max(min_width_for_number_on_gutter)
14236        } else {
14237            0.0.into()
14238        };
14239
14240        let show_code_actions = self
14241            .show_code_actions
14242            .unwrap_or(gutter_settings.code_actions);
14243
14244        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14245
14246        let git_blame_entries_width =
14247            self.git_blame_gutter_max_author_length
14248                .map(|max_author_length| {
14249                    // Length of the author name, but also space for the commit hash,
14250                    // the spacing and the timestamp.
14251                    let max_char_count = max_author_length
14252                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14253                        + 7 // length of commit sha
14254                        + 14 // length of max relative timestamp ("60 minutes ago")
14255                        + 4; // gaps and margins
14256
14257                    em_advance * max_char_count
14258                });
14259
14260        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14261        left_padding += if show_code_actions || show_runnables {
14262            em_width * 3.0
14263        } else if show_git_gutter && show_line_numbers {
14264            em_width * 2.0
14265        } else if show_git_gutter || show_line_numbers {
14266            em_width
14267        } else {
14268            px(0.)
14269        };
14270
14271        let right_padding = if gutter_settings.folds && show_line_numbers {
14272            em_width * 4.0
14273        } else if gutter_settings.folds {
14274            em_width * 3.0
14275        } else if show_line_numbers {
14276            em_width
14277        } else {
14278            px(0.)
14279        };
14280
14281        GutterDimensions {
14282            left_padding,
14283            right_padding,
14284            width: line_gutter_width + left_padding + right_padding,
14285            margin: -descent,
14286            git_blame_entries_width,
14287        }
14288    }
14289
14290    pub fn render_crease_toggle(
14291        &self,
14292        buffer_row: MultiBufferRow,
14293        row_contains_cursor: bool,
14294        editor: View<Editor>,
14295        cx: &mut WindowContext,
14296    ) -> Option<AnyElement> {
14297        let folded = self.is_line_folded(buffer_row);
14298        let mut is_foldable = false;
14299
14300        if let Some(crease) = self
14301            .crease_snapshot
14302            .query_row(buffer_row, &self.buffer_snapshot)
14303        {
14304            is_foldable = true;
14305            match crease {
14306                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14307                    if let Some(render_toggle) = render_toggle {
14308                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14309                            if folded {
14310                                editor.update(cx, |editor, cx| {
14311                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14312                                });
14313                            } else {
14314                                editor.update(cx, |editor, cx| {
14315                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14316                                });
14317                            }
14318                        });
14319                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14320                    }
14321                }
14322            }
14323        }
14324
14325        is_foldable |= self.starts_indent(buffer_row);
14326
14327        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14328            Some(
14329                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14330                    .toggle_state(folded)
14331                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14332                        if folded {
14333                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14334                        } else {
14335                            this.fold_at(&FoldAt { buffer_row }, cx);
14336                        }
14337                    }))
14338                    .into_any_element(),
14339            )
14340        } else {
14341            None
14342        }
14343    }
14344
14345    pub fn render_crease_trailer(
14346        &self,
14347        buffer_row: MultiBufferRow,
14348        cx: &mut WindowContext,
14349    ) -> Option<AnyElement> {
14350        let folded = self.is_line_folded(buffer_row);
14351        if let Crease::Inline { render_trailer, .. } = self
14352            .crease_snapshot
14353            .query_row(buffer_row, &self.buffer_snapshot)?
14354        {
14355            let render_trailer = render_trailer.as_ref()?;
14356            Some(render_trailer(buffer_row, folded, cx))
14357        } else {
14358            None
14359        }
14360    }
14361}
14362
14363impl Deref for EditorSnapshot {
14364    type Target = DisplaySnapshot;
14365
14366    fn deref(&self) -> &Self::Target {
14367        &self.display_snapshot
14368    }
14369}
14370
14371#[derive(Clone, Debug, PartialEq, Eq)]
14372pub enum EditorEvent {
14373    InputIgnored {
14374        text: Arc<str>,
14375    },
14376    InputHandled {
14377        utf16_range_to_replace: Option<Range<isize>>,
14378        text: Arc<str>,
14379    },
14380    ExcerptsAdded {
14381        buffer: Model<Buffer>,
14382        predecessor: ExcerptId,
14383        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14384    },
14385    ExcerptsRemoved {
14386        ids: Vec<ExcerptId>,
14387    },
14388    BufferFoldToggled {
14389        ids: Vec<ExcerptId>,
14390        folded: bool,
14391    },
14392    ExcerptsEdited {
14393        ids: Vec<ExcerptId>,
14394    },
14395    ExcerptsExpanded {
14396        ids: Vec<ExcerptId>,
14397    },
14398    BufferEdited,
14399    Edited {
14400        transaction_id: clock::Lamport,
14401    },
14402    Reparsed(BufferId),
14403    Focused,
14404    FocusedIn,
14405    Blurred,
14406    DirtyChanged,
14407    Saved,
14408    TitleChanged,
14409    DiffBaseChanged,
14410    SelectionsChanged {
14411        local: bool,
14412    },
14413    ScrollPositionChanged {
14414        local: bool,
14415        autoscroll: bool,
14416    },
14417    Closed,
14418    TransactionUndone {
14419        transaction_id: clock::Lamport,
14420    },
14421    TransactionBegun {
14422        transaction_id: clock::Lamport,
14423    },
14424    Reloaded,
14425    CursorShapeChanged,
14426}
14427
14428impl EventEmitter<EditorEvent> for Editor {}
14429
14430impl FocusableView for Editor {
14431    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14432        self.focus_handle.clone()
14433    }
14434}
14435
14436impl Render for Editor {
14437    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14438        let settings = ThemeSettings::get_global(cx);
14439
14440        let mut text_style = match self.mode {
14441            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14442                color: cx.theme().colors().editor_foreground,
14443                font_family: settings.ui_font.family.clone(),
14444                font_features: settings.ui_font.features.clone(),
14445                font_fallbacks: settings.ui_font.fallbacks.clone(),
14446                font_size: rems(0.875).into(),
14447                font_weight: settings.ui_font.weight,
14448                line_height: relative(settings.buffer_line_height.value()),
14449                ..Default::default()
14450            },
14451            EditorMode::Full => TextStyle {
14452                color: cx.theme().colors().editor_foreground,
14453                font_family: settings.buffer_font.family.clone(),
14454                font_features: settings.buffer_font.features.clone(),
14455                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14456                font_size: settings.buffer_font_size().into(),
14457                font_weight: settings.buffer_font.weight,
14458                line_height: relative(settings.buffer_line_height.value()),
14459                ..Default::default()
14460            },
14461        };
14462        if let Some(text_style_refinement) = &self.text_style_refinement {
14463            text_style.refine(text_style_refinement)
14464        }
14465
14466        let background = match self.mode {
14467            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14468            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14469            EditorMode::Full => cx.theme().colors().editor_background,
14470        };
14471
14472        EditorElement::new(
14473            cx.view(),
14474            EditorStyle {
14475                background,
14476                local_player: cx.theme().players().local(),
14477                text: text_style,
14478                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14479                syntax: cx.theme().syntax().clone(),
14480                status: cx.theme().status().clone(),
14481                inlay_hints_style: make_inlay_hints_style(cx),
14482                inline_completion_styles: make_suggestion_styles(cx),
14483                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14484            },
14485        )
14486    }
14487}
14488
14489impl ViewInputHandler for Editor {
14490    fn text_for_range(
14491        &mut self,
14492        range_utf16: Range<usize>,
14493        adjusted_range: &mut Option<Range<usize>>,
14494        cx: &mut ViewContext<Self>,
14495    ) -> Option<String> {
14496        let snapshot = self.buffer.read(cx).read(cx);
14497        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14498        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14499        if (start.0..end.0) != range_utf16 {
14500            adjusted_range.replace(start.0..end.0);
14501        }
14502        Some(snapshot.text_for_range(start..end).collect())
14503    }
14504
14505    fn selected_text_range(
14506        &mut self,
14507        ignore_disabled_input: bool,
14508        cx: &mut ViewContext<Self>,
14509    ) -> Option<UTF16Selection> {
14510        // Prevent the IME menu from appearing when holding down an alphabetic key
14511        // while input is disabled.
14512        if !ignore_disabled_input && !self.input_enabled {
14513            return None;
14514        }
14515
14516        let selection = self.selections.newest::<OffsetUtf16>(cx);
14517        let range = selection.range();
14518
14519        Some(UTF16Selection {
14520            range: range.start.0..range.end.0,
14521            reversed: selection.reversed,
14522        })
14523    }
14524
14525    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14526        let snapshot = self.buffer.read(cx).read(cx);
14527        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14528        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14529    }
14530
14531    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14532        self.clear_highlights::<InputComposition>(cx);
14533        self.ime_transaction.take();
14534    }
14535
14536    fn replace_text_in_range(
14537        &mut self,
14538        range_utf16: Option<Range<usize>>,
14539        text: &str,
14540        cx: &mut ViewContext<Self>,
14541    ) {
14542        if !self.input_enabled {
14543            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14544            return;
14545        }
14546
14547        self.transact(cx, |this, cx| {
14548            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14549                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14550                Some(this.selection_replacement_ranges(range_utf16, cx))
14551            } else {
14552                this.marked_text_ranges(cx)
14553            };
14554
14555            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14556                let newest_selection_id = this.selections.newest_anchor().id;
14557                this.selections
14558                    .all::<OffsetUtf16>(cx)
14559                    .iter()
14560                    .zip(ranges_to_replace.iter())
14561                    .find_map(|(selection, range)| {
14562                        if selection.id == newest_selection_id {
14563                            Some(
14564                                (range.start.0 as isize - selection.head().0 as isize)
14565                                    ..(range.end.0 as isize - selection.head().0 as isize),
14566                            )
14567                        } else {
14568                            None
14569                        }
14570                    })
14571            });
14572
14573            cx.emit(EditorEvent::InputHandled {
14574                utf16_range_to_replace: range_to_replace,
14575                text: text.into(),
14576            });
14577
14578            if let Some(new_selected_ranges) = new_selected_ranges {
14579                this.change_selections(None, cx, |selections| {
14580                    selections.select_ranges(new_selected_ranges)
14581                });
14582                this.backspace(&Default::default(), cx);
14583            }
14584
14585            this.handle_input(text, cx);
14586        });
14587
14588        if let Some(transaction) = self.ime_transaction {
14589            self.buffer.update(cx, |buffer, cx| {
14590                buffer.group_until_transaction(transaction, cx);
14591            });
14592        }
14593
14594        self.unmark_text(cx);
14595    }
14596
14597    fn replace_and_mark_text_in_range(
14598        &mut self,
14599        range_utf16: Option<Range<usize>>,
14600        text: &str,
14601        new_selected_range_utf16: Option<Range<usize>>,
14602        cx: &mut ViewContext<Self>,
14603    ) {
14604        if !self.input_enabled {
14605            return;
14606        }
14607
14608        let transaction = self.transact(cx, |this, cx| {
14609            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14610                let snapshot = this.buffer.read(cx).read(cx);
14611                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14612                    for marked_range in &mut marked_ranges {
14613                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14614                        marked_range.start.0 += relative_range_utf16.start;
14615                        marked_range.start =
14616                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14617                        marked_range.end =
14618                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14619                    }
14620                }
14621                Some(marked_ranges)
14622            } else if let Some(range_utf16) = range_utf16 {
14623                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14624                Some(this.selection_replacement_ranges(range_utf16, cx))
14625            } else {
14626                None
14627            };
14628
14629            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14630                let newest_selection_id = this.selections.newest_anchor().id;
14631                this.selections
14632                    .all::<OffsetUtf16>(cx)
14633                    .iter()
14634                    .zip(ranges_to_replace.iter())
14635                    .find_map(|(selection, range)| {
14636                        if selection.id == newest_selection_id {
14637                            Some(
14638                                (range.start.0 as isize - selection.head().0 as isize)
14639                                    ..(range.end.0 as isize - selection.head().0 as isize),
14640                            )
14641                        } else {
14642                            None
14643                        }
14644                    })
14645            });
14646
14647            cx.emit(EditorEvent::InputHandled {
14648                utf16_range_to_replace: range_to_replace,
14649                text: text.into(),
14650            });
14651
14652            if let Some(ranges) = ranges_to_replace {
14653                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14654            }
14655
14656            let marked_ranges = {
14657                let snapshot = this.buffer.read(cx).read(cx);
14658                this.selections
14659                    .disjoint_anchors()
14660                    .iter()
14661                    .map(|selection| {
14662                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14663                    })
14664                    .collect::<Vec<_>>()
14665            };
14666
14667            if text.is_empty() {
14668                this.unmark_text(cx);
14669            } else {
14670                this.highlight_text::<InputComposition>(
14671                    marked_ranges.clone(),
14672                    HighlightStyle {
14673                        underline: Some(UnderlineStyle {
14674                            thickness: px(1.),
14675                            color: None,
14676                            wavy: false,
14677                        }),
14678                        ..Default::default()
14679                    },
14680                    cx,
14681                );
14682            }
14683
14684            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14685            let use_autoclose = this.use_autoclose;
14686            let use_auto_surround = this.use_auto_surround;
14687            this.set_use_autoclose(false);
14688            this.set_use_auto_surround(false);
14689            this.handle_input(text, cx);
14690            this.set_use_autoclose(use_autoclose);
14691            this.set_use_auto_surround(use_auto_surround);
14692
14693            if let Some(new_selected_range) = new_selected_range_utf16 {
14694                let snapshot = this.buffer.read(cx).read(cx);
14695                let new_selected_ranges = marked_ranges
14696                    .into_iter()
14697                    .map(|marked_range| {
14698                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14699                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14700                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14701                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14702                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14703                    })
14704                    .collect::<Vec<_>>();
14705
14706                drop(snapshot);
14707                this.change_selections(None, cx, |selections| {
14708                    selections.select_ranges(new_selected_ranges)
14709                });
14710            }
14711        });
14712
14713        self.ime_transaction = self.ime_transaction.or(transaction);
14714        if let Some(transaction) = self.ime_transaction {
14715            self.buffer.update(cx, |buffer, cx| {
14716                buffer.group_until_transaction(transaction, cx);
14717            });
14718        }
14719
14720        if self.text_highlights::<InputComposition>(cx).is_none() {
14721            self.ime_transaction.take();
14722        }
14723    }
14724
14725    fn bounds_for_range(
14726        &mut self,
14727        range_utf16: Range<usize>,
14728        element_bounds: gpui::Bounds<Pixels>,
14729        cx: &mut ViewContext<Self>,
14730    ) -> Option<gpui::Bounds<Pixels>> {
14731        let text_layout_details = self.text_layout_details(cx);
14732        let gpui::Point {
14733            x: em_width,
14734            y: line_height,
14735        } = self.character_size(cx);
14736
14737        let snapshot = self.snapshot(cx);
14738        let scroll_position = snapshot.scroll_position();
14739        let scroll_left = scroll_position.x * em_width;
14740
14741        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14742        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14743            + self.gutter_dimensions.width
14744            + self.gutter_dimensions.margin;
14745        let y = line_height * (start.row().as_f32() - scroll_position.y);
14746
14747        Some(Bounds {
14748            origin: element_bounds.origin + point(x, y),
14749            size: size(em_width, line_height),
14750        })
14751    }
14752}
14753
14754trait SelectionExt {
14755    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14756    fn spanned_rows(
14757        &self,
14758        include_end_if_at_line_start: bool,
14759        map: &DisplaySnapshot,
14760    ) -> Range<MultiBufferRow>;
14761}
14762
14763impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14764    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14765        let start = self
14766            .start
14767            .to_point(&map.buffer_snapshot)
14768            .to_display_point(map);
14769        let end = self
14770            .end
14771            .to_point(&map.buffer_snapshot)
14772            .to_display_point(map);
14773        if self.reversed {
14774            end..start
14775        } else {
14776            start..end
14777        }
14778    }
14779
14780    fn spanned_rows(
14781        &self,
14782        include_end_if_at_line_start: bool,
14783        map: &DisplaySnapshot,
14784    ) -> Range<MultiBufferRow> {
14785        let start = self.start.to_point(&map.buffer_snapshot);
14786        let mut end = self.end.to_point(&map.buffer_snapshot);
14787        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14788            end.row -= 1;
14789        }
14790
14791        let buffer_start = map.prev_line_boundary(start).0;
14792        let buffer_end = map.next_line_boundary(end).0;
14793        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14794    }
14795}
14796
14797impl<T: InvalidationRegion> InvalidationStack<T> {
14798    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14799    where
14800        S: Clone + ToOffset,
14801    {
14802        while let Some(region) = self.last() {
14803            let all_selections_inside_invalidation_ranges =
14804                if selections.len() == region.ranges().len() {
14805                    selections
14806                        .iter()
14807                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14808                        .all(|(selection, invalidation_range)| {
14809                            let head = selection.head().to_offset(buffer);
14810                            invalidation_range.start <= head && invalidation_range.end >= head
14811                        })
14812                } else {
14813                    false
14814                };
14815
14816            if all_selections_inside_invalidation_ranges {
14817                break;
14818            } else {
14819                self.pop();
14820            }
14821        }
14822    }
14823}
14824
14825impl<T> Default for InvalidationStack<T> {
14826    fn default() -> Self {
14827        Self(Default::default())
14828    }
14829}
14830
14831impl<T> Deref for InvalidationStack<T> {
14832    type Target = Vec<T>;
14833
14834    fn deref(&self) -> &Self::Target {
14835        &self.0
14836    }
14837}
14838
14839impl<T> DerefMut for InvalidationStack<T> {
14840    fn deref_mut(&mut self) -> &mut Self::Target {
14841        &mut self.0
14842    }
14843}
14844
14845impl InvalidationRegion for SnippetState {
14846    fn ranges(&self) -> &[Range<Anchor>] {
14847        &self.ranges[self.active_index]
14848    }
14849}
14850
14851pub fn diagnostic_block_renderer(
14852    diagnostic: Diagnostic,
14853    max_message_rows: Option<u8>,
14854    allow_closing: bool,
14855    _is_valid: bool,
14856) -> RenderBlock {
14857    let (text_without_backticks, code_ranges) =
14858        highlight_diagnostic_message(&diagnostic, max_message_rows);
14859
14860    Arc::new(move |cx: &mut BlockContext| {
14861        let group_id: SharedString = cx.block_id.to_string().into();
14862
14863        let mut text_style = cx.text_style().clone();
14864        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14865        let theme_settings = ThemeSettings::get_global(cx);
14866        text_style.font_family = theme_settings.buffer_font.family.clone();
14867        text_style.font_style = theme_settings.buffer_font.style;
14868        text_style.font_features = theme_settings.buffer_font.features.clone();
14869        text_style.font_weight = theme_settings.buffer_font.weight;
14870
14871        let multi_line_diagnostic = diagnostic.message.contains('\n');
14872
14873        let buttons = |diagnostic: &Diagnostic| {
14874            if multi_line_diagnostic {
14875                v_flex()
14876            } else {
14877                h_flex()
14878            }
14879            .when(allow_closing, |div| {
14880                div.children(diagnostic.is_primary.then(|| {
14881                    IconButton::new("close-block", IconName::XCircle)
14882                        .icon_color(Color::Muted)
14883                        .size(ButtonSize::Compact)
14884                        .style(ButtonStyle::Transparent)
14885                        .visible_on_hover(group_id.clone())
14886                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14887                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14888                }))
14889            })
14890            .child(
14891                IconButton::new("copy-block", IconName::Copy)
14892                    .icon_color(Color::Muted)
14893                    .size(ButtonSize::Compact)
14894                    .style(ButtonStyle::Transparent)
14895                    .visible_on_hover(group_id.clone())
14896                    .on_click({
14897                        let message = diagnostic.message.clone();
14898                        move |_click, cx| {
14899                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14900                        }
14901                    })
14902                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14903            )
14904        };
14905
14906        let icon_size = buttons(&diagnostic)
14907            .into_any_element()
14908            .layout_as_root(AvailableSpace::min_size(), cx);
14909
14910        h_flex()
14911            .id(cx.block_id)
14912            .group(group_id.clone())
14913            .relative()
14914            .size_full()
14915            .block_mouse_down()
14916            .pl(cx.gutter_dimensions.width)
14917            .w(cx.max_width - cx.gutter_dimensions.full_width())
14918            .child(
14919                div()
14920                    .flex()
14921                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14922                    .flex_shrink(),
14923            )
14924            .child(buttons(&diagnostic))
14925            .child(div().flex().flex_shrink_0().child(
14926                StyledText::new(text_without_backticks.clone()).with_highlights(
14927                    &text_style,
14928                    code_ranges.iter().map(|range| {
14929                        (
14930                            range.clone(),
14931                            HighlightStyle {
14932                                font_weight: Some(FontWeight::BOLD),
14933                                ..Default::default()
14934                            },
14935                        )
14936                    }),
14937                ),
14938            ))
14939            .into_any_element()
14940    })
14941}
14942
14943fn inline_completion_edit_text(
14944    editor_snapshot: &EditorSnapshot,
14945    edits: &Vec<(Range<Anchor>, String)>,
14946    include_deletions: bool,
14947    cx: &WindowContext,
14948) -> InlineCompletionText {
14949    let edit_start = edits
14950        .first()
14951        .unwrap()
14952        .0
14953        .start
14954        .to_display_point(editor_snapshot);
14955
14956    let mut text = String::new();
14957    let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14958    let mut highlights = Vec::new();
14959    for (old_range, new_text) in edits {
14960        let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14961        text.extend(
14962            editor_snapshot
14963                .buffer_snapshot
14964                .chunks(offset..old_offset_range.start, false)
14965                .map(|chunk| chunk.text),
14966        );
14967        offset = old_offset_range.end;
14968
14969        let start = text.len();
14970        let color = if include_deletions && new_text.is_empty() {
14971            text.extend(
14972                editor_snapshot
14973                    .buffer_snapshot
14974                    .chunks(old_offset_range.start..offset, false)
14975                    .map(|chunk| chunk.text),
14976            );
14977            cx.theme().status().deleted_background
14978        } else {
14979            text.push_str(new_text);
14980            cx.theme().status().created_background
14981        };
14982        let end = text.len();
14983
14984        highlights.push((
14985            start..end,
14986            HighlightStyle {
14987                background_color: Some(color),
14988                ..Default::default()
14989            },
14990        ));
14991    }
14992
14993    let edit_end = edits
14994        .last()
14995        .unwrap()
14996        .0
14997        .end
14998        .to_display_point(editor_snapshot);
14999    let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
15000        .to_offset(editor_snapshot, Bias::Right);
15001    text.extend(
15002        editor_snapshot
15003            .buffer_snapshot
15004            .chunks(offset..end_of_line, false)
15005            .map(|chunk| chunk.text),
15006    );
15007
15008    InlineCompletionText::Edit {
15009        text: text.into(),
15010        highlights,
15011    }
15012}
15013
15014pub fn highlight_diagnostic_message(
15015    diagnostic: &Diagnostic,
15016    mut max_message_rows: Option<u8>,
15017) -> (SharedString, Vec<Range<usize>>) {
15018    let mut text_without_backticks = String::new();
15019    let mut code_ranges = Vec::new();
15020
15021    if let Some(source) = &diagnostic.source {
15022        text_without_backticks.push_str(source);
15023        code_ranges.push(0..source.len());
15024        text_without_backticks.push_str(": ");
15025    }
15026
15027    let mut prev_offset = 0;
15028    let mut in_code_block = false;
15029    let has_row_limit = max_message_rows.is_some();
15030    let mut newline_indices = diagnostic
15031        .message
15032        .match_indices('\n')
15033        .filter(|_| has_row_limit)
15034        .map(|(ix, _)| ix)
15035        .fuse()
15036        .peekable();
15037
15038    for (quote_ix, _) in diagnostic
15039        .message
15040        .match_indices('`')
15041        .chain([(diagnostic.message.len(), "")])
15042    {
15043        let mut first_newline_ix = None;
15044        let mut last_newline_ix = None;
15045        while let Some(newline_ix) = newline_indices.peek() {
15046            if *newline_ix < quote_ix {
15047                if first_newline_ix.is_none() {
15048                    first_newline_ix = Some(*newline_ix);
15049                }
15050                last_newline_ix = Some(*newline_ix);
15051
15052                if let Some(rows_left) = &mut max_message_rows {
15053                    if *rows_left == 0 {
15054                        break;
15055                    } else {
15056                        *rows_left -= 1;
15057                    }
15058                }
15059                let _ = newline_indices.next();
15060            } else {
15061                break;
15062            }
15063        }
15064        let prev_len = text_without_backticks.len();
15065        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
15066        text_without_backticks.push_str(new_text);
15067        if in_code_block {
15068            code_ranges.push(prev_len..text_without_backticks.len());
15069        }
15070        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15071        in_code_block = !in_code_block;
15072        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15073            text_without_backticks.push_str("...");
15074            break;
15075        }
15076    }
15077
15078    (text_without_backticks.into(), code_ranges)
15079}
15080
15081fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15082    match severity {
15083        DiagnosticSeverity::ERROR => colors.error,
15084        DiagnosticSeverity::WARNING => colors.warning,
15085        DiagnosticSeverity::INFORMATION => colors.info,
15086        DiagnosticSeverity::HINT => colors.info,
15087        _ => colors.ignored,
15088    }
15089}
15090
15091pub fn styled_runs_for_code_label<'a>(
15092    label: &'a CodeLabel,
15093    syntax_theme: &'a theme::SyntaxTheme,
15094) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15095    let fade_out = HighlightStyle {
15096        fade_out: Some(0.35),
15097        ..Default::default()
15098    };
15099
15100    let mut prev_end = label.filter_range.end;
15101    label
15102        .runs
15103        .iter()
15104        .enumerate()
15105        .flat_map(move |(ix, (range, highlight_id))| {
15106            let style = if let Some(style) = highlight_id.style(syntax_theme) {
15107                style
15108            } else {
15109                return Default::default();
15110            };
15111            let mut muted_style = style;
15112            muted_style.highlight(fade_out);
15113
15114            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15115            if range.start >= label.filter_range.end {
15116                if range.start > prev_end {
15117                    runs.push((prev_end..range.start, fade_out));
15118                }
15119                runs.push((range.clone(), muted_style));
15120            } else if range.end <= label.filter_range.end {
15121                runs.push((range.clone(), style));
15122            } else {
15123                runs.push((range.start..label.filter_range.end, style));
15124                runs.push((label.filter_range.end..range.end, muted_style));
15125            }
15126            prev_end = cmp::max(prev_end, range.end);
15127
15128            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15129                runs.push((prev_end..label.text.len(), fade_out));
15130            }
15131
15132            runs
15133        })
15134}
15135
15136pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15137    let mut prev_index = 0;
15138    let mut prev_codepoint: Option<char> = None;
15139    text.char_indices()
15140        .chain([(text.len(), '\0')])
15141        .filter_map(move |(index, codepoint)| {
15142            let prev_codepoint = prev_codepoint.replace(codepoint)?;
15143            let is_boundary = index == text.len()
15144                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15145                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15146            if is_boundary {
15147                let chunk = &text[prev_index..index];
15148                prev_index = index;
15149                Some(chunk)
15150            } else {
15151                None
15152            }
15153        })
15154}
15155
15156pub trait RangeToAnchorExt: Sized {
15157    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15158
15159    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15160        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15161        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15162    }
15163}
15164
15165impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15166    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15167        let start_offset = self.start.to_offset(snapshot);
15168        let end_offset = self.end.to_offset(snapshot);
15169        if start_offset == end_offset {
15170            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15171        } else {
15172            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15173        }
15174    }
15175}
15176
15177pub trait RowExt {
15178    fn as_f32(&self) -> f32;
15179
15180    fn next_row(&self) -> Self;
15181
15182    fn previous_row(&self) -> Self;
15183
15184    fn minus(&self, other: Self) -> u32;
15185}
15186
15187impl RowExt for DisplayRow {
15188    fn as_f32(&self) -> f32 {
15189        self.0 as f32
15190    }
15191
15192    fn next_row(&self) -> Self {
15193        Self(self.0 + 1)
15194    }
15195
15196    fn previous_row(&self) -> Self {
15197        Self(self.0.saturating_sub(1))
15198    }
15199
15200    fn minus(&self, other: Self) -> u32 {
15201        self.0 - other.0
15202    }
15203}
15204
15205impl RowExt for MultiBufferRow {
15206    fn as_f32(&self) -> f32 {
15207        self.0 as f32
15208    }
15209
15210    fn next_row(&self) -> Self {
15211        Self(self.0 + 1)
15212    }
15213
15214    fn previous_row(&self) -> Self {
15215        Self(self.0.saturating_sub(1))
15216    }
15217
15218    fn minus(&self, other: Self) -> u32 {
15219        self.0 - other.0
15220    }
15221}
15222
15223trait RowRangeExt {
15224    type Row;
15225
15226    fn len(&self) -> usize;
15227
15228    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15229}
15230
15231impl RowRangeExt for Range<MultiBufferRow> {
15232    type Row = MultiBufferRow;
15233
15234    fn len(&self) -> usize {
15235        (self.end.0 - self.start.0) as usize
15236    }
15237
15238    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15239        (self.start.0..self.end.0).map(MultiBufferRow)
15240    }
15241}
15242
15243impl RowRangeExt for Range<DisplayRow> {
15244    type Row = DisplayRow;
15245
15246    fn len(&self) -> usize {
15247        (self.end.0 - self.start.0) as usize
15248    }
15249
15250    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15251        (self.start.0..self.end.0).map(DisplayRow)
15252    }
15253}
15254
15255fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15256    if hunk.diff_base_byte_range.is_empty() {
15257        DiffHunkStatus::Added
15258    } else if hunk.row_range.is_empty() {
15259        DiffHunkStatus::Removed
15260    } else {
15261        DiffHunkStatus::Modified
15262    }
15263}
15264
15265/// If select range has more than one line, we
15266/// just point the cursor to range.start.
15267fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15268    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15269        range
15270    } else {
15271        range.start..range.start
15272    }
15273}
15274pub struct KillRing(ClipboardItem);
15275impl Global for KillRing {}
15276
15277const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);