editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod code_context_menus;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod hunk_diff;
   29mod indent_guides;
   30mod inlay_hint_cache;
   31pub mod items;
   32mod linked_editing_ranges;
   33mod lsp_ext;
   34mod mouse_context_menu;
   35pub mod movement;
   36mod persistence;
   37mod proposed_changes_editor;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45#[cfg(test)]
   46mod inline_completion_tests;
   47mod signature_help;
   48#[cfg(any(test, feature = "test-support"))]
   49pub mod test;
   50
   51use ::git::diff::DiffHunkStatus;
   52pub(crate) use actions::*;
   53pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   54use aho_corasick::AhoCorasick;
   55use anyhow::{anyhow, Context as _, Result};
   56use blink_manager::BlinkManager;
   57use client::{Collaborator, ParticipantIndex};
   58use clock::ReplicaId;
   59use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   60use convert_case::{Case, Casing};
   61use display_map::*;
   62pub use display_map::{DisplayPoint, FoldPlaceholder};
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   65};
   66pub use editor_settings_controls::*;
   67use element::LineWithInvisibles;
   68pub use element::{
   69    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   70};
   71use futures::{future, FutureExt};
   72use fuzzy::StringMatchCandidate;
   73
   74use code_context_menus::{
   75    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   76    CompletionEntry, CompletionsMenu, ContextMenuOrigin,
   77};
   78use git::blame::GitBlame;
   79use gpui::{
   80    div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, AppContext,
   81    AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
   82    DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView, FontId,
   83    FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, ModelContext,
   84    MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
   85    Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
   86    UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
   87    WeakView, WindowContext,
   88};
   89use highlight_matching_bracket::refresh_matching_bracket_highlights;
   90use hover_popover::{hide_hover, HoverState};
   91pub(crate) use hunk_diff::HoveredHunk;
   92use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
   93use indent_guides::ActiveIndentGuidesState;
   94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   95pub use inline_completion::Direction;
   96use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
   97pub use items::MAX_TAB_TITLE_LEN;
   98use itertools::Itertools;
   99use language::{
  100    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
  101    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  102    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
  103    Point, Selection, SelectionGoal, TransactionId,
  104};
  105use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  106use linked_editing_ranges::refresh_linked_ranges;
  107use mouse_context_menu::MouseContextMenu;
  108pub use proposed_changes_editor::{
  109    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  110};
  111use similar::{ChangeTag, TextDiff};
  112use std::iter::Peekable;
  113use task::{ResolvedTask, TaskTemplate, TaskVariables};
  114
  115use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  116pub use lsp::CompletionContext;
  117use lsp::{
  118    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  119    LanguageServerId, LanguageServerName,
  120};
  121
  122use movement::TextLayoutDetails;
  123pub use multi_buffer::{
  124    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  125    ToPoint,
  126};
  127use multi_buffer::{
  128    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  129};
  130use project::{
  131    buffer_store::BufferChangeSet,
  132    lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  133    project_settings::{GitGutterSetting, ProjectSettings},
  134    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  135    LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  136};
  137use rand::prelude::*;
  138use rpc::{proto::*, ErrorExt};
  139use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  140use selections_collection::{
  141    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  142};
  143use serde::{Deserialize, Serialize};
  144use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  145use smallvec::SmallVec;
  146use snippet::Snippet;
  147use std::{
  148    any::TypeId,
  149    borrow::Cow,
  150    cell::RefCell,
  151    cmp::{self, Ordering, Reverse},
  152    mem,
  153    num::NonZeroU32,
  154    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  155    path::{Path, PathBuf},
  156    rc::Rc,
  157    sync::Arc,
  158    time::{Duration, Instant},
  159};
  160pub use sum_tree::Bias;
  161use sum_tree::TreeMap;
  162use text::{BufferId, OffsetUtf16, Rope};
  163use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
  164use ui::{
  165    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  166    PopoverMenuHandle, Tooltip,
  167};
  168use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  169use workspace::item::{ItemHandle, PreviewTabsSettings};
  170use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  171use workspace::{
  172    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  173};
  174use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  175
  176use crate::hover_links::{find_url, find_url_from_range};
  177use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  178
  179pub const FILE_HEADER_HEIGHT: u32 = 2;
  180pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  181pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  182pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  183const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  184const MAX_LINE_LEN: usize = 1024;
  185const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  186const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  187pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  188#[doc(hidden)]
  189pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  190
  191pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  192pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  193
  194pub fn render_parsed_markdown(
  195    element_id: impl Into<ElementId>,
  196    parsed: &language::ParsedMarkdown,
  197    editor_style: &EditorStyle,
  198    workspace: Option<WeakView<Workspace>>,
  199    cx: &mut WindowContext,
  200) -> InteractiveText {
  201    let code_span_background_color = cx
  202        .theme()
  203        .colors()
  204        .editor_document_highlight_read_background;
  205
  206    let highlights = gpui::combine_highlights(
  207        parsed.highlights.iter().filter_map(|(range, highlight)| {
  208            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  209            Some((range.clone(), highlight))
  210        }),
  211        parsed
  212            .regions
  213            .iter()
  214            .zip(&parsed.region_ranges)
  215            .filter_map(|(region, range)| {
  216                if region.code {
  217                    Some((
  218                        range.clone(),
  219                        HighlightStyle {
  220                            background_color: Some(code_span_background_color),
  221                            ..Default::default()
  222                        },
  223                    ))
  224                } else {
  225                    None
  226                }
  227            }),
  228    );
  229
  230    let mut links = Vec::new();
  231    let mut link_ranges = Vec::new();
  232    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  233        if let Some(link) = region.link.clone() {
  234            links.push(link);
  235            link_ranges.push(range.clone());
  236        }
  237    }
  238
  239    InteractiveText::new(
  240        element_id,
  241        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  242    )
  243    .on_click(link_ranges, move |clicked_range_ix, cx| {
  244        match &links[clicked_range_ix] {
  245            markdown::Link::Web { url } => cx.open_url(url),
  246            markdown::Link::Path { path } => {
  247                if let Some(workspace) = &workspace {
  248                    _ = workspace.update(cx, |workspace, cx| {
  249                        workspace.open_abs_path(path.clone(), false, cx).detach();
  250                    });
  251                }
  252            }
  253        }
  254    })
  255}
  256
  257#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  258pub enum InlayId {
  259    InlineCompletion(usize),
  260    Hint(usize),
  261}
  262
  263impl InlayId {
  264    fn id(&self) -> usize {
  265        match self {
  266            Self::InlineCompletion(id) => *id,
  267            Self::Hint(id) => *id,
  268        }
  269    }
  270}
  271
  272enum DiffRowHighlight {}
  273enum DocumentHighlightRead {}
  274enum DocumentHighlightWrite {}
  275enum InputComposition {}
  276
  277#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  278pub enum Navigated {
  279    Yes,
  280    No,
  281}
  282
  283impl Navigated {
  284    pub fn from_bool(yes: bool) -> Navigated {
  285        if yes {
  286            Navigated::Yes
  287        } else {
  288            Navigated::No
  289        }
  290    }
  291}
  292
  293pub fn init_settings(cx: &mut AppContext) {
  294    EditorSettings::register(cx);
  295}
  296
  297pub fn init(cx: &mut AppContext) {
  298    init_settings(cx);
  299
  300    workspace::register_project_item::<Editor>(cx);
  301    workspace::FollowableViewRegistry::register::<Editor>(cx);
  302    workspace::register_serializable_item::<Editor>(cx);
  303
  304    cx.observe_new_views(
  305        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  306            workspace.register_action(Editor::new_file);
  307            workspace.register_action(Editor::new_file_vertical);
  308            workspace.register_action(Editor::new_file_horizontal);
  309        },
  310    )
  311    .detach();
  312
  313    cx.on_action(move |_: &workspace::NewFile, cx| {
  314        let app_state = workspace::AppState::global(cx);
  315        if let Some(app_state) = app_state.upgrade() {
  316            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  317                Editor::new_file(workspace, &Default::default(), cx)
  318            })
  319            .detach();
  320        }
  321    });
  322    cx.on_action(move |_: &workspace::NewWindow, cx| {
  323        let app_state = workspace::AppState::global(cx);
  324        if let Some(app_state) = app_state.upgrade() {
  325            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  326                Editor::new_file(workspace, &Default::default(), cx)
  327            })
  328            .detach();
  329        }
  330    });
  331    git::project_diff::init(cx);
  332}
  333
  334pub struct SearchWithinRange;
  335
  336trait InvalidationRegion {
  337    fn ranges(&self) -> &[Range<Anchor>];
  338}
  339
  340#[derive(Clone, Debug, PartialEq)]
  341pub enum SelectPhase {
  342    Begin {
  343        position: DisplayPoint,
  344        add: bool,
  345        click_count: usize,
  346    },
  347    BeginColumnar {
  348        position: DisplayPoint,
  349        reset: bool,
  350        goal_column: u32,
  351    },
  352    Extend {
  353        position: DisplayPoint,
  354        click_count: usize,
  355    },
  356    Update {
  357        position: DisplayPoint,
  358        goal_column: u32,
  359        scroll_delta: gpui::Point<f32>,
  360    },
  361    End,
  362}
  363
  364#[derive(Clone, Debug)]
  365pub enum SelectMode {
  366    Character,
  367    Word(Range<Anchor>),
  368    Line(Range<Anchor>),
  369    All,
  370}
  371
  372#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  373pub enum EditorMode {
  374    SingleLine { auto_width: bool },
  375    AutoHeight { max_lines: usize },
  376    Full,
  377}
  378
  379#[derive(Copy, Clone, Debug)]
  380pub enum SoftWrap {
  381    /// Prefer not to wrap at all.
  382    ///
  383    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  384    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  385    GitDiff,
  386    /// Prefer a single line generally, unless an overly long line is encountered.
  387    None,
  388    /// Soft wrap lines that exceed the editor width.
  389    EditorWidth,
  390    /// Soft wrap lines at the preferred line length.
  391    Column(u32),
  392    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  393    Bounded(u32),
  394}
  395
  396#[derive(Clone)]
  397pub struct EditorStyle {
  398    pub background: Hsla,
  399    pub local_player: PlayerColor,
  400    pub text: TextStyle,
  401    pub scrollbar_width: Pixels,
  402    pub syntax: Arc<SyntaxTheme>,
  403    pub status: StatusColors,
  404    pub inlay_hints_style: HighlightStyle,
  405    pub inline_completion_styles: InlineCompletionStyles,
  406    pub unnecessary_code_fade: f32,
  407}
  408
  409impl Default for EditorStyle {
  410    fn default() -> Self {
  411        Self {
  412            background: Hsla::default(),
  413            local_player: PlayerColor::default(),
  414            text: TextStyle::default(),
  415            scrollbar_width: Pixels::default(),
  416            syntax: Default::default(),
  417            // HACK: Status colors don't have a real default.
  418            // We should look into removing the status colors from the editor
  419            // style and retrieve them directly from the theme.
  420            status: StatusColors::dark(),
  421            inlay_hints_style: HighlightStyle::default(),
  422            inline_completion_styles: InlineCompletionStyles {
  423                insertion: HighlightStyle::default(),
  424                whitespace: HighlightStyle::default(),
  425            },
  426            unnecessary_code_fade: Default::default(),
  427        }
  428    }
  429}
  430
  431pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  432    let show_background = language_settings::language_settings(None, None, cx)
  433        .inlay_hints
  434        .show_background;
  435
  436    HighlightStyle {
  437        color: Some(cx.theme().status().hint),
  438        background_color: show_background.then(|| cx.theme().status().hint_background),
  439        ..HighlightStyle::default()
  440    }
  441}
  442
  443pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
  444    InlineCompletionStyles {
  445        insertion: HighlightStyle {
  446            color: Some(cx.theme().status().predictive),
  447            ..HighlightStyle::default()
  448        },
  449        whitespace: HighlightStyle {
  450            background_color: Some(cx.theme().status().created_background),
  451            ..HighlightStyle::default()
  452        },
  453    }
  454}
  455
  456type CompletionId = usize;
  457
  458#[derive(Debug, Clone)]
  459enum InlineCompletionMenuHint {
  460    Loading,
  461    Loaded { text: InlineCompletionText },
  462    None,
  463}
  464
  465impl InlineCompletionMenuHint {
  466    pub fn label(&self) -> &'static str {
  467        match self {
  468            InlineCompletionMenuHint::Loading | InlineCompletionMenuHint::Loaded { .. } => {
  469                "Edit Prediction"
  470            }
  471            InlineCompletionMenuHint::None => "No Prediction",
  472        }
  473    }
  474}
  475
  476#[derive(Clone, Debug)]
  477enum InlineCompletionText {
  478    Move(SharedString),
  479    Edit {
  480        text: SharedString,
  481        highlights: Vec<(Range<usize>, HighlightStyle)>,
  482    },
  483}
  484
  485enum InlineCompletion {
  486    Edit(Vec<(Range<Anchor>, String)>),
  487    Move(Anchor),
  488}
  489
  490struct InlineCompletionState {
  491    inlay_ids: Vec<InlayId>,
  492    completion: InlineCompletion,
  493    invalidation_range: Range<Anchor>,
  494}
  495
  496enum InlineCompletionHighlight {}
  497
  498#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  499struct EditorActionId(usize);
  500
  501impl EditorActionId {
  502    pub fn post_inc(&mut self) -> Self {
  503        let answer = self.0;
  504
  505        *self = Self(answer + 1);
  506
  507        Self(answer)
  508    }
  509}
  510
  511// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  512// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  513
  514type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  515type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  516
  517#[derive(Default)]
  518struct ScrollbarMarkerState {
  519    scrollbar_size: Size<Pixels>,
  520    dirty: bool,
  521    markers: Arc<[PaintQuad]>,
  522    pending_refresh: Option<Task<Result<()>>>,
  523}
  524
  525impl ScrollbarMarkerState {
  526    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  527        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  528    }
  529}
  530
  531#[derive(Clone, Debug)]
  532struct RunnableTasks {
  533    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  534    offset: MultiBufferOffset,
  535    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  536    column: u32,
  537    // Values of all named captures, including those starting with '_'
  538    extra_variables: HashMap<String, String>,
  539    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  540    context_range: Range<BufferOffset>,
  541}
  542
  543impl RunnableTasks {
  544    fn resolve<'a>(
  545        &'a self,
  546        cx: &'a task::TaskContext,
  547    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  548        self.templates.iter().filter_map(|(kind, template)| {
  549            template
  550                .resolve_task(&kind.to_id_base(), cx)
  551                .map(|task| (kind.clone(), task))
  552        })
  553    }
  554}
  555
  556#[derive(Clone)]
  557struct ResolvedTasks {
  558    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  559    position: Anchor,
  560}
  561#[derive(Copy, Clone, Debug)]
  562struct MultiBufferOffset(usize);
  563#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  564struct BufferOffset(usize);
  565
  566// Addons allow storing per-editor state in other crates (e.g. Vim)
  567pub trait Addon: 'static {
  568    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  569
  570    fn to_any(&self) -> &dyn std::any::Any;
  571}
  572
  573#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  574pub enum IsVimMode {
  575    Yes,
  576    No,
  577}
  578
  579/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  580///
  581/// See the [module level documentation](self) for more information.
  582pub struct Editor {
  583    focus_handle: FocusHandle,
  584    last_focused_descendant: Option<WeakFocusHandle>,
  585    /// The text buffer being edited
  586    buffer: Model<MultiBuffer>,
  587    /// Map of how text in the buffer should be displayed.
  588    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  589    pub display_map: Model<DisplayMap>,
  590    pub selections: SelectionsCollection,
  591    pub scroll_manager: ScrollManager,
  592    /// When inline assist editors are linked, they all render cursors because
  593    /// typing enters text into each of them, even the ones that aren't focused.
  594    pub(crate) show_cursor_when_unfocused: bool,
  595    columnar_selection_tail: Option<Anchor>,
  596    add_selections_state: Option<AddSelectionsState>,
  597    select_next_state: Option<SelectNextState>,
  598    select_prev_state: Option<SelectNextState>,
  599    selection_history: SelectionHistory,
  600    autoclose_regions: Vec<AutocloseRegion>,
  601    snippet_stack: InvalidationStack<SnippetState>,
  602    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  603    ime_transaction: Option<TransactionId>,
  604    active_diagnostics: Option<ActiveDiagnosticGroup>,
  605    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  606
  607    project: Option<Model<Project>>,
  608    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  609    completion_provider: Option<Box<dyn CompletionProvider>>,
  610    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  611    blink_manager: Model<BlinkManager>,
  612    show_cursor_names: bool,
  613    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  614    pub show_local_selections: bool,
  615    mode: EditorMode,
  616    show_breadcrumbs: bool,
  617    show_gutter: bool,
  618    show_scrollbars: bool,
  619    show_line_numbers: Option<bool>,
  620    use_relative_line_numbers: Option<bool>,
  621    show_git_diff_gutter: Option<bool>,
  622    show_code_actions: Option<bool>,
  623    show_runnables: Option<bool>,
  624    show_wrap_guides: Option<bool>,
  625    show_indent_guides: Option<bool>,
  626    placeholder_text: Option<Arc<str>>,
  627    highlight_order: usize,
  628    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  629    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  630    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  631    scrollbar_marker_state: ScrollbarMarkerState,
  632    active_indent_guides_state: ActiveIndentGuidesState,
  633    nav_history: Option<ItemNavHistory>,
  634    context_menu: RefCell<Option<CodeContextMenu>>,
  635    mouse_context_menu: Option<MouseContextMenu>,
  636    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  637    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  638    signature_help_state: SignatureHelpState,
  639    auto_signature_help: Option<bool>,
  640    find_all_references_task_sources: Vec<Anchor>,
  641    next_completion_id: CompletionId,
  642    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  643    code_actions_task: Option<Task<Result<()>>>,
  644    document_highlights_task: Option<Task<()>>,
  645    linked_editing_range_task: Option<Task<Option<()>>>,
  646    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  647    pending_rename: Option<RenameState>,
  648    searchable: bool,
  649    cursor_shape: CursorShape,
  650    current_line_highlight: Option<CurrentLineHighlight>,
  651    collapse_matches: bool,
  652    autoindent_mode: Option<AutoindentMode>,
  653    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  654    input_enabled: bool,
  655    use_modal_editing: bool,
  656    read_only: bool,
  657    leader_peer_id: Option<PeerId>,
  658    remote_id: Option<ViewId>,
  659    hover_state: HoverState,
  660    gutter_hovered: bool,
  661    hovered_link_state: Option<HoveredLinkState>,
  662    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  663    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  664    active_inline_completion: Option<InlineCompletionState>,
  665    // enable_inline_completions is a switch that Vim can use to disable
  666    // inline completions based on its mode.
  667    enable_inline_completions: bool,
  668    show_inline_completions_override: Option<bool>,
  669    inlay_hint_cache: InlayHintCache,
  670    diff_map: DiffMap,
  671    next_inlay_id: usize,
  672    _subscriptions: Vec<Subscription>,
  673    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  674    gutter_dimensions: GutterDimensions,
  675    style: Option<EditorStyle>,
  676    text_style_refinement: Option<TextStyleRefinement>,
  677    next_editor_action_id: EditorActionId,
  678    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  679    use_autoclose: bool,
  680    use_auto_surround: bool,
  681    auto_replace_emoji_shortcode: bool,
  682    show_git_blame_gutter: bool,
  683    show_git_blame_inline: bool,
  684    show_git_blame_inline_delay_task: Option<Task<()>>,
  685    git_blame_inline_enabled: bool,
  686    serialize_dirty_buffers: bool,
  687    show_selection_menu: Option<bool>,
  688    blame: Option<Model<GitBlame>>,
  689    blame_subscription: Option<Subscription>,
  690    custom_context_menu: Option<
  691        Box<
  692            dyn 'static
  693                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  694        >,
  695    >,
  696    last_bounds: Option<Bounds<Pixels>>,
  697    expect_bounds_change: Option<Bounds<Pixels>>,
  698    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  699    tasks_update_task: Option<Task<()>>,
  700    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  701    breadcrumb_header: Option<String>,
  702    focused_block: Option<FocusedBlock>,
  703    next_scroll_position: NextScrollCursorCenterTopBottom,
  704    addons: HashMap<TypeId, Box<dyn Addon>>,
  705    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  706    toggle_fold_multiple_buffers: Task<()>,
  707    _scroll_cursor_center_top_bottom_task: Task<()>,
  708}
  709
  710#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  711enum NextScrollCursorCenterTopBottom {
  712    #[default]
  713    Center,
  714    Top,
  715    Bottom,
  716}
  717
  718impl NextScrollCursorCenterTopBottom {
  719    fn next(&self) -> Self {
  720        match self {
  721            Self::Center => Self::Top,
  722            Self::Top => Self::Bottom,
  723            Self::Bottom => Self::Center,
  724        }
  725    }
  726}
  727
  728#[derive(Clone)]
  729pub struct EditorSnapshot {
  730    pub mode: EditorMode,
  731    show_gutter: bool,
  732    show_line_numbers: Option<bool>,
  733    show_git_diff_gutter: Option<bool>,
  734    show_code_actions: Option<bool>,
  735    show_runnables: Option<bool>,
  736    git_blame_gutter_max_author_length: Option<usize>,
  737    pub display_snapshot: DisplaySnapshot,
  738    pub placeholder_text: Option<Arc<str>>,
  739    diff_map: DiffMapSnapshot,
  740    is_focused: bool,
  741    scroll_anchor: ScrollAnchor,
  742    ongoing_scroll: OngoingScroll,
  743    current_line_highlight: CurrentLineHighlight,
  744    gutter_hovered: bool,
  745}
  746
  747const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  748
  749#[derive(Default, Debug, Clone, Copy)]
  750pub struct GutterDimensions {
  751    pub left_padding: Pixels,
  752    pub right_padding: Pixels,
  753    pub width: Pixels,
  754    pub margin: Pixels,
  755    pub git_blame_entries_width: Option<Pixels>,
  756}
  757
  758impl GutterDimensions {
  759    /// The full width of the space taken up by the gutter.
  760    pub fn full_width(&self) -> Pixels {
  761        self.margin + self.width
  762    }
  763
  764    /// The width of the space reserved for the fold indicators,
  765    /// use alongside 'justify_end' and `gutter_width` to
  766    /// right align content with the line numbers
  767    pub fn fold_area_width(&self) -> Pixels {
  768        self.margin + self.right_padding
  769    }
  770}
  771
  772#[derive(Debug)]
  773pub struct RemoteSelection {
  774    pub replica_id: ReplicaId,
  775    pub selection: Selection<Anchor>,
  776    pub cursor_shape: CursorShape,
  777    pub peer_id: PeerId,
  778    pub line_mode: bool,
  779    pub participant_index: Option<ParticipantIndex>,
  780    pub user_name: Option<SharedString>,
  781}
  782
  783#[derive(Clone, Debug)]
  784struct SelectionHistoryEntry {
  785    selections: Arc<[Selection<Anchor>]>,
  786    select_next_state: Option<SelectNextState>,
  787    select_prev_state: Option<SelectNextState>,
  788    add_selections_state: Option<AddSelectionsState>,
  789}
  790
  791enum SelectionHistoryMode {
  792    Normal,
  793    Undoing,
  794    Redoing,
  795}
  796
  797#[derive(Clone, PartialEq, Eq, Hash)]
  798struct HoveredCursor {
  799    replica_id: u16,
  800    selection_id: usize,
  801}
  802
  803impl Default for SelectionHistoryMode {
  804    fn default() -> Self {
  805        Self::Normal
  806    }
  807}
  808
  809#[derive(Default)]
  810struct SelectionHistory {
  811    #[allow(clippy::type_complexity)]
  812    selections_by_transaction:
  813        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  814    mode: SelectionHistoryMode,
  815    undo_stack: VecDeque<SelectionHistoryEntry>,
  816    redo_stack: VecDeque<SelectionHistoryEntry>,
  817}
  818
  819impl SelectionHistory {
  820    fn insert_transaction(
  821        &mut self,
  822        transaction_id: TransactionId,
  823        selections: Arc<[Selection<Anchor>]>,
  824    ) {
  825        self.selections_by_transaction
  826            .insert(transaction_id, (selections, None));
  827    }
  828
  829    #[allow(clippy::type_complexity)]
  830    fn transaction(
  831        &self,
  832        transaction_id: TransactionId,
  833    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  834        self.selections_by_transaction.get(&transaction_id)
  835    }
  836
  837    #[allow(clippy::type_complexity)]
  838    fn transaction_mut(
  839        &mut self,
  840        transaction_id: TransactionId,
  841    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  842        self.selections_by_transaction.get_mut(&transaction_id)
  843    }
  844
  845    fn push(&mut self, entry: SelectionHistoryEntry) {
  846        if !entry.selections.is_empty() {
  847            match self.mode {
  848                SelectionHistoryMode::Normal => {
  849                    self.push_undo(entry);
  850                    self.redo_stack.clear();
  851                }
  852                SelectionHistoryMode::Undoing => self.push_redo(entry),
  853                SelectionHistoryMode::Redoing => self.push_undo(entry),
  854            }
  855        }
  856    }
  857
  858    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  859        if self
  860            .undo_stack
  861            .back()
  862            .map_or(true, |e| e.selections != entry.selections)
  863        {
  864            self.undo_stack.push_back(entry);
  865            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  866                self.undo_stack.pop_front();
  867            }
  868        }
  869    }
  870
  871    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  872        if self
  873            .redo_stack
  874            .back()
  875            .map_or(true, |e| e.selections != entry.selections)
  876        {
  877            self.redo_stack.push_back(entry);
  878            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  879                self.redo_stack.pop_front();
  880            }
  881        }
  882    }
  883}
  884
  885struct RowHighlight {
  886    index: usize,
  887    range: Range<Anchor>,
  888    color: Hsla,
  889    should_autoscroll: bool,
  890}
  891
  892#[derive(Clone, Debug)]
  893struct AddSelectionsState {
  894    above: bool,
  895    stack: Vec<usize>,
  896}
  897
  898#[derive(Clone)]
  899struct SelectNextState {
  900    query: AhoCorasick,
  901    wordwise: bool,
  902    done: bool,
  903}
  904
  905impl std::fmt::Debug for SelectNextState {
  906    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  907        f.debug_struct(std::any::type_name::<Self>())
  908            .field("wordwise", &self.wordwise)
  909            .field("done", &self.done)
  910            .finish()
  911    }
  912}
  913
  914#[derive(Debug)]
  915struct AutocloseRegion {
  916    selection_id: usize,
  917    range: Range<Anchor>,
  918    pair: BracketPair,
  919}
  920
  921#[derive(Debug)]
  922struct SnippetState {
  923    ranges: Vec<Vec<Range<Anchor>>>,
  924    active_index: usize,
  925    choices: Vec<Option<Vec<String>>>,
  926}
  927
  928#[doc(hidden)]
  929pub struct RenameState {
  930    pub range: Range<Anchor>,
  931    pub old_name: Arc<str>,
  932    pub editor: View<Editor>,
  933    block_id: CustomBlockId,
  934}
  935
  936struct InvalidationStack<T>(Vec<T>);
  937
  938struct RegisteredInlineCompletionProvider {
  939    provider: Arc<dyn InlineCompletionProviderHandle>,
  940    _subscription: Subscription,
  941}
  942
  943#[derive(Debug)]
  944struct ActiveDiagnosticGroup {
  945    primary_range: Range<Anchor>,
  946    primary_message: String,
  947    group_id: usize,
  948    blocks: HashMap<CustomBlockId, Diagnostic>,
  949    is_valid: bool,
  950}
  951
  952#[derive(Serialize, Deserialize, Clone, Debug)]
  953pub struct ClipboardSelection {
  954    pub len: usize,
  955    pub is_entire_line: bool,
  956    pub first_line_indent: u32,
  957}
  958
  959#[derive(Debug)]
  960pub(crate) struct NavigationData {
  961    cursor_anchor: Anchor,
  962    cursor_position: Point,
  963    scroll_anchor: ScrollAnchor,
  964    scroll_top_row: u32,
  965}
  966
  967#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  968pub enum GotoDefinitionKind {
  969    Symbol,
  970    Declaration,
  971    Type,
  972    Implementation,
  973}
  974
  975#[derive(Debug, Clone)]
  976enum InlayHintRefreshReason {
  977    Toggle(bool),
  978    SettingsChange(InlayHintSettings),
  979    NewLinesShown,
  980    BufferEdited(HashSet<Arc<Language>>),
  981    RefreshRequested,
  982    ExcerptsRemoved(Vec<ExcerptId>),
  983}
  984
  985impl InlayHintRefreshReason {
  986    fn description(&self) -> &'static str {
  987        match self {
  988            Self::Toggle(_) => "toggle",
  989            Self::SettingsChange(_) => "settings change",
  990            Self::NewLinesShown => "new lines shown",
  991            Self::BufferEdited(_) => "buffer edited",
  992            Self::RefreshRequested => "refresh requested",
  993            Self::ExcerptsRemoved(_) => "excerpts removed",
  994        }
  995    }
  996}
  997
  998pub enum FormatTarget {
  999    Buffers,
 1000    Ranges(Vec<Range<MultiBufferPoint>>),
 1001}
 1002
 1003pub(crate) struct FocusedBlock {
 1004    id: BlockId,
 1005    focus_handle: WeakFocusHandle,
 1006}
 1007
 1008#[derive(Clone)]
 1009enum JumpData {
 1010    MultiBufferRow {
 1011        row: MultiBufferRow,
 1012        line_offset_from_top: u32,
 1013    },
 1014    MultiBufferPoint {
 1015        excerpt_id: ExcerptId,
 1016        position: Point,
 1017        anchor: text::Anchor,
 1018        line_offset_from_top: u32,
 1019    },
 1020}
 1021
 1022impl Editor {
 1023    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1024        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1025        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1026        Self::new(
 1027            EditorMode::SingleLine { auto_width: false },
 1028            buffer,
 1029            None,
 1030            false,
 1031            cx,
 1032        )
 1033    }
 1034
 1035    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1036        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1037        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1038        Self::new(EditorMode::Full, buffer, None, false, cx)
 1039    }
 1040
 1041    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1042        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1043        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1044        Self::new(
 1045            EditorMode::SingleLine { auto_width: true },
 1046            buffer,
 1047            None,
 1048            false,
 1049            cx,
 1050        )
 1051    }
 1052
 1053    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1054        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1055        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1056        Self::new(
 1057            EditorMode::AutoHeight { max_lines },
 1058            buffer,
 1059            None,
 1060            false,
 1061            cx,
 1062        )
 1063    }
 1064
 1065    pub fn for_buffer(
 1066        buffer: Model<Buffer>,
 1067        project: Option<Model<Project>>,
 1068        cx: &mut ViewContext<Self>,
 1069    ) -> Self {
 1070        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1071        Self::new(EditorMode::Full, buffer, project, false, cx)
 1072    }
 1073
 1074    pub fn for_multibuffer(
 1075        buffer: Model<MultiBuffer>,
 1076        project: Option<Model<Project>>,
 1077        show_excerpt_controls: bool,
 1078        cx: &mut ViewContext<Self>,
 1079    ) -> Self {
 1080        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1081    }
 1082
 1083    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1084        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1085        let mut clone = Self::new(
 1086            self.mode,
 1087            self.buffer.clone(),
 1088            self.project.clone(),
 1089            show_excerpt_controls,
 1090            cx,
 1091        );
 1092        self.display_map.update(cx, |display_map, cx| {
 1093            let snapshot = display_map.snapshot(cx);
 1094            clone.display_map.update(cx, |display_map, cx| {
 1095                display_map.set_state(&snapshot, cx);
 1096            });
 1097        });
 1098        clone.selections.clone_state(&self.selections);
 1099        clone.scroll_manager.clone_state(&self.scroll_manager);
 1100        clone.searchable = self.searchable;
 1101        clone
 1102    }
 1103
 1104    pub fn new(
 1105        mode: EditorMode,
 1106        buffer: Model<MultiBuffer>,
 1107        project: Option<Model<Project>>,
 1108        show_excerpt_controls: bool,
 1109        cx: &mut ViewContext<Self>,
 1110    ) -> Self {
 1111        let style = cx.text_style();
 1112        let font_size = style.font_size.to_pixels(cx.rem_size());
 1113        let editor = cx.view().downgrade();
 1114        let fold_placeholder = FoldPlaceholder {
 1115            constrain_width: true,
 1116            render: Arc::new(move |fold_id, fold_range, cx| {
 1117                let editor = editor.clone();
 1118                div()
 1119                    .id(fold_id)
 1120                    .bg(cx.theme().colors().ghost_element_background)
 1121                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1122                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1123                    .rounded_sm()
 1124                    .size_full()
 1125                    .cursor_pointer()
 1126                    .child("")
 1127                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1128                    .on_click(move |_, cx| {
 1129                        editor
 1130                            .update(cx, |editor, cx| {
 1131                                editor.unfold_ranges(
 1132                                    &[fold_range.start..fold_range.end],
 1133                                    true,
 1134                                    false,
 1135                                    cx,
 1136                                );
 1137                                cx.stop_propagation();
 1138                            })
 1139                            .ok();
 1140                    })
 1141                    .into_any()
 1142            }),
 1143            merge_adjacent: true,
 1144            ..Default::default()
 1145        };
 1146        let display_map = cx.new_model(|cx| {
 1147            DisplayMap::new(
 1148                buffer.clone(),
 1149                style.font(),
 1150                font_size,
 1151                None,
 1152                show_excerpt_controls,
 1153                FILE_HEADER_HEIGHT,
 1154                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1155                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1156                fold_placeholder,
 1157                cx,
 1158            )
 1159        });
 1160
 1161        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1162
 1163        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1164
 1165        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1166            .then(|| language_settings::SoftWrap::None);
 1167
 1168        let mut project_subscriptions = Vec::new();
 1169        if mode == EditorMode::Full {
 1170            if let Some(project) = project.as_ref() {
 1171                if buffer.read(cx).is_singleton() {
 1172                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1173                        cx.emit(EditorEvent::TitleChanged);
 1174                    }));
 1175                }
 1176                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1177                    if let project::Event::RefreshInlayHints = event {
 1178                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1179                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1180                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1181                            let focus_handle = editor.focus_handle(cx);
 1182                            if focus_handle.is_focused(cx) {
 1183                                let snapshot = buffer.read(cx).snapshot();
 1184                                for (range, snippet) in snippet_edits {
 1185                                    let editor_range =
 1186                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1187                                    editor
 1188                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1189                                        .ok();
 1190                                }
 1191                            }
 1192                        }
 1193                    }
 1194                }));
 1195                if let Some(task_inventory) = project
 1196                    .read(cx)
 1197                    .task_store()
 1198                    .read(cx)
 1199                    .task_inventory()
 1200                    .cloned()
 1201                {
 1202                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1203                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1204                    }));
 1205                }
 1206            }
 1207        }
 1208
 1209        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1210
 1211        let inlay_hint_settings =
 1212            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1213        let focus_handle = cx.focus_handle();
 1214        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1215        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1216            .detach();
 1217        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1218            .detach();
 1219        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1220
 1221        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1222            Some(false)
 1223        } else {
 1224            None
 1225        };
 1226
 1227        let mut code_action_providers = Vec::new();
 1228        if let Some(project) = project.clone() {
 1229            get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
 1230            code_action_providers.push(Rc::new(project) as Rc<_>);
 1231        }
 1232
 1233        let mut this = Self {
 1234            focus_handle,
 1235            show_cursor_when_unfocused: false,
 1236            last_focused_descendant: None,
 1237            buffer: buffer.clone(),
 1238            display_map: display_map.clone(),
 1239            selections,
 1240            scroll_manager: ScrollManager::new(cx),
 1241            columnar_selection_tail: None,
 1242            add_selections_state: None,
 1243            select_next_state: None,
 1244            select_prev_state: None,
 1245            selection_history: Default::default(),
 1246            autoclose_regions: Default::default(),
 1247            snippet_stack: Default::default(),
 1248            select_larger_syntax_node_stack: Vec::new(),
 1249            ime_transaction: Default::default(),
 1250            active_diagnostics: None,
 1251            soft_wrap_mode_override,
 1252            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1253            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1254            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1255            project,
 1256            blink_manager: blink_manager.clone(),
 1257            show_local_selections: true,
 1258            show_scrollbars: true,
 1259            mode,
 1260            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1261            show_gutter: mode == EditorMode::Full,
 1262            show_line_numbers: None,
 1263            use_relative_line_numbers: None,
 1264            show_git_diff_gutter: None,
 1265            show_code_actions: None,
 1266            show_runnables: None,
 1267            show_wrap_guides: None,
 1268            show_indent_guides,
 1269            placeholder_text: None,
 1270            highlight_order: 0,
 1271            highlighted_rows: HashMap::default(),
 1272            background_highlights: Default::default(),
 1273            gutter_highlights: TreeMap::default(),
 1274            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1275            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1276            nav_history: None,
 1277            context_menu: RefCell::new(None),
 1278            mouse_context_menu: None,
 1279            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1280            completion_tasks: Default::default(),
 1281            signature_help_state: SignatureHelpState::default(),
 1282            auto_signature_help: None,
 1283            find_all_references_task_sources: Vec::new(),
 1284            next_completion_id: 0,
 1285            next_inlay_id: 0,
 1286            code_action_providers,
 1287            available_code_actions: Default::default(),
 1288            code_actions_task: Default::default(),
 1289            document_highlights_task: Default::default(),
 1290            linked_editing_range_task: Default::default(),
 1291            pending_rename: Default::default(),
 1292            searchable: true,
 1293            cursor_shape: EditorSettings::get_global(cx)
 1294                .cursor_shape
 1295                .unwrap_or_default(),
 1296            current_line_highlight: None,
 1297            autoindent_mode: Some(AutoindentMode::EachLine),
 1298            collapse_matches: false,
 1299            workspace: None,
 1300            input_enabled: true,
 1301            use_modal_editing: mode == EditorMode::Full,
 1302            read_only: false,
 1303            use_autoclose: true,
 1304            use_auto_surround: true,
 1305            auto_replace_emoji_shortcode: false,
 1306            leader_peer_id: None,
 1307            remote_id: None,
 1308            hover_state: Default::default(),
 1309            hovered_link_state: Default::default(),
 1310            inline_completion_provider: None,
 1311            active_inline_completion: None,
 1312            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1313            diff_map: DiffMap::default(),
 1314            gutter_hovered: false,
 1315            pixel_position_of_newest_cursor: None,
 1316            last_bounds: None,
 1317            expect_bounds_change: None,
 1318            gutter_dimensions: GutterDimensions::default(),
 1319            style: None,
 1320            show_cursor_names: false,
 1321            hovered_cursors: Default::default(),
 1322            next_editor_action_id: EditorActionId::default(),
 1323            editor_actions: Rc::default(),
 1324            show_inline_completions_override: None,
 1325            enable_inline_completions: true,
 1326            custom_context_menu: None,
 1327            show_git_blame_gutter: false,
 1328            show_git_blame_inline: false,
 1329            show_selection_menu: None,
 1330            show_git_blame_inline_delay_task: None,
 1331            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1332            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1333                .session
 1334                .restore_unsaved_buffers,
 1335            blame: None,
 1336            blame_subscription: None,
 1337            tasks: Default::default(),
 1338            _subscriptions: vec![
 1339                cx.observe(&buffer, Self::on_buffer_changed),
 1340                cx.subscribe(&buffer, Self::on_buffer_event),
 1341                cx.observe(&display_map, Self::on_display_map_changed),
 1342                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1343                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1344                cx.observe_window_activation(|editor, cx| {
 1345                    let active = cx.is_window_active();
 1346                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1347                        if active {
 1348                            blink_manager.enable(cx);
 1349                        } else {
 1350                            blink_manager.disable(cx);
 1351                        }
 1352                    });
 1353                }),
 1354            ],
 1355            tasks_update_task: None,
 1356            linked_edit_ranges: Default::default(),
 1357            previous_search_ranges: None,
 1358            breadcrumb_header: None,
 1359            focused_block: None,
 1360            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1361            addons: HashMap::default(),
 1362            registered_buffers: HashMap::default(),
 1363            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1364            toggle_fold_multiple_buffers: Task::ready(()),
 1365            text_style_refinement: None,
 1366        };
 1367        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1368        this._subscriptions.extend(project_subscriptions);
 1369
 1370        this.end_selection(cx);
 1371        this.scroll_manager.show_scrollbar(cx);
 1372
 1373        if mode == EditorMode::Full {
 1374            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1375            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1376
 1377            if this.git_blame_inline_enabled {
 1378                this.git_blame_inline_enabled = true;
 1379                this.start_git_blame_inline(false, cx);
 1380            }
 1381
 1382            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1383                if let Some(project) = this.project.as_ref() {
 1384                    let lsp_store = project.read(cx).lsp_store();
 1385                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1386                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1387                    });
 1388                    this.registered_buffers
 1389                        .insert(buffer.read(cx).remote_id(), handle);
 1390                }
 1391            }
 1392        }
 1393
 1394        this.report_editor_event("Editor Opened", None, cx);
 1395        this
 1396    }
 1397
 1398    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 1399        self.mouse_context_menu
 1400            .as_ref()
 1401            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1402    }
 1403
 1404    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 1405        let mut key_context = KeyContext::new_with_defaults();
 1406        key_context.add("Editor");
 1407        let mode = match self.mode {
 1408            EditorMode::SingleLine { .. } => "single_line",
 1409            EditorMode::AutoHeight { .. } => "auto_height",
 1410            EditorMode::Full => "full",
 1411        };
 1412
 1413        if EditorSettings::jupyter_enabled(cx) {
 1414            key_context.add("jupyter");
 1415        }
 1416
 1417        key_context.set("mode", mode);
 1418        if self.pending_rename.is_some() {
 1419            key_context.add("renaming");
 1420        }
 1421        match self.context_menu.borrow().as_ref() {
 1422            Some(CodeContextMenu::Completions(_)) => {
 1423                key_context.add("menu");
 1424                key_context.add("showing_completions")
 1425            }
 1426            Some(CodeContextMenu::CodeActions(_)) => {
 1427                key_context.add("menu");
 1428                key_context.add("showing_code_actions")
 1429            }
 1430            None => {}
 1431        }
 1432
 1433        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1434        if !self.focus_handle(cx).contains_focused(cx)
 1435            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 1436        {
 1437            for addon in self.addons.values() {
 1438                addon.extend_key_context(&mut key_context, cx)
 1439            }
 1440        }
 1441
 1442        if let Some(extension) = self
 1443            .buffer
 1444            .read(cx)
 1445            .as_singleton()
 1446            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1447        {
 1448            key_context.set("extension", extension.to_string());
 1449        }
 1450
 1451        if self.has_active_inline_completion() {
 1452            key_context.add("copilot_suggestion");
 1453            key_context.add("inline_completion");
 1454        }
 1455
 1456        if !self
 1457            .selections
 1458            .disjoint
 1459            .iter()
 1460            .all(|selection| selection.start == selection.end)
 1461        {
 1462            key_context.add("selection");
 1463        }
 1464
 1465        key_context
 1466    }
 1467
 1468    pub fn new_file(
 1469        workspace: &mut Workspace,
 1470        _: &workspace::NewFile,
 1471        cx: &mut ViewContext<Workspace>,
 1472    ) {
 1473        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1474            "Failed to create buffer",
 1475            cx,
 1476            |e, _| match e.error_code() {
 1477                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1478                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1479                e.error_tag("required").unwrap_or("the latest version")
 1480            )),
 1481                _ => None,
 1482            },
 1483        );
 1484    }
 1485
 1486    pub fn new_in_workspace(
 1487        workspace: &mut Workspace,
 1488        cx: &mut ViewContext<Workspace>,
 1489    ) -> Task<Result<View<Editor>>> {
 1490        let project = workspace.project().clone();
 1491        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1492
 1493        cx.spawn(|workspace, mut cx| async move {
 1494            let buffer = create.await?;
 1495            workspace.update(&mut cx, |workspace, cx| {
 1496                let editor =
 1497                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 1498                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 1499                editor
 1500            })
 1501        })
 1502    }
 1503
 1504    fn new_file_vertical(
 1505        workspace: &mut Workspace,
 1506        _: &workspace::NewFileSplitVertical,
 1507        cx: &mut ViewContext<Workspace>,
 1508    ) {
 1509        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 1510    }
 1511
 1512    fn new_file_horizontal(
 1513        workspace: &mut Workspace,
 1514        _: &workspace::NewFileSplitHorizontal,
 1515        cx: &mut ViewContext<Workspace>,
 1516    ) {
 1517        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 1518    }
 1519
 1520    fn new_file_in_direction(
 1521        workspace: &mut Workspace,
 1522        direction: SplitDirection,
 1523        cx: &mut ViewContext<Workspace>,
 1524    ) {
 1525        let project = workspace.project().clone();
 1526        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1527
 1528        cx.spawn(|workspace, mut cx| async move {
 1529            let buffer = create.await?;
 1530            workspace.update(&mut cx, move |workspace, cx| {
 1531                workspace.split_item(
 1532                    direction,
 1533                    Box::new(
 1534                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1535                    ),
 1536                    cx,
 1537                )
 1538            })?;
 1539            anyhow::Ok(())
 1540        })
 1541        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1542            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1543                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1544                e.error_tag("required").unwrap_or("the latest version")
 1545            )),
 1546            _ => None,
 1547        });
 1548    }
 1549
 1550    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1551        self.leader_peer_id
 1552    }
 1553
 1554    pub fn buffer(&self) -> &Model<MultiBuffer> {
 1555        &self.buffer
 1556    }
 1557
 1558    pub fn workspace(&self) -> Option<View<Workspace>> {
 1559        self.workspace.as_ref()?.0.upgrade()
 1560    }
 1561
 1562    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 1563        self.buffer().read(cx).title(cx)
 1564    }
 1565
 1566    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 1567        let git_blame_gutter_max_author_length = self
 1568            .render_git_blame_gutter(cx)
 1569            .then(|| {
 1570                if let Some(blame) = self.blame.as_ref() {
 1571                    let max_author_length =
 1572                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1573                    Some(max_author_length)
 1574                } else {
 1575                    None
 1576                }
 1577            })
 1578            .flatten();
 1579
 1580        EditorSnapshot {
 1581            mode: self.mode,
 1582            show_gutter: self.show_gutter,
 1583            show_line_numbers: self.show_line_numbers,
 1584            show_git_diff_gutter: self.show_git_diff_gutter,
 1585            show_code_actions: self.show_code_actions,
 1586            show_runnables: self.show_runnables,
 1587            git_blame_gutter_max_author_length,
 1588            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1589            scroll_anchor: self.scroll_manager.anchor(),
 1590            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1591            placeholder_text: self.placeholder_text.clone(),
 1592            diff_map: self.diff_map.snapshot(),
 1593            is_focused: self.focus_handle.is_focused(cx),
 1594            current_line_highlight: self
 1595                .current_line_highlight
 1596                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1597            gutter_hovered: self.gutter_hovered,
 1598        }
 1599    }
 1600
 1601    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 1602        self.buffer.read(cx).language_at(point, cx)
 1603    }
 1604
 1605    pub fn file_at<T: ToOffset>(
 1606        &self,
 1607        point: T,
 1608        cx: &AppContext,
 1609    ) -> Option<Arc<dyn language::File>> {
 1610        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1611    }
 1612
 1613    pub fn active_excerpt(
 1614        &self,
 1615        cx: &AppContext,
 1616    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 1617        self.buffer
 1618            .read(cx)
 1619            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1620    }
 1621
 1622    pub fn mode(&self) -> EditorMode {
 1623        self.mode
 1624    }
 1625
 1626    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1627        self.collaboration_hub.as_deref()
 1628    }
 1629
 1630    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1631        self.collaboration_hub = Some(hub);
 1632    }
 1633
 1634    pub fn set_custom_context_menu(
 1635        &mut self,
 1636        f: impl 'static
 1637            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 1638    ) {
 1639        self.custom_context_menu = Some(Box::new(f))
 1640    }
 1641
 1642    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1643        self.completion_provider = provider;
 1644    }
 1645
 1646    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1647        self.semantics_provider.clone()
 1648    }
 1649
 1650    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1651        self.semantics_provider = provider;
 1652    }
 1653
 1654    pub fn set_inline_completion_provider<T>(
 1655        &mut self,
 1656        provider: Option<Model<T>>,
 1657        cx: &mut ViewContext<Self>,
 1658    ) where
 1659        T: InlineCompletionProvider,
 1660    {
 1661        self.inline_completion_provider =
 1662            provider.map(|provider| RegisteredInlineCompletionProvider {
 1663                _subscription: cx.observe(&provider, |this, _, cx| {
 1664                    if this.focus_handle.is_focused(cx) {
 1665                        this.update_visible_inline_completion(cx);
 1666                    }
 1667                }),
 1668                provider: Arc::new(provider),
 1669            });
 1670        self.refresh_inline_completion(false, false, cx);
 1671    }
 1672
 1673    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 1674        self.placeholder_text.as_deref()
 1675    }
 1676
 1677    pub fn set_placeholder_text(
 1678        &mut self,
 1679        placeholder_text: impl Into<Arc<str>>,
 1680        cx: &mut ViewContext<Self>,
 1681    ) {
 1682        let placeholder_text = Some(placeholder_text.into());
 1683        if self.placeholder_text != placeholder_text {
 1684            self.placeholder_text = placeholder_text;
 1685            cx.notify();
 1686        }
 1687    }
 1688
 1689    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 1690        self.cursor_shape = cursor_shape;
 1691
 1692        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1693        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1694
 1695        cx.notify();
 1696    }
 1697
 1698    pub fn set_current_line_highlight(
 1699        &mut self,
 1700        current_line_highlight: Option<CurrentLineHighlight>,
 1701    ) {
 1702        self.current_line_highlight = current_line_highlight;
 1703    }
 1704
 1705    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1706        self.collapse_matches = collapse_matches;
 1707    }
 1708
 1709    pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
 1710        let buffers = self.buffer.read(cx).all_buffers();
 1711        let Some(lsp_store) = self.lsp_store(cx) else {
 1712            return;
 1713        };
 1714        lsp_store.update(cx, |lsp_store, cx| {
 1715            for buffer in buffers {
 1716                self.registered_buffers
 1717                    .entry(buffer.read(cx).remote_id())
 1718                    .or_insert_with(|| {
 1719                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1720                    });
 1721            }
 1722        })
 1723    }
 1724
 1725    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1726        if self.collapse_matches {
 1727            return range.start..range.start;
 1728        }
 1729        range.clone()
 1730    }
 1731
 1732    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 1733        if self.display_map.read(cx).clip_at_line_ends != clip {
 1734            self.display_map
 1735                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1736        }
 1737    }
 1738
 1739    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1740        self.input_enabled = input_enabled;
 1741    }
 1742
 1743    pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut ViewContext<Self>) {
 1744        self.enable_inline_completions = enabled;
 1745        if !self.enable_inline_completions {
 1746            self.take_active_inline_completion(cx);
 1747            cx.notify();
 1748        }
 1749    }
 1750
 1751    pub fn set_autoindent(&mut self, autoindent: bool) {
 1752        if autoindent {
 1753            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1754        } else {
 1755            self.autoindent_mode = None;
 1756        }
 1757    }
 1758
 1759    pub fn read_only(&self, cx: &AppContext) -> bool {
 1760        self.read_only || self.buffer.read(cx).read_only()
 1761    }
 1762
 1763    pub fn set_read_only(&mut self, read_only: bool) {
 1764        self.read_only = read_only;
 1765    }
 1766
 1767    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1768        self.use_autoclose = autoclose;
 1769    }
 1770
 1771    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1772        self.use_auto_surround = auto_surround;
 1773    }
 1774
 1775    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1776        self.auto_replace_emoji_shortcode = auto_replace;
 1777    }
 1778
 1779    pub fn toggle_inline_completions(
 1780        &mut self,
 1781        _: &ToggleInlineCompletions,
 1782        cx: &mut ViewContext<Self>,
 1783    ) {
 1784        if self.show_inline_completions_override.is_some() {
 1785            self.set_show_inline_completions(None, cx);
 1786        } else {
 1787            let cursor = self.selections.newest_anchor().head();
 1788            if let Some((buffer, cursor_buffer_position)) =
 1789                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1790            {
 1791                let show_inline_completions =
 1792                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1793                self.set_show_inline_completions(Some(show_inline_completions), cx);
 1794            }
 1795        }
 1796    }
 1797
 1798    pub fn set_show_inline_completions(
 1799        &mut self,
 1800        show_inline_completions: Option<bool>,
 1801        cx: &mut ViewContext<Self>,
 1802    ) {
 1803        self.show_inline_completions_override = show_inline_completions;
 1804        self.refresh_inline_completion(false, true, cx);
 1805    }
 1806
 1807    pub fn inline_completions_enabled(&self, cx: &AppContext) -> bool {
 1808        let cursor = self.selections.newest_anchor().head();
 1809        if let Some((buffer, buffer_position)) =
 1810            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1811        {
 1812            self.should_show_inline_completions(&buffer, buffer_position, cx)
 1813        } else {
 1814            false
 1815        }
 1816    }
 1817
 1818    fn should_show_inline_completions(
 1819        &self,
 1820        buffer: &Model<Buffer>,
 1821        buffer_position: language::Anchor,
 1822        cx: &AppContext,
 1823    ) -> bool {
 1824        if !self.snippet_stack.is_empty() {
 1825            return false;
 1826        }
 1827
 1828        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1829            return false;
 1830        }
 1831
 1832        if let Some(provider) = self.inline_completion_provider() {
 1833            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1834                show_inline_completions
 1835            } else {
 1836                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1837            }
 1838        } else {
 1839            false
 1840        }
 1841    }
 1842
 1843    fn inline_completions_disabled_in_scope(
 1844        &self,
 1845        buffer: &Model<Buffer>,
 1846        buffer_position: language::Anchor,
 1847        cx: &AppContext,
 1848    ) -> bool {
 1849        let snapshot = buffer.read(cx).snapshot();
 1850        let settings = snapshot.settings_at(buffer_position, cx);
 1851
 1852        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1853            return false;
 1854        };
 1855
 1856        scope.override_name().map_or(false, |scope_name| {
 1857            settings
 1858                .inline_completions_disabled_in
 1859                .iter()
 1860                .any(|s| s == scope_name)
 1861        })
 1862    }
 1863
 1864    pub fn set_use_modal_editing(&mut self, to: bool) {
 1865        self.use_modal_editing = to;
 1866    }
 1867
 1868    pub fn use_modal_editing(&self) -> bool {
 1869        self.use_modal_editing
 1870    }
 1871
 1872    fn selections_did_change(
 1873        &mut self,
 1874        local: bool,
 1875        old_cursor_position: &Anchor,
 1876        show_completions: bool,
 1877        cx: &mut ViewContext<Self>,
 1878    ) {
 1879        cx.invalidate_character_coordinates();
 1880
 1881        // Copy selections to primary selection buffer
 1882        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1883        if local {
 1884            let selections = self.selections.all::<usize>(cx);
 1885            let buffer_handle = self.buffer.read(cx).read(cx);
 1886
 1887            let mut text = String::new();
 1888            for (index, selection) in selections.iter().enumerate() {
 1889                let text_for_selection = buffer_handle
 1890                    .text_for_range(selection.start..selection.end)
 1891                    .collect::<String>();
 1892
 1893                text.push_str(&text_for_selection);
 1894                if index != selections.len() - 1 {
 1895                    text.push('\n');
 1896                }
 1897            }
 1898
 1899            if !text.is_empty() {
 1900                cx.write_to_primary(ClipboardItem::new_string(text));
 1901            }
 1902        }
 1903
 1904        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 1905            self.buffer.update(cx, |buffer, cx| {
 1906                buffer.set_active_selections(
 1907                    &self.selections.disjoint_anchors(),
 1908                    self.selections.line_mode,
 1909                    self.cursor_shape,
 1910                    cx,
 1911                )
 1912            });
 1913        }
 1914        let display_map = self
 1915            .display_map
 1916            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1917        let buffer = &display_map.buffer_snapshot;
 1918        self.add_selections_state = None;
 1919        self.select_next_state = None;
 1920        self.select_prev_state = None;
 1921        self.select_larger_syntax_node_stack.clear();
 1922        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 1923        self.snippet_stack
 1924            .invalidate(&self.selections.disjoint_anchors(), buffer);
 1925        self.take_rename(false, cx);
 1926
 1927        let new_cursor_position = self.selections.newest_anchor().head();
 1928
 1929        self.push_to_nav_history(
 1930            *old_cursor_position,
 1931            Some(new_cursor_position.to_point(buffer)),
 1932            cx,
 1933        );
 1934
 1935        if local {
 1936            let new_cursor_position = self.selections.newest_anchor().head();
 1937            let mut context_menu = self.context_menu.borrow_mut();
 1938            let completion_menu = match context_menu.as_ref() {
 1939                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 1940                _ => {
 1941                    *context_menu = None;
 1942                    None
 1943                }
 1944            };
 1945
 1946            if let Some(completion_menu) = completion_menu {
 1947                let cursor_position = new_cursor_position.to_offset(buffer);
 1948                let (word_range, kind) =
 1949                    buffer.surrounding_word(completion_menu.initial_position, true);
 1950                if kind == Some(CharKind::Word)
 1951                    && word_range.to_inclusive().contains(&cursor_position)
 1952                {
 1953                    let mut completion_menu = completion_menu.clone();
 1954                    drop(context_menu);
 1955
 1956                    let query = Self::completion_query(buffer, cursor_position);
 1957                    cx.spawn(move |this, mut cx| async move {
 1958                        completion_menu
 1959                            .filter(query.as_deref(), cx.background_executor().clone())
 1960                            .await;
 1961
 1962                        this.update(&mut cx, |this, cx| {
 1963                            let mut context_menu = this.context_menu.borrow_mut();
 1964                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 1965                            else {
 1966                                return;
 1967                            };
 1968
 1969                            if menu.id > completion_menu.id {
 1970                                return;
 1971                            }
 1972
 1973                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 1974                            drop(context_menu);
 1975                            cx.notify();
 1976                        })
 1977                    })
 1978                    .detach();
 1979
 1980                    if show_completions {
 1981                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 1982                    }
 1983                } else {
 1984                    drop(context_menu);
 1985                    self.hide_context_menu(cx);
 1986                }
 1987            } else {
 1988                drop(context_menu);
 1989            }
 1990
 1991            hide_hover(self, cx);
 1992
 1993            if old_cursor_position.to_display_point(&display_map).row()
 1994                != new_cursor_position.to_display_point(&display_map).row()
 1995            {
 1996                self.available_code_actions.take();
 1997            }
 1998            self.refresh_code_actions(cx);
 1999            self.refresh_document_highlights(cx);
 2000            refresh_matching_bracket_highlights(self, cx);
 2001            self.update_visible_inline_completion(cx);
 2002            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2003            if self.git_blame_inline_enabled {
 2004                self.start_inline_blame_timer(cx);
 2005            }
 2006        }
 2007
 2008        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2009        cx.emit(EditorEvent::SelectionsChanged { local });
 2010
 2011        if self.selections.disjoint_anchors().len() == 1 {
 2012            cx.emit(SearchEvent::ActiveMatchChanged)
 2013        }
 2014        cx.notify();
 2015    }
 2016
 2017    pub fn change_selections<R>(
 2018        &mut self,
 2019        autoscroll: Option<Autoscroll>,
 2020        cx: &mut ViewContext<Self>,
 2021        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2022    ) -> R {
 2023        self.change_selections_inner(autoscroll, true, cx, change)
 2024    }
 2025
 2026    pub fn change_selections_inner<R>(
 2027        &mut self,
 2028        autoscroll: Option<Autoscroll>,
 2029        request_completions: bool,
 2030        cx: &mut ViewContext<Self>,
 2031        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2032    ) -> R {
 2033        let old_cursor_position = self.selections.newest_anchor().head();
 2034        self.push_to_selection_history();
 2035
 2036        let (changed, result) = self.selections.change_with(cx, change);
 2037
 2038        if changed {
 2039            if let Some(autoscroll) = autoscroll {
 2040                self.request_autoscroll(autoscroll, cx);
 2041            }
 2042            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2043
 2044            if self.should_open_signature_help_automatically(
 2045                &old_cursor_position,
 2046                self.signature_help_state.backspace_pressed(),
 2047                cx,
 2048            ) {
 2049                self.show_signature_help(&ShowSignatureHelp, cx);
 2050            }
 2051            self.signature_help_state.set_backspace_pressed(false);
 2052        }
 2053
 2054        result
 2055    }
 2056
 2057    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2058    where
 2059        I: IntoIterator<Item = (Range<S>, T)>,
 2060        S: ToOffset,
 2061        T: Into<Arc<str>>,
 2062    {
 2063        if self.read_only(cx) {
 2064            return;
 2065        }
 2066
 2067        self.buffer
 2068            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2069    }
 2070
 2071    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2072    where
 2073        I: IntoIterator<Item = (Range<S>, T)>,
 2074        S: ToOffset,
 2075        T: Into<Arc<str>>,
 2076    {
 2077        if self.read_only(cx) {
 2078            return;
 2079        }
 2080
 2081        self.buffer.update(cx, |buffer, cx| {
 2082            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2083        });
 2084    }
 2085
 2086    pub fn edit_with_block_indent<I, S, T>(
 2087        &mut self,
 2088        edits: I,
 2089        original_indent_columns: Vec<u32>,
 2090        cx: &mut ViewContext<Self>,
 2091    ) where
 2092        I: IntoIterator<Item = (Range<S>, T)>,
 2093        S: ToOffset,
 2094        T: Into<Arc<str>>,
 2095    {
 2096        if self.read_only(cx) {
 2097            return;
 2098        }
 2099
 2100        self.buffer.update(cx, |buffer, cx| {
 2101            buffer.edit(
 2102                edits,
 2103                Some(AutoindentMode::Block {
 2104                    original_indent_columns,
 2105                }),
 2106                cx,
 2107            )
 2108        });
 2109    }
 2110
 2111    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2112        self.hide_context_menu(cx);
 2113
 2114        match phase {
 2115            SelectPhase::Begin {
 2116                position,
 2117                add,
 2118                click_count,
 2119            } => self.begin_selection(position, add, click_count, cx),
 2120            SelectPhase::BeginColumnar {
 2121                position,
 2122                goal_column,
 2123                reset,
 2124            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2125            SelectPhase::Extend {
 2126                position,
 2127                click_count,
 2128            } => self.extend_selection(position, click_count, cx),
 2129            SelectPhase::Update {
 2130                position,
 2131                goal_column,
 2132                scroll_delta,
 2133            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2134            SelectPhase::End => self.end_selection(cx),
 2135        }
 2136    }
 2137
 2138    fn extend_selection(
 2139        &mut self,
 2140        position: DisplayPoint,
 2141        click_count: usize,
 2142        cx: &mut ViewContext<Self>,
 2143    ) {
 2144        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2145        let tail = self.selections.newest::<usize>(cx).tail();
 2146        self.begin_selection(position, false, click_count, cx);
 2147
 2148        let position = position.to_offset(&display_map, Bias::Left);
 2149        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2150
 2151        let mut pending_selection = self
 2152            .selections
 2153            .pending_anchor()
 2154            .expect("extend_selection not called with pending selection");
 2155        if position >= tail {
 2156            pending_selection.start = tail_anchor;
 2157        } else {
 2158            pending_selection.end = tail_anchor;
 2159            pending_selection.reversed = true;
 2160        }
 2161
 2162        let mut pending_mode = self.selections.pending_mode().unwrap();
 2163        match &mut pending_mode {
 2164            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2165            _ => {}
 2166        }
 2167
 2168        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2169            s.set_pending(pending_selection, pending_mode)
 2170        });
 2171    }
 2172
 2173    fn begin_selection(
 2174        &mut self,
 2175        position: DisplayPoint,
 2176        add: bool,
 2177        click_count: usize,
 2178        cx: &mut ViewContext<Self>,
 2179    ) {
 2180        if !self.focus_handle.is_focused(cx) {
 2181            self.last_focused_descendant = None;
 2182            cx.focus(&self.focus_handle);
 2183        }
 2184
 2185        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2186        let buffer = &display_map.buffer_snapshot;
 2187        let newest_selection = self.selections.newest_anchor().clone();
 2188        let position = display_map.clip_point(position, Bias::Left);
 2189
 2190        let start;
 2191        let end;
 2192        let mode;
 2193        let mut auto_scroll;
 2194        match click_count {
 2195            1 => {
 2196                start = buffer.anchor_before(position.to_point(&display_map));
 2197                end = start;
 2198                mode = SelectMode::Character;
 2199                auto_scroll = true;
 2200            }
 2201            2 => {
 2202                let range = movement::surrounding_word(&display_map, position);
 2203                start = buffer.anchor_before(range.start.to_point(&display_map));
 2204                end = buffer.anchor_before(range.end.to_point(&display_map));
 2205                mode = SelectMode::Word(start..end);
 2206                auto_scroll = true;
 2207            }
 2208            3 => {
 2209                let position = display_map
 2210                    .clip_point(position, Bias::Left)
 2211                    .to_point(&display_map);
 2212                let line_start = display_map.prev_line_boundary(position).0;
 2213                let next_line_start = buffer.clip_point(
 2214                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2215                    Bias::Left,
 2216                );
 2217                start = buffer.anchor_before(line_start);
 2218                end = buffer.anchor_before(next_line_start);
 2219                mode = SelectMode::Line(start..end);
 2220                auto_scroll = true;
 2221            }
 2222            _ => {
 2223                start = buffer.anchor_before(0);
 2224                end = buffer.anchor_before(buffer.len());
 2225                mode = SelectMode::All;
 2226                auto_scroll = false;
 2227            }
 2228        }
 2229        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2230
 2231        let point_to_delete: Option<usize> = {
 2232            let selected_points: Vec<Selection<Point>> =
 2233                self.selections.disjoint_in_range(start..end, cx);
 2234
 2235            if !add || click_count > 1 {
 2236                None
 2237            } else if !selected_points.is_empty() {
 2238                Some(selected_points[0].id)
 2239            } else {
 2240                let clicked_point_already_selected =
 2241                    self.selections.disjoint.iter().find(|selection| {
 2242                        selection.start.to_point(buffer) == start.to_point(buffer)
 2243                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2244                    });
 2245
 2246                clicked_point_already_selected.map(|selection| selection.id)
 2247            }
 2248        };
 2249
 2250        let selections_count = self.selections.count();
 2251
 2252        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2253            if let Some(point_to_delete) = point_to_delete {
 2254                s.delete(point_to_delete);
 2255
 2256                if selections_count == 1 {
 2257                    s.set_pending_anchor_range(start..end, mode);
 2258                }
 2259            } else {
 2260                if !add {
 2261                    s.clear_disjoint();
 2262                } else if click_count > 1 {
 2263                    s.delete(newest_selection.id)
 2264                }
 2265
 2266                s.set_pending_anchor_range(start..end, mode);
 2267            }
 2268        });
 2269    }
 2270
 2271    fn begin_columnar_selection(
 2272        &mut self,
 2273        position: DisplayPoint,
 2274        goal_column: u32,
 2275        reset: bool,
 2276        cx: &mut ViewContext<Self>,
 2277    ) {
 2278        if !self.focus_handle.is_focused(cx) {
 2279            self.last_focused_descendant = None;
 2280            cx.focus(&self.focus_handle);
 2281        }
 2282
 2283        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2284
 2285        if reset {
 2286            let pointer_position = display_map
 2287                .buffer_snapshot
 2288                .anchor_before(position.to_point(&display_map));
 2289
 2290            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2291                s.clear_disjoint();
 2292                s.set_pending_anchor_range(
 2293                    pointer_position..pointer_position,
 2294                    SelectMode::Character,
 2295                );
 2296            });
 2297        }
 2298
 2299        let tail = self.selections.newest::<Point>(cx).tail();
 2300        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2301
 2302        if !reset {
 2303            self.select_columns(
 2304                tail.to_display_point(&display_map),
 2305                position,
 2306                goal_column,
 2307                &display_map,
 2308                cx,
 2309            );
 2310        }
 2311    }
 2312
 2313    fn update_selection(
 2314        &mut self,
 2315        position: DisplayPoint,
 2316        goal_column: u32,
 2317        scroll_delta: gpui::Point<f32>,
 2318        cx: &mut ViewContext<Self>,
 2319    ) {
 2320        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2321
 2322        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2323            let tail = tail.to_display_point(&display_map);
 2324            self.select_columns(tail, position, goal_column, &display_map, cx);
 2325        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2326            let buffer = self.buffer.read(cx).snapshot(cx);
 2327            let head;
 2328            let tail;
 2329            let mode = self.selections.pending_mode().unwrap();
 2330            match &mode {
 2331                SelectMode::Character => {
 2332                    head = position.to_point(&display_map);
 2333                    tail = pending.tail().to_point(&buffer);
 2334                }
 2335                SelectMode::Word(original_range) => {
 2336                    let original_display_range = original_range.start.to_display_point(&display_map)
 2337                        ..original_range.end.to_display_point(&display_map);
 2338                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2339                        ..original_display_range.end.to_point(&display_map);
 2340                    if movement::is_inside_word(&display_map, position)
 2341                        || original_display_range.contains(&position)
 2342                    {
 2343                        let word_range = movement::surrounding_word(&display_map, position);
 2344                        if word_range.start < original_display_range.start {
 2345                            head = word_range.start.to_point(&display_map);
 2346                        } else {
 2347                            head = word_range.end.to_point(&display_map);
 2348                        }
 2349                    } else {
 2350                        head = position.to_point(&display_map);
 2351                    }
 2352
 2353                    if head <= original_buffer_range.start {
 2354                        tail = original_buffer_range.end;
 2355                    } else {
 2356                        tail = original_buffer_range.start;
 2357                    }
 2358                }
 2359                SelectMode::Line(original_range) => {
 2360                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2361
 2362                    let position = display_map
 2363                        .clip_point(position, Bias::Left)
 2364                        .to_point(&display_map);
 2365                    let line_start = display_map.prev_line_boundary(position).0;
 2366                    let next_line_start = buffer.clip_point(
 2367                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2368                        Bias::Left,
 2369                    );
 2370
 2371                    if line_start < original_range.start {
 2372                        head = line_start
 2373                    } else {
 2374                        head = next_line_start
 2375                    }
 2376
 2377                    if head <= original_range.start {
 2378                        tail = original_range.end;
 2379                    } else {
 2380                        tail = original_range.start;
 2381                    }
 2382                }
 2383                SelectMode::All => {
 2384                    return;
 2385                }
 2386            };
 2387
 2388            if head < tail {
 2389                pending.start = buffer.anchor_before(head);
 2390                pending.end = buffer.anchor_before(tail);
 2391                pending.reversed = true;
 2392            } else {
 2393                pending.start = buffer.anchor_before(tail);
 2394                pending.end = buffer.anchor_before(head);
 2395                pending.reversed = false;
 2396            }
 2397
 2398            self.change_selections(None, cx, |s| {
 2399                s.set_pending(pending, mode);
 2400            });
 2401        } else {
 2402            log::error!("update_selection dispatched with no pending selection");
 2403            return;
 2404        }
 2405
 2406        self.apply_scroll_delta(scroll_delta, cx);
 2407        cx.notify();
 2408    }
 2409
 2410    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2411        self.columnar_selection_tail.take();
 2412        if self.selections.pending_anchor().is_some() {
 2413            let selections = self.selections.all::<usize>(cx);
 2414            self.change_selections(None, cx, |s| {
 2415                s.select(selections);
 2416                s.clear_pending();
 2417            });
 2418        }
 2419    }
 2420
 2421    fn select_columns(
 2422        &mut self,
 2423        tail: DisplayPoint,
 2424        head: DisplayPoint,
 2425        goal_column: u32,
 2426        display_map: &DisplaySnapshot,
 2427        cx: &mut ViewContext<Self>,
 2428    ) {
 2429        let start_row = cmp::min(tail.row(), head.row());
 2430        let end_row = cmp::max(tail.row(), head.row());
 2431        let start_column = cmp::min(tail.column(), goal_column);
 2432        let end_column = cmp::max(tail.column(), goal_column);
 2433        let reversed = start_column < tail.column();
 2434
 2435        let selection_ranges = (start_row.0..=end_row.0)
 2436            .map(DisplayRow)
 2437            .filter_map(|row| {
 2438                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2439                    let start = display_map
 2440                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2441                        .to_point(display_map);
 2442                    let end = display_map
 2443                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2444                        .to_point(display_map);
 2445                    if reversed {
 2446                        Some(end..start)
 2447                    } else {
 2448                        Some(start..end)
 2449                    }
 2450                } else {
 2451                    None
 2452                }
 2453            })
 2454            .collect::<Vec<_>>();
 2455
 2456        self.change_selections(None, cx, |s| {
 2457            s.select_ranges(selection_ranges);
 2458        });
 2459        cx.notify();
 2460    }
 2461
 2462    pub fn has_pending_nonempty_selection(&self) -> bool {
 2463        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2464            Some(Selection { start, end, .. }) => start != end,
 2465            None => false,
 2466        };
 2467
 2468        pending_nonempty_selection
 2469            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2470    }
 2471
 2472    pub fn has_pending_selection(&self) -> bool {
 2473        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2474    }
 2475
 2476    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2477        if self.clear_expanded_diff_hunks(cx) {
 2478            cx.notify();
 2479            return;
 2480        }
 2481        if self.dismiss_menus_and_popups(true, cx) {
 2482            return;
 2483        }
 2484
 2485        if self.mode == EditorMode::Full
 2486            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 2487        {
 2488            return;
 2489        }
 2490
 2491        cx.propagate();
 2492    }
 2493
 2494    pub fn dismiss_menus_and_popups(
 2495        &mut self,
 2496        should_report_inline_completion_event: bool,
 2497        cx: &mut ViewContext<Self>,
 2498    ) -> bool {
 2499        if self.take_rename(false, cx).is_some() {
 2500            return true;
 2501        }
 2502
 2503        if hide_hover(self, cx) {
 2504            return true;
 2505        }
 2506
 2507        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2508            return true;
 2509        }
 2510
 2511        if self.hide_context_menu(cx).is_some() {
 2512            if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
 2513                self.update_visible_inline_completion(cx);
 2514            }
 2515            return true;
 2516        }
 2517
 2518        if self.mouse_context_menu.take().is_some() {
 2519            return true;
 2520        }
 2521
 2522        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2523            return true;
 2524        }
 2525
 2526        if self.snippet_stack.pop().is_some() {
 2527            return true;
 2528        }
 2529
 2530        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2531            self.dismiss_diagnostics(cx);
 2532            return true;
 2533        }
 2534
 2535        false
 2536    }
 2537
 2538    fn linked_editing_ranges_for(
 2539        &self,
 2540        selection: Range<text::Anchor>,
 2541        cx: &AppContext,
 2542    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2543        if self.linked_edit_ranges.is_empty() {
 2544            return None;
 2545        }
 2546        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2547            selection.end.buffer_id.and_then(|end_buffer_id| {
 2548                if selection.start.buffer_id != Some(end_buffer_id) {
 2549                    return None;
 2550                }
 2551                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2552                let snapshot = buffer.read(cx).snapshot();
 2553                self.linked_edit_ranges
 2554                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2555                    .map(|ranges| (ranges, snapshot, buffer))
 2556            })?;
 2557        use text::ToOffset as TO;
 2558        // find offset from the start of current range to current cursor position
 2559        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2560
 2561        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2562        let start_difference = start_offset - start_byte_offset;
 2563        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2564        let end_difference = end_offset - start_byte_offset;
 2565        // Current range has associated linked ranges.
 2566        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2567        for range in linked_ranges.iter() {
 2568            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2569            let end_offset = start_offset + end_difference;
 2570            let start_offset = start_offset + start_difference;
 2571            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2572                continue;
 2573            }
 2574            if self.selections.disjoint_anchor_ranges().any(|s| {
 2575                if s.start.buffer_id != selection.start.buffer_id
 2576                    || s.end.buffer_id != selection.end.buffer_id
 2577                {
 2578                    return false;
 2579                }
 2580                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2581                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2582            }) {
 2583                continue;
 2584            }
 2585            let start = buffer_snapshot.anchor_after(start_offset);
 2586            let end = buffer_snapshot.anchor_after(end_offset);
 2587            linked_edits
 2588                .entry(buffer.clone())
 2589                .or_default()
 2590                .push(start..end);
 2591        }
 2592        Some(linked_edits)
 2593    }
 2594
 2595    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2596        let text: Arc<str> = text.into();
 2597
 2598        if self.read_only(cx) {
 2599            return;
 2600        }
 2601
 2602        let selections = self.selections.all_adjusted(cx);
 2603        let mut bracket_inserted = false;
 2604        let mut edits = Vec::new();
 2605        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2606        let mut new_selections = Vec::with_capacity(selections.len());
 2607        let mut new_autoclose_regions = Vec::new();
 2608        let snapshot = self.buffer.read(cx).read(cx);
 2609
 2610        for (selection, autoclose_region) in
 2611            self.selections_with_autoclose_regions(selections, &snapshot)
 2612        {
 2613            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2614                // Determine if the inserted text matches the opening or closing
 2615                // bracket of any of this language's bracket pairs.
 2616                let mut bracket_pair = None;
 2617                let mut is_bracket_pair_start = false;
 2618                let mut is_bracket_pair_end = false;
 2619                if !text.is_empty() {
 2620                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2621                    //  and they are removing the character that triggered IME popup.
 2622                    for (pair, enabled) in scope.brackets() {
 2623                        if !pair.close && !pair.surround {
 2624                            continue;
 2625                        }
 2626
 2627                        if enabled && pair.start.ends_with(text.as_ref()) {
 2628                            let prefix_len = pair.start.len() - text.len();
 2629                            let preceding_text_matches_prefix = prefix_len == 0
 2630                                || (selection.start.column >= (prefix_len as u32)
 2631                                    && snapshot.contains_str_at(
 2632                                        Point::new(
 2633                                            selection.start.row,
 2634                                            selection.start.column - (prefix_len as u32),
 2635                                        ),
 2636                                        &pair.start[..prefix_len],
 2637                                    ));
 2638                            if preceding_text_matches_prefix {
 2639                                bracket_pair = Some(pair.clone());
 2640                                is_bracket_pair_start = true;
 2641                                break;
 2642                            }
 2643                        }
 2644                        if pair.end.as_str() == text.as_ref() {
 2645                            bracket_pair = Some(pair.clone());
 2646                            is_bracket_pair_end = true;
 2647                            break;
 2648                        }
 2649                    }
 2650                }
 2651
 2652                if let Some(bracket_pair) = bracket_pair {
 2653                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2654                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2655                    let auto_surround =
 2656                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2657                    if selection.is_empty() {
 2658                        if is_bracket_pair_start {
 2659                            // If the inserted text is a suffix of an opening bracket and the
 2660                            // selection is preceded by the rest of the opening bracket, then
 2661                            // insert the closing bracket.
 2662                            let following_text_allows_autoclose = snapshot
 2663                                .chars_at(selection.start)
 2664                                .next()
 2665                                .map_or(true, |c| scope.should_autoclose_before(c));
 2666
 2667                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2668                                && bracket_pair.start.len() == 1
 2669                            {
 2670                                let target = bracket_pair.start.chars().next().unwrap();
 2671                                let current_line_count = snapshot
 2672                                    .reversed_chars_at(selection.start)
 2673                                    .take_while(|&c| c != '\n')
 2674                                    .filter(|&c| c == target)
 2675                                    .count();
 2676                                current_line_count % 2 == 1
 2677                            } else {
 2678                                false
 2679                            };
 2680
 2681                            if autoclose
 2682                                && bracket_pair.close
 2683                                && following_text_allows_autoclose
 2684                                && !is_closing_quote
 2685                            {
 2686                                let anchor = snapshot.anchor_before(selection.end);
 2687                                new_selections.push((selection.map(|_| anchor), text.len()));
 2688                                new_autoclose_regions.push((
 2689                                    anchor,
 2690                                    text.len(),
 2691                                    selection.id,
 2692                                    bracket_pair.clone(),
 2693                                ));
 2694                                edits.push((
 2695                                    selection.range(),
 2696                                    format!("{}{}", text, bracket_pair.end).into(),
 2697                                ));
 2698                                bracket_inserted = true;
 2699                                continue;
 2700                            }
 2701                        }
 2702
 2703                        if let Some(region) = autoclose_region {
 2704                            // If the selection is followed by an auto-inserted closing bracket,
 2705                            // then don't insert that closing bracket again; just move the selection
 2706                            // past the closing bracket.
 2707                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2708                                && text.as_ref() == region.pair.end.as_str();
 2709                            if should_skip {
 2710                                let anchor = snapshot.anchor_after(selection.end);
 2711                                new_selections
 2712                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2713                                continue;
 2714                            }
 2715                        }
 2716
 2717                        let always_treat_brackets_as_autoclosed = snapshot
 2718                            .settings_at(selection.start, cx)
 2719                            .always_treat_brackets_as_autoclosed;
 2720                        if always_treat_brackets_as_autoclosed
 2721                            && is_bracket_pair_end
 2722                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2723                        {
 2724                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2725                            // and the inserted text is a closing bracket and the selection is followed
 2726                            // by the closing bracket then move the selection past the closing bracket.
 2727                            let anchor = snapshot.anchor_after(selection.end);
 2728                            new_selections.push((selection.map(|_| anchor), text.len()));
 2729                            continue;
 2730                        }
 2731                    }
 2732                    // If an opening bracket is 1 character long and is typed while
 2733                    // text is selected, then surround that text with the bracket pair.
 2734                    else if auto_surround
 2735                        && bracket_pair.surround
 2736                        && is_bracket_pair_start
 2737                        && bracket_pair.start.chars().count() == 1
 2738                    {
 2739                        edits.push((selection.start..selection.start, text.clone()));
 2740                        edits.push((
 2741                            selection.end..selection.end,
 2742                            bracket_pair.end.as_str().into(),
 2743                        ));
 2744                        bracket_inserted = true;
 2745                        new_selections.push((
 2746                            Selection {
 2747                                id: selection.id,
 2748                                start: snapshot.anchor_after(selection.start),
 2749                                end: snapshot.anchor_before(selection.end),
 2750                                reversed: selection.reversed,
 2751                                goal: selection.goal,
 2752                            },
 2753                            0,
 2754                        ));
 2755                        continue;
 2756                    }
 2757                }
 2758            }
 2759
 2760            if self.auto_replace_emoji_shortcode
 2761                && selection.is_empty()
 2762                && text.as_ref().ends_with(':')
 2763            {
 2764                if let Some(possible_emoji_short_code) =
 2765                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2766                {
 2767                    if !possible_emoji_short_code.is_empty() {
 2768                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2769                            let emoji_shortcode_start = Point::new(
 2770                                selection.start.row,
 2771                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2772                            );
 2773
 2774                            // Remove shortcode from buffer
 2775                            edits.push((
 2776                                emoji_shortcode_start..selection.start,
 2777                                "".to_string().into(),
 2778                            ));
 2779                            new_selections.push((
 2780                                Selection {
 2781                                    id: selection.id,
 2782                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2783                                    end: snapshot.anchor_before(selection.start),
 2784                                    reversed: selection.reversed,
 2785                                    goal: selection.goal,
 2786                                },
 2787                                0,
 2788                            ));
 2789
 2790                            // Insert emoji
 2791                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2792                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2793                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2794
 2795                            continue;
 2796                        }
 2797                    }
 2798                }
 2799            }
 2800
 2801            // If not handling any auto-close operation, then just replace the selected
 2802            // text with the given input and move the selection to the end of the
 2803            // newly inserted text.
 2804            let anchor = snapshot.anchor_after(selection.end);
 2805            if !self.linked_edit_ranges.is_empty() {
 2806                let start_anchor = snapshot.anchor_before(selection.start);
 2807
 2808                let is_word_char = text.chars().next().map_or(true, |char| {
 2809                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2810                    classifier.is_word(char)
 2811                });
 2812
 2813                if is_word_char {
 2814                    if let Some(ranges) = self
 2815                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2816                    {
 2817                        for (buffer, edits) in ranges {
 2818                            linked_edits
 2819                                .entry(buffer.clone())
 2820                                .or_default()
 2821                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2822                        }
 2823                    }
 2824                }
 2825            }
 2826
 2827            new_selections.push((selection.map(|_| anchor), 0));
 2828            edits.push((selection.start..selection.end, text.clone()));
 2829        }
 2830
 2831        drop(snapshot);
 2832
 2833        self.transact(cx, |this, cx| {
 2834            this.buffer.update(cx, |buffer, cx| {
 2835                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2836            });
 2837            for (buffer, edits) in linked_edits {
 2838                buffer.update(cx, |buffer, cx| {
 2839                    let snapshot = buffer.snapshot();
 2840                    let edits = edits
 2841                        .into_iter()
 2842                        .map(|(range, text)| {
 2843                            use text::ToPoint as TP;
 2844                            let end_point = TP::to_point(&range.end, &snapshot);
 2845                            let start_point = TP::to_point(&range.start, &snapshot);
 2846                            (start_point..end_point, text)
 2847                        })
 2848                        .sorted_by_key(|(range, _)| range.start)
 2849                        .collect::<Vec<_>>();
 2850                    buffer.edit(edits, None, cx);
 2851                })
 2852            }
 2853            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2854            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2855            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2856            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2857                .zip(new_selection_deltas)
 2858                .map(|(selection, delta)| Selection {
 2859                    id: selection.id,
 2860                    start: selection.start + delta,
 2861                    end: selection.end + delta,
 2862                    reversed: selection.reversed,
 2863                    goal: SelectionGoal::None,
 2864                })
 2865                .collect::<Vec<_>>();
 2866
 2867            let mut i = 0;
 2868            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2869                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2870                let start = map.buffer_snapshot.anchor_before(position);
 2871                let end = map.buffer_snapshot.anchor_after(position);
 2872                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2873                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2874                        Ordering::Less => i += 1,
 2875                        Ordering::Greater => break,
 2876                        Ordering::Equal => {
 2877                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2878                                Ordering::Less => i += 1,
 2879                                Ordering::Equal => break,
 2880                                Ordering::Greater => break,
 2881                            }
 2882                        }
 2883                    }
 2884                }
 2885                this.autoclose_regions.insert(
 2886                    i,
 2887                    AutocloseRegion {
 2888                        selection_id,
 2889                        range: start..end,
 2890                        pair,
 2891                    },
 2892                );
 2893            }
 2894
 2895            let had_active_inline_completion = this.has_active_inline_completion();
 2896            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 2897                s.select(new_selections)
 2898            });
 2899
 2900            if !bracket_inserted {
 2901                if let Some(on_type_format_task) =
 2902                    this.trigger_on_type_formatting(text.to_string(), cx)
 2903                {
 2904                    on_type_format_task.detach_and_log_err(cx);
 2905                }
 2906            }
 2907
 2908            let editor_settings = EditorSettings::get_global(cx);
 2909            if bracket_inserted
 2910                && (editor_settings.auto_signature_help
 2911                    || editor_settings.show_signature_help_after_edits)
 2912            {
 2913                this.show_signature_help(&ShowSignatureHelp, cx);
 2914            }
 2915
 2916            let trigger_in_words =
 2917                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 2918            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 2919            linked_editing_ranges::refresh_linked_ranges(this, cx);
 2920            this.refresh_inline_completion(true, false, cx);
 2921        });
 2922    }
 2923
 2924    fn find_possible_emoji_shortcode_at_position(
 2925        snapshot: &MultiBufferSnapshot,
 2926        position: Point,
 2927    ) -> Option<String> {
 2928        let mut chars = Vec::new();
 2929        let mut found_colon = false;
 2930        for char in snapshot.reversed_chars_at(position).take(100) {
 2931            // Found a possible emoji shortcode in the middle of the buffer
 2932            if found_colon {
 2933                if char.is_whitespace() {
 2934                    chars.reverse();
 2935                    return Some(chars.iter().collect());
 2936                }
 2937                // If the previous character is not a whitespace, we are in the middle of a word
 2938                // and we only want to complete the shortcode if the word is made up of other emojis
 2939                let mut containing_word = String::new();
 2940                for ch in snapshot
 2941                    .reversed_chars_at(position)
 2942                    .skip(chars.len() + 1)
 2943                    .take(100)
 2944                {
 2945                    if ch.is_whitespace() {
 2946                        break;
 2947                    }
 2948                    containing_word.push(ch);
 2949                }
 2950                let containing_word = containing_word.chars().rev().collect::<String>();
 2951                if util::word_consists_of_emojis(containing_word.as_str()) {
 2952                    chars.reverse();
 2953                    return Some(chars.iter().collect());
 2954                }
 2955            }
 2956
 2957            if char.is_whitespace() || !char.is_ascii() {
 2958                return None;
 2959            }
 2960            if char == ':' {
 2961                found_colon = true;
 2962            } else {
 2963                chars.push(char);
 2964            }
 2965        }
 2966        // Found a possible emoji shortcode at the beginning of the buffer
 2967        chars.reverse();
 2968        Some(chars.iter().collect())
 2969    }
 2970
 2971    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 2972        self.transact(cx, |this, cx| {
 2973            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 2974                let selections = this.selections.all::<usize>(cx);
 2975                let multi_buffer = this.buffer.read(cx);
 2976                let buffer = multi_buffer.snapshot(cx);
 2977                selections
 2978                    .iter()
 2979                    .map(|selection| {
 2980                        let start_point = selection.start.to_point(&buffer);
 2981                        let mut indent =
 2982                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 2983                        indent.len = cmp::min(indent.len, start_point.column);
 2984                        let start = selection.start;
 2985                        let end = selection.end;
 2986                        let selection_is_empty = start == end;
 2987                        let language_scope = buffer.language_scope_at(start);
 2988                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 2989                            &language_scope
 2990                        {
 2991                            let leading_whitespace_len = buffer
 2992                                .reversed_chars_at(start)
 2993                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2994                                .map(|c| c.len_utf8())
 2995                                .sum::<usize>();
 2996
 2997                            let trailing_whitespace_len = buffer
 2998                                .chars_at(end)
 2999                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3000                                .map(|c| c.len_utf8())
 3001                                .sum::<usize>();
 3002
 3003                            let insert_extra_newline =
 3004                                language.brackets().any(|(pair, enabled)| {
 3005                                    let pair_start = pair.start.trim_end();
 3006                                    let pair_end = pair.end.trim_start();
 3007
 3008                                    enabled
 3009                                        && pair.newline
 3010                                        && buffer.contains_str_at(
 3011                                            end + trailing_whitespace_len,
 3012                                            pair_end,
 3013                                        )
 3014                                        && buffer.contains_str_at(
 3015                                            (start - leading_whitespace_len)
 3016                                                .saturating_sub(pair_start.len()),
 3017                                            pair_start,
 3018                                        )
 3019                                });
 3020
 3021                            // Comment extension on newline is allowed only for cursor selections
 3022                            let comment_delimiter = maybe!({
 3023                                if !selection_is_empty {
 3024                                    return None;
 3025                                }
 3026
 3027                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3028                                    return None;
 3029                                }
 3030
 3031                                let delimiters = language.line_comment_prefixes();
 3032                                let max_len_of_delimiter =
 3033                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3034                                let (snapshot, range) =
 3035                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3036
 3037                                let mut index_of_first_non_whitespace = 0;
 3038                                let comment_candidate = snapshot
 3039                                    .chars_for_range(range)
 3040                                    .skip_while(|c| {
 3041                                        let should_skip = c.is_whitespace();
 3042                                        if should_skip {
 3043                                            index_of_first_non_whitespace += 1;
 3044                                        }
 3045                                        should_skip
 3046                                    })
 3047                                    .take(max_len_of_delimiter)
 3048                                    .collect::<String>();
 3049                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3050                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3051                                })?;
 3052                                let cursor_is_placed_after_comment_marker =
 3053                                    index_of_first_non_whitespace + comment_prefix.len()
 3054                                        <= start_point.column as usize;
 3055                                if cursor_is_placed_after_comment_marker {
 3056                                    Some(comment_prefix.clone())
 3057                                } else {
 3058                                    None
 3059                                }
 3060                            });
 3061                            (comment_delimiter, insert_extra_newline)
 3062                        } else {
 3063                            (None, false)
 3064                        };
 3065
 3066                        let capacity_for_delimiter = comment_delimiter
 3067                            .as_deref()
 3068                            .map(str::len)
 3069                            .unwrap_or_default();
 3070                        let mut new_text =
 3071                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3072                        new_text.push('\n');
 3073                        new_text.extend(indent.chars());
 3074                        if let Some(delimiter) = &comment_delimiter {
 3075                            new_text.push_str(delimiter);
 3076                        }
 3077                        if insert_extra_newline {
 3078                            new_text = new_text.repeat(2);
 3079                        }
 3080
 3081                        let anchor = buffer.anchor_after(end);
 3082                        let new_selection = selection.map(|_| anchor);
 3083                        (
 3084                            (start..end, new_text),
 3085                            (insert_extra_newline, new_selection),
 3086                        )
 3087                    })
 3088                    .unzip()
 3089            };
 3090
 3091            this.edit_with_autoindent(edits, cx);
 3092            let buffer = this.buffer.read(cx).snapshot(cx);
 3093            let new_selections = selection_fixup_info
 3094                .into_iter()
 3095                .map(|(extra_newline_inserted, new_selection)| {
 3096                    let mut cursor = new_selection.end.to_point(&buffer);
 3097                    if extra_newline_inserted {
 3098                        cursor.row -= 1;
 3099                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3100                    }
 3101                    new_selection.map(|_| cursor)
 3102                })
 3103                .collect();
 3104
 3105            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3106            this.refresh_inline_completion(true, false, cx);
 3107        });
 3108    }
 3109
 3110    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3111        let buffer = self.buffer.read(cx);
 3112        let snapshot = buffer.snapshot(cx);
 3113
 3114        let mut edits = Vec::new();
 3115        let mut rows = Vec::new();
 3116
 3117        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3118            let cursor = selection.head();
 3119            let row = cursor.row;
 3120
 3121            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3122
 3123            let newline = "\n".to_string();
 3124            edits.push((start_of_line..start_of_line, newline));
 3125
 3126            rows.push(row + rows_inserted as u32);
 3127        }
 3128
 3129        self.transact(cx, |editor, cx| {
 3130            editor.edit(edits, cx);
 3131
 3132            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3133                let mut index = 0;
 3134                s.move_cursors_with(|map, _, _| {
 3135                    let row = rows[index];
 3136                    index += 1;
 3137
 3138                    let point = Point::new(row, 0);
 3139                    let boundary = map.next_line_boundary(point).1;
 3140                    let clipped = map.clip_point(boundary, Bias::Left);
 3141
 3142                    (clipped, SelectionGoal::None)
 3143                });
 3144            });
 3145
 3146            let mut indent_edits = Vec::new();
 3147            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3148            for row in rows {
 3149                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3150                for (row, indent) in indents {
 3151                    if indent.len == 0 {
 3152                        continue;
 3153                    }
 3154
 3155                    let text = match indent.kind {
 3156                        IndentKind::Space => " ".repeat(indent.len as usize),
 3157                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3158                    };
 3159                    let point = Point::new(row.0, 0);
 3160                    indent_edits.push((point..point, text));
 3161                }
 3162            }
 3163            editor.edit(indent_edits, cx);
 3164        });
 3165    }
 3166
 3167    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3168        let buffer = self.buffer.read(cx);
 3169        let snapshot = buffer.snapshot(cx);
 3170
 3171        let mut edits = Vec::new();
 3172        let mut rows = Vec::new();
 3173        let mut rows_inserted = 0;
 3174
 3175        for selection in self.selections.all_adjusted(cx) {
 3176            let cursor = selection.head();
 3177            let row = cursor.row;
 3178
 3179            let point = Point::new(row + 1, 0);
 3180            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3181
 3182            let newline = "\n".to_string();
 3183            edits.push((start_of_line..start_of_line, newline));
 3184
 3185            rows_inserted += 1;
 3186            rows.push(row + rows_inserted);
 3187        }
 3188
 3189        self.transact(cx, |editor, cx| {
 3190            editor.edit(edits, cx);
 3191
 3192            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3193                let mut index = 0;
 3194                s.move_cursors_with(|map, _, _| {
 3195                    let row = rows[index];
 3196                    index += 1;
 3197
 3198                    let point = Point::new(row, 0);
 3199                    let boundary = map.next_line_boundary(point).1;
 3200                    let clipped = map.clip_point(boundary, Bias::Left);
 3201
 3202                    (clipped, SelectionGoal::None)
 3203                });
 3204            });
 3205
 3206            let mut indent_edits = Vec::new();
 3207            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3208            for row in rows {
 3209                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3210                for (row, indent) in indents {
 3211                    if indent.len == 0 {
 3212                        continue;
 3213                    }
 3214
 3215                    let text = match indent.kind {
 3216                        IndentKind::Space => " ".repeat(indent.len as usize),
 3217                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3218                    };
 3219                    let point = Point::new(row.0, 0);
 3220                    indent_edits.push((point..point, text));
 3221                }
 3222            }
 3223            editor.edit(indent_edits, cx);
 3224        });
 3225    }
 3226
 3227    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3228        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3229            original_indent_columns: Vec::new(),
 3230        });
 3231        self.insert_with_autoindent_mode(text, autoindent, cx);
 3232    }
 3233
 3234    fn insert_with_autoindent_mode(
 3235        &mut self,
 3236        text: &str,
 3237        autoindent_mode: Option<AutoindentMode>,
 3238        cx: &mut ViewContext<Self>,
 3239    ) {
 3240        if self.read_only(cx) {
 3241            return;
 3242        }
 3243
 3244        let text: Arc<str> = text.into();
 3245        self.transact(cx, |this, cx| {
 3246            let old_selections = this.selections.all_adjusted(cx);
 3247            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3248                let anchors = {
 3249                    let snapshot = buffer.read(cx);
 3250                    old_selections
 3251                        .iter()
 3252                        .map(|s| {
 3253                            let anchor = snapshot.anchor_after(s.head());
 3254                            s.map(|_| anchor)
 3255                        })
 3256                        .collect::<Vec<_>>()
 3257                };
 3258                buffer.edit(
 3259                    old_selections
 3260                        .iter()
 3261                        .map(|s| (s.start..s.end, text.clone())),
 3262                    autoindent_mode,
 3263                    cx,
 3264                );
 3265                anchors
 3266            });
 3267
 3268            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3269                s.select_anchors(selection_anchors);
 3270            })
 3271        });
 3272    }
 3273
 3274    fn trigger_completion_on_input(
 3275        &mut self,
 3276        text: &str,
 3277        trigger_in_words: bool,
 3278        cx: &mut ViewContext<Self>,
 3279    ) {
 3280        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3281            self.show_completions(
 3282                &ShowCompletions {
 3283                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3284                },
 3285                cx,
 3286            );
 3287        } else {
 3288            self.hide_context_menu(cx);
 3289        }
 3290    }
 3291
 3292    fn is_completion_trigger(
 3293        &self,
 3294        text: &str,
 3295        trigger_in_words: bool,
 3296        cx: &mut ViewContext<Self>,
 3297    ) -> bool {
 3298        let position = self.selections.newest_anchor().head();
 3299        let multibuffer = self.buffer.read(cx);
 3300        let Some(buffer) = position
 3301            .buffer_id
 3302            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3303        else {
 3304            return false;
 3305        };
 3306
 3307        if let Some(completion_provider) = &self.completion_provider {
 3308            completion_provider.is_completion_trigger(
 3309                &buffer,
 3310                position.text_anchor,
 3311                text,
 3312                trigger_in_words,
 3313                cx,
 3314            )
 3315        } else {
 3316            false
 3317        }
 3318    }
 3319
 3320    /// If any empty selections is touching the start of its innermost containing autoclose
 3321    /// region, expand it to select the brackets.
 3322    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3323        let selections = self.selections.all::<usize>(cx);
 3324        let buffer = self.buffer.read(cx).read(cx);
 3325        let new_selections = self
 3326            .selections_with_autoclose_regions(selections, &buffer)
 3327            .map(|(mut selection, region)| {
 3328                if !selection.is_empty() {
 3329                    return selection;
 3330                }
 3331
 3332                if let Some(region) = region {
 3333                    let mut range = region.range.to_offset(&buffer);
 3334                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3335                        range.start -= region.pair.start.len();
 3336                        if buffer.contains_str_at(range.start, &region.pair.start)
 3337                            && buffer.contains_str_at(range.end, &region.pair.end)
 3338                        {
 3339                            range.end += region.pair.end.len();
 3340                            selection.start = range.start;
 3341                            selection.end = range.end;
 3342
 3343                            return selection;
 3344                        }
 3345                    }
 3346                }
 3347
 3348                let always_treat_brackets_as_autoclosed = buffer
 3349                    .settings_at(selection.start, cx)
 3350                    .always_treat_brackets_as_autoclosed;
 3351
 3352                if !always_treat_brackets_as_autoclosed {
 3353                    return selection;
 3354                }
 3355
 3356                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3357                    for (pair, enabled) in scope.brackets() {
 3358                        if !enabled || !pair.close {
 3359                            continue;
 3360                        }
 3361
 3362                        if buffer.contains_str_at(selection.start, &pair.end) {
 3363                            let pair_start_len = pair.start.len();
 3364                            if buffer.contains_str_at(
 3365                                selection.start.saturating_sub(pair_start_len),
 3366                                &pair.start,
 3367                            ) {
 3368                                selection.start -= pair_start_len;
 3369                                selection.end += pair.end.len();
 3370
 3371                                return selection;
 3372                            }
 3373                        }
 3374                    }
 3375                }
 3376
 3377                selection
 3378            })
 3379            .collect();
 3380
 3381        drop(buffer);
 3382        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3383    }
 3384
 3385    /// Iterate the given selections, and for each one, find the smallest surrounding
 3386    /// autoclose region. This uses the ordering of the selections and the autoclose
 3387    /// regions to avoid repeated comparisons.
 3388    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3389        &'a self,
 3390        selections: impl IntoIterator<Item = Selection<D>>,
 3391        buffer: &'a MultiBufferSnapshot,
 3392    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3393        let mut i = 0;
 3394        let mut regions = self.autoclose_regions.as_slice();
 3395        selections.into_iter().map(move |selection| {
 3396            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3397
 3398            let mut enclosing = None;
 3399            while let Some(pair_state) = regions.get(i) {
 3400                if pair_state.range.end.to_offset(buffer) < range.start {
 3401                    regions = &regions[i + 1..];
 3402                    i = 0;
 3403                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3404                    break;
 3405                } else {
 3406                    if pair_state.selection_id == selection.id {
 3407                        enclosing = Some(pair_state);
 3408                    }
 3409                    i += 1;
 3410                }
 3411            }
 3412
 3413            (selection, enclosing)
 3414        })
 3415    }
 3416
 3417    /// Remove any autoclose regions that no longer contain their selection.
 3418    fn invalidate_autoclose_regions(
 3419        &mut self,
 3420        mut selections: &[Selection<Anchor>],
 3421        buffer: &MultiBufferSnapshot,
 3422    ) {
 3423        self.autoclose_regions.retain(|state| {
 3424            let mut i = 0;
 3425            while let Some(selection) = selections.get(i) {
 3426                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3427                    selections = &selections[1..];
 3428                    continue;
 3429                }
 3430                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3431                    break;
 3432                }
 3433                if selection.id == state.selection_id {
 3434                    return true;
 3435                } else {
 3436                    i += 1;
 3437                }
 3438            }
 3439            false
 3440        });
 3441    }
 3442
 3443    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3444        let offset = position.to_offset(buffer);
 3445        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3446        if offset > word_range.start && kind == Some(CharKind::Word) {
 3447            Some(
 3448                buffer
 3449                    .text_for_range(word_range.start..offset)
 3450                    .collect::<String>(),
 3451            )
 3452        } else {
 3453            None
 3454        }
 3455    }
 3456
 3457    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3458        self.refresh_inlay_hints(
 3459            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3460            cx,
 3461        );
 3462    }
 3463
 3464    pub fn inlay_hints_enabled(&self) -> bool {
 3465        self.inlay_hint_cache.enabled
 3466    }
 3467
 3468    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3469        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3470            return;
 3471        }
 3472
 3473        let reason_description = reason.description();
 3474        let ignore_debounce = matches!(
 3475            reason,
 3476            InlayHintRefreshReason::SettingsChange(_)
 3477                | InlayHintRefreshReason::Toggle(_)
 3478                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3479        );
 3480        let (invalidate_cache, required_languages) = match reason {
 3481            InlayHintRefreshReason::Toggle(enabled) => {
 3482                self.inlay_hint_cache.enabled = enabled;
 3483                if enabled {
 3484                    (InvalidationStrategy::RefreshRequested, None)
 3485                } else {
 3486                    self.inlay_hint_cache.clear();
 3487                    self.splice_inlays(
 3488                        self.visible_inlay_hints(cx)
 3489                            .iter()
 3490                            .map(|inlay| inlay.id)
 3491                            .collect(),
 3492                        Vec::new(),
 3493                        cx,
 3494                    );
 3495                    return;
 3496                }
 3497            }
 3498            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3499                match self.inlay_hint_cache.update_settings(
 3500                    &self.buffer,
 3501                    new_settings,
 3502                    self.visible_inlay_hints(cx),
 3503                    cx,
 3504                ) {
 3505                    ControlFlow::Break(Some(InlaySplice {
 3506                        to_remove,
 3507                        to_insert,
 3508                    })) => {
 3509                        self.splice_inlays(to_remove, to_insert, cx);
 3510                        return;
 3511                    }
 3512                    ControlFlow::Break(None) => return,
 3513                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3514                }
 3515            }
 3516            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3517                if let Some(InlaySplice {
 3518                    to_remove,
 3519                    to_insert,
 3520                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3521                {
 3522                    self.splice_inlays(to_remove, to_insert, cx);
 3523                }
 3524                return;
 3525            }
 3526            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3527            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3528                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3529            }
 3530            InlayHintRefreshReason::RefreshRequested => {
 3531                (InvalidationStrategy::RefreshRequested, None)
 3532            }
 3533        };
 3534
 3535        if let Some(InlaySplice {
 3536            to_remove,
 3537            to_insert,
 3538        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3539            reason_description,
 3540            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3541            invalidate_cache,
 3542            ignore_debounce,
 3543            cx,
 3544        ) {
 3545            self.splice_inlays(to_remove, to_insert, cx);
 3546        }
 3547    }
 3548
 3549    fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
 3550        self.display_map
 3551            .read(cx)
 3552            .current_inlays()
 3553            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3554            .cloned()
 3555            .collect()
 3556    }
 3557
 3558    pub fn excerpts_for_inlay_hints_query(
 3559        &self,
 3560        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3561        cx: &mut ViewContext<Editor>,
 3562    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3563        let Some(project) = self.project.as_ref() else {
 3564            return HashMap::default();
 3565        };
 3566        let project = project.read(cx);
 3567        let multi_buffer = self.buffer().read(cx);
 3568        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3569        let multi_buffer_visible_start = self
 3570            .scroll_manager
 3571            .anchor()
 3572            .anchor
 3573            .to_point(&multi_buffer_snapshot);
 3574        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3575            multi_buffer_visible_start
 3576                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3577            Bias::Left,
 3578        );
 3579        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3580        multi_buffer_snapshot
 3581            .range_to_buffer_ranges(multi_buffer_visible_range)
 3582            .into_iter()
 3583            .filter(|(_, excerpt_visible_range)| !excerpt_visible_range.is_empty())
 3584            .filter_map(|(excerpt, excerpt_visible_range)| {
 3585                let buffer_file = project::File::from_dyn(excerpt.buffer().file())?;
 3586                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3587                let worktree_entry = buffer_worktree
 3588                    .read(cx)
 3589                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3590                if worktree_entry.is_ignored {
 3591                    return None;
 3592                }
 3593
 3594                let language = excerpt.buffer().language()?;
 3595                if let Some(restrict_to_languages) = restrict_to_languages {
 3596                    if !restrict_to_languages.contains(language) {
 3597                        return None;
 3598                    }
 3599                }
 3600                Some((
 3601                    excerpt.id(),
 3602                    (
 3603                        multi_buffer.buffer(excerpt.buffer_id()).unwrap(),
 3604                        excerpt.buffer().version().clone(),
 3605                        excerpt_visible_range,
 3606                    ),
 3607                ))
 3608            })
 3609            .collect()
 3610    }
 3611
 3612    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3613        TextLayoutDetails {
 3614            text_system: cx.text_system().clone(),
 3615            editor_style: self.style.clone().unwrap(),
 3616            rem_size: cx.rem_size(),
 3617            scroll_anchor: self.scroll_manager.anchor(),
 3618            visible_rows: self.visible_line_count(),
 3619            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3620        }
 3621    }
 3622
 3623    pub fn splice_inlays(
 3624        &self,
 3625        to_remove: Vec<InlayId>,
 3626        to_insert: Vec<Inlay>,
 3627        cx: &mut ViewContext<Self>,
 3628    ) {
 3629        self.display_map.update(cx, |display_map, cx| {
 3630            display_map.splice_inlays(to_remove, to_insert, cx)
 3631        });
 3632        cx.notify();
 3633    }
 3634
 3635    fn trigger_on_type_formatting(
 3636        &self,
 3637        input: String,
 3638        cx: &mut ViewContext<Self>,
 3639    ) -> Option<Task<Result<()>>> {
 3640        if input.len() != 1 {
 3641            return None;
 3642        }
 3643
 3644        let project = self.project.as_ref()?;
 3645        let position = self.selections.newest_anchor().head();
 3646        let (buffer, buffer_position) = self
 3647            .buffer
 3648            .read(cx)
 3649            .text_anchor_for_position(position, cx)?;
 3650
 3651        let settings = language_settings::language_settings(
 3652            buffer
 3653                .read(cx)
 3654                .language_at(buffer_position)
 3655                .map(|l| l.name()),
 3656            buffer.read(cx).file(),
 3657            cx,
 3658        );
 3659        if !settings.use_on_type_format {
 3660            return None;
 3661        }
 3662
 3663        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3664        // hence we do LSP request & edit on host side only — add formats to host's history.
 3665        let push_to_lsp_host_history = true;
 3666        // If this is not the host, append its history with new edits.
 3667        let push_to_client_history = project.read(cx).is_via_collab();
 3668
 3669        let on_type_formatting = project.update(cx, |project, cx| {
 3670            project.on_type_format(
 3671                buffer.clone(),
 3672                buffer_position,
 3673                input,
 3674                push_to_lsp_host_history,
 3675                cx,
 3676            )
 3677        });
 3678        Some(cx.spawn(|editor, mut cx| async move {
 3679            if let Some(transaction) = on_type_formatting.await? {
 3680                if push_to_client_history {
 3681                    buffer
 3682                        .update(&mut cx, |buffer, _| {
 3683                            buffer.push_transaction(transaction, Instant::now());
 3684                        })
 3685                        .ok();
 3686                }
 3687                editor.update(&mut cx, |editor, cx| {
 3688                    editor.refresh_document_highlights(cx);
 3689                })?;
 3690            }
 3691            Ok(())
 3692        }))
 3693    }
 3694
 3695    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3696        if self.pending_rename.is_some() {
 3697            return;
 3698        }
 3699
 3700        let Some(provider) = self.completion_provider.as_ref() else {
 3701            return;
 3702        };
 3703
 3704        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3705            return;
 3706        }
 3707
 3708        let position = self.selections.newest_anchor().head();
 3709        let (buffer, buffer_position) =
 3710            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3711                output
 3712            } else {
 3713                return;
 3714            };
 3715        let show_completion_documentation = buffer
 3716            .read(cx)
 3717            .snapshot()
 3718            .settings_at(buffer_position, cx)
 3719            .show_completion_documentation;
 3720
 3721        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3722
 3723        let trigger_kind = match &options.trigger {
 3724            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3725                CompletionTriggerKind::TRIGGER_CHARACTER
 3726            }
 3727            _ => CompletionTriggerKind::INVOKED,
 3728        };
 3729        let completion_context = CompletionContext {
 3730            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3731                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3732                    Some(String::from(trigger))
 3733                } else {
 3734                    None
 3735                }
 3736            }),
 3737            trigger_kind,
 3738        };
 3739        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 3740        let sort_completions = provider.sort_completions();
 3741
 3742        let id = post_inc(&mut self.next_completion_id);
 3743        let task = cx.spawn(|editor, mut cx| {
 3744            async move {
 3745                editor.update(&mut cx, |this, _| {
 3746                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3747                })?;
 3748                let completions = completions.await.log_err();
 3749                let menu = if let Some(completions) = completions {
 3750                    let mut menu = CompletionsMenu::new(
 3751                        id,
 3752                        sort_completions,
 3753                        show_completion_documentation,
 3754                        position,
 3755                        buffer.clone(),
 3756                        completions.into(),
 3757                    );
 3758
 3759                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3760                        .await;
 3761
 3762                    menu.visible().then_some(menu)
 3763                } else {
 3764                    None
 3765                };
 3766
 3767                editor.update(&mut cx, |editor, cx| {
 3768                    match editor.context_menu.borrow().as_ref() {
 3769                        None => {}
 3770                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3771                            if prev_menu.id > id {
 3772                                return;
 3773                            }
 3774                        }
 3775                        _ => return,
 3776                    }
 3777
 3778                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 3779                        let mut menu = menu.unwrap();
 3780                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3781
 3782                        if editor.show_inline_completions_in_menu(cx) {
 3783                            if let Some(hint) = editor.inline_completion_menu_hint(cx) {
 3784                                menu.show_inline_completion_hint(hint);
 3785                            }
 3786                        } else {
 3787                            editor.discard_inline_completion(false, cx);
 3788                        }
 3789
 3790                        *editor.context_menu.borrow_mut() =
 3791                            Some(CodeContextMenu::Completions(menu));
 3792
 3793                        cx.notify();
 3794                    } else if editor.completion_tasks.len() <= 1 {
 3795                        // If there are no more completion tasks and the last menu was
 3796                        // empty, we should hide it.
 3797                        let was_hidden = editor.hide_context_menu(cx).is_none();
 3798                        // If it was already hidden and we don't show inline
 3799                        // completions in the menu, we should also show the
 3800                        // inline-completion when available.
 3801                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3802                            editor.update_visible_inline_completion(cx);
 3803                        }
 3804                    }
 3805                })?;
 3806
 3807                Ok::<_, anyhow::Error>(())
 3808            }
 3809            .log_err()
 3810        });
 3811
 3812        self.completion_tasks.push((id, task));
 3813    }
 3814
 3815    pub fn confirm_completion(
 3816        &mut self,
 3817        action: &ConfirmCompletion,
 3818        cx: &mut ViewContext<Self>,
 3819    ) -> Option<Task<Result<()>>> {
 3820        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 3821    }
 3822
 3823    pub fn compose_completion(
 3824        &mut self,
 3825        action: &ComposeCompletion,
 3826        cx: &mut ViewContext<Self>,
 3827    ) -> Option<Task<Result<()>>> {
 3828        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 3829    }
 3830
 3831    fn do_completion(
 3832        &mut self,
 3833        item_ix: Option<usize>,
 3834        intent: CompletionIntent,
 3835        cx: &mut ViewContext<Editor>,
 3836    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3837        use language::ToOffset as _;
 3838
 3839        {
 3840            let context_menu = self.context_menu.borrow();
 3841            if let CodeContextMenu::Completions(menu) = context_menu.as_ref()? {
 3842                let entries = menu.entries.borrow();
 3843                let entry = entries.get(item_ix.unwrap_or(menu.selected_item));
 3844                match entry {
 3845                    Some(CompletionEntry::InlineCompletionHint(
 3846                        InlineCompletionMenuHint::Loading,
 3847                    )) => return Some(Task::ready(Ok(()))),
 3848                    Some(CompletionEntry::InlineCompletionHint(InlineCompletionMenuHint::None)) => {
 3849                        drop(entries);
 3850                        drop(context_menu);
 3851                        self.context_menu_next(&Default::default(), cx);
 3852                        return Some(Task::ready(Ok(())));
 3853                    }
 3854                    _ => {}
 3855                }
 3856            }
 3857        }
 3858
 3859        let completions_menu =
 3860            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3861                menu
 3862            } else {
 3863                return None;
 3864            };
 3865
 3866        let entries = completions_menu.entries.borrow();
 3867        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3868        let mat = match mat {
 3869            CompletionEntry::InlineCompletionHint(_) => {
 3870                self.accept_inline_completion(&AcceptInlineCompletion, cx);
 3871                cx.stop_propagation();
 3872                return Some(Task::ready(Ok(())));
 3873            }
 3874            CompletionEntry::Match(mat) => {
 3875                if self.show_inline_completions_in_menu(cx) {
 3876                    self.discard_inline_completion(true, cx);
 3877                }
 3878                mat
 3879            }
 3880        };
 3881        let candidate_id = mat.candidate_id;
 3882        drop(entries);
 3883
 3884        let buffer_handle = completions_menu.buffer;
 3885        let completion = completions_menu
 3886            .completions
 3887            .borrow()
 3888            .get(candidate_id)?
 3889            .clone();
 3890        cx.stop_propagation();
 3891
 3892        let snippet;
 3893        let text;
 3894
 3895        if completion.is_snippet() {
 3896            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3897            text = snippet.as_ref().unwrap().text.clone();
 3898        } else {
 3899            snippet = None;
 3900            text = completion.new_text.clone();
 3901        };
 3902        let selections = self.selections.all::<usize>(cx);
 3903        let buffer = buffer_handle.read(cx);
 3904        let old_range = completion.old_range.to_offset(buffer);
 3905        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3906
 3907        let newest_selection = self.selections.newest_anchor();
 3908        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3909            return None;
 3910        }
 3911
 3912        let lookbehind = newest_selection
 3913            .start
 3914            .text_anchor
 3915            .to_offset(buffer)
 3916            .saturating_sub(old_range.start);
 3917        let lookahead = old_range
 3918            .end
 3919            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3920        let mut common_prefix_len = old_text
 3921            .bytes()
 3922            .zip(text.bytes())
 3923            .take_while(|(a, b)| a == b)
 3924            .count();
 3925
 3926        let snapshot = self.buffer.read(cx).snapshot(cx);
 3927        let mut range_to_replace: Option<Range<isize>> = None;
 3928        let mut ranges = Vec::new();
 3929        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3930        for selection in &selections {
 3931            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3932                let start = selection.start.saturating_sub(lookbehind);
 3933                let end = selection.end + lookahead;
 3934                if selection.id == newest_selection.id {
 3935                    range_to_replace = Some(
 3936                        ((start + common_prefix_len) as isize - selection.start as isize)
 3937                            ..(end as isize - selection.start as isize),
 3938                    );
 3939                }
 3940                ranges.push(start + common_prefix_len..end);
 3941            } else {
 3942                common_prefix_len = 0;
 3943                ranges.clear();
 3944                ranges.extend(selections.iter().map(|s| {
 3945                    if s.id == newest_selection.id {
 3946                        range_to_replace = Some(
 3947                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3948                                - selection.start as isize
 3949                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3950                                    - selection.start as isize,
 3951                        );
 3952                        old_range.clone()
 3953                    } else {
 3954                        s.start..s.end
 3955                    }
 3956                }));
 3957                break;
 3958            }
 3959            if !self.linked_edit_ranges.is_empty() {
 3960                let start_anchor = snapshot.anchor_before(selection.head());
 3961                let end_anchor = snapshot.anchor_after(selection.tail());
 3962                if let Some(ranges) = self
 3963                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 3964                {
 3965                    for (buffer, edits) in ranges {
 3966                        linked_edits.entry(buffer.clone()).or_default().extend(
 3967                            edits
 3968                                .into_iter()
 3969                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 3970                        );
 3971                    }
 3972                }
 3973            }
 3974        }
 3975        let text = &text[common_prefix_len..];
 3976
 3977        cx.emit(EditorEvent::InputHandled {
 3978            utf16_range_to_replace: range_to_replace,
 3979            text: text.into(),
 3980        });
 3981
 3982        self.transact(cx, |this, cx| {
 3983            if let Some(mut snippet) = snippet {
 3984                snippet.text = text.to_string();
 3985                for tabstop in snippet
 3986                    .tabstops
 3987                    .iter_mut()
 3988                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 3989                {
 3990                    tabstop.start -= common_prefix_len as isize;
 3991                    tabstop.end -= common_prefix_len as isize;
 3992                }
 3993
 3994                this.insert_snippet(&ranges, snippet, cx).log_err();
 3995            } else {
 3996                this.buffer.update(cx, |buffer, cx| {
 3997                    buffer.edit(
 3998                        ranges.iter().map(|range| (range.clone(), text)),
 3999                        this.autoindent_mode.clone(),
 4000                        cx,
 4001                    );
 4002                });
 4003            }
 4004            for (buffer, edits) in linked_edits {
 4005                buffer.update(cx, |buffer, cx| {
 4006                    let snapshot = buffer.snapshot();
 4007                    let edits = edits
 4008                        .into_iter()
 4009                        .map(|(range, text)| {
 4010                            use text::ToPoint as TP;
 4011                            let end_point = TP::to_point(&range.end, &snapshot);
 4012                            let start_point = TP::to_point(&range.start, &snapshot);
 4013                            (start_point..end_point, text)
 4014                        })
 4015                        .sorted_by_key(|(range, _)| range.start)
 4016                        .collect::<Vec<_>>();
 4017                    buffer.edit(edits, None, cx);
 4018                })
 4019            }
 4020
 4021            this.refresh_inline_completion(true, false, cx);
 4022        });
 4023
 4024        let show_new_completions_on_confirm = completion
 4025            .confirm
 4026            .as_ref()
 4027            .map_or(false, |confirm| confirm(intent, cx));
 4028        if show_new_completions_on_confirm {
 4029            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4030        }
 4031
 4032        let provider = self.completion_provider.as_ref()?;
 4033        drop(completion);
 4034        let apply_edits = provider.apply_additional_edits_for_completion(
 4035            buffer_handle,
 4036            completions_menu.completions.clone(),
 4037            candidate_id,
 4038            true,
 4039            cx,
 4040        );
 4041
 4042        let editor_settings = EditorSettings::get_global(cx);
 4043        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4044            // After the code completion is finished, users often want to know what signatures are needed.
 4045            // so we should automatically call signature_help
 4046            self.show_signature_help(&ShowSignatureHelp, cx);
 4047        }
 4048
 4049        Some(cx.foreground_executor().spawn(async move {
 4050            apply_edits.await?;
 4051            Ok(())
 4052        }))
 4053    }
 4054
 4055    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4056        let mut context_menu = self.context_menu.borrow_mut();
 4057        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4058            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4059                // Toggle if we're selecting the same one
 4060                *context_menu = None;
 4061                cx.notify();
 4062                return;
 4063            } else {
 4064                // Otherwise, clear it and start a new one
 4065                *context_menu = None;
 4066                cx.notify();
 4067            }
 4068        }
 4069        drop(context_menu);
 4070        let snapshot = self.snapshot(cx);
 4071        let deployed_from_indicator = action.deployed_from_indicator;
 4072        let mut task = self.code_actions_task.take();
 4073        let action = action.clone();
 4074        cx.spawn(|editor, mut cx| async move {
 4075            while let Some(prev_task) = task {
 4076                prev_task.await.log_err();
 4077                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4078            }
 4079
 4080            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4081                if editor.focus_handle.is_focused(cx) {
 4082                    let multibuffer_point = action
 4083                        .deployed_from_indicator
 4084                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4085                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4086                    let (buffer, buffer_row) = snapshot
 4087                        .buffer_snapshot
 4088                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4089                        .and_then(|(buffer_snapshot, range)| {
 4090                            editor
 4091                                .buffer
 4092                                .read(cx)
 4093                                .buffer(buffer_snapshot.remote_id())
 4094                                .map(|buffer| (buffer, range.start.row))
 4095                        })?;
 4096                    let (_, code_actions) = editor
 4097                        .available_code_actions
 4098                        .clone()
 4099                        .and_then(|(location, code_actions)| {
 4100                            let snapshot = location.buffer.read(cx).snapshot();
 4101                            let point_range = location.range.to_point(&snapshot);
 4102                            let point_range = point_range.start.row..=point_range.end.row;
 4103                            if point_range.contains(&buffer_row) {
 4104                                Some((location, code_actions))
 4105                            } else {
 4106                                None
 4107                            }
 4108                        })
 4109                        .unzip();
 4110                    let buffer_id = buffer.read(cx).remote_id();
 4111                    let tasks = editor
 4112                        .tasks
 4113                        .get(&(buffer_id, buffer_row))
 4114                        .map(|t| Arc::new(t.to_owned()));
 4115                    if tasks.is_none() && code_actions.is_none() {
 4116                        return None;
 4117                    }
 4118
 4119                    editor.completion_tasks.clear();
 4120                    editor.discard_inline_completion(false, cx);
 4121                    let task_context =
 4122                        tasks
 4123                            .as_ref()
 4124                            .zip(editor.project.clone())
 4125                            .map(|(tasks, project)| {
 4126                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4127                            });
 4128
 4129                    Some(cx.spawn(|editor, mut cx| async move {
 4130                        let task_context = match task_context {
 4131                            Some(task_context) => task_context.await,
 4132                            None => None,
 4133                        };
 4134                        let resolved_tasks =
 4135                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4136                                Rc::new(ResolvedTasks {
 4137                                    templates: tasks.resolve(&task_context).collect(),
 4138                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4139                                        multibuffer_point.row,
 4140                                        tasks.column,
 4141                                    )),
 4142                                })
 4143                            });
 4144                        let spawn_straight_away = resolved_tasks
 4145                            .as_ref()
 4146                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4147                            && code_actions
 4148                                .as_ref()
 4149                                .map_or(true, |actions| actions.is_empty());
 4150                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4151                            *editor.context_menu.borrow_mut() =
 4152                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4153                                    buffer,
 4154                                    actions: CodeActionContents {
 4155                                        tasks: resolved_tasks,
 4156                                        actions: code_actions,
 4157                                    },
 4158                                    selected_item: Default::default(),
 4159                                    scroll_handle: UniformListScrollHandle::default(),
 4160                                    deployed_from_indicator,
 4161                                }));
 4162                            if spawn_straight_away {
 4163                                if let Some(task) = editor.confirm_code_action(
 4164                                    &ConfirmCodeAction { item_ix: Some(0) },
 4165                                    cx,
 4166                                ) {
 4167                                    cx.notify();
 4168                                    return task;
 4169                                }
 4170                            }
 4171                            cx.notify();
 4172                            Task::ready(Ok(()))
 4173                        }) {
 4174                            task.await
 4175                        } else {
 4176                            Ok(())
 4177                        }
 4178                    }))
 4179                } else {
 4180                    Some(Task::ready(Ok(())))
 4181                }
 4182            })?;
 4183            if let Some(task) = spawned_test_task {
 4184                task.await?;
 4185            }
 4186
 4187            Ok::<_, anyhow::Error>(())
 4188        })
 4189        .detach_and_log_err(cx);
 4190    }
 4191
 4192    pub fn confirm_code_action(
 4193        &mut self,
 4194        action: &ConfirmCodeAction,
 4195        cx: &mut ViewContext<Self>,
 4196    ) -> Option<Task<Result<()>>> {
 4197        let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4198            menu
 4199        } else {
 4200            return None;
 4201        };
 4202        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4203        let action = actions_menu.actions.get(action_ix)?;
 4204        let title = action.label();
 4205        let buffer = actions_menu.buffer;
 4206        let workspace = self.workspace()?;
 4207
 4208        match action {
 4209            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4210                workspace.update(cx, |workspace, cx| {
 4211                    workspace::tasks::schedule_resolved_task(
 4212                        workspace,
 4213                        task_source_kind,
 4214                        resolved_task,
 4215                        false,
 4216                        cx,
 4217                    );
 4218
 4219                    Some(Task::ready(Ok(())))
 4220                })
 4221            }
 4222            CodeActionsItem::CodeAction {
 4223                excerpt_id,
 4224                action,
 4225                provider,
 4226            } => {
 4227                let apply_code_action =
 4228                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4229                let workspace = workspace.downgrade();
 4230                Some(cx.spawn(|editor, cx| async move {
 4231                    let project_transaction = apply_code_action.await?;
 4232                    Self::open_project_transaction(
 4233                        &editor,
 4234                        workspace,
 4235                        project_transaction,
 4236                        title,
 4237                        cx,
 4238                    )
 4239                    .await
 4240                }))
 4241            }
 4242        }
 4243    }
 4244
 4245    pub async fn open_project_transaction(
 4246        this: &WeakView<Editor>,
 4247        workspace: WeakView<Workspace>,
 4248        transaction: ProjectTransaction,
 4249        title: String,
 4250        mut cx: AsyncWindowContext,
 4251    ) -> Result<()> {
 4252        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4253        cx.update(|cx| {
 4254            entries.sort_unstable_by_key(|(buffer, _)| {
 4255                buffer.read(cx).file().map(|f| f.path().clone())
 4256            });
 4257        })?;
 4258
 4259        // If the project transaction's edits are all contained within this editor, then
 4260        // avoid opening a new editor to display them.
 4261
 4262        if let Some((buffer, transaction)) = entries.first() {
 4263            if entries.len() == 1 {
 4264                let excerpt = this.update(&mut cx, |editor, cx| {
 4265                    editor
 4266                        .buffer()
 4267                        .read(cx)
 4268                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4269                })?;
 4270                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4271                    if excerpted_buffer == *buffer {
 4272                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4273                            let excerpt_range = excerpt_range.to_offset(buffer);
 4274                            buffer
 4275                                .edited_ranges_for_transaction::<usize>(transaction)
 4276                                .all(|range| {
 4277                                    excerpt_range.start <= range.start
 4278                                        && excerpt_range.end >= range.end
 4279                                })
 4280                        })?;
 4281
 4282                        if all_edits_within_excerpt {
 4283                            return Ok(());
 4284                        }
 4285                    }
 4286                }
 4287            }
 4288        } else {
 4289            return Ok(());
 4290        }
 4291
 4292        let mut ranges_to_highlight = Vec::new();
 4293        let excerpt_buffer = cx.new_model(|cx| {
 4294            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4295            for (buffer_handle, transaction) in &entries {
 4296                let buffer = buffer_handle.read(cx);
 4297                ranges_to_highlight.extend(
 4298                    multibuffer.push_excerpts_with_context_lines(
 4299                        buffer_handle.clone(),
 4300                        buffer
 4301                            .edited_ranges_for_transaction::<usize>(transaction)
 4302                            .collect(),
 4303                        DEFAULT_MULTIBUFFER_CONTEXT,
 4304                        cx,
 4305                    ),
 4306                );
 4307            }
 4308            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4309            multibuffer
 4310        })?;
 4311
 4312        workspace.update(&mut cx, |workspace, cx| {
 4313            let project = workspace.project().clone();
 4314            let editor =
 4315                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4316            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4317            editor.update(cx, |editor, cx| {
 4318                editor.highlight_background::<Self>(
 4319                    &ranges_to_highlight,
 4320                    |theme| theme.editor_highlighted_line_background,
 4321                    cx,
 4322                );
 4323            });
 4324        })?;
 4325
 4326        Ok(())
 4327    }
 4328
 4329    pub fn clear_code_action_providers(&mut self) {
 4330        self.code_action_providers.clear();
 4331        self.available_code_actions.take();
 4332    }
 4333
 4334    pub fn add_code_action_provider(
 4335        &mut self,
 4336        provider: Rc<dyn CodeActionProvider>,
 4337        cx: &mut ViewContext<Self>,
 4338    ) {
 4339        if self
 4340            .code_action_providers
 4341            .iter()
 4342            .any(|existing_provider| existing_provider.id() == provider.id())
 4343        {
 4344            return;
 4345        }
 4346
 4347        self.code_action_providers.push(provider);
 4348        self.refresh_code_actions(cx);
 4349    }
 4350
 4351    pub fn remove_code_action_provider(&mut self, id: Arc<str>, cx: &mut ViewContext<Self>) {
 4352        self.code_action_providers
 4353            .retain(|provider| provider.id() != id);
 4354        self.refresh_code_actions(cx);
 4355    }
 4356
 4357    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4358        let buffer = self.buffer.read(cx);
 4359        let newest_selection = self.selections.newest_anchor().clone();
 4360        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4361        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4362        if start_buffer != end_buffer {
 4363            return None;
 4364        }
 4365
 4366        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4367            cx.background_executor()
 4368                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4369                .await;
 4370
 4371            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4372                let providers = this.code_action_providers.clone();
 4373                let tasks = this
 4374                    .code_action_providers
 4375                    .iter()
 4376                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4377                    .collect::<Vec<_>>();
 4378                (providers, tasks)
 4379            })?;
 4380
 4381            let mut actions = Vec::new();
 4382            for (provider, provider_actions) in
 4383                providers.into_iter().zip(future::join_all(tasks).await)
 4384            {
 4385                if let Some(provider_actions) = provider_actions.log_err() {
 4386                    actions.extend(provider_actions.into_iter().map(|action| {
 4387                        AvailableCodeAction {
 4388                            excerpt_id: newest_selection.start.excerpt_id,
 4389                            action,
 4390                            provider: provider.clone(),
 4391                        }
 4392                    }));
 4393                }
 4394            }
 4395
 4396            this.update(&mut cx, |this, cx| {
 4397                this.available_code_actions = if actions.is_empty() {
 4398                    None
 4399                } else {
 4400                    Some((
 4401                        Location {
 4402                            buffer: start_buffer,
 4403                            range: start..end,
 4404                        },
 4405                        actions.into(),
 4406                    ))
 4407                };
 4408                cx.notify();
 4409            })
 4410        }));
 4411        None
 4412    }
 4413
 4414    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4415        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4416            self.show_git_blame_inline = false;
 4417
 4418            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4419                cx.background_executor().timer(delay).await;
 4420
 4421                this.update(&mut cx, |this, cx| {
 4422                    this.show_git_blame_inline = true;
 4423                    cx.notify();
 4424                })
 4425                .log_err();
 4426            }));
 4427        }
 4428    }
 4429
 4430    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4431        if self.pending_rename.is_some() {
 4432            return None;
 4433        }
 4434
 4435        let provider = self.semantics_provider.clone()?;
 4436        let buffer = self.buffer.read(cx);
 4437        let newest_selection = self.selections.newest_anchor().clone();
 4438        let cursor_position = newest_selection.head();
 4439        let (cursor_buffer, cursor_buffer_position) =
 4440            buffer.text_anchor_for_position(cursor_position, cx)?;
 4441        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4442        if cursor_buffer != tail_buffer {
 4443            return None;
 4444        }
 4445        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4446        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4447            cx.background_executor()
 4448                .timer(Duration::from_millis(debounce))
 4449                .await;
 4450
 4451            let highlights = if let Some(highlights) = cx
 4452                .update(|cx| {
 4453                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4454                })
 4455                .ok()
 4456                .flatten()
 4457            {
 4458                highlights.await.log_err()
 4459            } else {
 4460                None
 4461            };
 4462
 4463            if let Some(highlights) = highlights {
 4464                this.update(&mut cx, |this, cx| {
 4465                    if this.pending_rename.is_some() {
 4466                        return;
 4467                    }
 4468
 4469                    let buffer_id = cursor_position.buffer_id;
 4470                    let buffer = this.buffer.read(cx);
 4471                    if !buffer
 4472                        .text_anchor_for_position(cursor_position, cx)
 4473                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4474                    {
 4475                        return;
 4476                    }
 4477
 4478                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4479                    let mut write_ranges = Vec::new();
 4480                    let mut read_ranges = Vec::new();
 4481                    for highlight in highlights {
 4482                        for (excerpt_id, excerpt_range) in
 4483                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4484                        {
 4485                            let start = highlight
 4486                                .range
 4487                                .start
 4488                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4489                            let end = highlight
 4490                                .range
 4491                                .end
 4492                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4493                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4494                                continue;
 4495                            }
 4496
 4497                            let range = Anchor {
 4498                                buffer_id,
 4499                                excerpt_id,
 4500                                text_anchor: start,
 4501                            }..Anchor {
 4502                                buffer_id,
 4503                                excerpt_id,
 4504                                text_anchor: end,
 4505                            };
 4506                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4507                                write_ranges.push(range);
 4508                            } else {
 4509                                read_ranges.push(range);
 4510                            }
 4511                        }
 4512                    }
 4513
 4514                    this.highlight_background::<DocumentHighlightRead>(
 4515                        &read_ranges,
 4516                        |theme| theme.editor_document_highlight_read_background,
 4517                        cx,
 4518                    );
 4519                    this.highlight_background::<DocumentHighlightWrite>(
 4520                        &write_ranges,
 4521                        |theme| theme.editor_document_highlight_write_background,
 4522                        cx,
 4523                    );
 4524                    cx.notify();
 4525                })
 4526                .log_err();
 4527            }
 4528        }));
 4529        None
 4530    }
 4531
 4532    pub fn refresh_inline_completion(
 4533        &mut self,
 4534        debounce: bool,
 4535        user_requested: bool,
 4536        cx: &mut ViewContext<Self>,
 4537    ) -> Option<()> {
 4538        let provider = self.inline_completion_provider()?;
 4539        let cursor = self.selections.newest_anchor().head();
 4540        let (buffer, cursor_buffer_position) =
 4541            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4542
 4543        if !user_requested
 4544            && (!self.enable_inline_completions
 4545                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4546                || !self.is_focused(cx)
 4547                || buffer.read(cx).is_empty())
 4548        {
 4549            self.discard_inline_completion(false, cx);
 4550            return None;
 4551        }
 4552
 4553        self.update_visible_inline_completion(cx);
 4554        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4555        Some(())
 4556    }
 4557
 4558    fn cycle_inline_completion(
 4559        &mut self,
 4560        direction: Direction,
 4561        cx: &mut ViewContext<Self>,
 4562    ) -> Option<()> {
 4563        let provider = self.inline_completion_provider()?;
 4564        let cursor = self.selections.newest_anchor().head();
 4565        let (buffer, cursor_buffer_position) =
 4566            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4567        if !self.enable_inline_completions
 4568            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4569        {
 4570            return None;
 4571        }
 4572
 4573        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4574        self.update_visible_inline_completion(cx);
 4575
 4576        Some(())
 4577    }
 4578
 4579    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4580        if !self.has_active_inline_completion() {
 4581            self.refresh_inline_completion(false, true, cx);
 4582            return;
 4583        }
 4584
 4585        self.update_visible_inline_completion(cx);
 4586    }
 4587
 4588    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4589        self.show_cursor_names(cx);
 4590    }
 4591
 4592    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4593        self.show_cursor_names = true;
 4594        cx.notify();
 4595        cx.spawn(|this, mut cx| async move {
 4596            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4597            this.update(&mut cx, |this, cx| {
 4598                this.show_cursor_names = false;
 4599                cx.notify()
 4600            })
 4601            .ok()
 4602        })
 4603        .detach();
 4604    }
 4605
 4606    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4607        if self.has_active_inline_completion() {
 4608            self.cycle_inline_completion(Direction::Next, cx);
 4609        } else {
 4610            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4611            if is_copilot_disabled {
 4612                cx.propagate();
 4613            }
 4614        }
 4615    }
 4616
 4617    pub fn previous_inline_completion(
 4618        &mut self,
 4619        _: &PreviousInlineCompletion,
 4620        cx: &mut ViewContext<Self>,
 4621    ) {
 4622        if self.has_active_inline_completion() {
 4623            self.cycle_inline_completion(Direction::Prev, cx);
 4624        } else {
 4625            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4626            if is_copilot_disabled {
 4627                cx.propagate();
 4628            }
 4629        }
 4630    }
 4631
 4632    pub fn accept_inline_completion(
 4633        &mut self,
 4634        _: &AcceptInlineCompletion,
 4635        cx: &mut ViewContext<Self>,
 4636    ) {
 4637        let buffer = self.buffer.read(cx);
 4638        let snapshot = buffer.snapshot(cx);
 4639        let selection = self.selections.newest_adjusted(cx);
 4640        let cursor = selection.head();
 4641        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4642        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4643        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4644        {
 4645            if cursor.column < suggested_indent.len
 4646                && cursor.column <= current_indent.len
 4647                && current_indent.len <= suggested_indent.len
 4648            {
 4649                self.tab(&Default::default(), cx);
 4650                return;
 4651            }
 4652        }
 4653
 4654        if self.show_inline_completions_in_menu(cx) {
 4655            self.hide_context_menu(cx);
 4656        }
 4657
 4658        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4659            return;
 4660        };
 4661
 4662        self.report_inline_completion_event(true, cx);
 4663
 4664        match &active_inline_completion.completion {
 4665            InlineCompletion::Move(position) => {
 4666                let position = *position;
 4667                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4668                    selections.select_anchor_ranges([position..position]);
 4669                });
 4670            }
 4671            InlineCompletion::Edit(edits) => {
 4672                if let Some(provider) = self.inline_completion_provider() {
 4673                    provider.accept(cx);
 4674                }
 4675
 4676                let snapshot = self.buffer.read(cx).snapshot(cx);
 4677                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4678
 4679                self.buffer.update(cx, |buffer, cx| {
 4680                    buffer.edit(edits.iter().cloned(), None, cx)
 4681                });
 4682
 4683                self.change_selections(None, cx, |s| {
 4684                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4685                });
 4686
 4687                self.update_visible_inline_completion(cx);
 4688                if self.active_inline_completion.is_none() {
 4689                    self.refresh_inline_completion(true, true, cx);
 4690                }
 4691
 4692                cx.notify();
 4693            }
 4694        }
 4695    }
 4696
 4697    pub fn accept_partial_inline_completion(
 4698        &mut self,
 4699        _: &AcceptPartialInlineCompletion,
 4700        cx: &mut ViewContext<Self>,
 4701    ) {
 4702        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4703            return;
 4704        };
 4705        if self.selections.count() != 1 {
 4706            return;
 4707        }
 4708
 4709        self.report_inline_completion_event(true, cx);
 4710
 4711        match &active_inline_completion.completion {
 4712            InlineCompletion::Move(position) => {
 4713                let position = *position;
 4714                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4715                    selections.select_anchor_ranges([position..position]);
 4716                });
 4717            }
 4718            InlineCompletion::Edit(edits) => {
 4719                if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
 4720                    let text = edits[0].1.as_str();
 4721                    let mut partial_completion = text
 4722                        .chars()
 4723                        .by_ref()
 4724                        .take_while(|c| c.is_alphabetic())
 4725                        .collect::<String>();
 4726                    if partial_completion.is_empty() {
 4727                        partial_completion = text
 4728                            .chars()
 4729                            .by_ref()
 4730                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4731                            .collect::<String>();
 4732                    }
 4733
 4734                    cx.emit(EditorEvent::InputHandled {
 4735                        utf16_range_to_replace: None,
 4736                        text: partial_completion.clone().into(),
 4737                    });
 4738
 4739                    self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4740
 4741                    self.refresh_inline_completion(true, true, cx);
 4742                    cx.notify();
 4743                }
 4744            }
 4745        }
 4746    }
 4747
 4748    fn discard_inline_completion(
 4749        &mut self,
 4750        should_report_inline_completion_event: bool,
 4751        cx: &mut ViewContext<Self>,
 4752    ) -> bool {
 4753        if should_report_inline_completion_event {
 4754            self.report_inline_completion_event(false, cx);
 4755        }
 4756
 4757        if let Some(provider) = self.inline_completion_provider() {
 4758            provider.discard(cx);
 4759        }
 4760
 4761        self.take_active_inline_completion(cx).is_some()
 4762    }
 4763
 4764    fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
 4765        let Some(provider) = self.inline_completion_provider() else {
 4766            return;
 4767        };
 4768
 4769        let Some((_, buffer, _)) = self
 4770            .buffer
 4771            .read(cx)
 4772            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4773        else {
 4774            return;
 4775        };
 4776
 4777        let extension = buffer
 4778            .read(cx)
 4779            .file()
 4780            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4781
 4782        let event_type = match accepted {
 4783            true => "Inline Completion Accepted",
 4784            false => "Inline Completion Discarded",
 4785        };
 4786        telemetry::event!(
 4787            event_type,
 4788            provider = provider.name(),
 4789            suggestion_accepted = accepted,
 4790            file_extension = extension,
 4791        );
 4792    }
 4793
 4794    pub fn has_active_inline_completion(&self) -> bool {
 4795        self.active_inline_completion.is_some()
 4796    }
 4797
 4798    fn take_active_inline_completion(
 4799        &mut self,
 4800        cx: &mut ViewContext<Self>,
 4801    ) -> Option<InlineCompletion> {
 4802        let active_inline_completion = self.active_inline_completion.take()?;
 4803        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 4804        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4805        Some(active_inline_completion.completion)
 4806    }
 4807
 4808    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4809        let selection = self.selections.newest_anchor();
 4810        let cursor = selection.head();
 4811        let multibuffer = self.buffer.read(cx).snapshot(cx);
 4812        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 4813        let excerpt_id = cursor.excerpt_id;
 4814
 4815        let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
 4816            && (self.context_menu.borrow().is_some()
 4817                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 4818        if completions_menu_has_precedence
 4819            || !offset_selection.is_empty()
 4820            || !self.enable_inline_completions
 4821            || self
 4822                .active_inline_completion
 4823                .as_ref()
 4824                .map_or(false, |completion| {
 4825                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 4826                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 4827                    !invalidation_range.contains(&offset_selection.head())
 4828                })
 4829        {
 4830            self.discard_inline_completion(false, cx);
 4831            return None;
 4832        }
 4833
 4834        self.take_active_inline_completion(cx);
 4835        let provider = self.inline_completion_provider()?;
 4836
 4837        let (buffer, cursor_buffer_position) =
 4838            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4839
 4840        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 4841        let edits = completion
 4842            .edits
 4843            .into_iter()
 4844            .flat_map(|(range, new_text)| {
 4845                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 4846                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 4847                Some((start..end, new_text))
 4848            })
 4849            .collect::<Vec<_>>();
 4850        if edits.is_empty() {
 4851            return None;
 4852        }
 4853
 4854        let first_edit_start = edits.first().unwrap().0.start;
 4855        let edit_start_row = first_edit_start
 4856            .to_point(&multibuffer)
 4857            .row
 4858            .saturating_sub(2);
 4859
 4860        let last_edit_end = edits.last().unwrap().0.end;
 4861        let edit_end_row = cmp::min(
 4862            multibuffer.max_point().row,
 4863            last_edit_end.to_point(&multibuffer).row + 2,
 4864        );
 4865
 4866        let cursor_row = cursor.to_point(&multibuffer).row;
 4867
 4868        let mut inlay_ids = Vec::new();
 4869        let invalidation_row_range;
 4870        let completion;
 4871        if cursor_row < edit_start_row {
 4872            invalidation_row_range = cursor_row..edit_end_row;
 4873            completion = InlineCompletion::Move(first_edit_start);
 4874        } else if cursor_row > edit_end_row {
 4875            invalidation_row_range = edit_start_row..cursor_row;
 4876            completion = InlineCompletion::Move(first_edit_start);
 4877        } else {
 4878            if edits
 4879                .iter()
 4880                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 4881            {
 4882                let mut inlays = Vec::new();
 4883                for (range, new_text) in &edits {
 4884                    let inlay = Inlay::inline_completion(
 4885                        post_inc(&mut self.next_inlay_id),
 4886                        range.start,
 4887                        new_text.as_str(),
 4888                    );
 4889                    inlay_ids.push(inlay.id);
 4890                    inlays.push(inlay);
 4891                }
 4892
 4893                self.splice_inlays(vec![], inlays, cx);
 4894            } else {
 4895                let background_color = cx.theme().status().deleted_background;
 4896                self.highlight_text::<InlineCompletionHighlight>(
 4897                    edits.iter().map(|(range, _)| range.clone()).collect(),
 4898                    HighlightStyle {
 4899                        background_color: Some(background_color),
 4900                        ..Default::default()
 4901                    },
 4902                    cx,
 4903                );
 4904            }
 4905
 4906            invalidation_row_range = edit_start_row..edit_end_row;
 4907            completion = InlineCompletion::Edit(edits);
 4908        };
 4909
 4910        let invalidation_range = multibuffer
 4911            .anchor_before(Point::new(invalidation_row_range.start, 0))
 4912            ..multibuffer.anchor_after(Point::new(
 4913                invalidation_row_range.end,
 4914                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 4915            ));
 4916
 4917        self.active_inline_completion = Some(InlineCompletionState {
 4918            inlay_ids,
 4919            completion,
 4920            invalidation_range,
 4921        });
 4922
 4923        if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
 4924            if let Some(hint) = self.inline_completion_menu_hint(cx) {
 4925                match self.context_menu.borrow_mut().as_mut() {
 4926                    Some(CodeContextMenu::Completions(menu)) => {
 4927                        menu.show_inline_completion_hint(hint);
 4928                    }
 4929                    _ => {}
 4930                }
 4931            }
 4932        }
 4933
 4934        cx.notify();
 4935
 4936        Some(())
 4937    }
 4938
 4939    fn inline_completion_menu_hint(
 4940        &mut self,
 4941        cx: &mut ViewContext<Self>,
 4942    ) -> Option<InlineCompletionMenuHint> {
 4943        let provider = self.inline_completion_provider()?;
 4944        if self.has_active_inline_completion() {
 4945            let editor_snapshot = self.snapshot(cx);
 4946
 4947            let text = match &self.active_inline_completion.as_ref()?.completion {
 4948                InlineCompletion::Edit(edits) => {
 4949                    inline_completion_edit_text(&editor_snapshot, edits, true, cx)
 4950                }
 4951                InlineCompletion::Move(target) => {
 4952                    let target_point =
 4953                        target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
 4954                    let target_line = target_point.row + 1;
 4955                    InlineCompletionText::Move(
 4956                        format!("Jump to edit in line {}", target_line).into(),
 4957                    )
 4958                }
 4959            };
 4960
 4961            Some(InlineCompletionMenuHint::Loaded { text })
 4962        } else if provider.is_refreshing(cx) {
 4963            Some(InlineCompletionMenuHint::Loading)
 4964        } else {
 4965            Some(InlineCompletionMenuHint::None)
 4966        }
 4967    }
 4968
 4969    pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4970        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4971    }
 4972
 4973    fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
 4974        EditorSettings::get_global(cx).show_inline_completions_in_menu
 4975            && self
 4976                .inline_completion_provider()
 4977                .map_or(false, |provider| provider.show_completions_in_menu())
 4978    }
 4979
 4980    fn render_code_actions_indicator(
 4981        &self,
 4982        _style: &EditorStyle,
 4983        row: DisplayRow,
 4984        is_active: bool,
 4985        cx: &mut ViewContext<Self>,
 4986    ) -> Option<IconButton> {
 4987        if self.available_code_actions.is_some() {
 4988            Some(
 4989                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 4990                    .shape(ui::IconButtonShape::Square)
 4991                    .icon_size(IconSize::XSmall)
 4992                    .icon_color(Color::Muted)
 4993                    .toggle_state(is_active)
 4994                    .tooltip({
 4995                        let focus_handle = self.focus_handle.clone();
 4996                        move |cx| {
 4997                            Tooltip::for_action_in(
 4998                                "Toggle Code Actions",
 4999                                &ToggleCodeActions {
 5000                                    deployed_from_indicator: None,
 5001                                },
 5002                                &focus_handle,
 5003                                cx,
 5004                            )
 5005                        }
 5006                    })
 5007                    .on_click(cx.listener(move |editor, _e, cx| {
 5008                        editor.focus(cx);
 5009                        editor.toggle_code_actions(
 5010                            &ToggleCodeActions {
 5011                                deployed_from_indicator: Some(row),
 5012                            },
 5013                            cx,
 5014                        );
 5015                    })),
 5016            )
 5017        } else {
 5018            None
 5019        }
 5020    }
 5021
 5022    fn clear_tasks(&mut self) {
 5023        self.tasks.clear()
 5024    }
 5025
 5026    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5027        if self.tasks.insert(key, value).is_some() {
 5028            // This case should hopefully be rare, but just in case...
 5029            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5030        }
 5031    }
 5032
 5033    fn build_tasks_context(
 5034        project: &Model<Project>,
 5035        buffer: &Model<Buffer>,
 5036        buffer_row: u32,
 5037        tasks: &Arc<RunnableTasks>,
 5038        cx: &mut ViewContext<Self>,
 5039    ) -> Task<Option<task::TaskContext>> {
 5040        let position = Point::new(buffer_row, tasks.column);
 5041        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5042        let location = Location {
 5043            buffer: buffer.clone(),
 5044            range: range_start..range_start,
 5045        };
 5046        // Fill in the environmental variables from the tree-sitter captures
 5047        let mut captured_task_variables = TaskVariables::default();
 5048        for (capture_name, value) in tasks.extra_variables.clone() {
 5049            captured_task_variables.insert(
 5050                task::VariableName::Custom(capture_name.into()),
 5051                value.clone(),
 5052            );
 5053        }
 5054        project.update(cx, |project, cx| {
 5055            project.task_store().update(cx, |task_store, cx| {
 5056                task_store.task_context_for_location(captured_task_variables, location, cx)
 5057            })
 5058        })
 5059    }
 5060
 5061    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5062        let Some((workspace, _)) = self.workspace.clone() else {
 5063            return;
 5064        };
 5065        let Some(project) = self.project.clone() else {
 5066            return;
 5067        };
 5068
 5069        // Try to find a closest, enclosing node using tree-sitter that has a
 5070        // task
 5071        let Some((buffer, buffer_row, tasks)) = self
 5072            .find_enclosing_node_task(cx)
 5073            // Or find the task that's closest in row-distance.
 5074            .or_else(|| self.find_closest_task(cx))
 5075        else {
 5076            return;
 5077        };
 5078
 5079        let reveal_strategy = action.reveal;
 5080        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5081        cx.spawn(|_, mut cx| async move {
 5082            let context = task_context.await?;
 5083            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5084
 5085            let resolved = resolved_task.resolved.as_mut()?;
 5086            resolved.reveal = reveal_strategy;
 5087
 5088            workspace
 5089                .update(&mut cx, |workspace, cx| {
 5090                    workspace::tasks::schedule_resolved_task(
 5091                        workspace,
 5092                        task_source_kind,
 5093                        resolved_task,
 5094                        false,
 5095                        cx,
 5096                    );
 5097                })
 5098                .ok()
 5099        })
 5100        .detach();
 5101    }
 5102
 5103    fn find_closest_task(
 5104        &mut self,
 5105        cx: &mut ViewContext<Self>,
 5106    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5107        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5108
 5109        let ((buffer_id, row), tasks) = self
 5110            .tasks
 5111            .iter()
 5112            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5113
 5114        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5115        let tasks = Arc::new(tasks.to_owned());
 5116        Some((buffer, *row, tasks))
 5117    }
 5118
 5119    fn find_enclosing_node_task(
 5120        &mut self,
 5121        cx: &mut ViewContext<Self>,
 5122    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5123        let snapshot = self.buffer.read(cx).snapshot(cx);
 5124        let offset = self.selections.newest::<usize>(cx).head();
 5125        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5126        let buffer_id = excerpt.buffer().remote_id();
 5127
 5128        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5129        let mut cursor = layer.node().walk();
 5130
 5131        while cursor.goto_first_child_for_byte(offset).is_some() {
 5132            if cursor.node().end_byte() == offset {
 5133                cursor.goto_next_sibling();
 5134            }
 5135        }
 5136
 5137        // Ascend to the smallest ancestor that contains the range and has a task.
 5138        loop {
 5139            let node = cursor.node();
 5140            let node_range = node.byte_range();
 5141            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5142
 5143            // Check if this node contains our offset
 5144            if node_range.start <= offset && node_range.end >= offset {
 5145                // If it contains offset, check for task
 5146                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5147                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5148                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5149                }
 5150            }
 5151
 5152            if !cursor.goto_parent() {
 5153                break;
 5154            }
 5155        }
 5156        None
 5157    }
 5158
 5159    fn render_run_indicator(
 5160        &self,
 5161        _style: &EditorStyle,
 5162        is_active: bool,
 5163        row: DisplayRow,
 5164        cx: &mut ViewContext<Self>,
 5165    ) -> IconButton {
 5166        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5167            .shape(ui::IconButtonShape::Square)
 5168            .icon_size(IconSize::XSmall)
 5169            .icon_color(Color::Muted)
 5170            .toggle_state(is_active)
 5171            .on_click(cx.listener(move |editor, _e, cx| {
 5172                editor.focus(cx);
 5173                editor.toggle_code_actions(
 5174                    &ToggleCodeActions {
 5175                        deployed_from_indicator: Some(row),
 5176                    },
 5177                    cx,
 5178                );
 5179            }))
 5180    }
 5181
 5182    #[cfg(any(feature = "test-support", test))]
 5183    pub fn context_menu_visible(&self) -> bool {
 5184        self.context_menu
 5185            .borrow()
 5186            .as_ref()
 5187            .map_or(false, |menu| menu.visible())
 5188    }
 5189
 5190    #[cfg(feature = "test-support")]
 5191    pub fn context_menu_contains_inline_completion(&self) -> bool {
 5192        self.context_menu
 5193            .borrow()
 5194            .as_ref()
 5195            .map_or(false, |menu| match menu {
 5196                CodeContextMenu::Completions(menu) => {
 5197                    menu.entries.borrow().first().map_or(false, |entry| {
 5198                        matches!(entry, CompletionEntry::InlineCompletionHint(_))
 5199                    })
 5200                }
 5201                CodeContextMenu::CodeActions(_) => false,
 5202            })
 5203    }
 5204
 5205    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5206        self.context_menu
 5207            .borrow()
 5208            .as_ref()
 5209            .map(|menu| menu.origin(cursor_position))
 5210    }
 5211
 5212    fn render_context_menu(
 5213        &self,
 5214        style: &EditorStyle,
 5215        max_height_in_lines: u32,
 5216        cx: &mut ViewContext<Editor>,
 5217    ) -> Option<AnyElement> {
 5218        self.context_menu.borrow().as_ref().and_then(|menu| {
 5219            if menu.visible() {
 5220                Some(menu.render(style, max_height_in_lines, cx))
 5221            } else {
 5222                None
 5223            }
 5224        })
 5225    }
 5226
 5227    fn render_context_menu_aside(
 5228        &self,
 5229        style: &EditorStyle,
 5230        max_size: Size<Pixels>,
 5231        cx: &mut ViewContext<Editor>,
 5232    ) -> Option<AnyElement> {
 5233        self.context_menu.borrow().as_ref().and_then(|menu| {
 5234            if menu.visible() {
 5235                menu.render_aside(
 5236                    style,
 5237                    max_size,
 5238                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5239                    cx,
 5240                )
 5241            } else {
 5242                None
 5243            }
 5244        })
 5245    }
 5246
 5247    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
 5248        cx.notify();
 5249        self.completion_tasks.clear();
 5250        let context_menu = self.context_menu.borrow_mut().take();
 5251        if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
 5252            self.update_visible_inline_completion(cx);
 5253        }
 5254        context_menu
 5255    }
 5256
 5257    fn show_snippet_choices(
 5258        &mut self,
 5259        choices: &Vec<String>,
 5260        selection: Range<Anchor>,
 5261        cx: &mut ViewContext<Self>,
 5262    ) {
 5263        if selection.start.buffer_id.is_none() {
 5264            return;
 5265        }
 5266        let buffer_id = selection.start.buffer_id.unwrap();
 5267        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5268        let id = post_inc(&mut self.next_completion_id);
 5269
 5270        if let Some(buffer) = buffer {
 5271            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5272                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5273            ));
 5274        }
 5275    }
 5276
 5277    pub fn insert_snippet(
 5278        &mut self,
 5279        insertion_ranges: &[Range<usize>],
 5280        snippet: Snippet,
 5281        cx: &mut ViewContext<Self>,
 5282    ) -> Result<()> {
 5283        struct Tabstop<T> {
 5284            is_end_tabstop: bool,
 5285            ranges: Vec<Range<T>>,
 5286            choices: Option<Vec<String>>,
 5287        }
 5288
 5289        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5290            let snippet_text: Arc<str> = snippet.text.clone().into();
 5291            buffer.edit(
 5292                insertion_ranges
 5293                    .iter()
 5294                    .cloned()
 5295                    .map(|range| (range, snippet_text.clone())),
 5296                Some(AutoindentMode::EachLine),
 5297                cx,
 5298            );
 5299
 5300            let snapshot = &*buffer.read(cx);
 5301            let snippet = &snippet;
 5302            snippet
 5303                .tabstops
 5304                .iter()
 5305                .map(|tabstop| {
 5306                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5307                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5308                    });
 5309                    let mut tabstop_ranges = tabstop
 5310                        .ranges
 5311                        .iter()
 5312                        .flat_map(|tabstop_range| {
 5313                            let mut delta = 0_isize;
 5314                            insertion_ranges.iter().map(move |insertion_range| {
 5315                                let insertion_start = insertion_range.start as isize + delta;
 5316                                delta +=
 5317                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5318
 5319                                let start = ((insertion_start + tabstop_range.start) as usize)
 5320                                    .min(snapshot.len());
 5321                                let end = ((insertion_start + tabstop_range.end) as usize)
 5322                                    .min(snapshot.len());
 5323                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5324                            })
 5325                        })
 5326                        .collect::<Vec<_>>();
 5327                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5328
 5329                    Tabstop {
 5330                        is_end_tabstop,
 5331                        ranges: tabstop_ranges,
 5332                        choices: tabstop.choices.clone(),
 5333                    }
 5334                })
 5335                .collect::<Vec<_>>()
 5336        });
 5337        if let Some(tabstop) = tabstops.first() {
 5338            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5339                s.select_ranges(tabstop.ranges.iter().cloned());
 5340            });
 5341
 5342            if let Some(choices) = &tabstop.choices {
 5343                if let Some(selection) = tabstop.ranges.first() {
 5344                    self.show_snippet_choices(choices, selection.clone(), cx)
 5345                }
 5346            }
 5347
 5348            // If we're already at the last tabstop and it's at the end of the snippet,
 5349            // we're done, we don't need to keep the state around.
 5350            if !tabstop.is_end_tabstop {
 5351                let choices = tabstops
 5352                    .iter()
 5353                    .map(|tabstop| tabstop.choices.clone())
 5354                    .collect();
 5355
 5356                let ranges = tabstops
 5357                    .into_iter()
 5358                    .map(|tabstop| tabstop.ranges)
 5359                    .collect::<Vec<_>>();
 5360
 5361                self.snippet_stack.push(SnippetState {
 5362                    active_index: 0,
 5363                    ranges,
 5364                    choices,
 5365                });
 5366            }
 5367
 5368            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5369            if self.autoclose_regions.is_empty() {
 5370                let snapshot = self.buffer.read(cx).snapshot(cx);
 5371                for selection in &mut self.selections.all::<Point>(cx) {
 5372                    let selection_head = selection.head();
 5373                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5374                        continue;
 5375                    };
 5376
 5377                    let mut bracket_pair = None;
 5378                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5379                    let prev_chars = snapshot
 5380                        .reversed_chars_at(selection_head)
 5381                        .collect::<String>();
 5382                    for (pair, enabled) in scope.brackets() {
 5383                        if enabled
 5384                            && pair.close
 5385                            && prev_chars.starts_with(pair.start.as_str())
 5386                            && next_chars.starts_with(pair.end.as_str())
 5387                        {
 5388                            bracket_pair = Some(pair.clone());
 5389                            break;
 5390                        }
 5391                    }
 5392                    if let Some(pair) = bracket_pair {
 5393                        let start = snapshot.anchor_after(selection_head);
 5394                        let end = snapshot.anchor_after(selection_head);
 5395                        self.autoclose_regions.push(AutocloseRegion {
 5396                            selection_id: selection.id,
 5397                            range: start..end,
 5398                            pair,
 5399                        });
 5400                    }
 5401                }
 5402            }
 5403        }
 5404        Ok(())
 5405    }
 5406
 5407    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5408        self.move_to_snippet_tabstop(Bias::Right, cx)
 5409    }
 5410
 5411    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5412        self.move_to_snippet_tabstop(Bias::Left, cx)
 5413    }
 5414
 5415    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5416        if let Some(mut snippet) = self.snippet_stack.pop() {
 5417            match bias {
 5418                Bias::Left => {
 5419                    if snippet.active_index > 0 {
 5420                        snippet.active_index -= 1;
 5421                    } else {
 5422                        self.snippet_stack.push(snippet);
 5423                        return false;
 5424                    }
 5425                }
 5426                Bias::Right => {
 5427                    if snippet.active_index + 1 < snippet.ranges.len() {
 5428                        snippet.active_index += 1;
 5429                    } else {
 5430                        self.snippet_stack.push(snippet);
 5431                        return false;
 5432                    }
 5433                }
 5434            }
 5435            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5436                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5437                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5438                });
 5439
 5440                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5441                    if let Some(selection) = current_ranges.first() {
 5442                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5443                    }
 5444                }
 5445
 5446                // If snippet state is not at the last tabstop, push it back on the stack
 5447                if snippet.active_index + 1 < snippet.ranges.len() {
 5448                    self.snippet_stack.push(snippet);
 5449                }
 5450                return true;
 5451            }
 5452        }
 5453
 5454        false
 5455    }
 5456
 5457    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5458        self.transact(cx, |this, cx| {
 5459            this.select_all(&SelectAll, cx);
 5460            this.insert("", cx);
 5461        });
 5462    }
 5463
 5464    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5465        self.transact(cx, |this, cx| {
 5466            this.select_autoclose_pair(cx);
 5467            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5468            if !this.linked_edit_ranges.is_empty() {
 5469                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5470                let snapshot = this.buffer.read(cx).snapshot(cx);
 5471
 5472                for selection in selections.iter() {
 5473                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5474                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5475                    if selection_start.buffer_id != selection_end.buffer_id {
 5476                        continue;
 5477                    }
 5478                    if let Some(ranges) =
 5479                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5480                    {
 5481                        for (buffer, entries) in ranges {
 5482                            linked_ranges.entry(buffer).or_default().extend(entries);
 5483                        }
 5484                    }
 5485                }
 5486            }
 5487
 5488            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5489            if !this.selections.line_mode {
 5490                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5491                for selection in &mut selections {
 5492                    if selection.is_empty() {
 5493                        let old_head = selection.head();
 5494                        let mut new_head =
 5495                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5496                                .to_point(&display_map);
 5497                        if let Some((buffer, line_buffer_range)) = display_map
 5498                            .buffer_snapshot
 5499                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5500                        {
 5501                            let indent_size =
 5502                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5503                            let indent_len = match indent_size.kind {
 5504                                IndentKind::Space => {
 5505                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5506                                }
 5507                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5508                            };
 5509                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5510                                let indent_len = indent_len.get();
 5511                                new_head = cmp::min(
 5512                                    new_head,
 5513                                    MultiBufferPoint::new(
 5514                                        old_head.row,
 5515                                        ((old_head.column - 1) / indent_len) * indent_len,
 5516                                    ),
 5517                                );
 5518                            }
 5519                        }
 5520
 5521                        selection.set_head(new_head, SelectionGoal::None);
 5522                    }
 5523                }
 5524            }
 5525
 5526            this.signature_help_state.set_backspace_pressed(true);
 5527            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5528            this.insert("", cx);
 5529            let empty_str: Arc<str> = Arc::from("");
 5530            for (buffer, edits) in linked_ranges {
 5531                let snapshot = buffer.read(cx).snapshot();
 5532                use text::ToPoint as TP;
 5533
 5534                let edits = edits
 5535                    .into_iter()
 5536                    .map(|range| {
 5537                        let end_point = TP::to_point(&range.end, &snapshot);
 5538                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5539
 5540                        if end_point == start_point {
 5541                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5542                                .saturating_sub(1);
 5543                            start_point =
 5544                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5545                        };
 5546
 5547                        (start_point..end_point, empty_str.clone())
 5548                    })
 5549                    .sorted_by_key(|(range, _)| range.start)
 5550                    .collect::<Vec<_>>();
 5551                buffer.update(cx, |this, cx| {
 5552                    this.edit(edits, None, cx);
 5553                })
 5554            }
 5555            this.refresh_inline_completion(true, false, cx);
 5556            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5557        });
 5558    }
 5559
 5560    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5561        self.transact(cx, |this, cx| {
 5562            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5563                let line_mode = s.line_mode;
 5564                s.move_with(|map, selection| {
 5565                    if selection.is_empty() && !line_mode {
 5566                        let cursor = movement::right(map, selection.head());
 5567                        selection.end = cursor;
 5568                        selection.reversed = true;
 5569                        selection.goal = SelectionGoal::None;
 5570                    }
 5571                })
 5572            });
 5573            this.insert("", cx);
 5574            this.refresh_inline_completion(true, false, cx);
 5575        });
 5576    }
 5577
 5578    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5579        if self.move_to_prev_snippet_tabstop(cx) {
 5580            return;
 5581        }
 5582
 5583        self.outdent(&Outdent, cx);
 5584    }
 5585
 5586    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5587        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5588            return;
 5589        }
 5590
 5591        let mut selections = self.selections.all_adjusted(cx);
 5592        let buffer = self.buffer.read(cx);
 5593        let snapshot = buffer.snapshot(cx);
 5594        let rows_iter = selections.iter().map(|s| s.head().row);
 5595        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5596
 5597        let mut edits = Vec::new();
 5598        let mut prev_edited_row = 0;
 5599        let mut row_delta = 0;
 5600        for selection in &mut selections {
 5601            if selection.start.row != prev_edited_row {
 5602                row_delta = 0;
 5603            }
 5604            prev_edited_row = selection.end.row;
 5605
 5606            // If the selection is non-empty, then increase the indentation of the selected lines.
 5607            if !selection.is_empty() {
 5608                row_delta =
 5609                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5610                continue;
 5611            }
 5612
 5613            // If the selection is empty and the cursor is in the leading whitespace before the
 5614            // suggested indentation, then auto-indent the line.
 5615            let cursor = selection.head();
 5616            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5617            if let Some(suggested_indent) =
 5618                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5619            {
 5620                if cursor.column < suggested_indent.len
 5621                    && cursor.column <= current_indent.len
 5622                    && current_indent.len <= suggested_indent.len
 5623                {
 5624                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5625                    selection.end = selection.start;
 5626                    if row_delta == 0 {
 5627                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5628                            cursor.row,
 5629                            current_indent,
 5630                            suggested_indent,
 5631                        ));
 5632                        row_delta = suggested_indent.len - current_indent.len;
 5633                    }
 5634                    continue;
 5635                }
 5636            }
 5637
 5638            // Otherwise, insert a hard or soft tab.
 5639            let settings = buffer.settings_at(cursor, cx);
 5640            let tab_size = if settings.hard_tabs {
 5641                IndentSize::tab()
 5642            } else {
 5643                let tab_size = settings.tab_size.get();
 5644                let char_column = snapshot
 5645                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5646                    .flat_map(str::chars)
 5647                    .count()
 5648                    + row_delta as usize;
 5649                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5650                IndentSize::spaces(chars_to_next_tab_stop)
 5651            };
 5652            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5653            selection.end = selection.start;
 5654            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5655            row_delta += tab_size.len;
 5656        }
 5657
 5658        self.transact(cx, |this, cx| {
 5659            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5660            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5661            this.refresh_inline_completion(true, false, cx);
 5662        });
 5663    }
 5664
 5665    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5666        if self.read_only(cx) {
 5667            return;
 5668        }
 5669        let mut selections = self.selections.all::<Point>(cx);
 5670        let mut prev_edited_row = 0;
 5671        let mut row_delta = 0;
 5672        let mut edits = Vec::new();
 5673        let buffer = self.buffer.read(cx);
 5674        let snapshot = buffer.snapshot(cx);
 5675        for selection in &mut selections {
 5676            if selection.start.row != prev_edited_row {
 5677                row_delta = 0;
 5678            }
 5679            prev_edited_row = selection.end.row;
 5680
 5681            row_delta =
 5682                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5683        }
 5684
 5685        self.transact(cx, |this, cx| {
 5686            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5687            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5688        });
 5689    }
 5690
 5691    fn indent_selection(
 5692        buffer: &MultiBuffer,
 5693        snapshot: &MultiBufferSnapshot,
 5694        selection: &mut Selection<Point>,
 5695        edits: &mut Vec<(Range<Point>, String)>,
 5696        delta_for_start_row: u32,
 5697        cx: &AppContext,
 5698    ) -> u32 {
 5699        let settings = buffer.settings_at(selection.start, cx);
 5700        let tab_size = settings.tab_size.get();
 5701        let indent_kind = if settings.hard_tabs {
 5702            IndentKind::Tab
 5703        } else {
 5704            IndentKind::Space
 5705        };
 5706        let mut start_row = selection.start.row;
 5707        let mut end_row = selection.end.row + 1;
 5708
 5709        // If a selection ends at the beginning of a line, don't indent
 5710        // that last line.
 5711        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5712            end_row -= 1;
 5713        }
 5714
 5715        // Avoid re-indenting a row that has already been indented by a
 5716        // previous selection, but still update this selection's column
 5717        // to reflect that indentation.
 5718        if delta_for_start_row > 0 {
 5719            start_row += 1;
 5720            selection.start.column += delta_for_start_row;
 5721            if selection.end.row == selection.start.row {
 5722                selection.end.column += delta_for_start_row;
 5723            }
 5724        }
 5725
 5726        let mut delta_for_end_row = 0;
 5727        let has_multiple_rows = start_row + 1 != end_row;
 5728        for row in start_row..end_row {
 5729            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5730            let indent_delta = match (current_indent.kind, indent_kind) {
 5731                (IndentKind::Space, IndentKind::Space) => {
 5732                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5733                    IndentSize::spaces(columns_to_next_tab_stop)
 5734                }
 5735                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5736                (_, IndentKind::Tab) => IndentSize::tab(),
 5737            };
 5738
 5739            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5740                0
 5741            } else {
 5742                selection.start.column
 5743            };
 5744            let row_start = Point::new(row, start);
 5745            edits.push((
 5746                row_start..row_start,
 5747                indent_delta.chars().collect::<String>(),
 5748            ));
 5749
 5750            // Update this selection's endpoints to reflect the indentation.
 5751            if row == selection.start.row {
 5752                selection.start.column += indent_delta.len;
 5753            }
 5754            if row == selection.end.row {
 5755                selection.end.column += indent_delta.len;
 5756                delta_for_end_row = indent_delta.len;
 5757            }
 5758        }
 5759
 5760        if selection.start.row == selection.end.row {
 5761            delta_for_start_row + delta_for_end_row
 5762        } else {
 5763            delta_for_end_row
 5764        }
 5765    }
 5766
 5767    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5768        if self.read_only(cx) {
 5769            return;
 5770        }
 5771        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5772        let selections = self.selections.all::<Point>(cx);
 5773        let mut deletion_ranges = Vec::new();
 5774        let mut last_outdent = None;
 5775        {
 5776            let buffer = self.buffer.read(cx);
 5777            let snapshot = buffer.snapshot(cx);
 5778            for selection in &selections {
 5779                let settings = buffer.settings_at(selection.start, cx);
 5780                let tab_size = settings.tab_size.get();
 5781                let mut rows = selection.spanned_rows(false, &display_map);
 5782
 5783                // Avoid re-outdenting a row that has already been outdented by a
 5784                // previous selection.
 5785                if let Some(last_row) = last_outdent {
 5786                    if last_row == rows.start {
 5787                        rows.start = rows.start.next_row();
 5788                    }
 5789                }
 5790                let has_multiple_rows = rows.len() > 1;
 5791                for row in rows.iter_rows() {
 5792                    let indent_size = snapshot.indent_size_for_line(row);
 5793                    if indent_size.len > 0 {
 5794                        let deletion_len = match indent_size.kind {
 5795                            IndentKind::Space => {
 5796                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5797                                if columns_to_prev_tab_stop == 0 {
 5798                                    tab_size
 5799                                } else {
 5800                                    columns_to_prev_tab_stop
 5801                                }
 5802                            }
 5803                            IndentKind::Tab => 1,
 5804                        };
 5805                        let start = if has_multiple_rows
 5806                            || deletion_len > selection.start.column
 5807                            || indent_size.len < selection.start.column
 5808                        {
 5809                            0
 5810                        } else {
 5811                            selection.start.column - deletion_len
 5812                        };
 5813                        deletion_ranges.push(
 5814                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5815                        );
 5816                        last_outdent = Some(row);
 5817                    }
 5818                }
 5819            }
 5820        }
 5821
 5822        self.transact(cx, |this, cx| {
 5823            this.buffer.update(cx, |buffer, cx| {
 5824                let empty_str: Arc<str> = Arc::default();
 5825                buffer.edit(
 5826                    deletion_ranges
 5827                        .into_iter()
 5828                        .map(|range| (range, empty_str.clone())),
 5829                    None,
 5830                    cx,
 5831                );
 5832            });
 5833            let selections = this.selections.all::<usize>(cx);
 5834            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5835        });
 5836    }
 5837
 5838    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 5839        if self.read_only(cx) {
 5840            return;
 5841        }
 5842        let selections = self
 5843            .selections
 5844            .all::<usize>(cx)
 5845            .into_iter()
 5846            .map(|s| s.range());
 5847
 5848        self.transact(cx, |this, cx| {
 5849            this.buffer.update(cx, |buffer, cx| {
 5850                buffer.autoindent_ranges(selections, cx);
 5851            });
 5852            let selections = this.selections.all::<usize>(cx);
 5853            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5854        });
 5855    }
 5856
 5857    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5858        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5859        let selections = self.selections.all::<Point>(cx);
 5860
 5861        let mut new_cursors = Vec::new();
 5862        let mut edit_ranges = Vec::new();
 5863        let mut selections = selections.iter().peekable();
 5864        while let Some(selection) = selections.next() {
 5865            let mut rows = selection.spanned_rows(false, &display_map);
 5866            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5867
 5868            // Accumulate contiguous regions of rows that we want to delete.
 5869            while let Some(next_selection) = selections.peek() {
 5870                let next_rows = next_selection.spanned_rows(false, &display_map);
 5871                if next_rows.start <= rows.end {
 5872                    rows.end = next_rows.end;
 5873                    selections.next().unwrap();
 5874                } else {
 5875                    break;
 5876                }
 5877            }
 5878
 5879            let buffer = &display_map.buffer_snapshot;
 5880            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5881            let edit_end;
 5882            let cursor_buffer_row;
 5883            if buffer.max_point().row >= rows.end.0 {
 5884                // If there's a line after the range, delete the \n from the end of the row range
 5885                // and position the cursor on the next line.
 5886                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5887                cursor_buffer_row = rows.end;
 5888            } else {
 5889                // If there isn't a line after the range, delete the \n from the line before the
 5890                // start of the row range and position the cursor there.
 5891                edit_start = edit_start.saturating_sub(1);
 5892                edit_end = buffer.len();
 5893                cursor_buffer_row = rows.start.previous_row();
 5894            }
 5895
 5896            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5897            *cursor.column_mut() =
 5898                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5899
 5900            new_cursors.push((
 5901                selection.id,
 5902                buffer.anchor_after(cursor.to_point(&display_map)),
 5903            ));
 5904            edit_ranges.push(edit_start..edit_end);
 5905        }
 5906
 5907        self.transact(cx, |this, cx| {
 5908            let buffer = this.buffer.update(cx, |buffer, cx| {
 5909                let empty_str: Arc<str> = Arc::default();
 5910                buffer.edit(
 5911                    edit_ranges
 5912                        .into_iter()
 5913                        .map(|range| (range, empty_str.clone())),
 5914                    None,
 5915                    cx,
 5916                );
 5917                buffer.snapshot(cx)
 5918            });
 5919            let new_selections = new_cursors
 5920                .into_iter()
 5921                .map(|(id, cursor)| {
 5922                    let cursor = cursor.to_point(&buffer);
 5923                    Selection {
 5924                        id,
 5925                        start: cursor,
 5926                        end: cursor,
 5927                        reversed: false,
 5928                        goal: SelectionGoal::None,
 5929                    }
 5930                })
 5931                .collect();
 5932
 5933            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5934                s.select(new_selections);
 5935            });
 5936        });
 5937    }
 5938
 5939    pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
 5940        if self.read_only(cx) {
 5941            return;
 5942        }
 5943        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5944        for selection in self.selections.all::<Point>(cx) {
 5945            let start = MultiBufferRow(selection.start.row);
 5946            // Treat single line selections as if they include the next line. Otherwise this action
 5947            // would do nothing for single line selections individual cursors.
 5948            let end = if selection.start.row == selection.end.row {
 5949                MultiBufferRow(selection.start.row + 1)
 5950            } else {
 5951                MultiBufferRow(selection.end.row)
 5952            };
 5953
 5954            if let Some(last_row_range) = row_ranges.last_mut() {
 5955                if start <= last_row_range.end {
 5956                    last_row_range.end = end;
 5957                    continue;
 5958                }
 5959            }
 5960            row_ranges.push(start..end);
 5961        }
 5962
 5963        let snapshot = self.buffer.read(cx).snapshot(cx);
 5964        let mut cursor_positions = Vec::new();
 5965        for row_range in &row_ranges {
 5966            let anchor = snapshot.anchor_before(Point::new(
 5967                row_range.end.previous_row().0,
 5968                snapshot.line_len(row_range.end.previous_row()),
 5969            ));
 5970            cursor_positions.push(anchor..anchor);
 5971        }
 5972
 5973        self.transact(cx, |this, cx| {
 5974            for row_range in row_ranges.into_iter().rev() {
 5975                for row in row_range.iter_rows().rev() {
 5976                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5977                    let next_line_row = row.next_row();
 5978                    let indent = snapshot.indent_size_for_line(next_line_row);
 5979                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5980
 5981                    let replace =
 5982                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 5983                            " "
 5984                        } else {
 5985                            ""
 5986                        };
 5987
 5988                    this.buffer.update(cx, |buffer, cx| {
 5989                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5990                    });
 5991                }
 5992            }
 5993
 5994            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5995                s.select_anchor_ranges(cursor_positions)
 5996            });
 5997        });
 5998    }
 5999
 6000    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6001        self.join_lines_impl(true, cx);
 6002    }
 6003
 6004    pub fn sort_lines_case_sensitive(
 6005        &mut self,
 6006        _: &SortLinesCaseSensitive,
 6007        cx: &mut ViewContext<Self>,
 6008    ) {
 6009        self.manipulate_lines(cx, |lines| lines.sort())
 6010    }
 6011
 6012    pub fn sort_lines_case_insensitive(
 6013        &mut self,
 6014        _: &SortLinesCaseInsensitive,
 6015        cx: &mut ViewContext<Self>,
 6016    ) {
 6017        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6018    }
 6019
 6020    pub fn unique_lines_case_insensitive(
 6021        &mut self,
 6022        _: &UniqueLinesCaseInsensitive,
 6023        cx: &mut ViewContext<Self>,
 6024    ) {
 6025        self.manipulate_lines(cx, |lines| {
 6026            let mut seen = HashSet::default();
 6027            lines.retain(|line| seen.insert(line.to_lowercase()));
 6028        })
 6029    }
 6030
 6031    pub fn unique_lines_case_sensitive(
 6032        &mut self,
 6033        _: &UniqueLinesCaseSensitive,
 6034        cx: &mut ViewContext<Self>,
 6035    ) {
 6036        self.manipulate_lines(cx, |lines| {
 6037            let mut seen = HashSet::default();
 6038            lines.retain(|line| seen.insert(*line));
 6039        })
 6040    }
 6041
 6042    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6043        let mut revert_changes = HashMap::default();
 6044        let snapshot = self.snapshot(cx);
 6045        for hunk in hunks_for_ranges(
 6046            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 6047            &snapshot,
 6048        ) {
 6049            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6050        }
 6051        if !revert_changes.is_empty() {
 6052            self.transact(cx, |editor, cx| {
 6053                editor.revert(revert_changes, cx);
 6054            });
 6055        }
 6056    }
 6057
 6058    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6059        let Some(project) = self.project.clone() else {
 6060            return;
 6061        };
 6062        self.reload(project, cx).detach_and_notify_err(cx);
 6063    }
 6064
 6065    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6066        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 6067        if !revert_changes.is_empty() {
 6068            self.transact(cx, |editor, cx| {
 6069                editor.revert(revert_changes, cx);
 6070            });
 6071        }
 6072    }
 6073
 6074    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 6075        let snapshot = self.buffer.read(cx).read(cx);
 6076        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 6077            drop(snapshot);
 6078            let mut revert_changes = HashMap::default();
 6079            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6080            if !revert_changes.is_empty() {
 6081                self.revert(revert_changes, cx)
 6082            }
 6083        }
 6084    }
 6085
 6086    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6087        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6088            let project_path = buffer.read(cx).project_path(cx)?;
 6089            let project = self.project.as_ref()?.read(cx);
 6090            let entry = project.entry_for_path(&project_path, cx)?;
 6091            let parent = match &entry.canonical_path {
 6092                Some(canonical_path) => canonical_path.to_path_buf(),
 6093                None => project.absolute_path(&project_path, cx)?,
 6094            }
 6095            .parent()?
 6096            .to_path_buf();
 6097            Some(parent)
 6098        }) {
 6099            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6100        }
 6101    }
 6102
 6103    fn gather_revert_changes(
 6104        &mut self,
 6105        selections: &[Selection<Point>],
 6106        cx: &mut ViewContext<Editor>,
 6107    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6108        let mut revert_changes = HashMap::default();
 6109        let snapshot = self.snapshot(cx);
 6110        for hunk in hunks_for_selections(&snapshot, selections) {
 6111            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6112        }
 6113        revert_changes
 6114    }
 6115
 6116    pub fn prepare_revert_change(
 6117        &mut self,
 6118        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6119        hunk: &MultiBufferDiffHunk,
 6120        cx: &AppContext,
 6121    ) -> Option<()> {
 6122        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 6123        let buffer = buffer.read(cx);
 6124        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 6125        let original_text = change_set
 6126            .read(cx)
 6127            .base_text
 6128            .as_ref()?
 6129            .read(cx)
 6130            .as_rope()
 6131            .slice(hunk.diff_base_byte_range.clone());
 6132        let buffer_snapshot = buffer.snapshot();
 6133        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6134        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6135            probe
 6136                .0
 6137                .start
 6138                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6139                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6140        }) {
 6141            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6142            Some(())
 6143        } else {
 6144            None
 6145        }
 6146    }
 6147
 6148    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6149        self.manipulate_lines(cx, |lines| lines.reverse())
 6150    }
 6151
 6152    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6153        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6154    }
 6155
 6156    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6157    where
 6158        Fn: FnMut(&mut Vec<&str>),
 6159    {
 6160        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6161        let buffer = self.buffer.read(cx).snapshot(cx);
 6162
 6163        let mut edits = Vec::new();
 6164
 6165        let selections = self.selections.all::<Point>(cx);
 6166        let mut selections = selections.iter().peekable();
 6167        let mut contiguous_row_selections = Vec::new();
 6168        let mut new_selections = Vec::new();
 6169        let mut added_lines = 0;
 6170        let mut removed_lines = 0;
 6171
 6172        while let Some(selection) = selections.next() {
 6173            let (start_row, end_row) = consume_contiguous_rows(
 6174                &mut contiguous_row_selections,
 6175                selection,
 6176                &display_map,
 6177                &mut selections,
 6178            );
 6179
 6180            let start_point = Point::new(start_row.0, 0);
 6181            let end_point = Point::new(
 6182                end_row.previous_row().0,
 6183                buffer.line_len(end_row.previous_row()),
 6184            );
 6185            let text = buffer
 6186                .text_for_range(start_point..end_point)
 6187                .collect::<String>();
 6188
 6189            let mut lines = text.split('\n').collect_vec();
 6190
 6191            let lines_before = lines.len();
 6192            callback(&mut lines);
 6193            let lines_after = lines.len();
 6194
 6195            edits.push((start_point..end_point, lines.join("\n")));
 6196
 6197            // Selections must change based on added and removed line count
 6198            let start_row =
 6199                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6200            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6201            new_selections.push(Selection {
 6202                id: selection.id,
 6203                start: start_row,
 6204                end: end_row,
 6205                goal: SelectionGoal::None,
 6206                reversed: selection.reversed,
 6207            });
 6208
 6209            if lines_after > lines_before {
 6210                added_lines += lines_after - lines_before;
 6211            } else if lines_before > lines_after {
 6212                removed_lines += lines_before - lines_after;
 6213            }
 6214        }
 6215
 6216        self.transact(cx, |this, cx| {
 6217            let buffer = this.buffer.update(cx, |buffer, cx| {
 6218                buffer.edit(edits, None, cx);
 6219                buffer.snapshot(cx)
 6220            });
 6221
 6222            // Recalculate offsets on newly edited buffer
 6223            let new_selections = new_selections
 6224                .iter()
 6225                .map(|s| {
 6226                    let start_point = Point::new(s.start.0, 0);
 6227                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6228                    Selection {
 6229                        id: s.id,
 6230                        start: buffer.point_to_offset(start_point),
 6231                        end: buffer.point_to_offset(end_point),
 6232                        goal: s.goal,
 6233                        reversed: s.reversed,
 6234                    }
 6235                })
 6236                .collect();
 6237
 6238            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6239                s.select(new_selections);
 6240            });
 6241
 6242            this.request_autoscroll(Autoscroll::fit(), cx);
 6243        });
 6244    }
 6245
 6246    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6247        self.manipulate_text(cx, |text| text.to_uppercase())
 6248    }
 6249
 6250    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6251        self.manipulate_text(cx, |text| text.to_lowercase())
 6252    }
 6253
 6254    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6255        self.manipulate_text(cx, |text| {
 6256            text.split('\n')
 6257                .map(|line| line.to_case(Case::Title))
 6258                .join("\n")
 6259        })
 6260    }
 6261
 6262    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6263        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6264    }
 6265
 6266    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6267        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6268    }
 6269
 6270    pub fn convert_to_upper_camel_case(
 6271        &mut self,
 6272        _: &ConvertToUpperCamelCase,
 6273        cx: &mut ViewContext<Self>,
 6274    ) {
 6275        self.manipulate_text(cx, |text| {
 6276            text.split('\n')
 6277                .map(|line| line.to_case(Case::UpperCamel))
 6278                .join("\n")
 6279        })
 6280    }
 6281
 6282    pub fn convert_to_lower_camel_case(
 6283        &mut self,
 6284        _: &ConvertToLowerCamelCase,
 6285        cx: &mut ViewContext<Self>,
 6286    ) {
 6287        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6288    }
 6289
 6290    pub fn convert_to_opposite_case(
 6291        &mut self,
 6292        _: &ConvertToOppositeCase,
 6293        cx: &mut ViewContext<Self>,
 6294    ) {
 6295        self.manipulate_text(cx, |text| {
 6296            text.chars()
 6297                .fold(String::with_capacity(text.len()), |mut t, c| {
 6298                    if c.is_uppercase() {
 6299                        t.extend(c.to_lowercase());
 6300                    } else {
 6301                        t.extend(c.to_uppercase());
 6302                    }
 6303                    t
 6304                })
 6305        })
 6306    }
 6307
 6308    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6309    where
 6310        Fn: FnMut(&str) -> String,
 6311    {
 6312        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6313        let buffer = self.buffer.read(cx).snapshot(cx);
 6314
 6315        let mut new_selections = Vec::new();
 6316        let mut edits = Vec::new();
 6317        let mut selection_adjustment = 0i32;
 6318
 6319        for selection in self.selections.all::<usize>(cx) {
 6320            let selection_is_empty = selection.is_empty();
 6321
 6322            let (start, end) = if selection_is_empty {
 6323                let word_range = movement::surrounding_word(
 6324                    &display_map,
 6325                    selection.start.to_display_point(&display_map),
 6326                );
 6327                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6328                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6329                (start, end)
 6330            } else {
 6331                (selection.start, selection.end)
 6332            };
 6333
 6334            let text = buffer.text_for_range(start..end).collect::<String>();
 6335            let old_length = text.len() as i32;
 6336            let text = callback(&text);
 6337
 6338            new_selections.push(Selection {
 6339                start: (start as i32 - selection_adjustment) as usize,
 6340                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6341                goal: SelectionGoal::None,
 6342                ..selection
 6343            });
 6344
 6345            selection_adjustment += old_length - text.len() as i32;
 6346
 6347            edits.push((start..end, text));
 6348        }
 6349
 6350        self.transact(cx, |this, cx| {
 6351            this.buffer.update(cx, |buffer, cx| {
 6352                buffer.edit(edits, None, cx);
 6353            });
 6354
 6355            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6356                s.select(new_selections);
 6357            });
 6358
 6359            this.request_autoscroll(Autoscroll::fit(), cx);
 6360        });
 6361    }
 6362
 6363    pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
 6364        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6365        let buffer = &display_map.buffer_snapshot;
 6366        let selections = self.selections.all::<Point>(cx);
 6367
 6368        let mut edits = Vec::new();
 6369        let mut selections_iter = selections.iter().peekable();
 6370        while let Some(selection) = selections_iter.next() {
 6371            let mut rows = selection.spanned_rows(false, &display_map);
 6372            // duplicate line-wise
 6373            if whole_lines || selection.start == selection.end {
 6374                // Avoid duplicating the same lines twice.
 6375                while let Some(next_selection) = selections_iter.peek() {
 6376                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6377                    if next_rows.start < rows.end {
 6378                        rows.end = next_rows.end;
 6379                        selections_iter.next().unwrap();
 6380                    } else {
 6381                        break;
 6382                    }
 6383                }
 6384
 6385                // Copy the text from the selected row region and splice it either at the start
 6386                // or end of the region.
 6387                let start = Point::new(rows.start.0, 0);
 6388                let end = Point::new(
 6389                    rows.end.previous_row().0,
 6390                    buffer.line_len(rows.end.previous_row()),
 6391                );
 6392                let text = buffer
 6393                    .text_for_range(start..end)
 6394                    .chain(Some("\n"))
 6395                    .collect::<String>();
 6396                let insert_location = if upwards {
 6397                    Point::new(rows.end.0, 0)
 6398                } else {
 6399                    start
 6400                };
 6401                edits.push((insert_location..insert_location, text));
 6402            } else {
 6403                // duplicate character-wise
 6404                let start = selection.start;
 6405                let end = selection.end;
 6406                let text = buffer.text_for_range(start..end).collect::<String>();
 6407                edits.push((selection.end..selection.end, text));
 6408            }
 6409        }
 6410
 6411        self.transact(cx, |this, cx| {
 6412            this.buffer.update(cx, |buffer, cx| {
 6413                buffer.edit(edits, None, cx);
 6414            });
 6415
 6416            this.request_autoscroll(Autoscroll::fit(), cx);
 6417        });
 6418    }
 6419
 6420    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6421        self.duplicate(true, true, cx);
 6422    }
 6423
 6424    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6425        self.duplicate(false, true, cx);
 6426    }
 6427
 6428    pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
 6429        self.duplicate(false, false, cx);
 6430    }
 6431
 6432    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6433        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6434        let buffer = self.buffer.read(cx).snapshot(cx);
 6435
 6436        let mut edits = Vec::new();
 6437        let mut unfold_ranges = Vec::new();
 6438        let mut refold_creases = Vec::new();
 6439
 6440        let selections = self.selections.all::<Point>(cx);
 6441        let mut selections = selections.iter().peekable();
 6442        let mut contiguous_row_selections = Vec::new();
 6443        let mut new_selections = Vec::new();
 6444
 6445        while let Some(selection) = selections.next() {
 6446            // Find all the selections that span a contiguous row range
 6447            let (start_row, end_row) = consume_contiguous_rows(
 6448                &mut contiguous_row_selections,
 6449                selection,
 6450                &display_map,
 6451                &mut selections,
 6452            );
 6453
 6454            // Move the text spanned by the row range to be before the line preceding the row range
 6455            if start_row.0 > 0 {
 6456                let range_to_move = Point::new(
 6457                    start_row.previous_row().0,
 6458                    buffer.line_len(start_row.previous_row()),
 6459                )
 6460                    ..Point::new(
 6461                        end_row.previous_row().0,
 6462                        buffer.line_len(end_row.previous_row()),
 6463                    );
 6464                let insertion_point = display_map
 6465                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6466                    .0;
 6467
 6468                // Don't move lines across excerpts
 6469                if buffer
 6470                    .excerpt_boundaries_in_range((
 6471                        Bound::Excluded(insertion_point),
 6472                        Bound::Included(range_to_move.end),
 6473                    ))
 6474                    .next()
 6475                    .is_none()
 6476                {
 6477                    let text = buffer
 6478                        .text_for_range(range_to_move.clone())
 6479                        .flat_map(|s| s.chars())
 6480                        .skip(1)
 6481                        .chain(['\n'])
 6482                        .collect::<String>();
 6483
 6484                    edits.push((
 6485                        buffer.anchor_after(range_to_move.start)
 6486                            ..buffer.anchor_before(range_to_move.end),
 6487                        String::new(),
 6488                    ));
 6489                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6490                    edits.push((insertion_anchor..insertion_anchor, text));
 6491
 6492                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6493
 6494                    // Move selections up
 6495                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6496                        |mut selection| {
 6497                            selection.start.row -= row_delta;
 6498                            selection.end.row -= row_delta;
 6499                            selection
 6500                        },
 6501                    ));
 6502
 6503                    // Move folds up
 6504                    unfold_ranges.push(range_to_move.clone());
 6505                    for fold in display_map.folds_in_range(
 6506                        buffer.anchor_before(range_to_move.start)
 6507                            ..buffer.anchor_after(range_to_move.end),
 6508                    ) {
 6509                        let mut start = fold.range.start.to_point(&buffer);
 6510                        let mut end = fold.range.end.to_point(&buffer);
 6511                        start.row -= row_delta;
 6512                        end.row -= row_delta;
 6513                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6514                    }
 6515                }
 6516            }
 6517
 6518            // If we didn't move line(s), preserve the existing selections
 6519            new_selections.append(&mut contiguous_row_selections);
 6520        }
 6521
 6522        self.transact(cx, |this, cx| {
 6523            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6524            this.buffer.update(cx, |buffer, cx| {
 6525                for (range, text) in edits {
 6526                    buffer.edit([(range, text)], None, cx);
 6527                }
 6528            });
 6529            this.fold_creases(refold_creases, true, cx);
 6530            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6531                s.select(new_selections);
 6532            })
 6533        });
 6534    }
 6535
 6536    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6537        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6538        let buffer = self.buffer.read(cx).snapshot(cx);
 6539
 6540        let mut edits = Vec::new();
 6541        let mut unfold_ranges = Vec::new();
 6542        let mut refold_creases = Vec::new();
 6543
 6544        let selections = self.selections.all::<Point>(cx);
 6545        let mut selections = selections.iter().peekable();
 6546        let mut contiguous_row_selections = Vec::new();
 6547        let mut new_selections = Vec::new();
 6548
 6549        while let Some(selection) = selections.next() {
 6550            // Find all the selections that span a contiguous row range
 6551            let (start_row, end_row) = consume_contiguous_rows(
 6552                &mut contiguous_row_selections,
 6553                selection,
 6554                &display_map,
 6555                &mut selections,
 6556            );
 6557
 6558            // Move the text spanned by the row range to be after the last line of the row range
 6559            if end_row.0 <= buffer.max_point().row {
 6560                let range_to_move =
 6561                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6562                let insertion_point = display_map
 6563                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6564                    .0;
 6565
 6566                // Don't move lines across excerpt boundaries
 6567                if buffer
 6568                    .excerpt_boundaries_in_range((
 6569                        Bound::Excluded(range_to_move.start),
 6570                        Bound::Included(insertion_point),
 6571                    ))
 6572                    .next()
 6573                    .is_none()
 6574                {
 6575                    let mut text = String::from("\n");
 6576                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6577                    text.pop(); // Drop trailing newline
 6578                    edits.push((
 6579                        buffer.anchor_after(range_to_move.start)
 6580                            ..buffer.anchor_before(range_to_move.end),
 6581                        String::new(),
 6582                    ));
 6583                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6584                    edits.push((insertion_anchor..insertion_anchor, text));
 6585
 6586                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6587
 6588                    // Move selections down
 6589                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6590                        |mut selection| {
 6591                            selection.start.row += row_delta;
 6592                            selection.end.row += row_delta;
 6593                            selection
 6594                        },
 6595                    ));
 6596
 6597                    // Move folds down
 6598                    unfold_ranges.push(range_to_move.clone());
 6599                    for fold in display_map.folds_in_range(
 6600                        buffer.anchor_before(range_to_move.start)
 6601                            ..buffer.anchor_after(range_to_move.end),
 6602                    ) {
 6603                        let mut start = fold.range.start.to_point(&buffer);
 6604                        let mut end = fold.range.end.to_point(&buffer);
 6605                        start.row += row_delta;
 6606                        end.row += row_delta;
 6607                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6608                    }
 6609                }
 6610            }
 6611
 6612            // If we didn't move line(s), preserve the existing selections
 6613            new_selections.append(&mut contiguous_row_selections);
 6614        }
 6615
 6616        self.transact(cx, |this, cx| {
 6617            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6618            this.buffer.update(cx, |buffer, cx| {
 6619                for (range, text) in edits {
 6620                    buffer.edit([(range, text)], None, cx);
 6621                }
 6622            });
 6623            this.fold_creases(refold_creases, true, cx);
 6624            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6625        });
 6626    }
 6627
 6628    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6629        let text_layout_details = &self.text_layout_details(cx);
 6630        self.transact(cx, |this, cx| {
 6631            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6632                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6633                let line_mode = s.line_mode;
 6634                s.move_with(|display_map, selection| {
 6635                    if !selection.is_empty() || line_mode {
 6636                        return;
 6637                    }
 6638
 6639                    let mut head = selection.head();
 6640                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6641                    if head.column() == display_map.line_len(head.row()) {
 6642                        transpose_offset = display_map
 6643                            .buffer_snapshot
 6644                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6645                    }
 6646
 6647                    if transpose_offset == 0 {
 6648                        return;
 6649                    }
 6650
 6651                    *head.column_mut() += 1;
 6652                    head = display_map.clip_point(head, Bias::Right);
 6653                    let goal = SelectionGoal::HorizontalPosition(
 6654                        display_map
 6655                            .x_for_display_point(head, text_layout_details)
 6656                            .into(),
 6657                    );
 6658                    selection.collapse_to(head, goal);
 6659
 6660                    let transpose_start = display_map
 6661                        .buffer_snapshot
 6662                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6663                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6664                        let transpose_end = display_map
 6665                            .buffer_snapshot
 6666                            .clip_offset(transpose_offset + 1, Bias::Right);
 6667                        if let Some(ch) =
 6668                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6669                        {
 6670                            edits.push((transpose_start..transpose_offset, String::new()));
 6671                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6672                        }
 6673                    }
 6674                });
 6675                edits
 6676            });
 6677            this.buffer
 6678                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6679            let selections = this.selections.all::<usize>(cx);
 6680            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6681                s.select(selections);
 6682            });
 6683        });
 6684    }
 6685
 6686    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6687        self.rewrap_impl(IsVimMode::No, cx)
 6688    }
 6689
 6690    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 6691        let buffer = self.buffer.read(cx).snapshot(cx);
 6692        let selections = self.selections.all::<Point>(cx);
 6693        let mut selections = selections.iter().peekable();
 6694
 6695        let mut edits = Vec::new();
 6696        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6697
 6698        while let Some(selection) = selections.next() {
 6699            let mut start_row = selection.start.row;
 6700            let mut end_row = selection.end.row;
 6701
 6702            // Skip selections that overlap with a range that has already been rewrapped.
 6703            let selection_range = start_row..end_row;
 6704            if rewrapped_row_ranges
 6705                .iter()
 6706                .any(|range| range.overlaps(&selection_range))
 6707            {
 6708                continue;
 6709            }
 6710
 6711            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 6712
 6713            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6714                match language_scope.language_name().0.as_ref() {
 6715                    "Markdown" | "Plain Text" => {
 6716                        should_rewrap = true;
 6717                    }
 6718                    _ => {}
 6719                }
 6720            }
 6721
 6722            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 6723
 6724            // Since not all lines in the selection may be at the same indent
 6725            // level, choose the indent size that is the most common between all
 6726            // of the lines.
 6727            //
 6728            // If there is a tie, we use the deepest indent.
 6729            let (indent_size, indent_end) = {
 6730                let mut indent_size_occurrences = HashMap::default();
 6731                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6732
 6733                for row in start_row..=end_row {
 6734                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6735                    rows_by_indent_size.entry(indent).or_default().push(row);
 6736                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6737                }
 6738
 6739                let indent_size = indent_size_occurrences
 6740                    .into_iter()
 6741                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 6742                    .map(|(indent, _)| indent)
 6743                    .unwrap_or_default();
 6744                let row = rows_by_indent_size[&indent_size][0];
 6745                let indent_end = Point::new(row, indent_size.len);
 6746
 6747                (indent_size, indent_end)
 6748            };
 6749
 6750            let mut line_prefix = indent_size.chars().collect::<String>();
 6751
 6752            if let Some(comment_prefix) =
 6753                buffer
 6754                    .language_scope_at(selection.head())
 6755                    .and_then(|language| {
 6756                        language
 6757                            .line_comment_prefixes()
 6758                            .iter()
 6759                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6760                            .cloned()
 6761                    })
 6762            {
 6763                line_prefix.push_str(&comment_prefix);
 6764                should_rewrap = true;
 6765            }
 6766
 6767            if !should_rewrap {
 6768                continue;
 6769            }
 6770
 6771            if selection.is_empty() {
 6772                'expand_upwards: while start_row > 0 {
 6773                    let prev_row = start_row - 1;
 6774                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6775                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6776                    {
 6777                        start_row = prev_row;
 6778                    } else {
 6779                        break 'expand_upwards;
 6780                    }
 6781                }
 6782
 6783                'expand_downwards: while end_row < buffer.max_point().row {
 6784                    let next_row = end_row + 1;
 6785                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6786                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6787                    {
 6788                        end_row = next_row;
 6789                    } else {
 6790                        break 'expand_downwards;
 6791                    }
 6792                }
 6793            }
 6794
 6795            let start = Point::new(start_row, 0);
 6796            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6797            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6798            let Some(lines_without_prefixes) = selection_text
 6799                .lines()
 6800                .map(|line| {
 6801                    line.strip_prefix(&line_prefix)
 6802                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6803                        .ok_or_else(|| {
 6804                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6805                        })
 6806                })
 6807                .collect::<Result<Vec<_>, _>>()
 6808                .log_err()
 6809            else {
 6810                continue;
 6811            };
 6812
 6813            let wrap_column = buffer
 6814                .settings_at(Point::new(start_row, 0), cx)
 6815                .preferred_line_length as usize;
 6816            let wrapped_text = wrap_with_prefix(
 6817                line_prefix,
 6818                lines_without_prefixes.join(" "),
 6819                wrap_column,
 6820                tab_size,
 6821            );
 6822
 6823            // TODO: should always use char-based diff while still supporting cursor behavior that
 6824            // matches vim.
 6825            let diff = match is_vim_mode {
 6826                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 6827                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 6828            };
 6829            let mut offset = start.to_offset(&buffer);
 6830            let mut moved_since_edit = true;
 6831
 6832            for change in diff.iter_all_changes() {
 6833                let value = change.value();
 6834                match change.tag() {
 6835                    ChangeTag::Equal => {
 6836                        offset += value.len();
 6837                        moved_since_edit = true;
 6838                    }
 6839                    ChangeTag::Delete => {
 6840                        let start = buffer.anchor_after(offset);
 6841                        let end = buffer.anchor_before(offset + value.len());
 6842
 6843                        if moved_since_edit {
 6844                            edits.push((start..end, String::new()));
 6845                        } else {
 6846                            edits.last_mut().unwrap().0.end = end;
 6847                        }
 6848
 6849                        offset += value.len();
 6850                        moved_since_edit = false;
 6851                    }
 6852                    ChangeTag::Insert => {
 6853                        if moved_since_edit {
 6854                            let anchor = buffer.anchor_after(offset);
 6855                            edits.push((anchor..anchor, value.to_string()));
 6856                        } else {
 6857                            edits.last_mut().unwrap().1.push_str(value);
 6858                        }
 6859
 6860                        moved_since_edit = false;
 6861                    }
 6862                }
 6863            }
 6864
 6865            rewrapped_row_ranges.push(start_row..=end_row);
 6866        }
 6867
 6868        self.buffer
 6869            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6870    }
 6871
 6872    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 6873        let mut text = String::new();
 6874        let buffer = self.buffer.read(cx).snapshot(cx);
 6875        let mut selections = self.selections.all::<Point>(cx);
 6876        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6877        {
 6878            let max_point = buffer.max_point();
 6879            let mut is_first = true;
 6880            for selection in &mut selections {
 6881                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6882                if is_entire_line {
 6883                    selection.start = Point::new(selection.start.row, 0);
 6884                    if !selection.is_empty() && selection.end.column == 0 {
 6885                        selection.end = cmp::min(max_point, selection.end);
 6886                    } else {
 6887                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6888                    }
 6889                    selection.goal = SelectionGoal::None;
 6890                }
 6891                if is_first {
 6892                    is_first = false;
 6893                } else {
 6894                    text += "\n";
 6895                }
 6896                let mut len = 0;
 6897                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6898                    text.push_str(chunk);
 6899                    len += chunk.len();
 6900                }
 6901                clipboard_selections.push(ClipboardSelection {
 6902                    len,
 6903                    is_entire_line,
 6904                    first_line_indent: buffer
 6905                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6906                        .len,
 6907                });
 6908            }
 6909        }
 6910
 6911        self.transact(cx, |this, cx| {
 6912            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6913                s.select(selections);
 6914            });
 6915            this.insert("", cx);
 6916        });
 6917        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 6918    }
 6919
 6920    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6921        let item = self.cut_common(cx);
 6922        cx.write_to_clipboard(item);
 6923    }
 6924
 6925    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 6926        self.change_selections(None, cx, |s| {
 6927            s.move_with(|snapshot, sel| {
 6928                if sel.is_empty() {
 6929                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 6930                }
 6931            });
 6932        });
 6933        let item = self.cut_common(cx);
 6934        cx.set_global(KillRing(item))
 6935    }
 6936
 6937    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 6938        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 6939            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 6940                (kill_ring.text().to_string(), kill_ring.metadata_json())
 6941            } else {
 6942                return;
 6943            }
 6944        } else {
 6945            return;
 6946        };
 6947        self.do_paste(&text, metadata, false, cx);
 6948    }
 6949
 6950    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6951        let selections = self.selections.all::<Point>(cx);
 6952        let buffer = self.buffer.read(cx).read(cx);
 6953        let mut text = String::new();
 6954
 6955        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6956        {
 6957            let max_point = buffer.max_point();
 6958            let mut is_first = true;
 6959            for selection in selections.iter() {
 6960                let mut start = selection.start;
 6961                let mut end = selection.end;
 6962                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6963                if is_entire_line {
 6964                    start = Point::new(start.row, 0);
 6965                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6966                }
 6967                if is_first {
 6968                    is_first = false;
 6969                } else {
 6970                    text += "\n";
 6971                }
 6972                let mut len = 0;
 6973                for chunk in buffer.text_for_range(start..end) {
 6974                    text.push_str(chunk);
 6975                    len += chunk.len();
 6976                }
 6977                clipboard_selections.push(ClipboardSelection {
 6978                    len,
 6979                    is_entire_line,
 6980                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6981                });
 6982            }
 6983        }
 6984
 6985        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6986            text,
 6987            clipboard_selections,
 6988        ));
 6989    }
 6990
 6991    pub fn do_paste(
 6992        &mut self,
 6993        text: &String,
 6994        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6995        handle_entire_lines: bool,
 6996        cx: &mut ViewContext<Self>,
 6997    ) {
 6998        if self.read_only(cx) {
 6999            return;
 7000        }
 7001
 7002        let clipboard_text = Cow::Borrowed(text);
 7003
 7004        self.transact(cx, |this, cx| {
 7005            if let Some(mut clipboard_selections) = clipboard_selections {
 7006                let old_selections = this.selections.all::<usize>(cx);
 7007                let all_selections_were_entire_line =
 7008                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7009                let first_selection_indent_column =
 7010                    clipboard_selections.first().map(|s| s.first_line_indent);
 7011                if clipboard_selections.len() != old_selections.len() {
 7012                    clipboard_selections.drain(..);
 7013                }
 7014                let cursor_offset = this.selections.last::<usize>(cx).head();
 7015                let mut auto_indent_on_paste = true;
 7016
 7017                this.buffer.update(cx, |buffer, cx| {
 7018                    let snapshot = buffer.read(cx);
 7019                    auto_indent_on_paste =
 7020                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7021
 7022                    let mut start_offset = 0;
 7023                    let mut edits = Vec::new();
 7024                    let mut original_indent_columns = Vec::new();
 7025                    for (ix, selection) in old_selections.iter().enumerate() {
 7026                        let to_insert;
 7027                        let entire_line;
 7028                        let original_indent_column;
 7029                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7030                            let end_offset = start_offset + clipboard_selection.len;
 7031                            to_insert = &clipboard_text[start_offset..end_offset];
 7032                            entire_line = clipboard_selection.is_entire_line;
 7033                            start_offset = end_offset + 1;
 7034                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7035                        } else {
 7036                            to_insert = clipboard_text.as_str();
 7037                            entire_line = all_selections_were_entire_line;
 7038                            original_indent_column = first_selection_indent_column
 7039                        }
 7040
 7041                        // If the corresponding selection was empty when this slice of the
 7042                        // clipboard text was written, then the entire line containing the
 7043                        // selection was copied. If this selection is also currently empty,
 7044                        // then paste the line before the current line of the buffer.
 7045                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7046                            let column = selection.start.to_point(&snapshot).column as usize;
 7047                            let line_start = selection.start - column;
 7048                            line_start..line_start
 7049                        } else {
 7050                            selection.range()
 7051                        };
 7052
 7053                        edits.push((range, to_insert));
 7054                        original_indent_columns.extend(original_indent_column);
 7055                    }
 7056                    drop(snapshot);
 7057
 7058                    buffer.edit(
 7059                        edits,
 7060                        if auto_indent_on_paste {
 7061                            Some(AutoindentMode::Block {
 7062                                original_indent_columns,
 7063                            })
 7064                        } else {
 7065                            None
 7066                        },
 7067                        cx,
 7068                    );
 7069                });
 7070
 7071                let selections = this.selections.all::<usize>(cx);
 7072                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7073            } else {
 7074                this.insert(&clipboard_text, cx);
 7075            }
 7076        });
 7077    }
 7078
 7079    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7080        if let Some(item) = cx.read_from_clipboard() {
 7081            let entries = item.entries();
 7082
 7083            match entries.first() {
 7084                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7085                // of all the pasted entries.
 7086                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7087                    .do_paste(
 7088                        clipboard_string.text(),
 7089                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7090                        true,
 7091                        cx,
 7092                    ),
 7093                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7094            }
 7095        }
 7096    }
 7097
 7098    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7099        if self.read_only(cx) {
 7100            return;
 7101        }
 7102
 7103        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7104            if let Some((selections, _)) =
 7105                self.selection_history.transaction(transaction_id).cloned()
 7106            {
 7107                self.change_selections(None, cx, |s| {
 7108                    s.select_anchors(selections.to_vec());
 7109                });
 7110            }
 7111            self.request_autoscroll(Autoscroll::fit(), cx);
 7112            self.unmark_text(cx);
 7113            self.refresh_inline_completion(true, false, cx);
 7114            cx.emit(EditorEvent::Edited { transaction_id });
 7115            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7116        }
 7117    }
 7118
 7119    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7120        if self.read_only(cx) {
 7121            return;
 7122        }
 7123
 7124        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7125            if let Some((_, Some(selections))) =
 7126                self.selection_history.transaction(transaction_id).cloned()
 7127            {
 7128                self.change_selections(None, cx, |s| {
 7129                    s.select_anchors(selections.to_vec());
 7130                });
 7131            }
 7132            self.request_autoscroll(Autoscroll::fit(), cx);
 7133            self.unmark_text(cx);
 7134            self.refresh_inline_completion(true, false, cx);
 7135            cx.emit(EditorEvent::Edited { transaction_id });
 7136        }
 7137    }
 7138
 7139    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7140        self.buffer
 7141            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7142    }
 7143
 7144    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7145        self.buffer
 7146            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7147    }
 7148
 7149    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7150        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7151            let line_mode = s.line_mode;
 7152            s.move_with(|map, selection| {
 7153                let cursor = if selection.is_empty() && !line_mode {
 7154                    movement::left(map, selection.start)
 7155                } else {
 7156                    selection.start
 7157                };
 7158                selection.collapse_to(cursor, SelectionGoal::None);
 7159            });
 7160        })
 7161    }
 7162
 7163    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7164        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7165            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7166        })
 7167    }
 7168
 7169    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7170        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7171            let line_mode = s.line_mode;
 7172            s.move_with(|map, selection| {
 7173                let cursor = if selection.is_empty() && !line_mode {
 7174                    movement::right(map, selection.end)
 7175                } else {
 7176                    selection.end
 7177                };
 7178                selection.collapse_to(cursor, SelectionGoal::None)
 7179            });
 7180        })
 7181    }
 7182
 7183    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7184        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7185            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7186        })
 7187    }
 7188
 7189    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7190        if self.take_rename(true, cx).is_some() {
 7191            return;
 7192        }
 7193
 7194        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7195            cx.propagate();
 7196            return;
 7197        }
 7198
 7199        let text_layout_details = &self.text_layout_details(cx);
 7200        let selection_count = self.selections.count();
 7201        let first_selection = self.selections.first_anchor();
 7202
 7203        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7204            let line_mode = s.line_mode;
 7205            s.move_with(|map, selection| {
 7206                if !selection.is_empty() && !line_mode {
 7207                    selection.goal = SelectionGoal::None;
 7208                }
 7209                let (cursor, goal) = movement::up(
 7210                    map,
 7211                    selection.start,
 7212                    selection.goal,
 7213                    false,
 7214                    text_layout_details,
 7215                );
 7216                selection.collapse_to(cursor, goal);
 7217            });
 7218        });
 7219
 7220        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7221        {
 7222            cx.propagate();
 7223        }
 7224    }
 7225
 7226    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7227        if self.take_rename(true, cx).is_some() {
 7228            return;
 7229        }
 7230
 7231        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7232            cx.propagate();
 7233            return;
 7234        }
 7235
 7236        let text_layout_details = &self.text_layout_details(cx);
 7237
 7238        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7239            let line_mode = s.line_mode;
 7240            s.move_with(|map, selection| {
 7241                if !selection.is_empty() && !line_mode {
 7242                    selection.goal = SelectionGoal::None;
 7243                }
 7244                let (cursor, goal) = movement::up_by_rows(
 7245                    map,
 7246                    selection.start,
 7247                    action.lines,
 7248                    selection.goal,
 7249                    false,
 7250                    text_layout_details,
 7251                );
 7252                selection.collapse_to(cursor, goal);
 7253            });
 7254        })
 7255    }
 7256
 7257    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7258        if self.take_rename(true, cx).is_some() {
 7259            return;
 7260        }
 7261
 7262        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7263            cx.propagate();
 7264            return;
 7265        }
 7266
 7267        let text_layout_details = &self.text_layout_details(cx);
 7268
 7269        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7270            let line_mode = s.line_mode;
 7271            s.move_with(|map, selection| {
 7272                if !selection.is_empty() && !line_mode {
 7273                    selection.goal = SelectionGoal::None;
 7274                }
 7275                let (cursor, goal) = movement::down_by_rows(
 7276                    map,
 7277                    selection.start,
 7278                    action.lines,
 7279                    selection.goal,
 7280                    false,
 7281                    text_layout_details,
 7282                );
 7283                selection.collapse_to(cursor, goal);
 7284            });
 7285        })
 7286    }
 7287
 7288    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7289        let text_layout_details = &self.text_layout_details(cx);
 7290        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7291            s.move_heads_with(|map, head, goal| {
 7292                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7293            })
 7294        })
 7295    }
 7296
 7297    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7298        let text_layout_details = &self.text_layout_details(cx);
 7299        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7300            s.move_heads_with(|map, head, goal| {
 7301                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7302            })
 7303        })
 7304    }
 7305
 7306    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7307        let Some(row_count) = self.visible_row_count() else {
 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            s.move_heads_with(|map, head, goal| {
 7315                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7316            })
 7317        })
 7318    }
 7319
 7320    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7321        if self.take_rename(true, cx).is_some() {
 7322            return;
 7323        }
 7324
 7325        if self
 7326            .context_menu
 7327            .borrow_mut()
 7328            .as_mut()
 7329            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7330            .unwrap_or(false)
 7331        {
 7332            return;
 7333        }
 7334
 7335        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7336            cx.propagate();
 7337            return;
 7338        }
 7339
 7340        let Some(row_count) = self.visible_row_count() else {
 7341            return;
 7342        };
 7343
 7344        let autoscroll = if action.center_cursor {
 7345            Autoscroll::center()
 7346        } else {
 7347            Autoscroll::fit()
 7348        };
 7349
 7350        let text_layout_details = &self.text_layout_details(cx);
 7351
 7352        self.change_selections(Some(autoscroll), cx, |s| {
 7353            let line_mode = s.line_mode;
 7354            s.move_with(|map, selection| {
 7355                if !selection.is_empty() && !line_mode {
 7356                    selection.goal = SelectionGoal::None;
 7357                }
 7358                let (cursor, goal) = movement::up_by_rows(
 7359                    map,
 7360                    selection.end,
 7361                    row_count,
 7362                    selection.goal,
 7363                    false,
 7364                    text_layout_details,
 7365                );
 7366                selection.collapse_to(cursor, goal);
 7367            });
 7368        });
 7369    }
 7370
 7371    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7372        let text_layout_details = &self.text_layout_details(cx);
 7373        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7374            s.move_heads_with(|map, head, goal| {
 7375                movement::up(map, head, goal, false, text_layout_details)
 7376            })
 7377        })
 7378    }
 7379
 7380    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7381        self.take_rename(true, cx);
 7382
 7383        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7384            cx.propagate();
 7385            return;
 7386        }
 7387
 7388        let text_layout_details = &self.text_layout_details(cx);
 7389        let selection_count = self.selections.count();
 7390        let first_selection = self.selections.first_anchor();
 7391
 7392        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7393            let line_mode = s.line_mode;
 7394            s.move_with(|map, selection| {
 7395                if !selection.is_empty() && !line_mode {
 7396                    selection.goal = SelectionGoal::None;
 7397                }
 7398                let (cursor, goal) = movement::down(
 7399                    map,
 7400                    selection.end,
 7401                    selection.goal,
 7402                    false,
 7403                    text_layout_details,
 7404                );
 7405                selection.collapse_to(cursor, goal);
 7406            });
 7407        });
 7408
 7409        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7410        {
 7411            cx.propagate();
 7412        }
 7413    }
 7414
 7415    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7416        let Some(row_count) = self.visible_row_count() else {
 7417            return;
 7418        };
 7419
 7420        let text_layout_details = &self.text_layout_details(cx);
 7421
 7422        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7423            s.move_heads_with(|map, head, goal| {
 7424                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7425            })
 7426        })
 7427    }
 7428
 7429    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7430        if self.take_rename(true, cx).is_some() {
 7431            return;
 7432        }
 7433
 7434        if self
 7435            .context_menu
 7436            .borrow_mut()
 7437            .as_mut()
 7438            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7439            .unwrap_or(false)
 7440        {
 7441            return;
 7442        }
 7443
 7444        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7445            cx.propagate();
 7446            return;
 7447        }
 7448
 7449        let Some(row_count) = self.visible_row_count() else {
 7450            return;
 7451        };
 7452
 7453        let autoscroll = if action.center_cursor {
 7454            Autoscroll::center()
 7455        } else {
 7456            Autoscroll::fit()
 7457        };
 7458
 7459        let text_layout_details = &self.text_layout_details(cx);
 7460        self.change_selections(Some(autoscroll), cx, |s| {
 7461            let line_mode = s.line_mode;
 7462            s.move_with(|map, selection| {
 7463                if !selection.is_empty() && !line_mode {
 7464                    selection.goal = SelectionGoal::None;
 7465                }
 7466                let (cursor, goal) = movement::down_by_rows(
 7467                    map,
 7468                    selection.end,
 7469                    row_count,
 7470                    selection.goal,
 7471                    false,
 7472                    text_layout_details,
 7473                );
 7474                selection.collapse_to(cursor, goal);
 7475            });
 7476        });
 7477    }
 7478
 7479    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7480        let text_layout_details = &self.text_layout_details(cx);
 7481        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7482            s.move_heads_with(|map, head, goal| {
 7483                movement::down(map, head, goal, false, text_layout_details)
 7484            })
 7485        });
 7486    }
 7487
 7488    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7489        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7490            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7491        }
 7492    }
 7493
 7494    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7495        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7496            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7497        }
 7498    }
 7499
 7500    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7501        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7502            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7503        }
 7504    }
 7505
 7506    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7507        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7508            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7509        }
 7510    }
 7511
 7512    pub fn move_to_previous_word_start(
 7513        &mut self,
 7514        _: &MoveToPreviousWordStart,
 7515        cx: &mut ViewContext<Self>,
 7516    ) {
 7517        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7518            s.move_cursors_with(|map, head, _| {
 7519                (
 7520                    movement::previous_word_start(map, head),
 7521                    SelectionGoal::None,
 7522                )
 7523            });
 7524        })
 7525    }
 7526
 7527    pub fn move_to_previous_subword_start(
 7528        &mut self,
 7529        _: &MoveToPreviousSubwordStart,
 7530        cx: &mut ViewContext<Self>,
 7531    ) {
 7532        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7533            s.move_cursors_with(|map, head, _| {
 7534                (
 7535                    movement::previous_subword_start(map, head),
 7536                    SelectionGoal::None,
 7537                )
 7538            });
 7539        })
 7540    }
 7541
 7542    pub fn select_to_previous_word_start(
 7543        &mut self,
 7544        _: &SelectToPreviousWordStart,
 7545        cx: &mut ViewContext<Self>,
 7546    ) {
 7547        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7548            s.move_heads_with(|map, head, _| {
 7549                (
 7550                    movement::previous_word_start(map, head),
 7551                    SelectionGoal::None,
 7552                )
 7553            });
 7554        })
 7555    }
 7556
 7557    pub fn select_to_previous_subword_start(
 7558        &mut self,
 7559        _: &SelectToPreviousSubwordStart,
 7560        cx: &mut ViewContext<Self>,
 7561    ) {
 7562        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7563            s.move_heads_with(|map, head, _| {
 7564                (
 7565                    movement::previous_subword_start(map, head),
 7566                    SelectionGoal::None,
 7567                )
 7568            });
 7569        })
 7570    }
 7571
 7572    pub fn delete_to_previous_word_start(
 7573        &mut self,
 7574        action: &DeleteToPreviousWordStart,
 7575        cx: &mut ViewContext<Self>,
 7576    ) {
 7577        self.transact(cx, |this, cx| {
 7578            this.select_autoclose_pair(cx);
 7579            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7580                let line_mode = s.line_mode;
 7581                s.move_with(|map, selection| {
 7582                    if selection.is_empty() && !line_mode {
 7583                        let cursor = if action.ignore_newlines {
 7584                            movement::previous_word_start(map, selection.head())
 7585                        } else {
 7586                            movement::previous_word_start_or_newline(map, selection.head())
 7587                        };
 7588                        selection.set_head(cursor, SelectionGoal::None);
 7589                    }
 7590                });
 7591            });
 7592            this.insert("", cx);
 7593        });
 7594    }
 7595
 7596    pub fn delete_to_previous_subword_start(
 7597        &mut self,
 7598        _: &DeleteToPreviousSubwordStart,
 7599        cx: &mut ViewContext<Self>,
 7600    ) {
 7601        self.transact(cx, |this, cx| {
 7602            this.select_autoclose_pair(cx);
 7603            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7604                let line_mode = s.line_mode;
 7605                s.move_with(|map, selection| {
 7606                    if selection.is_empty() && !line_mode {
 7607                        let cursor = movement::previous_subword_start(map, selection.head());
 7608                        selection.set_head(cursor, SelectionGoal::None);
 7609                    }
 7610                });
 7611            });
 7612            this.insert("", cx);
 7613        });
 7614    }
 7615
 7616    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7617        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7618            s.move_cursors_with(|map, head, _| {
 7619                (movement::next_word_end(map, head), SelectionGoal::None)
 7620            });
 7621        })
 7622    }
 7623
 7624    pub fn move_to_next_subword_end(
 7625        &mut self,
 7626        _: &MoveToNextSubwordEnd,
 7627        cx: &mut ViewContext<Self>,
 7628    ) {
 7629        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7630            s.move_cursors_with(|map, head, _| {
 7631                (movement::next_subword_end(map, head), SelectionGoal::None)
 7632            });
 7633        })
 7634    }
 7635
 7636    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7637        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7638            s.move_heads_with(|map, head, _| {
 7639                (movement::next_word_end(map, head), SelectionGoal::None)
 7640            });
 7641        })
 7642    }
 7643
 7644    pub fn select_to_next_subword_end(
 7645        &mut self,
 7646        _: &SelectToNextSubwordEnd,
 7647        cx: &mut ViewContext<Self>,
 7648    ) {
 7649        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7650            s.move_heads_with(|map, head, _| {
 7651                (movement::next_subword_end(map, head), SelectionGoal::None)
 7652            });
 7653        })
 7654    }
 7655
 7656    pub fn delete_to_next_word_end(
 7657        &mut self,
 7658        action: &DeleteToNextWordEnd,
 7659        cx: &mut ViewContext<Self>,
 7660    ) {
 7661        self.transact(cx, |this, cx| {
 7662            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7663                let line_mode = s.line_mode;
 7664                s.move_with(|map, selection| {
 7665                    if selection.is_empty() && !line_mode {
 7666                        let cursor = if action.ignore_newlines {
 7667                            movement::next_word_end(map, selection.head())
 7668                        } else {
 7669                            movement::next_word_end_or_newline(map, selection.head())
 7670                        };
 7671                        selection.set_head(cursor, SelectionGoal::None);
 7672                    }
 7673                });
 7674            });
 7675            this.insert("", cx);
 7676        });
 7677    }
 7678
 7679    pub fn delete_to_next_subword_end(
 7680        &mut self,
 7681        _: &DeleteToNextSubwordEnd,
 7682        cx: &mut ViewContext<Self>,
 7683    ) {
 7684        self.transact(cx, |this, cx| {
 7685            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7686                s.move_with(|map, selection| {
 7687                    if selection.is_empty() {
 7688                        let cursor = movement::next_subword_end(map, selection.head());
 7689                        selection.set_head(cursor, SelectionGoal::None);
 7690                    }
 7691                });
 7692            });
 7693            this.insert("", cx);
 7694        });
 7695    }
 7696
 7697    pub fn move_to_beginning_of_line(
 7698        &mut self,
 7699        action: &MoveToBeginningOfLine,
 7700        cx: &mut ViewContext<Self>,
 7701    ) {
 7702        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7703            s.move_cursors_with(|map, head, _| {
 7704                (
 7705                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7706                    SelectionGoal::None,
 7707                )
 7708            });
 7709        })
 7710    }
 7711
 7712    pub fn select_to_beginning_of_line(
 7713        &mut self,
 7714        action: &SelectToBeginningOfLine,
 7715        cx: &mut ViewContext<Self>,
 7716    ) {
 7717        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7718            s.move_heads_with(|map, head, _| {
 7719                (
 7720                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7721                    SelectionGoal::None,
 7722                )
 7723            });
 7724        });
 7725    }
 7726
 7727    pub fn delete_to_beginning_of_line(
 7728        &mut self,
 7729        _: &DeleteToBeginningOfLine,
 7730        cx: &mut ViewContext<Self>,
 7731    ) {
 7732        self.transact(cx, |this, cx| {
 7733            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7734                s.move_with(|_, selection| {
 7735                    selection.reversed = true;
 7736                });
 7737            });
 7738
 7739            this.select_to_beginning_of_line(
 7740                &SelectToBeginningOfLine {
 7741                    stop_at_soft_wraps: false,
 7742                },
 7743                cx,
 7744            );
 7745            this.backspace(&Backspace, cx);
 7746        });
 7747    }
 7748
 7749    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7750        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7751            s.move_cursors_with(|map, head, _| {
 7752                (
 7753                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7754                    SelectionGoal::None,
 7755                )
 7756            });
 7757        })
 7758    }
 7759
 7760    pub fn select_to_end_of_line(
 7761        &mut self,
 7762        action: &SelectToEndOfLine,
 7763        cx: &mut ViewContext<Self>,
 7764    ) {
 7765        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7766            s.move_heads_with(|map, head, _| {
 7767                (
 7768                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7769                    SelectionGoal::None,
 7770                )
 7771            });
 7772        })
 7773    }
 7774
 7775    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7776        self.transact(cx, |this, cx| {
 7777            this.select_to_end_of_line(
 7778                &SelectToEndOfLine {
 7779                    stop_at_soft_wraps: false,
 7780                },
 7781                cx,
 7782            );
 7783            this.delete(&Delete, cx);
 7784        });
 7785    }
 7786
 7787    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7788        self.transact(cx, |this, cx| {
 7789            this.select_to_end_of_line(
 7790                &SelectToEndOfLine {
 7791                    stop_at_soft_wraps: false,
 7792                },
 7793                cx,
 7794            );
 7795            this.cut(&Cut, cx);
 7796        });
 7797    }
 7798
 7799    pub fn move_to_start_of_paragraph(
 7800        &mut self,
 7801        _: &MoveToStartOfParagraph,
 7802        cx: &mut ViewContext<Self>,
 7803    ) {
 7804        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7805            cx.propagate();
 7806            return;
 7807        }
 7808
 7809        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7810            s.move_with(|map, selection| {
 7811                selection.collapse_to(
 7812                    movement::start_of_paragraph(map, selection.head(), 1),
 7813                    SelectionGoal::None,
 7814                )
 7815            });
 7816        })
 7817    }
 7818
 7819    pub fn move_to_end_of_paragraph(
 7820        &mut self,
 7821        _: &MoveToEndOfParagraph,
 7822        cx: &mut ViewContext<Self>,
 7823    ) {
 7824        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7825            cx.propagate();
 7826            return;
 7827        }
 7828
 7829        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7830            s.move_with(|map, selection| {
 7831                selection.collapse_to(
 7832                    movement::end_of_paragraph(map, selection.head(), 1),
 7833                    SelectionGoal::None,
 7834                )
 7835            });
 7836        })
 7837    }
 7838
 7839    pub fn select_to_start_of_paragraph(
 7840        &mut self,
 7841        _: &SelectToStartOfParagraph,
 7842        cx: &mut ViewContext<Self>,
 7843    ) {
 7844        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7845            cx.propagate();
 7846            return;
 7847        }
 7848
 7849        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7850            s.move_heads_with(|map, head, _| {
 7851                (
 7852                    movement::start_of_paragraph(map, head, 1),
 7853                    SelectionGoal::None,
 7854                )
 7855            });
 7856        })
 7857    }
 7858
 7859    pub fn select_to_end_of_paragraph(
 7860        &mut self,
 7861        _: &SelectToEndOfParagraph,
 7862        cx: &mut ViewContext<Self>,
 7863    ) {
 7864        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7865            cx.propagate();
 7866            return;
 7867        }
 7868
 7869        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7870            s.move_heads_with(|map, head, _| {
 7871                (
 7872                    movement::end_of_paragraph(map, head, 1),
 7873                    SelectionGoal::None,
 7874                )
 7875            });
 7876        })
 7877    }
 7878
 7879    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7880        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7881            cx.propagate();
 7882            return;
 7883        }
 7884
 7885        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7886            s.select_ranges(vec![0..0]);
 7887        });
 7888    }
 7889
 7890    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7891        let mut selection = self.selections.last::<Point>(cx);
 7892        selection.set_head(Point::zero(), SelectionGoal::None);
 7893
 7894        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7895            s.select(vec![selection]);
 7896        });
 7897    }
 7898
 7899    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7900        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7901            cx.propagate();
 7902            return;
 7903        }
 7904
 7905        let cursor = self.buffer.read(cx).read(cx).len();
 7906        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7907            s.select_ranges(vec![cursor..cursor])
 7908        });
 7909    }
 7910
 7911    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7912        self.nav_history = nav_history;
 7913    }
 7914
 7915    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7916        self.nav_history.as_ref()
 7917    }
 7918
 7919    fn push_to_nav_history(
 7920        &mut self,
 7921        cursor_anchor: Anchor,
 7922        new_position: Option<Point>,
 7923        cx: &mut ViewContext<Self>,
 7924    ) {
 7925        if let Some(nav_history) = self.nav_history.as_mut() {
 7926            let buffer = self.buffer.read(cx).read(cx);
 7927            let cursor_position = cursor_anchor.to_point(&buffer);
 7928            let scroll_state = self.scroll_manager.anchor();
 7929            let scroll_top_row = scroll_state.top_row(&buffer);
 7930            drop(buffer);
 7931
 7932            if let Some(new_position) = new_position {
 7933                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7934                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7935                    return;
 7936                }
 7937            }
 7938
 7939            nav_history.push(
 7940                Some(NavigationData {
 7941                    cursor_anchor,
 7942                    cursor_position,
 7943                    scroll_anchor: scroll_state,
 7944                    scroll_top_row,
 7945                }),
 7946                cx,
 7947            );
 7948        }
 7949    }
 7950
 7951    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7952        let buffer = self.buffer.read(cx).snapshot(cx);
 7953        let mut selection = self.selections.first::<usize>(cx);
 7954        selection.set_head(buffer.len(), SelectionGoal::None);
 7955        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7956            s.select(vec![selection]);
 7957        });
 7958    }
 7959
 7960    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7961        let end = self.buffer.read(cx).read(cx).len();
 7962        self.change_selections(None, cx, |s| {
 7963            s.select_ranges(vec![0..end]);
 7964        });
 7965    }
 7966
 7967    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7968        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7969        let mut selections = self.selections.all::<Point>(cx);
 7970        let max_point = display_map.buffer_snapshot.max_point();
 7971        for selection in &mut selections {
 7972            let rows = selection.spanned_rows(true, &display_map);
 7973            selection.start = Point::new(rows.start.0, 0);
 7974            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7975            selection.reversed = false;
 7976        }
 7977        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7978            s.select(selections);
 7979        });
 7980    }
 7981
 7982    pub fn split_selection_into_lines(
 7983        &mut self,
 7984        _: &SplitSelectionIntoLines,
 7985        cx: &mut ViewContext<Self>,
 7986    ) {
 7987        let mut to_unfold = Vec::new();
 7988        let mut new_selection_ranges = Vec::new();
 7989        {
 7990            let selections = self.selections.all::<Point>(cx);
 7991            let buffer = self.buffer.read(cx).read(cx);
 7992            for selection in selections {
 7993                for row in selection.start.row..selection.end.row {
 7994                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7995                    new_selection_ranges.push(cursor..cursor);
 7996                }
 7997                new_selection_ranges.push(selection.end..selection.end);
 7998                to_unfold.push(selection.start..selection.end);
 7999            }
 8000        }
 8001        self.unfold_ranges(&to_unfold, true, true, cx);
 8002        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8003            s.select_ranges(new_selection_ranges);
 8004        });
 8005    }
 8006
 8007    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8008        self.add_selection(true, cx);
 8009    }
 8010
 8011    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8012        self.add_selection(false, cx);
 8013    }
 8014
 8015    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8016        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8017        let mut selections = self.selections.all::<Point>(cx);
 8018        let text_layout_details = self.text_layout_details(cx);
 8019        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8020            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8021            let range = oldest_selection.display_range(&display_map).sorted();
 8022
 8023            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8024            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8025            let positions = start_x.min(end_x)..start_x.max(end_x);
 8026
 8027            selections.clear();
 8028            let mut stack = Vec::new();
 8029            for row in range.start.row().0..=range.end.row().0 {
 8030                if let Some(selection) = self.selections.build_columnar_selection(
 8031                    &display_map,
 8032                    DisplayRow(row),
 8033                    &positions,
 8034                    oldest_selection.reversed,
 8035                    &text_layout_details,
 8036                ) {
 8037                    stack.push(selection.id);
 8038                    selections.push(selection);
 8039                }
 8040            }
 8041
 8042            if above {
 8043                stack.reverse();
 8044            }
 8045
 8046            AddSelectionsState { above, stack }
 8047        });
 8048
 8049        let last_added_selection = *state.stack.last().unwrap();
 8050        let mut new_selections = Vec::new();
 8051        if above == state.above {
 8052            let end_row = if above {
 8053                DisplayRow(0)
 8054            } else {
 8055                display_map.max_point().row()
 8056            };
 8057
 8058            'outer: for selection in selections {
 8059                if selection.id == last_added_selection {
 8060                    let range = selection.display_range(&display_map).sorted();
 8061                    debug_assert_eq!(range.start.row(), range.end.row());
 8062                    let mut row = range.start.row();
 8063                    let positions =
 8064                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8065                            px(start)..px(end)
 8066                        } else {
 8067                            let start_x =
 8068                                display_map.x_for_display_point(range.start, &text_layout_details);
 8069                            let end_x =
 8070                                display_map.x_for_display_point(range.end, &text_layout_details);
 8071                            start_x.min(end_x)..start_x.max(end_x)
 8072                        };
 8073
 8074                    while row != end_row {
 8075                        if above {
 8076                            row.0 -= 1;
 8077                        } else {
 8078                            row.0 += 1;
 8079                        }
 8080
 8081                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8082                            &display_map,
 8083                            row,
 8084                            &positions,
 8085                            selection.reversed,
 8086                            &text_layout_details,
 8087                        ) {
 8088                            state.stack.push(new_selection.id);
 8089                            if above {
 8090                                new_selections.push(new_selection);
 8091                                new_selections.push(selection);
 8092                            } else {
 8093                                new_selections.push(selection);
 8094                                new_selections.push(new_selection);
 8095                            }
 8096
 8097                            continue 'outer;
 8098                        }
 8099                    }
 8100                }
 8101
 8102                new_selections.push(selection);
 8103            }
 8104        } else {
 8105            new_selections = selections;
 8106            new_selections.retain(|s| s.id != last_added_selection);
 8107            state.stack.pop();
 8108        }
 8109
 8110        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8111            s.select(new_selections);
 8112        });
 8113        if state.stack.len() > 1 {
 8114            self.add_selections_state = Some(state);
 8115        }
 8116    }
 8117
 8118    pub fn select_next_match_internal(
 8119        &mut self,
 8120        display_map: &DisplaySnapshot,
 8121        replace_newest: bool,
 8122        autoscroll: Option<Autoscroll>,
 8123        cx: &mut ViewContext<Self>,
 8124    ) -> Result<()> {
 8125        fn select_next_match_ranges(
 8126            this: &mut Editor,
 8127            range: Range<usize>,
 8128            replace_newest: bool,
 8129            auto_scroll: Option<Autoscroll>,
 8130            cx: &mut ViewContext<Editor>,
 8131        ) {
 8132            this.unfold_ranges(&[range.clone()], false, true, cx);
 8133            this.change_selections(auto_scroll, cx, |s| {
 8134                if replace_newest {
 8135                    s.delete(s.newest_anchor().id);
 8136                }
 8137                s.insert_range(range.clone());
 8138            });
 8139        }
 8140
 8141        let buffer = &display_map.buffer_snapshot;
 8142        let mut selections = self.selections.all::<usize>(cx);
 8143        if let Some(mut select_next_state) = self.select_next_state.take() {
 8144            let query = &select_next_state.query;
 8145            if !select_next_state.done {
 8146                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8147                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8148                let mut next_selected_range = None;
 8149
 8150                let bytes_after_last_selection =
 8151                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8152                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8153                let query_matches = query
 8154                    .stream_find_iter(bytes_after_last_selection)
 8155                    .map(|result| (last_selection.end, result))
 8156                    .chain(
 8157                        query
 8158                            .stream_find_iter(bytes_before_first_selection)
 8159                            .map(|result| (0, result)),
 8160                    );
 8161
 8162                for (start_offset, query_match) in query_matches {
 8163                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8164                    let offset_range =
 8165                        start_offset + query_match.start()..start_offset + query_match.end();
 8166                    let display_range = offset_range.start.to_display_point(display_map)
 8167                        ..offset_range.end.to_display_point(display_map);
 8168
 8169                    if !select_next_state.wordwise
 8170                        || (!movement::is_inside_word(display_map, display_range.start)
 8171                            && !movement::is_inside_word(display_map, display_range.end))
 8172                    {
 8173                        // TODO: This is n^2, because we might check all the selections
 8174                        if !selections
 8175                            .iter()
 8176                            .any(|selection| selection.range().overlaps(&offset_range))
 8177                        {
 8178                            next_selected_range = Some(offset_range);
 8179                            break;
 8180                        }
 8181                    }
 8182                }
 8183
 8184                if let Some(next_selected_range) = next_selected_range {
 8185                    select_next_match_ranges(
 8186                        self,
 8187                        next_selected_range,
 8188                        replace_newest,
 8189                        autoscroll,
 8190                        cx,
 8191                    );
 8192                } else {
 8193                    select_next_state.done = true;
 8194                }
 8195            }
 8196
 8197            self.select_next_state = Some(select_next_state);
 8198        } else {
 8199            let mut only_carets = true;
 8200            let mut same_text_selected = true;
 8201            let mut selected_text = None;
 8202
 8203            let mut selections_iter = selections.iter().peekable();
 8204            while let Some(selection) = selections_iter.next() {
 8205                if selection.start != selection.end {
 8206                    only_carets = false;
 8207                }
 8208
 8209                if same_text_selected {
 8210                    if selected_text.is_none() {
 8211                        selected_text =
 8212                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8213                    }
 8214
 8215                    if let Some(next_selection) = selections_iter.peek() {
 8216                        if next_selection.range().len() == selection.range().len() {
 8217                            let next_selected_text = buffer
 8218                                .text_for_range(next_selection.range())
 8219                                .collect::<String>();
 8220                            if Some(next_selected_text) != selected_text {
 8221                                same_text_selected = false;
 8222                                selected_text = None;
 8223                            }
 8224                        } else {
 8225                            same_text_selected = false;
 8226                            selected_text = None;
 8227                        }
 8228                    }
 8229                }
 8230            }
 8231
 8232            if only_carets {
 8233                for selection in &mut selections {
 8234                    let word_range = movement::surrounding_word(
 8235                        display_map,
 8236                        selection.start.to_display_point(display_map),
 8237                    );
 8238                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8239                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8240                    selection.goal = SelectionGoal::None;
 8241                    selection.reversed = false;
 8242                    select_next_match_ranges(
 8243                        self,
 8244                        selection.start..selection.end,
 8245                        replace_newest,
 8246                        autoscroll,
 8247                        cx,
 8248                    );
 8249                }
 8250
 8251                if selections.len() == 1 {
 8252                    let selection = selections
 8253                        .last()
 8254                        .expect("ensured that there's only one selection");
 8255                    let query = buffer
 8256                        .text_for_range(selection.start..selection.end)
 8257                        .collect::<String>();
 8258                    let is_empty = query.is_empty();
 8259                    let select_state = SelectNextState {
 8260                        query: AhoCorasick::new(&[query])?,
 8261                        wordwise: true,
 8262                        done: is_empty,
 8263                    };
 8264                    self.select_next_state = Some(select_state);
 8265                } else {
 8266                    self.select_next_state = None;
 8267                }
 8268            } else if let Some(selected_text) = selected_text {
 8269                self.select_next_state = Some(SelectNextState {
 8270                    query: AhoCorasick::new(&[selected_text])?,
 8271                    wordwise: false,
 8272                    done: false,
 8273                });
 8274                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8275            }
 8276        }
 8277        Ok(())
 8278    }
 8279
 8280    pub fn select_all_matches(
 8281        &mut self,
 8282        _action: &SelectAllMatches,
 8283        cx: &mut ViewContext<Self>,
 8284    ) -> Result<()> {
 8285        self.push_to_selection_history();
 8286        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8287
 8288        self.select_next_match_internal(&display_map, false, None, cx)?;
 8289        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8290            return Ok(());
 8291        };
 8292        if select_next_state.done {
 8293            return Ok(());
 8294        }
 8295
 8296        let mut new_selections = self.selections.all::<usize>(cx);
 8297
 8298        let buffer = &display_map.buffer_snapshot;
 8299        let query_matches = select_next_state
 8300            .query
 8301            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8302
 8303        for query_match in query_matches {
 8304            let query_match = query_match.unwrap(); // can only fail due to I/O
 8305            let offset_range = query_match.start()..query_match.end();
 8306            let display_range = offset_range.start.to_display_point(&display_map)
 8307                ..offset_range.end.to_display_point(&display_map);
 8308
 8309            if !select_next_state.wordwise
 8310                || (!movement::is_inside_word(&display_map, display_range.start)
 8311                    && !movement::is_inside_word(&display_map, display_range.end))
 8312            {
 8313                self.selections.change_with(cx, |selections| {
 8314                    new_selections.push(Selection {
 8315                        id: selections.new_selection_id(),
 8316                        start: offset_range.start,
 8317                        end: offset_range.end,
 8318                        reversed: false,
 8319                        goal: SelectionGoal::None,
 8320                    });
 8321                });
 8322            }
 8323        }
 8324
 8325        new_selections.sort_by_key(|selection| selection.start);
 8326        let mut ix = 0;
 8327        while ix + 1 < new_selections.len() {
 8328            let current_selection = &new_selections[ix];
 8329            let next_selection = &new_selections[ix + 1];
 8330            if current_selection.range().overlaps(&next_selection.range()) {
 8331                if current_selection.id < next_selection.id {
 8332                    new_selections.remove(ix + 1);
 8333                } else {
 8334                    new_selections.remove(ix);
 8335                }
 8336            } else {
 8337                ix += 1;
 8338            }
 8339        }
 8340
 8341        select_next_state.done = true;
 8342        self.unfold_ranges(
 8343            &new_selections
 8344                .iter()
 8345                .map(|selection| selection.range())
 8346                .collect::<Vec<_>>(),
 8347            false,
 8348            false,
 8349            cx,
 8350        );
 8351        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8352            selections.select(new_selections)
 8353        });
 8354
 8355        Ok(())
 8356    }
 8357
 8358    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8359        self.push_to_selection_history();
 8360        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8361        self.select_next_match_internal(
 8362            &display_map,
 8363            action.replace_newest,
 8364            Some(Autoscroll::newest()),
 8365            cx,
 8366        )?;
 8367        Ok(())
 8368    }
 8369
 8370    pub fn select_previous(
 8371        &mut self,
 8372        action: &SelectPrevious,
 8373        cx: &mut ViewContext<Self>,
 8374    ) -> Result<()> {
 8375        self.push_to_selection_history();
 8376        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8377        let buffer = &display_map.buffer_snapshot;
 8378        let mut selections = self.selections.all::<usize>(cx);
 8379        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8380            let query = &select_prev_state.query;
 8381            if !select_prev_state.done {
 8382                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8383                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8384                let mut next_selected_range = None;
 8385                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8386                let bytes_before_last_selection =
 8387                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8388                let bytes_after_first_selection =
 8389                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8390                let query_matches = query
 8391                    .stream_find_iter(bytes_before_last_selection)
 8392                    .map(|result| (last_selection.start, result))
 8393                    .chain(
 8394                        query
 8395                            .stream_find_iter(bytes_after_first_selection)
 8396                            .map(|result| (buffer.len(), result)),
 8397                    );
 8398                for (end_offset, query_match) in query_matches {
 8399                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8400                    let offset_range =
 8401                        end_offset - query_match.end()..end_offset - query_match.start();
 8402                    let display_range = offset_range.start.to_display_point(&display_map)
 8403                        ..offset_range.end.to_display_point(&display_map);
 8404
 8405                    if !select_prev_state.wordwise
 8406                        || (!movement::is_inside_word(&display_map, display_range.start)
 8407                            && !movement::is_inside_word(&display_map, display_range.end))
 8408                    {
 8409                        next_selected_range = Some(offset_range);
 8410                        break;
 8411                    }
 8412                }
 8413
 8414                if let Some(next_selected_range) = next_selected_range {
 8415                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8416                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8417                        if action.replace_newest {
 8418                            s.delete(s.newest_anchor().id);
 8419                        }
 8420                        s.insert_range(next_selected_range);
 8421                    });
 8422                } else {
 8423                    select_prev_state.done = true;
 8424                }
 8425            }
 8426
 8427            self.select_prev_state = Some(select_prev_state);
 8428        } else {
 8429            let mut only_carets = true;
 8430            let mut same_text_selected = true;
 8431            let mut selected_text = None;
 8432
 8433            let mut selections_iter = selections.iter().peekable();
 8434            while let Some(selection) = selections_iter.next() {
 8435                if selection.start != selection.end {
 8436                    only_carets = false;
 8437                }
 8438
 8439                if same_text_selected {
 8440                    if selected_text.is_none() {
 8441                        selected_text =
 8442                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8443                    }
 8444
 8445                    if let Some(next_selection) = selections_iter.peek() {
 8446                        if next_selection.range().len() == selection.range().len() {
 8447                            let next_selected_text = buffer
 8448                                .text_for_range(next_selection.range())
 8449                                .collect::<String>();
 8450                            if Some(next_selected_text) != selected_text {
 8451                                same_text_selected = false;
 8452                                selected_text = None;
 8453                            }
 8454                        } else {
 8455                            same_text_selected = false;
 8456                            selected_text = None;
 8457                        }
 8458                    }
 8459                }
 8460            }
 8461
 8462            if only_carets {
 8463                for selection in &mut selections {
 8464                    let word_range = movement::surrounding_word(
 8465                        &display_map,
 8466                        selection.start.to_display_point(&display_map),
 8467                    );
 8468                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8469                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8470                    selection.goal = SelectionGoal::None;
 8471                    selection.reversed = false;
 8472                }
 8473                if selections.len() == 1 {
 8474                    let selection = selections
 8475                        .last()
 8476                        .expect("ensured that there's only one selection");
 8477                    let query = buffer
 8478                        .text_for_range(selection.start..selection.end)
 8479                        .collect::<String>();
 8480                    let is_empty = query.is_empty();
 8481                    let select_state = SelectNextState {
 8482                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8483                        wordwise: true,
 8484                        done: is_empty,
 8485                    };
 8486                    self.select_prev_state = Some(select_state);
 8487                } else {
 8488                    self.select_prev_state = None;
 8489                }
 8490
 8491                self.unfold_ranges(
 8492                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8493                    false,
 8494                    true,
 8495                    cx,
 8496                );
 8497                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8498                    s.select(selections);
 8499                });
 8500            } else if let Some(selected_text) = selected_text {
 8501                self.select_prev_state = Some(SelectNextState {
 8502                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8503                    wordwise: false,
 8504                    done: false,
 8505                });
 8506                self.select_previous(action, cx)?;
 8507            }
 8508        }
 8509        Ok(())
 8510    }
 8511
 8512    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8513        if self.read_only(cx) {
 8514            return;
 8515        }
 8516        let text_layout_details = &self.text_layout_details(cx);
 8517        self.transact(cx, |this, cx| {
 8518            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8519            let mut edits = Vec::new();
 8520            let mut selection_edit_ranges = Vec::new();
 8521            let mut last_toggled_row = None;
 8522            let snapshot = this.buffer.read(cx).read(cx);
 8523            let empty_str: Arc<str> = Arc::default();
 8524            let mut suffixes_inserted = Vec::new();
 8525            let ignore_indent = action.ignore_indent;
 8526
 8527            fn comment_prefix_range(
 8528                snapshot: &MultiBufferSnapshot,
 8529                row: MultiBufferRow,
 8530                comment_prefix: &str,
 8531                comment_prefix_whitespace: &str,
 8532                ignore_indent: bool,
 8533            ) -> Range<Point> {
 8534                let indent_size = if ignore_indent {
 8535                    0
 8536                } else {
 8537                    snapshot.indent_size_for_line(row).len
 8538                };
 8539
 8540                let start = Point::new(row.0, indent_size);
 8541
 8542                let mut line_bytes = snapshot
 8543                    .bytes_in_range(start..snapshot.max_point())
 8544                    .flatten()
 8545                    .copied();
 8546
 8547                // If this line currently begins with the line comment prefix, then record
 8548                // the range containing the prefix.
 8549                if line_bytes
 8550                    .by_ref()
 8551                    .take(comment_prefix.len())
 8552                    .eq(comment_prefix.bytes())
 8553                {
 8554                    // Include any whitespace that matches the comment prefix.
 8555                    let matching_whitespace_len = line_bytes
 8556                        .zip(comment_prefix_whitespace.bytes())
 8557                        .take_while(|(a, b)| a == b)
 8558                        .count() as u32;
 8559                    let end = Point::new(
 8560                        start.row,
 8561                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8562                    );
 8563                    start..end
 8564                } else {
 8565                    start..start
 8566                }
 8567            }
 8568
 8569            fn comment_suffix_range(
 8570                snapshot: &MultiBufferSnapshot,
 8571                row: MultiBufferRow,
 8572                comment_suffix: &str,
 8573                comment_suffix_has_leading_space: bool,
 8574            ) -> Range<Point> {
 8575                let end = Point::new(row.0, snapshot.line_len(row));
 8576                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8577
 8578                let mut line_end_bytes = snapshot
 8579                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8580                    .flatten()
 8581                    .copied();
 8582
 8583                let leading_space_len = if suffix_start_column > 0
 8584                    && line_end_bytes.next() == Some(b' ')
 8585                    && comment_suffix_has_leading_space
 8586                {
 8587                    1
 8588                } else {
 8589                    0
 8590                };
 8591
 8592                // If this line currently begins with the line comment prefix, then record
 8593                // the range containing the prefix.
 8594                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8595                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8596                    start..end
 8597                } else {
 8598                    end..end
 8599                }
 8600            }
 8601
 8602            // TODO: Handle selections that cross excerpts
 8603            for selection in &mut selections {
 8604                let start_column = snapshot
 8605                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8606                    .len;
 8607                let language = if let Some(language) =
 8608                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8609                {
 8610                    language
 8611                } else {
 8612                    continue;
 8613                };
 8614
 8615                selection_edit_ranges.clear();
 8616
 8617                // If multiple selections contain a given row, avoid processing that
 8618                // row more than once.
 8619                let mut start_row = MultiBufferRow(selection.start.row);
 8620                if last_toggled_row == Some(start_row) {
 8621                    start_row = start_row.next_row();
 8622                }
 8623                let end_row =
 8624                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8625                        MultiBufferRow(selection.end.row - 1)
 8626                    } else {
 8627                        MultiBufferRow(selection.end.row)
 8628                    };
 8629                last_toggled_row = Some(end_row);
 8630
 8631                if start_row > end_row {
 8632                    continue;
 8633                }
 8634
 8635                // If the language has line comments, toggle those.
 8636                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8637
 8638                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8639                if ignore_indent {
 8640                    full_comment_prefixes = full_comment_prefixes
 8641                        .into_iter()
 8642                        .map(|s| Arc::from(s.trim_end()))
 8643                        .collect();
 8644                }
 8645
 8646                if !full_comment_prefixes.is_empty() {
 8647                    let first_prefix = full_comment_prefixes
 8648                        .first()
 8649                        .expect("prefixes is non-empty");
 8650                    let prefix_trimmed_lengths = full_comment_prefixes
 8651                        .iter()
 8652                        .map(|p| p.trim_end_matches(' ').len())
 8653                        .collect::<SmallVec<[usize; 4]>>();
 8654
 8655                    let mut all_selection_lines_are_comments = true;
 8656
 8657                    for row in start_row.0..=end_row.0 {
 8658                        let row = MultiBufferRow(row);
 8659                        if start_row < end_row && snapshot.is_line_blank(row) {
 8660                            continue;
 8661                        }
 8662
 8663                        let prefix_range = full_comment_prefixes
 8664                            .iter()
 8665                            .zip(prefix_trimmed_lengths.iter().copied())
 8666                            .map(|(prefix, trimmed_prefix_len)| {
 8667                                comment_prefix_range(
 8668                                    snapshot.deref(),
 8669                                    row,
 8670                                    &prefix[..trimmed_prefix_len],
 8671                                    &prefix[trimmed_prefix_len..],
 8672                                    ignore_indent,
 8673                                )
 8674                            })
 8675                            .max_by_key(|range| range.end.column - range.start.column)
 8676                            .expect("prefixes is non-empty");
 8677
 8678                        if prefix_range.is_empty() {
 8679                            all_selection_lines_are_comments = false;
 8680                        }
 8681
 8682                        selection_edit_ranges.push(prefix_range);
 8683                    }
 8684
 8685                    if all_selection_lines_are_comments {
 8686                        edits.extend(
 8687                            selection_edit_ranges
 8688                                .iter()
 8689                                .cloned()
 8690                                .map(|range| (range, empty_str.clone())),
 8691                        );
 8692                    } else {
 8693                        let min_column = selection_edit_ranges
 8694                            .iter()
 8695                            .map(|range| range.start.column)
 8696                            .min()
 8697                            .unwrap_or(0);
 8698                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8699                            let position = Point::new(range.start.row, min_column);
 8700                            (position..position, first_prefix.clone())
 8701                        }));
 8702                    }
 8703                } else if let Some((full_comment_prefix, comment_suffix)) =
 8704                    language.block_comment_delimiters()
 8705                {
 8706                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8707                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8708                    let prefix_range = comment_prefix_range(
 8709                        snapshot.deref(),
 8710                        start_row,
 8711                        comment_prefix,
 8712                        comment_prefix_whitespace,
 8713                        ignore_indent,
 8714                    );
 8715                    let suffix_range = comment_suffix_range(
 8716                        snapshot.deref(),
 8717                        end_row,
 8718                        comment_suffix.trim_start_matches(' '),
 8719                        comment_suffix.starts_with(' '),
 8720                    );
 8721
 8722                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8723                        edits.push((
 8724                            prefix_range.start..prefix_range.start,
 8725                            full_comment_prefix.clone(),
 8726                        ));
 8727                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8728                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8729                    } else {
 8730                        edits.push((prefix_range, empty_str.clone()));
 8731                        edits.push((suffix_range, empty_str.clone()));
 8732                    }
 8733                } else {
 8734                    continue;
 8735                }
 8736            }
 8737
 8738            drop(snapshot);
 8739            this.buffer.update(cx, |buffer, cx| {
 8740                buffer.edit(edits, None, cx);
 8741            });
 8742
 8743            // Adjust selections so that they end before any comment suffixes that
 8744            // were inserted.
 8745            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8746            let mut selections = this.selections.all::<Point>(cx);
 8747            let snapshot = this.buffer.read(cx).read(cx);
 8748            for selection in &mut selections {
 8749                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8750                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8751                        Ordering::Less => {
 8752                            suffixes_inserted.next();
 8753                            continue;
 8754                        }
 8755                        Ordering::Greater => break,
 8756                        Ordering::Equal => {
 8757                            if selection.end.column == snapshot.line_len(row) {
 8758                                if selection.is_empty() {
 8759                                    selection.start.column -= suffix_len as u32;
 8760                                }
 8761                                selection.end.column -= suffix_len as u32;
 8762                            }
 8763                            break;
 8764                        }
 8765                    }
 8766                }
 8767            }
 8768
 8769            drop(snapshot);
 8770            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8771
 8772            let selections = this.selections.all::<Point>(cx);
 8773            let selections_on_single_row = selections.windows(2).all(|selections| {
 8774                selections[0].start.row == selections[1].start.row
 8775                    && selections[0].end.row == selections[1].end.row
 8776                    && selections[0].start.row == selections[0].end.row
 8777            });
 8778            let selections_selecting = selections
 8779                .iter()
 8780                .any(|selection| selection.start != selection.end);
 8781            let advance_downwards = action.advance_downwards
 8782                && selections_on_single_row
 8783                && !selections_selecting
 8784                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8785
 8786            if advance_downwards {
 8787                let snapshot = this.buffer.read(cx).snapshot(cx);
 8788
 8789                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8790                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8791                        let mut point = display_point.to_point(display_snapshot);
 8792                        point.row += 1;
 8793                        point = snapshot.clip_point(point, Bias::Left);
 8794                        let display_point = point.to_display_point(display_snapshot);
 8795                        let goal = SelectionGoal::HorizontalPosition(
 8796                            display_snapshot
 8797                                .x_for_display_point(display_point, text_layout_details)
 8798                                .into(),
 8799                        );
 8800                        (display_point, goal)
 8801                    })
 8802                });
 8803            }
 8804        });
 8805    }
 8806
 8807    pub fn select_enclosing_symbol(
 8808        &mut self,
 8809        _: &SelectEnclosingSymbol,
 8810        cx: &mut ViewContext<Self>,
 8811    ) {
 8812        let buffer = self.buffer.read(cx).snapshot(cx);
 8813        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8814
 8815        fn update_selection(
 8816            selection: &Selection<usize>,
 8817            buffer_snap: &MultiBufferSnapshot,
 8818        ) -> Option<Selection<usize>> {
 8819            let cursor = selection.head();
 8820            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8821            for symbol in symbols.iter().rev() {
 8822                let start = symbol.range.start.to_offset(buffer_snap);
 8823                let end = symbol.range.end.to_offset(buffer_snap);
 8824                let new_range = start..end;
 8825                if start < selection.start || end > selection.end {
 8826                    return Some(Selection {
 8827                        id: selection.id,
 8828                        start: new_range.start,
 8829                        end: new_range.end,
 8830                        goal: SelectionGoal::None,
 8831                        reversed: selection.reversed,
 8832                    });
 8833                }
 8834            }
 8835            None
 8836        }
 8837
 8838        let mut selected_larger_symbol = false;
 8839        let new_selections = old_selections
 8840            .iter()
 8841            .map(|selection| match update_selection(selection, &buffer) {
 8842                Some(new_selection) => {
 8843                    if new_selection.range() != selection.range() {
 8844                        selected_larger_symbol = true;
 8845                    }
 8846                    new_selection
 8847                }
 8848                None => selection.clone(),
 8849            })
 8850            .collect::<Vec<_>>();
 8851
 8852        if selected_larger_symbol {
 8853            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8854                s.select(new_selections);
 8855            });
 8856        }
 8857    }
 8858
 8859    pub fn select_larger_syntax_node(
 8860        &mut self,
 8861        _: &SelectLargerSyntaxNode,
 8862        cx: &mut ViewContext<Self>,
 8863    ) {
 8864        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8865        let buffer = self.buffer.read(cx).snapshot(cx);
 8866        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8867
 8868        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8869        let mut selected_larger_node = false;
 8870        let new_selections = old_selections
 8871            .iter()
 8872            .map(|selection| {
 8873                let old_range = selection.start..selection.end;
 8874                let mut new_range = old_range.clone();
 8875                let mut new_node = None;
 8876                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 8877                {
 8878                    new_node = Some(node);
 8879                    new_range = containing_range;
 8880                    if !display_map.intersects_fold(new_range.start)
 8881                        && !display_map.intersects_fold(new_range.end)
 8882                    {
 8883                        break;
 8884                    }
 8885                }
 8886
 8887                if let Some(node) = new_node {
 8888                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 8889                    // nodes. Parent and grandparent are also logged because this operation will not
 8890                    // visit nodes that have the same range as their parent.
 8891                    log::info!("Node: {node:?}");
 8892                    let parent = node.parent();
 8893                    log::info!("Parent: {parent:?}");
 8894                    let grandparent = parent.and_then(|x| x.parent());
 8895                    log::info!("Grandparent: {grandparent:?}");
 8896                }
 8897
 8898                selected_larger_node |= new_range != old_range;
 8899                Selection {
 8900                    id: selection.id,
 8901                    start: new_range.start,
 8902                    end: new_range.end,
 8903                    goal: SelectionGoal::None,
 8904                    reversed: selection.reversed,
 8905                }
 8906            })
 8907            .collect::<Vec<_>>();
 8908
 8909        if selected_larger_node {
 8910            stack.push(old_selections);
 8911            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8912                s.select(new_selections);
 8913            });
 8914        }
 8915        self.select_larger_syntax_node_stack = stack;
 8916    }
 8917
 8918    pub fn select_smaller_syntax_node(
 8919        &mut self,
 8920        _: &SelectSmallerSyntaxNode,
 8921        cx: &mut ViewContext<Self>,
 8922    ) {
 8923        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8924        if let Some(selections) = stack.pop() {
 8925            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8926                s.select(selections.to_vec());
 8927            });
 8928        }
 8929        self.select_larger_syntax_node_stack = stack;
 8930    }
 8931
 8932    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8933        if !EditorSettings::get_global(cx).gutter.runnables {
 8934            self.clear_tasks();
 8935            return Task::ready(());
 8936        }
 8937        let project = self.project.as_ref().map(Model::downgrade);
 8938        cx.spawn(|this, mut cx| async move {
 8939            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 8940            let Some(project) = project.and_then(|p| p.upgrade()) else {
 8941                return;
 8942            };
 8943            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8944                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8945            }) else {
 8946                return;
 8947            };
 8948
 8949            let hide_runnables = project
 8950                .update(&mut cx, |project, cx| {
 8951                    // Do not display any test indicators in non-dev server remote projects.
 8952                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8953                })
 8954                .unwrap_or(true);
 8955            if hide_runnables {
 8956                return;
 8957            }
 8958            let new_rows =
 8959                cx.background_executor()
 8960                    .spawn({
 8961                        let snapshot = display_snapshot.clone();
 8962                        async move {
 8963                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8964                        }
 8965                    })
 8966                    .await;
 8967            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8968
 8969            this.update(&mut cx, |this, _| {
 8970                this.clear_tasks();
 8971                for (key, value) in rows {
 8972                    this.insert_tasks(key, value);
 8973                }
 8974            })
 8975            .ok();
 8976        })
 8977    }
 8978    fn fetch_runnable_ranges(
 8979        snapshot: &DisplaySnapshot,
 8980        range: Range<Anchor>,
 8981    ) -> Vec<language::RunnableRange> {
 8982        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8983    }
 8984
 8985    fn runnable_rows(
 8986        project: Model<Project>,
 8987        snapshot: DisplaySnapshot,
 8988        runnable_ranges: Vec<RunnableRange>,
 8989        mut cx: AsyncWindowContext,
 8990    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8991        runnable_ranges
 8992            .into_iter()
 8993            .filter_map(|mut runnable| {
 8994                let tasks = cx
 8995                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8996                    .ok()?;
 8997                if tasks.is_empty() {
 8998                    return None;
 8999                }
 9000
 9001                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9002
 9003                let row = snapshot
 9004                    .buffer_snapshot
 9005                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9006                    .1
 9007                    .start
 9008                    .row;
 9009
 9010                let context_range =
 9011                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9012                Some((
 9013                    (runnable.buffer_id, row),
 9014                    RunnableTasks {
 9015                        templates: tasks,
 9016                        offset: MultiBufferOffset(runnable.run_range.start),
 9017                        context_range,
 9018                        column: point.column,
 9019                        extra_variables: runnable.extra_captures,
 9020                    },
 9021                ))
 9022            })
 9023            .collect()
 9024    }
 9025
 9026    fn templates_with_tags(
 9027        project: &Model<Project>,
 9028        runnable: &mut Runnable,
 9029        cx: &WindowContext,
 9030    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9031        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9032            let (worktree_id, file) = project
 9033                .buffer_for_id(runnable.buffer, cx)
 9034                .and_then(|buffer| buffer.read(cx).file())
 9035                .map(|file| (file.worktree_id(cx), file.clone()))
 9036                .unzip();
 9037
 9038            (
 9039                project.task_store().read(cx).task_inventory().cloned(),
 9040                worktree_id,
 9041                file,
 9042            )
 9043        });
 9044
 9045        let tags = mem::take(&mut runnable.tags);
 9046        let mut tags: Vec<_> = tags
 9047            .into_iter()
 9048            .flat_map(|tag| {
 9049                let tag = tag.0.clone();
 9050                inventory
 9051                    .as_ref()
 9052                    .into_iter()
 9053                    .flat_map(|inventory| {
 9054                        inventory.read(cx).list_tasks(
 9055                            file.clone(),
 9056                            Some(runnable.language.clone()),
 9057                            worktree_id,
 9058                            cx,
 9059                        )
 9060                    })
 9061                    .filter(move |(_, template)| {
 9062                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9063                    })
 9064            })
 9065            .sorted_by_key(|(kind, _)| kind.to_owned())
 9066            .collect();
 9067        if let Some((leading_tag_source, _)) = tags.first() {
 9068            // Strongest source wins; if we have worktree tag binding, prefer that to
 9069            // global and language bindings;
 9070            // if we have a global binding, prefer that to language binding.
 9071            let first_mismatch = tags
 9072                .iter()
 9073                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9074            if let Some(index) = first_mismatch {
 9075                tags.truncate(index);
 9076            }
 9077        }
 9078
 9079        tags
 9080    }
 9081
 9082    pub fn move_to_enclosing_bracket(
 9083        &mut self,
 9084        _: &MoveToEnclosingBracket,
 9085        cx: &mut ViewContext<Self>,
 9086    ) {
 9087        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9088            s.move_offsets_with(|snapshot, selection| {
 9089                let Some(enclosing_bracket_ranges) =
 9090                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9091                else {
 9092                    return;
 9093                };
 9094
 9095                let mut best_length = usize::MAX;
 9096                let mut best_inside = false;
 9097                let mut best_in_bracket_range = false;
 9098                let mut best_destination = None;
 9099                for (open, close) in enclosing_bracket_ranges {
 9100                    let close = close.to_inclusive();
 9101                    let length = close.end() - open.start;
 9102                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9103                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9104                        || close.contains(&selection.head());
 9105
 9106                    // If best is next to a bracket and current isn't, skip
 9107                    if !in_bracket_range && best_in_bracket_range {
 9108                        continue;
 9109                    }
 9110
 9111                    // Prefer smaller lengths unless best is inside and current isn't
 9112                    if length > best_length && (best_inside || !inside) {
 9113                        continue;
 9114                    }
 9115
 9116                    best_length = length;
 9117                    best_inside = inside;
 9118                    best_in_bracket_range = in_bracket_range;
 9119                    best_destination = Some(
 9120                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9121                            if inside {
 9122                                open.end
 9123                            } else {
 9124                                open.start
 9125                            }
 9126                        } else if inside {
 9127                            *close.start()
 9128                        } else {
 9129                            *close.end()
 9130                        },
 9131                    );
 9132                }
 9133
 9134                if let Some(destination) = best_destination {
 9135                    selection.collapse_to(destination, SelectionGoal::None);
 9136                }
 9137            })
 9138        });
 9139    }
 9140
 9141    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9142        self.end_selection(cx);
 9143        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9144        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9145            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9146            self.select_next_state = entry.select_next_state;
 9147            self.select_prev_state = entry.select_prev_state;
 9148            self.add_selections_state = entry.add_selections_state;
 9149            self.request_autoscroll(Autoscroll::newest(), cx);
 9150        }
 9151        self.selection_history.mode = SelectionHistoryMode::Normal;
 9152    }
 9153
 9154    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9155        self.end_selection(cx);
 9156        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9157        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9158            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9159            self.select_next_state = entry.select_next_state;
 9160            self.select_prev_state = entry.select_prev_state;
 9161            self.add_selections_state = entry.add_selections_state;
 9162            self.request_autoscroll(Autoscroll::newest(), cx);
 9163        }
 9164        self.selection_history.mode = SelectionHistoryMode::Normal;
 9165    }
 9166
 9167    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9168        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9169    }
 9170
 9171    pub fn expand_excerpts_down(
 9172        &mut self,
 9173        action: &ExpandExcerptsDown,
 9174        cx: &mut ViewContext<Self>,
 9175    ) {
 9176        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9177    }
 9178
 9179    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9180        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9181    }
 9182
 9183    pub fn expand_excerpts_for_direction(
 9184        &mut self,
 9185        lines: u32,
 9186        direction: ExpandExcerptDirection,
 9187        cx: &mut ViewContext<Self>,
 9188    ) {
 9189        let selections = self.selections.disjoint_anchors();
 9190
 9191        let lines = if lines == 0 {
 9192            EditorSettings::get_global(cx).expand_excerpt_lines
 9193        } else {
 9194            lines
 9195        };
 9196
 9197        self.buffer.update(cx, |buffer, cx| {
 9198            let snapshot = buffer.snapshot(cx);
 9199            let mut excerpt_ids = selections
 9200                .iter()
 9201                .flat_map(|selection| {
 9202                    snapshot
 9203                        .excerpts_for_range(selection.range())
 9204                        .map(|excerpt| excerpt.id())
 9205                })
 9206                .collect::<Vec<_>>();
 9207            excerpt_ids.sort();
 9208            excerpt_ids.dedup();
 9209            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
 9210        })
 9211    }
 9212
 9213    pub fn expand_excerpt(
 9214        &mut self,
 9215        excerpt: ExcerptId,
 9216        direction: ExpandExcerptDirection,
 9217        cx: &mut ViewContext<Self>,
 9218    ) {
 9219        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9220        self.buffer.update(cx, |buffer, cx| {
 9221            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9222        })
 9223    }
 9224
 9225    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9226        self.go_to_diagnostic_impl(Direction::Next, cx)
 9227    }
 9228
 9229    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9230        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9231    }
 9232
 9233    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9234        let buffer = self.buffer.read(cx).snapshot(cx);
 9235        let selection = self.selections.newest::<usize>(cx);
 9236
 9237        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9238        if direction == Direction::Next {
 9239            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9240                self.activate_diagnostics(popover.group_id(), cx);
 9241                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
 9242                    let primary_range_start = active_diagnostics.primary_range.start;
 9243                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9244                        let mut new_selection = s.newest_anchor().clone();
 9245                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
 9246                        s.select_anchors(vec![new_selection.clone()]);
 9247                    });
 9248                }
 9249                return;
 9250            }
 9251        }
 9252
 9253        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9254            active_diagnostics
 9255                .primary_range
 9256                .to_offset(&buffer)
 9257                .to_inclusive()
 9258        });
 9259        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9260            if active_primary_range.contains(&selection.head()) {
 9261                *active_primary_range.start()
 9262            } else {
 9263                selection.head()
 9264            }
 9265        } else {
 9266            selection.head()
 9267        };
 9268        let snapshot = self.snapshot(cx);
 9269        loop {
 9270            let diagnostics = if direction == Direction::Prev {
 9271                buffer.diagnostics_in_range(0..search_start, true)
 9272            } else {
 9273                buffer.diagnostics_in_range(search_start..buffer.len(), false)
 9274            }
 9275            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9276            let search_start_anchor = buffer.anchor_after(search_start);
 9277            let group = diagnostics
 9278                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9279                // be sorted in a stable way
 9280                // skip until we are at current active diagnostic, if it exists
 9281                .skip_while(|entry| {
 9282                    let is_in_range = match direction {
 9283                        Direction::Prev => {
 9284                            entry.range.start.cmp(&search_start_anchor, &buffer).is_ge()
 9285                        }
 9286                        Direction::Next => {
 9287                            entry.range.start.cmp(&search_start_anchor, &buffer).is_le()
 9288                        }
 9289                    };
 9290                    is_in_range
 9291                        && self
 9292                            .active_diagnostics
 9293                            .as_ref()
 9294                            .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9295                })
 9296                .find_map(|entry| {
 9297                    if entry.diagnostic.is_primary
 9298                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9299                        && !(entry.range.start == entry.range.end)
 9300                        // if we match with the active diagnostic, skip it
 9301                        && Some(entry.diagnostic.group_id)
 9302                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9303                    {
 9304                        Some((entry.range, entry.diagnostic.group_id))
 9305                    } else {
 9306                        None
 9307                    }
 9308                });
 9309
 9310            if let Some((primary_range, group_id)) = group {
 9311                self.activate_diagnostics(group_id, cx);
 9312                let primary_range = primary_range.to_offset(&buffer);
 9313                if self.active_diagnostics.is_some() {
 9314                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9315                        s.select(vec![Selection {
 9316                            id: selection.id,
 9317                            start: primary_range.start,
 9318                            end: primary_range.start,
 9319                            reversed: false,
 9320                            goal: SelectionGoal::None,
 9321                        }]);
 9322                    });
 9323                }
 9324                break;
 9325            } else {
 9326                // Cycle around to the start of the buffer, potentially moving back to the start of
 9327                // the currently active diagnostic.
 9328                active_primary_range.take();
 9329                if direction == Direction::Prev {
 9330                    if search_start == buffer.len() {
 9331                        break;
 9332                    } else {
 9333                        search_start = buffer.len();
 9334                    }
 9335                } else if search_start == 0 {
 9336                    break;
 9337                } else {
 9338                    search_start = 0;
 9339                }
 9340            }
 9341        }
 9342    }
 9343
 9344    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9345        let snapshot = self.snapshot(cx);
 9346        let selection = self.selections.newest::<Point>(cx);
 9347        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9348    }
 9349
 9350    fn go_to_hunk_after_position(
 9351        &mut self,
 9352        snapshot: &EditorSnapshot,
 9353        position: Point,
 9354        cx: &mut ViewContext<Editor>,
 9355    ) -> Option<MultiBufferDiffHunk> {
 9356        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9357            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9358                snapshot,
 9359                position,
 9360                ix > 0,
 9361                snapshot.diff_map.diff_hunks_in_range(
 9362                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9363                    &snapshot.buffer_snapshot,
 9364                ),
 9365                cx,
 9366            ) {
 9367                return Some(hunk);
 9368            }
 9369        }
 9370        None
 9371    }
 9372
 9373    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9374        let snapshot = self.snapshot(cx);
 9375        let selection = self.selections.newest::<Point>(cx);
 9376        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9377    }
 9378
 9379    fn go_to_hunk_before_position(
 9380        &mut self,
 9381        snapshot: &EditorSnapshot,
 9382        position: Point,
 9383        cx: &mut ViewContext<Editor>,
 9384    ) -> Option<MultiBufferDiffHunk> {
 9385        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9386            .into_iter()
 9387            .enumerate()
 9388        {
 9389            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9390                snapshot,
 9391                position,
 9392                ix > 0,
 9393                snapshot
 9394                    .diff_map
 9395                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9396                cx,
 9397            ) {
 9398                return Some(hunk);
 9399            }
 9400        }
 9401        None
 9402    }
 9403
 9404    fn go_to_next_hunk_in_direction(
 9405        &mut self,
 9406        snapshot: &DisplaySnapshot,
 9407        initial_point: Point,
 9408        is_wrapped: bool,
 9409        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9410        cx: &mut ViewContext<Editor>,
 9411    ) -> Option<MultiBufferDiffHunk> {
 9412        let display_point = initial_point.to_display_point(snapshot);
 9413        let mut hunks = hunks
 9414            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9415            .filter(|(display_hunk, _)| {
 9416                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9417            })
 9418            .dedup();
 9419
 9420        if let Some((display_hunk, hunk)) = hunks.next() {
 9421            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9422                let row = display_hunk.start_display_row();
 9423                let point = DisplayPoint::new(row, 0);
 9424                s.select_display_ranges([point..point]);
 9425            });
 9426
 9427            Some(hunk)
 9428        } else {
 9429            None
 9430        }
 9431    }
 9432
 9433    pub fn go_to_definition(
 9434        &mut self,
 9435        _: &GoToDefinition,
 9436        cx: &mut ViewContext<Self>,
 9437    ) -> Task<Result<Navigated>> {
 9438        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9439        cx.spawn(|editor, mut cx| async move {
 9440            if definition.await? == Navigated::Yes {
 9441                return Ok(Navigated::Yes);
 9442            }
 9443            match editor.update(&mut cx, |editor, cx| {
 9444                editor.find_all_references(&FindAllReferences, cx)
 9445            })? {
 9446                Some(references) => references.await,
 9447                None => Ok(Navigated::No),
 9448            }
 9449        })
 9450    }
 9451
 9452    pub fn go_to_declaration(
 9453        &mut self,
 9454        _: &GoToDeclaration,
 9455        cx: &mut ViewContext<Self>,
 9456    ) -> Task<Result<Navigated>> {
 9457        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9458    }
 9459
 9460    pub fn go_to_declaration_split(
 9461        &mut self,
 9462        _: &GoToDeclaration,
 9463        cx: &mut ViewContext<Self>,
 9464    ) -> Task<Result<Navigated>> {
 9465        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9466    }
 9467
 9468    pub fn go_to_implementation(
 9469        &mut self,
 9470        _: &GoToImplementation,
 9471        cx: &mut ViewContext<Self>,
 9472    ) -> Task<Result<Navigated>> {
 9473        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9474    }
 9475
 9476    pub fn go_to_implementation_split(
 9477        &mut self,
 9478        _: &GoToImplementationSplit,
 9479        cx: &mut ViewContext<Self>,
 9480    ) -> Task<Result<Navigated>> {
 9481        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9482    }
 9483
 9484    pub fn go_to_type_definition(
 9485        &mut self,
 9486        _: &GoToTypeDefinition,
 9487        cx: &mut ViewContext<Self>,
 9488    ) -> Task<Result<Navigated>> {
 9489        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9490    }
 9491
 9492    pub fn go_to_definition_split(
 9493        &mut self,
 9494        _: &GoToDefinitionSplit,
 9495        cx: &mut ViewContext<Self>,
 9496    ) -> Task<Result<Navigated>> {
 9497        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9498    }
 9499
 9500    pub fn go_to_type_definition_split(
 9501        &mut self,
 9502        _: &GoToTypeDefinitionSplit,
 9503        cx: &mut ViewContext<Self>,
 9504    ) -> Task<Result<Navigated>> {
 9505        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9506    }
 9507
 9508    fn go_to_definition_of_kind(
 9509        &mut self,
 9510        kind: GotoDefinitionKind,
 9511        split: bool,
 9512        cx: &mut ViewContext<Self>,
 9513    ) -> Task<Result<Navigated>> {
 9514        let Some(provider) = self.semantics_provider.clone() else {
 9515            return Task::ready(Ok(Navigated::No));
 9516        };
 9517        let head = self.selections.newest::<usize>(cx).head();
 9518        let buffer = self.buffer.read(cx);
 9519        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9520            text_anchor
 9521        } else {
 9522            return Task::ready(Ok(Navigated::No));
 9523        };
 9524
 9525        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9526            return Task::ready(Ok(Navigated::No));
 9527        };
 9528
 9529        cx.spawn(|editor, mut cx| async move {
 9530            let definitions = definitions.await?;
 9531            let navigated = editor
 9532                .update(&mut cx, |editor, cx| {
 9533                    editor.navigate_to_hover_links(
 9534                        Some(kind),
 9535                        definitions
 9536                            .into_iter()
 9537                            .filter(|location| {
 9538                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9539                            })
 9540                            .map(HoverLink::Text)
 9541                            .collect::<Vec<_>>(),
 9542                        split,
 9543                        cx,
 9544                    )
 9545                })?
 9546                .await?;
 9547            anyhow::Ok(navigated)
 9548        })
 9549    }
 9550
 9551    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9552        let selection = self.selections.newest_anchor();
 9553        let head = selection.head();
 9554        let tail = selection.tail();
 9555
 9556        let Some((buffer, start_position)) =
 9557            self.buffer.read(cx).text_anchor_for_position(head, cx)
 9558        else {
 9559            return;
 9560        };
 9561
 9562        let end_position = if head != tail {
 9563            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
 9564                return;
 9565            };
 9566            Some(pos)
 9567        } else {
 9568            None
 9569        };
 9570
 9571        let url_finder = cx.spawn(|editor, mut cx| async move {
 9572            let url = if let Some(end_pos) = end_position {
 9573                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
 9574            } else {
 9575                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
 9576            };
 9577
 9578            if let Some(url) = url {
 9579                editor.update(&mut cx, |_, cx| {
 9580                    cx.open_url(&url);
 9581                })
 9582            } else {
 9583                Ok(())
 9584            }
 9585        });
 9586
 9587        url_finder.detach();
 9588    }
 9589
 9590    pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
 9591        let Some(workspace) = self.workspace() else {
 9592            return;
 9593        };
 9594
 9595        let position = self.selections.newest_anchor().head();
 9596
 9597        let Some((buffer, buffer_position)) =
 9598            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9599        else {
 9600            return;
 9601        };
 9602
 9603        let project = self.project.clone();
 9604
 9605        cx.spawn(|_, mut cx| async move {
 9606            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9607
 9608            if let Some((_, path)) = result {
 9609                workspace
 9610                    .update(&mut cx, |workspace, cx| {
 9611                        workspace.open_resolved_path(path, cx)
 9612                    })?
 9613                    .await?;
 9614            }
 9615            anyhow::Ok(())
 9616        })
 9617        .detach();
 9618    }
 9619
 9620    pub(crate) fn navigate_to_hover_links(
 9621        &mut self,
 9622        kind: Option<GotoDefinitionKind>,
 9623        mut definitions: Vec<HoverLink>,
 9624        split: bool,
 9625        cx: &mut ViewContext<Editor>,
 9626    ) -> Task<Result<Navigated>> {
 9627        // If there is one definition, just open it directly
 9628        if definitions.len() == 1 {
 9629            let definition = definitions.pop().unwrap();
 9630
 9631            enum TargetTaskResult {
 9632                Location(Option<Location>),
 9633                AlreadyNavigated,
 9634            }
 9635
 9636            let target_task = match definition {
 9637                HoverLink::Text(link) => {
 9638                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9639                }
 9640                HoverLink::InlayHint(lsp_location, server_id) => {
 9641                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9642                    cx.background_executor().spawn(async move {
 9643                        let location = computation.await?;
 9644                        Ok(TargetTaskResult::Location(location))
 9645                    })
 9646                }
 9647                HoverLink::Url(url) => {
 9648                    cx.open_url(&url);
 9649                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9650                }
 9651                HoverLink::File(path) => {
 9652                    if let Some(workspace) = self.workspace() {
 9653                        cx.spawn(|_, mut cx| async move {
 9654                            workspace
 9655                                .update(&mut cx, |workspace, cx| {
 9656                                    workspace.open_resolved_path(path, cx)
 9657                                })?
 9658                                .await
 9659                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9660                        })
 9661                    } else {
 9662                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9663                    }
 9664                }
 9665            };
 9666            cx.spawn(|editor, mut cx| async move {
 9667                let target = match target_task.await.context("target resolution task")? {
 9668                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9669                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9670                    TargetTaskResult::Location(Some(target)) => target,
 9671                };
 9672
 9673                editor.update(&mut cx, |editor, cx| {
 9674                    let Some(workspace) = editor.workspace() else {
 9675                        return Navigated::No;
 9676                    };
 9677                    let pane = workspace.read(cx).active_pane().clone();
 9678
 9679                    let range = target.range.to_offset(target.buffer.read(cx));
 9680                    let range = editor.range_for_match(&range);
 9681
 9682                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9683                        let buffer = target.buffer.read(cx);
 9684                        let range = check_multiline_range(buffer, range);
 9685                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9686                            s.select_ranges([range]);
 9687                        });
 9688                    } else {
 9689                        cx.window_context().defer(move |cx| {
 9690                            let target_editor: View<Self> =
 9691                                workspace.update(cx, |workspace, cx| {
 9692                                    let pane = if split {
 9693                                        workspace.adjacent_pane(cx)
 9694                                    } else {
 9695                                        workspace.active_pane().clone()
 9696                                    };
 9697
 9698                                    workspace.open_project_item(
 9699                                        pane,
 9700                                        target.buffer.clone(),
 9701                                        true,
 9702                                        true,
 9703                                        cx,
 9704                                    )
 9705                                });
 9706                            target_editor.update(cx, |target_editor, cx| {
 9707                                // When selecting a definition in a different buffer, disable the nav history
 9708                                // to avoid creating a history entry at the previous cursor location.
 9709                                pane.update(cx, |pane, _| pane.disable_history());
 9710                                let buffer = target.buffer.read(cx);
 9711                                let range = check_multiline_range(buffer, range);
 9712                                target_editor.change_selections(
 9713                                    Some(Autoscroll::focused()),
 9714                                    cx,
 9715                                    |s| {
 9716                                        s.select_ranges([range]);
 9717                                    },
 9718                                );
 9719                                pane.update(cx, |pane, _| pane.enable_history());
 9720                            });
 9721                        });
 9722                    }
 9723                    Navigated::Yes
 9724                })
 9725            })
 9726        } else if !definitions.is_empty() {
 9727            cx.spawn(|editor, mut cx| async move {
 9728                let (title, location_tasks, workspace) = editor
 9729                    .update(&mut cx, |editor, cx| {
 9730                        let tab_kind = match kind {
 9731                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9732                            _ => "Definitions",
 9733                        };
 9734                        let title = definitions
 9735                            .iter()
 9736                            .find_map(|definition| match definition {
 9737                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9738                                    let buffer = origin.buffer.read(cx);
 9739                                    format!(
 9740                                        "{} for {}",
 9741                                        tab_kind,
 9742                                        buffer
 9743                                            .text_for_range(origin.range.clone())
 9744                                            .collect::<String>()
 9745                                    )
 9746                                }),
 9747                                HoverLink::InlayHint(_, _) => None,
 9748                                HoverLink::Url(_) => None,
 9749                                HoverLink::File(_) => None,
 9750                            })
 9751                            .unwrap_or(tab_kind.to_string());
 9752                        let location_tasks = definitions
 9753                            .into_iter()
 9754                            .map(|definition| match definition {
 9755                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
 9756                                HoverLink::InlayHint(lsp_location, server_id) => {
 9757                                    editor.compute_target_location(lsp_location, server_id, cx)
 9758                                }
 9759                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9760                                HoverLink::File(_) => Task::ready(Ok(None)),
 9761                            })
 9762                            .collect::<Vec<_>>();
 9763                        (title, location_tasks, editor.workspace().clone())
 9764                    })
 9765                    .context("location tasks preparation")?;
 9766
 9767                let locations = future::join_all(location_tasks)
 9768                    .await
 9769                    .into_iter()
 9770                    .filter_map(|location| location.transpose())
 9771                    .collect::<Result<_>>()
 9772                    .context("location tasks")?;
 9773
 9774                let Some(workspace) = workspace else {
 9775                    return Ok(Navigated::No);
 9776                };
 9777                let opened = workspace
 9778                    .update(&mut cx, |workspace, cx| {
 9779                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9780                    })
 9781                    .ok();
 9782
 9783                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9784            })
 9785        } else {
 9786            Task::ready(Ok(Navigated::No))
 9787        }
 9788    }
 9789
 9790    fn compute_target_location(
 9791        &self,
 9792        lsp_location: lsp::Location,
 9793        server_id: LanguageServerId,
 9794        cx: &mut ViewContext<Self>,
 9795    ) -> Task<anyhow::Result<Option<Location>>> {
 9796        let Some(project) = self.project.clone() else {
 9797            return Task::ready(Ok(None));
 9798        };
 9799
 9800        cx.spawn(move |editor, mut cx| async move {
 9801            let location_task = editor.update(&mut cx, |_, cx| {
 9802                project.update(cx, |project, cx| {
 9803                    let language_server_name = project
 9804                        .language_server_statuses(cx)
 9805                        .find(|(id, _)| server_id == *id)
 9806                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9807                    language_server_name.map(|language_server_name| {
 9808                        project.open_local_buffer_via_lsp(
 9809                            lsp_location.uri.clone(),
 9810                            server_id,
 9811                            language_server_name,
 9812                            cx,
 9813                        )
 9814                    })
 9815                })
 9816            })?;
 9817            let location = match location_task {
 9818                Some(task) => Some({
 9819                    let target_buffer_handle = task.await.context("open local buffer")?;
 9820                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9821                        let target_start = target_buffer
 9822                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9823                        let target_end = target_buffer
 9824                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9825                        target_buffer.anchor_after(target_start)
 9826                            ..target_buffer.anchor_before(target_end)
 9827                    })?;
 9828                    Location {
 9829                        buffer: target_buffer_handle,
 9830                        range,
 9831                    }
 9832                }),
 9833                None => None,
 9834            };
 9835            Ok(location)
 9836        })
 9837    }
 9838
 9839    pub fn find_all_references(
 9840        &mut self,
 9841        _: &FindAllReferences,
 9842        cx: &mut ViewContext<Self>,
 9843    ) -> Option<Task<Result<Navigated>>> {
 9844        let selection = self.selections.newest::<usize>(cx);
 9845        let multi_buffer = self.buffer.read(cx);
 9846        let head = selection.head();
 9847
 9848        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9849        let head_anchor = multi_buffer_snapshot.anchor_at(
 9850            head,
 9851            if head < selection.tail() {
 9852                Bias::Right
 9853            } else {
 9854                Bias::Left
 9855            },
 9856        );
 9857
 9858        match self
 9859            .find_all_references_task_sources
 9860            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9861        {
 9862            Ok(_) => {
 9863                log::info!(
 9864                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9865                );
 9866                return None;
 9867            }
 9868            Err(i) => {
 9869                self.find_all_references_task_sources.insert(i, head_anchor);
 9870            }
 9871        }
 9872
 9873        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9874        let workspace = self.workspace()?;
 9875        let project = workspace.read(cx).project().clone();
 9876        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9877        Some(cx.spawn(|editor, mut cx| async move {
 9878            let _cleanup = defer({
 9879                let mut cx = cx.clone();
 9880                move || {
 9881                    let _ = editor.update(&mut cx, |editor, _| {
 9882                        if let Ok(i) =
 9883                            editor
 9884                                .find_all_references_task_sources
 9885                                .binary_search_by(|anchor| {
 9886                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9887                                })
 9888                        {
 9889                            editor.find_all_references_task_sources.remove(i);
 9890                        }
 9891                    });
 9892                }
 9893            });
 9894
 9895            let locations = references.await?;
 9896            if locations.is_empty() {
 9897                return anyhow::Ok(Navigated::No);
 9898            }
 9899
 9900            workspace.update(&mut cx, |workspace, cx| {
 9901                let title = locations
 9902                    .first()
 9903                    .as_ref()
 9904                    .map(|location| {
 9905                        let buffer = location.buffer.read(cx);
 9906                        format!(
 9907                            "References to `{}`",
 9908                            buffer
 9909                                .text_for_range(location.range.clone())
 9910                                .collect::<String>()
 9911                        )
 9912                    })
 9913                    .unwrap();
 9914                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9915                Navigated::Yes
 9916            })
 9917        }))
 9918    }
 9919
 9920    /// Opens a multibuffer with the given project locations in it
 9921    pub fn open_locations_in_multibuffer(
 9922        workspace: &mut Workspace,
 9923        mut locations: Vec<Location>,
 9924        title: String,
 9925        split: bool,
 9926        cx: &mut ViewContext<Workspace>,
 9927    ) {
 9928        // If there are multiple definitions, open them in a multibuffer
 9929        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9930        let mut locations = locations.into_iter().peekable();
 9931        let mut ranges_to_highlight = Vec::new();
 9932        let capability = workspace.project().read(cx).capability();
 9933
 9934        let excerpt_buffer = cx.new_model(|cx| {
 9935            let mut multibuffer = MultiBuffer::new(capability);
 9936            while let Some(location) = locations.next() {
 9937                let buffer = location.buffer.read(cx);
 9938                let mut ranges_for_buffer = Vec::new();
 9939                let range = location.range.to_offset(buffer);
 9940                ranges_for_buffer.push(range.clone());
 9941
 9942                while let Some(next_location) = locations.peek() {
 9943                    if next_location.buffer == location.buffer {
 9944                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9945                        locations.next();
 9946                    } else {
 9947                        break;
 9948                    }
 9949                }
 9950
 9951                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9952                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9953                    location.buffer.clone(),
 9954                    ranges_for_buffer,
 9955                    DEFAULT_MULTIBUFFER_CONTEXT,
 9956                    cx,
 9957                ))
 9958            }
 9959
 9960            multibuffer.with_title(title)
 9961        });
 9962
 9963        let editor = cx.new_view(|cx| {
 9964            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9965        });
 9966        editor.update(cx, |editor, cx| {
 9967            if let Some(first_range) = ranges_to_highlight.first() {
 9968                editor.change_selections(None, cx, |selections| {
 9969                    selections.clear_disjoint();
 9970                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9971                });
 9972            }
 9973            editor.highlight_background::<Self>(
 9974                &ranges_to_highlight,
 9975                |theme| theme.editor_highlighted_line_background,
 9976                cx,
 9977            );
 9978            editor.register_buffers_with_language_servers(cx);
 9979        });
 9980
 9981        let item = Box::new(editor);
 9982        let item_id = item.item_id();
 9983
 9984        if split {
 9985            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9986        } else {
 9987            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9988                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9989                    pane.close_current_preview_item(cx)
 9990                } else {
 9991                    None
 9992                }
 9993            });
 9994            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9995        }
 9996        workspace.active_pane().update(cx, |pane, cx| {
 9997            pane.set_preview_item_id(Some(item_id), cx);
 9998        });
 9999    }
10000
10001    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10002        use language::ToOffset as _;
10003
10004        let provider = self.semantics_provider.clone()?;
10005        let selection = self.selections.newest_anchor().clone();
10006        let (cursor_buffer, cursor_buffer_position) = self
10007            .buffer
10008            .read(cx)
10009            .text_anchor_for_position(selection.head(), cx)?;
10010        let (tail_buffer, cursor_buffer_position_end) = self
10011            .buffer
10012            .read(cx)
10013            .text_anchor_for_position(selection.tail(), cx)?;
10014        if tail_buffer != cursor_buffer {
10015            return None;
10016        }
10017
10018        let snapshot = cursor_buffer.read(cx).snapshot();
10019        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10020        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10021        let prepare_rename = provider
10022            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10023            .unwrap_or_else(|| Task::ready(Ok(None)));
10024        drop(snapshot);
10025
10026        Some(cx.spawn(|this, mut cx| async move {
10027            let rename_range = if let Some(range) = prepare_rename.await? {
10028                Some(range)
10029            } else {
10030                this.update(&mut cx, |this, cx| {
10031                    let buffer = this.buffer.read(cx).snapshot(cx);
10032                    let mut buffer_highlights = this
10033                        .document_highlights_for_position(selection.head(), &buffer)
10034                        .filter(|highlight| {
10035                            highlight.start.excerpt_id == selection.head().excerpt_id
10036                                && highlight.end.excerpt_id == selection.head().excerpt_id
10037                        });
10038                    buffer_highlights
10039                        .next()
10040                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10041                })?
10042            };
10043            if let Some(rename_range) = rename_range {
10044                this.update(&mut cx, |this, cx| {
10045                    let snapshot = cursor_buffer.read(cx).snapshot();
10046                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10047                    let cursor_offset_in_rename_range =
10048                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10049                    let cursor_offset_in_rename_range_end =
10050                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10051
10052                    this.take_rename(false, cx);
10053                    let buffer = this.buffer.read(cx).read(cx);
10054                    let cursor_offset = selection.head().to_offset(&buffer);
10055                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10056                    let rename_end = rename_start + rename_buffer_range.len();
10057                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10058                    let mut old_highlight_id = None;
10059                    let old_name: Arc<str> = buffer
10060                        .chunks(rename_start..rename_end, true)
10061                        .map(|chunk| {
10062                            if old_highlight_id.is_none() {
10063                                old_highlight_id = chunk.syntax_highlight_id;
10064                            }
10065                            chunk.text
10066                        })
10067                        .collect::<String>()
10068                        .into();
10069
10070                    drop(buffer);
10071
10072                    // Position the selection in the rename editor so that it matches the current selection.
10073                    this.show_local_selections = false;
10074                    let rename_editor = cx.new_view(|cx| {
10075                        let mut editor = Editor::single_line(cx);
10076                        editor.buffer.update(cx, |buffer, cx| {
10077                            buffer.edit([(0..0, old_name.clone())], None, cx)
10078                        });
10079                        let rename_selection_range = match cursor_offset_in_rename_range
10080                            .cmp(&cursor_offset_in_rename_range_end)
10081                        {
10082                            Ordering::Equal => {
10083                                editor.select_all(&SelectAll, cx);
10084                                return editor;
10085                            }
10086                            Ordering::Less => {
10087                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10088                            }
10089                            Ordering::Greater => {
10090                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10091                            }
10092                        };
10093                        if rename_selection_range.end > old_name.len() {
10094                            editor.select_all(&SelectAll, cx);
10095                        } else {
10096                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10097                                s.select_ranges([rename_selection_range]);
10098                            });
10099                        }
10100                        editor
10101                    });
10102                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10103                        if e == &EditorEvent::Focused {
10104                            cx.emit(EditorEvent::FocusedIn)
10105                        }
10106                    })
10107                    .detach();
10108
10109                    let write_highlights =
10110                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10111                    let read_highlights =
10112                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10113                    let ranges = write_highlights
10114                        .iter()
10115                        .flat_map(|(_, ranges)| ranges.iter())
10116                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10117                        .cloned()
10118                        .collect();
10119
10120                    this.highlight_text::<Rename>(
10121                        ranges,
10122                        HighlightStyle {
10123                            fade_out: Some(0.6),
10124                            ..Default::default()
10125                        },
10126                        cx,
10127                    );
10128                    let rename_focus_handle = rename_editor.focus_handle(cx);
10129                    cx.focus(&rename_focus_handle);
10130                    let block_id = this.insert_blocks(
10131                        [BlockProperties {
10132                            style: BlockStyle::Flex,
10133                            placement: BlockPlacement::Below(range.start),
10134                            height: 1,
10135                            render: Arc::new({
10136                                let rename_editor = rename_editor.clone();
10137                                move |cx: &mut BlockContext| {
10138                                    let mut text_style = cx.editor_style.text.clone();
10139                                    if let Some(highlight_style) = old_highlight_id
10140                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10141                                    {
10142                                        text_style = text_style.highlight(highlight_style);
10143                                    }
10144                                    div()
10145                                        .block_mouse_down()
10146                                        .pl(cx.anchor_x)
10147                                        .child(EditorElement::new(
10148                                            &rename_editor,
10149                                            EditorStyle {
10150                                                background: cx.theme().system().transparent,
10151                                                local_player: cx.editor_style.local_player,
10152                                                text: text_style,
10153                                                scrollbar_width: cx.editor_style.scrollbar_width,
10154                                                syntax: cx.editor_style.syntax.clone(),
10155                                                status: cx.editor_style.status.clone(),
10156                                                inlay_hints_style: HighlightStyle {
10157                                                    font_weight: Some(FontWeight::BOLD),
10158                                                    ..make_inlay_hints_style(cx)
10159                                                },
10160                                                inline_completion_styles: make_suggestion_styles(
10161                                                    cx,
10162                                                ),
10163                                                ..EditorStyle::default()
10164                                            },
10165                                        ))
10166                                        .into_any_element()
10167                                }
10168                            }),
10169                            priority: 0,
10170                        }],
10171                        Some(Autoscroll::fit()),
10172                        cx,
10173                    )[0];
10174                    this.pending_rename = Some(RenameState {
10175                        range,
10176                        old_name,
10177                        editor: rename_editor,
10178                        block_id,
10179                    });
10180                })?;
10181            }
10182
10183            Ok(())
10184        }))
10185    }
10186
10187    pub fn confirm_rename(
10188        &mut self,
10189        _: &ConfirmRename,
10190        cx: &mut ViewContext<Self>,
10191    ) -> Option<Task<Result<()>>> {
10192        let rename = self.take_rename(false, cx)?;
10193        let workspace = self.workspace()?.downgrade();
10194        let (buffer, start) = self
10195            .buffer
10196            .read(cx)
10197            .text_anchor_for_position(rename.range.start, cx)?;
10198        let (end_buffer, _) = self
10199            .buffer
10200            .read(cx)
10201            .text_anchor_for_position(rename.range.end, cx)?;
10202        if buffer != end_buffer {
10203            return None;
10204        }
10205
10206        let old_name = rename.old_name;
10207        let new_name = rename.editor.read(cx).text(cx);
10208
10209        let rename = self.semantics_provider.as_ref()?.perform_rename(
10210            &buffer,
10211            start,
10212            new_name.clone(),
10213            cx,
10214        )?;
10215
10216        Some(cx.spawn(|editor, mut cx| async move {
10217            let project_transaction = rename.await?;
10218            Self::open_project_transaction(
10219                &editor,
10220                workspace,
10221                project_transaction,
10222                format!("Rename: {}{}", old_name, new_name),
10223                cx.clone(),
10224            )
10225            .await?;
10226
10227            editor.update(&mut cx, |editor, cx| {
10228                editor.refresh_document_highlights(cx);
10229            })?;
10230            Ok(())
10231        }))
10232    }
10233
10234    fn take_rename(
10235        &mut self,
10236        moving_cursor: bool,
10237        cx: &mut ViewContext<Self>,
10238    ) -> Option<RenameState> {
10239        let rename = self.pending_rename.take()?;
10240        if rename.editor.focus_handle(cx).is_focused(cx) {
10241            cx.focus(&self.focus_handle);
10242        }
10243
10244        self.remove_blocks(
10245            [rename.block_id].into_iter().collect(),
10246            Some(Autoscroll::fit()),
10247            cx,
10248        );
10249        self.clear_highlights::<Rename>(cx);
10250        self.show_local_selections = true;
10251
10252        if moving_cursor {
10253            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10254                editor.selections.newest::<usize>(cx).head()
10255            });
10256
10257            // Update the selection to match the position of the selection inside
10258            // the rename editor.
10259            let snapshot = self.buffer.read(cx).read(cx);
10260            let rename_range = rename.range.to_offset(&snapshot);
10261            let cursor_in_editor = snapshot
10262                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10263                .min(rename_range.end);
10264            drop(snapshot);
10265
10266            self.change_selections(None, cx, |s| {
10267                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10268            });
10269        } else {
10270            self.refresh_document_highlights(cx);
10271        }
10272
10273        Some(rename)
10274    }
10275
10276    pub fn pending_rename(&self) -> Option<&RenameState> {
10277        self.pending_rename.as_ref()
10278    }
10279
10280    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10281        let project = match &self.project {
10282            Some(project) => project.clone(),
10283            None => return None,
10284        };
10285
10286        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffers, cx))
10287    }
10288
10289    fn format_selections(
10290        &mut self,
10291        _: &FormatSelections,
10292        cx: &mut ViewContext<Self>,
10293    ) -> Option<Task<Result<()>>> {
10294        let project = match &self.project {
10295            Some(project) => project.clone(),
10296            None => return None,
10297        };
10298
10299        let ranges = self
10300            .selections
10301            .all_adjusted(cx)
10302            .into_iter()
10303            .map(|selection| selection.range())
10304            .collect_vec();
10305
10306        Some(self.perform_format(
10307            project,
10308            FormatTrigger::Manual,
10309            FormatTarget::Ranges(ranges),
10310            cx,
10311        ))
10312    }
10313
10314    fn perform_format(
10315        &mut self,
10316        project: Model<Project>,
10317        trigger: FormatTrigger,
10318        target: FormatTarget,
10319        cx: &mut ViewContext<Self>,
10320    ) -> Task<Result<()>> {
10321        let buffer = self.buffer.clone();
10322        let (buffers, target) = match target {
10323            FormatTarget::Buffers => {
10324                let mut buffers = buffer.read(cx).all_buffers();
10325                if trigger == FormatTrigger::Save {
10326                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
10327                }
10328                (buffers, LspFormatTarget::Buffers)
10329            }
10330            FormatTarget::Ranges(selection_ranges) => {
10331                let multi_buffer = buffer.read(cx);
10332                let snapshot = multi_buffer.read(cx);
10333                let mut buffers = HashSet::default();
10334                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10335                    BTreeMap::new();
10336                for selection_range in selection_ranges {
10337                    for (excerpt, buffer_range) in snapshot.range_to_buffer_ranges(selection_range)
10338                    {
10339                        let buffer_id = excerpt.buffer_id();
10340                        let start = excerpt.buffer().anchor_before(buffer_range.start);
10341                        let end = excerpt.buffer().anchor_after(buffer_range.end);
10342                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10343                        buffer_id_to_ranges
10344                            .entry(buffer_id)
10345                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10346                            .or_insert_with(|| vec![start..end]);
10347                    }
10348                }
10349                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10350            }
10351        };
10352
10353        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10354        let format = project.update(cx, |project, cx| {
10355            project.format(buffers, target, true, trigger, cx)
10356        });
10357
10358        cx.spawn(|_, mut cx| async move {
10359            let transaction = futures::select_biased! {
10360                () = timeout => {
10361                    log::warn!("timed out waiting for formatting");
10362                    None
10363                }
10364                transaction = format.log_err().fuse() => transaction,
10365            };
10366
10367            buffer
10368                .update(&mut cx, |buffer, cx| {
10369                    if let Some(transaction) = transaction {
10370                        if !buffer.is_singleton() {
10371                            buffer.push_transaction(&transaction.0, cx);
10372                        }
10373                    }
10374
10375                    cx.notify();
10376                })
10377                .ok();
10378
10379            Ok(())
10380        })
10381    }
10382
10383    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10384        if let Some(project) = self.project.clone() {
10385            self.buffer.update(cx, |multi_buffer, cx| {
10386                project.update(cx, |project, cx| {
10387                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10388                });
10389            })
10390        }
10391    }
10392
10393    fn cancel_language_server_work(
10394        &mut self,
10395        _: &actions::CancelLanguageServerWork,
10396        cx: &mut ViewContext<Self>,
10397    ) {
10398        if let Some(project) = self.project.clone() {
10399            self.buffer.update(cx, |multi_buffer, cx| {
10400                project.update(cx, |project, cx| {
10401                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10402                });
10403            })
10404        }
10405    }
10406
10407    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10408        cx.show_character_palette();
10409    }
10410
10411    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10412        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10413            let buffer = self.buffer.read(cx).snapshot(cx);
10414            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10415            let is_valid = buffer
10416                .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10417                .any(|entry| {
10418                    let range = entry.range.to_offset(&buffer);
10419                    entry.diagnostic.is_primary
10420                        && !range.is_empty()
10421                        && range.start == primary_range_start
10422                        && entry.diagnostic.message == active_diagnostics.primary_message
10423                });
10424
10425            if is_valid != active_diagnostics.is_valid {
10426                active_diagnostics.is_valid = is_valid;
10427                let mut new_styles = HashMap::default();
10428                for (block_id, diagnostic) in &active_diagnostics.blocks {
10429                    new_styles.insert(
10430                        *block_id,
10431                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10432                    );
10433                }
10434                self.display_map.update(cx, |display_map, _cx| {
10435                    display_map.replace_blocks(new_styles)
10436                });
10437            }
10438        }
10439    }
10440
10441    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10442        self.dismiss_diagnostics(cx);
10443        let snapshot = self.snapshot(cx);
10444        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10445            let buffer = self.buffer.read(cx).snapshot(cx);
10446
10447            let mut primary_range = None;
10448            let mut primary_message = None;
10449            let mut group_end = Point::zero();
10450            let diagnostic_group = buffer
10451                .diagnostic_group(group_id)
10452                .filter_map(|entry| {
10453                    let start = entry.range.start.to_point(&buffer);
10454                    let end = entry.range.end.to_point(&buffer);
10455                    if snapshot.is_line_folded(MultiBufferRow(start.row))
10456                        && (start.row == end.row
10457                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
10458                    {
10459                        return None;
10460                    }
10461                    if end > group_end {
10462                        group_end = end;
10463                    }
10464                    if entry.diagnostic.is_primary {
10465                        primary_range = Some(entry.range.clone());
10466                        primary_message = Some(entry.diagnostic.message.clone());
10467                    }
10468                    Some(entry)
10469                })
10470                .collect::<Vec<_>>();
10471            let primary_range = primary_range?;
10472            let primary_message = primary_message?;
10473
10474            let blocks = display_map
10475                .insert_blocks(
10476                    diagnostic_group.iter().map(|entry| {
10477                        let diagnostic = entry.diagnostic.clone();
10478                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10479                        BlockProperties {
10480                            style: BlockStyle::Fixed,
10481                            placement: BlockPlacement::Below(
10482                                buffer.anchor_after(entry.range.start),
10483                            ),
10484                            height: message_height,
10485                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10486                            priority: 0,
10487                        }
10488                    }),
10489                    cx,
10490                )
10491                .into_iter()
10492                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10493                .collect();
10494
10495            Some(ActiveDiagnosticGroup {
10496                primary_range,
10497                primary_message,
10498                group_id,
10499                blocks,
10500                is_valid: true,
10501            })
10502        });
10503    }
10504
10505    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10506        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10507            self.display_map.update(cx, |display_map, cx| {
10508                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10509            });
10510            cx.notify();
10511        }
10512    }
10513
10514    pub fn set_selections_from_remote(
10515        &mut self,
10516        selections: Vec<Selection<Anchor>>,
10517        pending_selection: Option<Selection<Anchor>>,
10518        cx: &mut ViewContext<Self>,
10519    ) {
10520        let old_cursor_position = self.selections.newest_anchor().head();
10521        self.selections.change_with(cx, |s| {
10522            s.select_anchors(selections);
10523            if let Some(pending_selection) = pending_selection {
10524                s.set_pending(pending_selection, SelectMode::Character);
10525            } else {
10526                s.clear_pending();
10527            }
10528        });
10529        self.selections_did_change(false, &old_cursor_position, true, cx);
10530    }
10531
10532    fn push_to_selection_history(&mut self) {
10533        self.selection_history.push(SelectionHistoryEntry {
10534            selections: self.selections.disjoint_anchors(),
10535            select_next_state: self.select_next_state.clone(),
10536            select_prev_state: self.select_prev_state.clone(),
10537            add_selections_state: self.add_selections_state.clone(),
10538        });
10539    }
10540
10541    pub fn transact(
10542        &mut self,
10543        cx: &mut ViewContext<Self>,
10544        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10545    ) -> Option<TransactionId> {
10546        self.start_transaction_at(Instant::now(), cx);
10547        update(self, cx);
10548        self.end_transaction_at(Instant::now(), cx)
10549    }
10550
10551    pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10552        self.end_selection(cx);
10553        if let Some(tx_id) = self
10554            .buffer
10555            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10556        {
10557            self.selection_history
10558                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10559            cx.emit(EditorEvent::TransactionBegun {
10560                transaction_id: tx_id,
10561            })
10562        }
10563    }
10564
10565    pub fn end_transaction_at(
10566        &mut self,
10567        now: Instant,
10568        cx: &mut ViewContext<Self>,
10569    ) -> Option<TransactionId> {
10570        if let Some(transaction_id) = self
10571            .buffer
10572            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10573        {
10574            if let Some((_, end_selections)) =
10575                self.selection_history.transaction_mut(transaction_id)
10576            {
10577                *end_selections = Some(self.selections.disjoint_anchors());
10578            } else {
10579                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10580            }
10581
10582            cx.emit(EditorEvent::Edited { transaction_id });
10583            Some(transaction_id)
10584        } else {
10585            None
10586        }
10587    }
10588
10589    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10590        if self.is_singleton(cx) {
10591            let selection = self.selections.newest::<Point>(cx);
10592
10593            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10594            let range = if selection.is_empty() {
10595                let point = selection.head().to_display_point(&display_map);
10596                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10597                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10598                    .to_point(&display_map);
10599                start..end
10600            } else {
10601                selection.range()
10602            };
10603            if display_map.folds_in_range(range).next().is_some() {
10604                self.unfold_lines(&Default::default(), cx)
10605            } else {
10606                self.fold(&Default::default(), cx)
10607            }
10608        } else {
10609            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10610            let mut toggled_buffers = HashSet::default();
10611            for (_, buffer_snapshot, _) in
10612                multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10613            {
10614                let buffer_id = buffer_snapshot.remote_id();
10615                if toggled_buffers.insert(buffer_id) {
10616                    if self.buffer_folded(buffer_id, cx) {
10617                        self.unfold_buffer(buffer_id, cx);
10618                    } else {
10619                        self.fold_buffer(buffer_id, cx);
10620                    }
10621                }
10622            }
10623        }
10624    }
10625
10626    pub fn toggle_fold_recursive(
10627        &mut self,
10628        _: &actions::ToggleFoldRecursive,
10629        cx: &mut ViewContext<Self>,
10630    ) {
10631        let selection = self.selections.newest::<Point>(cx);
10632
10633        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10634        let range = if selection.is_empty() {
10635            let point = selection.head().to_display_point(&display_map);
10636            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10637            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10638                .to_point(&display_map);
10639            start..end
10640        } else {
10641            selection.range()
10642        };
10643        if display_map.folds_in_range(range).next().is_some() {
10644            self.unfold_recursive(&Default::default(), cx)
10645        } else {
10646            self.fold_recursive(&Default::default(), cx)
10647        }
10648    }
10649
10650    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10651        if self.is_singleton(cx) {
10652            let mut to_fold = Vec::new();
10653            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10654            let selections = self.selections.all_adjusted(cx);
10655
10656            for selection in selections {
10657                let range = selection.range().sorted();
10658                let buffer_start_row = range.start.row;
10659
10660                if range.start.row != range.end.row {
10661                    let mut found = false;
10662                    let mut row = range.start.row;
10663                    while row <= range.end.row {
10664                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10665                        {
10666                            found = true;
10667                            row = crease.range().end.row + 1;
10668                            to_fold.push(crease);
10669                        } else {
10670                            row += 1
10671                        }
10672                    }
10673                    if found {
10674                        continue;
10675                    }
10676                }
10677
10678                for row in (0..=range.start.row).rev() {
10679                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10680                        if crease.range().end.row >= buffer_start_row {
10681                            to_fold.push(crease);
10682                            if row <= range.start.row {
10683                                break;
10684                            }
10685                        }
10686                    }
10687                }
10688            }
10689
10690            self.fold_creases(to_fold, true, cx);
10691        } else {
10692            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10693            let mut folded_buffers = HashSet::default();
10694            for (_, buffer_snapshot, _) in
10695                multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10696            {
10697                let buffer_id = buffer_snapshot.remote_id();
10698                if folded_buffers.insert(buffer_id) {
10699                    self.fold_buffer(buffer_id, cx);
10700                }
10701            }
10702        }
10703    }
10704
10705    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10706        if !self.buffer.read(cx).is_singleton() {
10707            return;
10708        }
10709
10710        let fold_at_level = fold_at.level;
10711        let snapshot = self.buffer.read(cx).snapshot(cx);
10712        let mut to_fold = Vec::new();
10713        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10714
10715        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10716            while start_row < end_row {
10717                match self
10718                    .snapshot(cx)
10719                    .crease_for_buffer_row(MultiBufferRow(start_row))
10720                {
10721                    Some(crease) => {
10722                        let nested_start_row = crease.range().start.row + 1;
10723                        let nested_end_row = crease.range().end.row;
10724
10725                        if current_level < fold_at_level {
10726                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10727                        } else if current_level == fold_at_level {
10728                            to_fold.push(crease);
10729                        }
10730
10731                        start_row = nested_end_row + 1;
10732                    }
10733                    None => start_row += 1,
10734                }
10735            }
10736        }
10737
10738        self.fold_creases(to_fold, true, cx);
10739    }
10740
10741    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10742        if self.buffer.read(cx).is_singleton() {
10743            let mut fold_ranges = Vec::new();
10744            let snapshot = self.buffer.read(cx).snapshot(cx);
10745
10746            for row in 0..snapshot.max_row().0 {
10747                if let Some(foldable_range) =
10748                    self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10749                {
10750                    fold_ranges.push(foldable_range);
10751                }
10752            }
10753
10754            self.fold_creases(fold_ranges, true, cx);
10755        } else {
10756            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10757                editor
10758                    .update(&mut cx, |editor, cx| {
10759                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10760                            editor.fold_buffer(buffer_id, cx);
10761                        }
10762                    })
10763                    .ok();
10764            });
10765        }
10766    }
10767
10768    pub fn fold_function_bodies(
10769        &mut self,
10770        _: &actions::FoldFunctionBodies,
10771        cx: &mut ViewContext<Self>,
10772    ) {
10773        let snapshot = self.buffer.read(cx).snapshot(cx);
10774        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10775            return;
10776        };
10777        let creases = buffer
10778            .function_body_fold_ranges(0..buffer.len())
10779            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10780            .collect();
10781
10782        self.fold_creases(creases, true, cx);
10783    }
10784
10785    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10786        let mut to_fold = Vec::new();
10787        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10788        let selections = self.selections.all_adjusted(cx);
10789
10790        for selection in selections {
10791            let range = selection.range().sorted();
10792            let buffer_start_row = range.start.row;
10793
10794            if range.start.row != range.end.row {
10795                let mut found = false;
10796                for row in range.start.row..=range.end.row {
10797                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10798                        found = true;
10799                        to_fold.push(crease);
10800                    }
10801                }
10802                if found {
10803                    continue;
10804                }
10805            }
10806
10807            for row in (0..=range.start.row).rev() {
10808                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10809                    if crease.range().end.row >= buffer_start_row {
10810                        to_fold.push(crease);
10811                    } else {
10812                        break;
10813                    }
10814                }
10815            }
10816        }
10817
10818        self.fold_creases(to_fold, true, cx);
10819    }
10820
10821    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10822        let buffer_row = fold_at.buffer_row;
10823        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10824
10825        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10826            let autoscroll = self
10827                .selections
10828                .all::<Point>(cx)
10829                .iter()
10830                .any(|selection| crease.range().overlaps(&selection.range()));
10831
10832            self.fold_creases(vec![crease], autoscroll, cx);
10833        }
10834    }
10835
10836    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10837        if self.is_singleton(cx) {
10838            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10839            let buffer = &display_map.buffer_snapshot;
10840            let selections = self.selections.all::<Point>(cx);
10841            let ranges = selections
10842                .iter()
10843                .map(|s| {
10844                    let range = s.display_range(&display_map).sorted();
10845                    let mut start = range.start.to_point(&display_map);
10846                    let mut end = range.end.to_point(&display_map);
10847                    start.column = 0;
10848                    end.column = buffer.line_len(MultiBufferRow(end.row));
10849                    start..end
10850                })
10851                .collect::<Vec<_>>();
10852
10853            self.unfold_ranges(&ranges, true, true, cx);
10854        } else {
10855            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10856            let mut unfolded_buffers = HashSet::default();
10857            for (_, buffer_snapshot, _) in
10858                multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10859            {
10860                let buffer_id = buffer_snapshot.remote_id();
10861                if unfolded_buffers.insert(buffer_id) {
10862                    self.unfold_buffer(buffer_id, cx);
10863                }
10864            }
10865        }
10866    }
10867
10868    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10869        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10870        let selections = self.selections.all::<Point>(cx);
10871        let ranges = selections
10872            .iter()
10873            .map(|s| {
10874                let mut range = s.display_range(&display_map).sorted();
10875                *range.start.column_mut() = 0;
10876                *range.end.column_mut() = display_map.line_len(range.end.row());
10877                let start = range.start.to_point(&display_map);
10878                let end = range.end.to_point(&display_map);
10879                start..end
10880            })
10881            .collect::<Vec<_>>();
10882
10883        self.unfold_ranges(&ranges, true, true, cx);
10884    }
10885
10886    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10887        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10888
10889        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10890            ..Point::new(
10891                unfold_at.buffer_row.0,
10892                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10893            );
10894
10895        let autoscroll = self
10896            .selections
10897            .all::<Point>(cx)
10898            .iter()
10899            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10900
10901        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10902    }
10903
10904    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10905        if self.buffer.read(cx).is_singleton() {
10906            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10907            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10908        } else {
10909            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10910                editor
10911                    .update(&mut cx, |editor, cx| {
10912                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10913                            editor.unfold_buffer(buffer_id, cx);
10914                        }
10915                    })
10916                    .ok();
10917            });
10918        }
10919    }
10920
10921    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10922        let selections = self.selections.all::<Point>(cx);
10923        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10924        let line_mode = self.selections.line_mode;
10925        let ranges = selections
10926            .into_iter()
10927            .map(|s| {
10928                if line_mode {
10929                    let start = Point::new(s.start.row, 0);
10930                    let end = Point::new(
10931                        s.end.row,
10932                        display_map
10933                            .buffer_snapshot
10934                            .line_len(MultiBufferRow(s.end.row)),
10935                    );
10936                    Crease::simple(start..end, display_map.fold_placeholder.clone())
10937                } else {
10938                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10939                }
10940            })
10941            .collect::<Vec<_>>();
10942        self.fold_creases(ranges, true, cx);
10943    }
10944
10945    pub fn fold_ranges<T: ToOffset + Clone>(
10946        &mut self,
10947        ranges: Vec<Range<T>>,
10948        auto_scroll: bool,
10949        cx: &mut ViewContext<Self>,
10950    ) {
10951        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10952        let ranges = ranges
10953            .into_iter()
10954            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
10955            .collect::<Vec<_>>();
10956        self.fold_creases(ranges, auto_scroll, cx);
10957    }
10958
10959    pub fn fold_creases<T: ToOffset + Clone>(
10960        &mut self,
10961        creases: Vec<Crease<T>>,
10962        auto_scroll: bool,
10963        cx: &mut ViewContext<Self>,
10964    ) {
10965        if creases.is_empty() {
10966            return;
10967        }
10968
10969        let mut buffers_affected = HashSet::default();
10970        let multi_buffer = self.buffer().read(cx);
10971        for crease in &creases {
10972            if let Some((_, buffer, _)) =
10973                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10974            {
10975                buffers_affected.insert(buffer.read(cx).remote_id());
10976            };
10977        }
10978
10979        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10980
10981        if auto_scroll {
10982            self.request_autoscroll(Autoscroll::fit(), cx);
10983        }
10984
10985        for buffer_id in buffers_affected {
10986            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10987        }
10988
10989        cx.notify();
10990
10991        if let Some(active_diagnostics) = self.active_diagnostics.take() {
10992            // Clear diagnostics block when folding a range that contains it.
10993            let snapshot = self.snapshot(cx);
10994            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10995                drop(snapshot);
10996                self.active_diagnostics = Some(active_diagnostics);
10997                self.dismiss_diagnostics(cx);
10998            } else {
10999                self.active_diagnostics = Some(active_diagnostics);
11000            }
11001        }
11002
11003        self.scrollbar_marker_state.dirty = true;
11004    }
11005
11006    /// Removes any folds whose ranges intersect any of the given ranges.
11007    pub fn unfold_ranges<T: ToOffset + Clone>(
11008        &mut self,
11009        ranges: &[Range<T>],
11010        inclusive: bool,
11011        auto_scroll: bool,
11012        cx: &mut ViewContext<Self>,
11013    ) {
11014        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11015            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11016        });
11017    }
11018
11019    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11020        if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
11021            return;
11022        }
11023        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11024            return;
11025        };
11026        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11027        self.display_map
11028            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11029        cx.emit(EditorEvent::BufferFoldToggled {
11030            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11031            folded: true,
11032        });
11033        cx.notify();
11034    }
11035
11036    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11037        if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
11038            return;
11039        }
11040        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11041            return;
11042        };
11043        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11044        self.display_map.update(cx, |display_map, cx| {
11045            display_map.unfold_buffer(buffer_id, cx);
11046        });
11047        cx.emit(EditorEvent::BufferFoldToggled {
11048            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11049            folded: false,
11050        });
11051        cx.notify();
11052    }
11053
11054    pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
11055        self.display_map.read(cx).buffer_folded(buffer)
11056    }
11057
11058    /// Removes any folds with the given ranges.
11059    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11060        &mut self,
11061        ranges: &[Range<T>],
11062        type_id: TypeId,
11063        auto_scroll: bool,
11064        cx: &mut ViewContext<Self>,
11065    ) {
11066        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11067            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11068        });
11069    }
11070
11071    fn remove_folds_with<T: ToOffset + Clone>(
11072        &mut self,
11073        ranges: &[Range<T>],
11074        auto_scroll: bool,
11075        cx: &mut ViewContext<Self>,
11076        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11077    ) {
11078        if ranges.is_empty() {
11079            return;
11080        }
11081
11082        let mut buffers_affected = HashSet::default();
11083        let multi_buffer = self.buffer().read(cx);
11084        for range in ranges {
11085            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11086                buffers_affected.insert(buffer.read(cx).remote_id());
11087            };
11088        }
11089
11090        self.display_map.update(cx, update);
11091
11092        if auto_scroll {
11093            self.request_autoscroll(Autoscroll::fit(), cx);
11094        }
11095
11096        for buffer_id in buffers_affected {
11097            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11098        }
11099
11100        cx.notify();
11101        self.scrollbar_marker_state.dirty = true;
11102        self.active_indent_guides_state.dirty = true;
11103    }
11104
11105    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11106        self.display_map.read(cx).fold_placeholder.clone()
11107    }
11108
11109    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11110        if hovered != self.gutter_hovered {
11111            self.gutter_hovered = hovered;
11112            cx.notify();
11113        }
11114    }
11115
11116    pub fn insert_blocks(
11117        &mut self,
11118        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11119        autoscroll: Option<Autoscroll>,
11120        cx: &mut ViewContext<Self>,
11121    ) -> Vec<CustomBlockId> {
11122        let blocks = self
11123            .display_map
11124            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11125        if let Some(autoscroll) = autoscroll {
11126            self.request_autoscroll(autoscroll, cx);
11127        }
11128        cx.notify();
11129        blocks
11130    }
11131
11132    pub fn resize_blocks(
11133        &mut self,
11134        heights: HashMap<CustomBlockId, u32>,
11135        autoscroll: Option<Autoscroll>,
11136        cx: &mut ViewContext<Self>,
11137    ) {
11138        self.display_map
11139            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11140        if let Some(autoscroll) = autoscroll {
11141            self.request_autoscroll(autoscroll, cx);
11142        }
11143        cx.notify();
11144    }
11145
11146    pub fn replace_blocks(
11147        &mut self,
11148        renderers: HashMap<CustomBlockId, RenderBlock>,
11149        autoscroll: Option<Autoscroll>,
11150        cx: &mut ViewContext<Self>,
11151    ) {
11152        self.display_map
11153            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11154        if let Some(autoscroll) = autoscroll {
11155            self.request_autoscroll(autoscroll, cx);
11156        }
11157        cx.notify();
11158    }
11159
11160    pub fn remove_blocks(
11161        &mut self,
11162        block_ids: HashSet<CustomBlockId>,
11163        autoscroll: Option<Autoscroll>,
11164        cx: &mut ViewContext<Self>,
11165    ) {
11166        self.display_map.update(cx, |display_map, cx| {
11167            display_map.remove_blocks(block_ids, cx)
11168        });
11169        if let Some(autoscroll) = autoscroll {
11170            self.request_autoscroll(autoscroll, cx);
11171        }
11172        cx.notify();
11173    }
11174
11175    pub fn row_for_block(
11176        &self,
11177        block_id: CustomBlockId,
11178        cx: &mut ViewContext<Self>,
11179    ) -> Option<DisplayRow> {
11180        self.display_map
11181            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11182    }
11183
11184    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11185        self.focused_block = Some(focused_block);
11186    }
11187
11188    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11189        self.focused_block.take()
11190    }
11191
11192    pub fn insert_creases(
11193        &mut self,
11194        creases: impl IntoIterator<Item = Crease<Anchor>>,
11195        cx: &mut ViewContext<Self>,
11196    ) -> Vec<CreaseId> {
11197        self.display_map
11198            .update(cx, |map, cx| map.insert_creases(creases, cx))
11199    }
11200
11201    pub fn remove_creases(
11202        &mut self,
11203        ids: impl IntoIterator<Item = CreaseId>,
11204        cx: &mut ViewContext<Self>,
11205    ) {
11206        self.display_map
11207            .update(cx, |map, cx| map.remove_creases(ids, cx));
11208    }
11209
11210    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11211        self.display_map
11212            .update(cx, |map, cx| map.snapshot(cx))
11213            .longest_row()
11214    }
11215
11216    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11217        self.display_map
11218            .update(cx, |map, cx| map.snapshot(cx))
11219            .max_point()
11220    }
11221
11222    pub fn text(&self, cx: &AppContext) -> String {
11223        self.buffer.read(cx).read(cx).text()
11224    }
11225
11226    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11227        let text = self.text(cx);
11228        let text = text.trim();
11229
11230        if text.is_empty() {
11231            return None;
11232        }
11233
11234        Some(text.to_string())
11235    }
11236
11237    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11238        self.transact(cx, |this, cx| {
11239            this.buffer
11240                .read(cx)
11241                .as_singleton()
11242                .expect("you can only call set_text on editors for singleton buffers")
11243                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11244        });
11245    }
11246
11247    pub fn display_text(&self, cx: &mut AppContext) -> String {
11248        self.display_map
11249            .update(cx, |map, cx| map.snapshot(cx))
11250            .text()
11251    }
11252
11253    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11254        let mut wrap_guides = smallvec::smallvec![];
11255
11256        if self.show_wrap_guides == Some(false) {
11257            return wrap_guides;
11258        }
11259
11260        let settings = self.buffer.read(cx).settings_at(0, cx);
11261        if settings.show_wrap_guides {
11262            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11263                wrap_guides.push((soft_wrap as usize, true));
11264            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11265                wrap_guides.push((soft_wrap as usize, true));
11266            }
11267            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11268        }
11269
11270        wrap_guides
11271    }
11272
11273    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11274        let settings = self.buffer.read(cx).settings_at(0, cx);
11275        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11276        match mode {
11277            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11278                SoftWrap::None
11279            }
11280            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11281            language_settings::SoftWrap::PreferredLineLength => {
11282                SoftWrap::Column(settings.preferred_line_length)
11283            }
11284            language_settings::SoftWrap::Bounded => {
11285                SoftWrap::Bounded(settings.preferred_line_length)
11286            }
11287        }
11288    }
11289
11290    pub fn set_soft_wrap_mode(
11291        &mut self,
11292        mode: language_settings::SoftWrap,
11293        cx: &mut ViewContext<Self>,
11294    ) {
11295        self.soft_wrap_mode_override = Some(mode);
11296        cx.notify();
11297    }
11298
11299    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11300        self.text_style_refinement = Some(style);
11301    }
11302
11303    /// called by the Element so we know what style we were most recently rendered with.
11304    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11305        let rem_size = cx.rem_size();
11306        self.display_map.update(cx, |map, cx| {
11307            map.set_font(
11308                style.text.font(),
11309                style.text.font_size.to_pixels(rem_size),
11310                cx,
11311            )
11312        });
11313        self.style = Some(style);
11314    }
11315
11316    pub fn style(&self) -> Option<&EditorStyle> {
11317        self.style.as_ref()
11318    }
11319
11320    // Called by the element. This method is not designed to be called outside of the editor
11321    // element's layout code because it does not notify when rewrapping is computed synchronously.
11322    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11323        self.display_map
11324            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11325    }
11326
11327    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11328        if self.soft_wrap_mode_override.is_some() {
11329            self.soft_wrap_mode_override.take();
11330        } else {
11331            let soft_wrap = match self.soft_wrap_mode(cx) {
11332                SoftWrap::GitDiff => return,
11333                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11334                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11335                    language_settings::SoftWrap::None
11336                }
11337            };
11338            self.soft_wrap_mode_override = Some(soft_wrap);
11339        }
11340        cx.notify();
11341    }
11342
11343    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11344        let Some(workspace) = self.workspace() else {
11345            return;
11346        };
11347        let fs = workspace.read(cx).app_state().fs.clone();
11348        let current_show = TabBarSettings::get_global(cx).show;
11349        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11350            setting.show = Some(!current_show);
11351        });
11352    }
11353
11354    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11355        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11356            self.buffer
11357                .read(cx)
11358                .settings_at(0, cx)
11359                .indent_guides
11360                .enabled
11361        });
11362        self.show_indent_guides = Some(!currently_enabled);
11363        cx.notify();
11364    }
11365
11366    fn should_show_indent_guides(&self) -> Option<bool> {
11367        self.show_indent_guides
11368    }
11369
11370    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11371        let mut editor_settings = EditorSettings::get_global(cx).clone();
11372        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11373        EditorSettings::override_global(editor_settings, cx);
11374    }
11375
11376    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11377        self.use_relative_line_numbers
11378            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11379    }
11380
11381    pub fn toggle_relative_line_numbers(
11382        &mut self,
11383        _: &ToggleRelativeLineNumbers,
11384        cx: &mut ViewContext<Self>,
11385    ) {
11386        let is_relative = self.should_use_relative_line_numbers(cx);
11387        self.set_relative_line_number(Some(!is_relative), cx)
11388    }
11389
11390    pub fn set_relative_line_number(
11391        &mut self,
11392        is_relative: Option<bool>,
11393        cx: &mut ViewContext<Self>,
11394    ) {
11395        self.use_relative_line_numbers = is_relative;
11396        cx.notify();
11397    }
11398
11399    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11400        self.show_gutter = show_gutter;
11401        cx.notify();
11402    }
11403
11404    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11405        self.show_scrollbars = show_scrollbars;
11406        cx.notify();
11407    }
11408
11409    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11410        self.show_line_numbers = Some(show_line_numbers);
11411        cx.notify();
11412    }
11413
11414    pub fn set_show_git_diff_gutter(
11415        &mut self,
11416        show_git_diff_gutter: bool,
11417        cx: &mut ViewContext<Self>,
11418    ) {
11419        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11420        cx.notify();
11421    }
11422
11423    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11424        self.show_code_actions = Some(show_code_actions);
11425        cx.notify();
11426    }
11427
11428    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11429        self.show_runnables = Some(show_runnables);
11430        cx.notify();
11431    }
11432
11433    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11434        if self.display_map.read(cx).masked != masked {
11435            self.display_map.update(cx, |map, _| map.masked = masked);
11436        }
11437        cx.notify()
11438    }
11439
11440    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11441        self.show_wrap_guides = Some(show_wrap_guides);
11442        cx.notify();
11443    }
11444
11445    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11446        self.show_indent_guides = Some(show_indent_guides);
11447        cx.notify();
11448    }
11449
11450    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11451        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11452            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11453                if let Some(dir) = file.abs_path(cx).parent() {
11454                    return Some(dir.to_owned());
11455                }
11456            }
11457
11458            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11459                return Some(project_path.path.to_path_buf());
11460            }
11461        }
11462
11463        None
11464    }
11465
11466    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11467        self.active_excerpt(cx)?
11468            .1
11469            .read(cx)
11470            .file()
11471            .and_then(|f| f.as_local())
11472    }
11473
11474    fn target_file_abs_path(&self, cx: &mut ViewContext<Self>) -> Option<PathBuf> {
11475        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
11476            let project_path = buffer.read(cx).project_path(cx)?;
11477            let project = self.project.as_ref()?.read(cx);
11478            project.absolute_path(&project_path, cx)
11479        })
11480    }
11481
11482    fn target_file_path(&self, cx: &mut ViewContext<Self>) -> Option<PathBuf> {
11483        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
11484            let project_path = buffer.read(cx).project_path(cx)?;
11485            let project = self.project.as_ref()?.read(cx);
11486            let entry = project.entry_for_path(&project_path, cx)?;
11487            let path = entry.path.to_path_buf();
11488            Some(path)
11489        })
11490    }
11491
11492    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11493        if let Some(target) = self.target_file(cx) {
11494            cx.reveal_path(&target.abs_path(cx));
11495        }
11496    }
11497
11498    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11499        if let Some(path) = self.target_file_abs_path(cx) {
11500            if let Some(path) = path.to_str() {
11501                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11502            }
11503        }
11504    }
11505
11506    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11507        if let Some(path) = self.target_file_path(cx) {
11508            if let Some(path) = path.to_str() {
11509                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11510            }
11511        }
11512    }
11513
11514    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11515        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11516
11517        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11518            self.start_git_blame(true, cx);
11519        }
11520
11521        cx.notify();
11522    }
11523
11524    pub fn toggle_git_blame_inline(
11525        &mut self,
11526        _: &ToggleGitBlameInline,
11527        cx: &mut ViewContext<Self>,
11528    ) {
11529        self.toggle_git_blame_inline_internal(true, cx);
11530        cx.notify();
11531    }
11532
11533    pub fn git_blame_inline_enabled(&self) -> bool {
11534        self.git_blame_inline_enabled
11535    }
11536
11537    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11538        self.show_selection_menu = self
11539            .show_selection_menu
11540            .map(|show_selections_menu| !show_selections_menu)
11541            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11542
11543        cx.notify();
11544    }
11545
11546    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11547        self.show_selection_menu
11548            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11549    }
11550
11551    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11552        if let Some(project) = self.project.as_ref() {
11553            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11554                return;
11555            };
11556
11557            if buffer.read(cx).file().is_none() {
11558                return;
11559            }
11560
11561            let focused = self.focus_handle(cx).contains_focused(cx);
11562
11563            let project = project.clone();
11564            let blame =
11565                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11566            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11567            self.blame = Some(blame);
11568        }
11569    }
11570
11571    fn toggle_git_blame_inline_internal(
11572        &mut self,
11573        user_triggered: bool,
11574        cx: &mut ViewContext<Self>,
11575    ) {
11576        if self.git_blame_inline_enabled {
11577            self.git_blame_inline_enabled = false;
11578            self.show_git_blame_inline = false;
11579            self.show_git_blame_inline_delay_task.take();
11580        } else {
11581            self.git_blame_inline_enabled = true;
11582            self.start_git_blame_inline(user_triggered, cx);
11583        }
11584
11585        cx.notify();
11586    }
11587
11588    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11589        self.start_git_blame(user_triggered, cx);
11590
11591        if ProjectSettings::get_global(cx)
11592            .git
11593            .inline_blame_delay()
11594            .is_some()
11595        {
11596            self.start_inline_blame_timer(cx);
11597        } else {
11598            self.show_git_blame_inline = true
11599        }
11600    }
11601
11602    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11603        self.blame.as_ref()
11604    }
11605
11606    pub fn show_git_blame_gutter(&self) -> bool {
11607        self.show_git_blame_gutter
11608    }
11609
11610    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11611        self.show_git_blame_gutter && self.has_blame_entries(cx)
11612    }
11613
11614    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11615        self.show_git_blame_inline
11616            && self.focus_handle.is_focused(cx)
11617            && !self.newest_selection_head_on_empty_line(cx)
11618            && self.has_blame_entries(cx)
11619    }
11620
11621    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11622        self.blame()
11623            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11624    }
11625
11626    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11627        let cursor_anchor = self.selections.newest_anchor().head();
11628
11629        let snapshot = self.buffer.read(cx).snapshot(cx);
11630        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11631
11632        snapshot.line_len(buffer_row) == 0
11633    }
11634
11635    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11636        let buffer_and_selection = maybe!({
11637            let selection = self.selections.newest::<Point>(cx);
11638            let selection_range = selection.range();
11639
11640            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11641                (buffer, selection_range.start.row..selection_range.end.row)
11642            } else {
11643                let multi_buffer = self.buffer().read(cx);
11644                let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11645                let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11646
11647                let (excerpt, range) = if selection.reversed {
11648                    buffer_ranges.first()
11649                } else {
11650                    buffer_ranges.last()
11651                }?;
11652
11653                let snapshot = excerpt.buffer();
11654                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11655                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11656                (
11657                    multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11658                    selection,
11659                )
11660            };
11661
11662            Some((buffer, selection))
11663        });
11664
11665        let Some((buffer, selection)) = buffer_and_selection else {
11666            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11667        };
11668
11669        let Some(project) = self.project.as_ref() else {
11670            return Task::ready(Err(anyhow!("editor does not have project")));
11671        };
11672
11673        project.update(cx, |project, cx| {
11674            project.get_permalink_to_line(&buffer, selection, cx)
11675        })
11676    }
11677
11678    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11679        let permalink_task = self.get_permalink_to_line(cx);
11680        let workspace = self.workspace();
11681
11682        cx.spawn(|_, mut cx| async move {
11683            match permalink_task.await {
11684                Ok(permalink) => {
11685                    cx.update(|cx| {
11686                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11687                    })
11688                    .ok();
11689                }
11690                Err(err) => {
11691                    let message = format!("Failed to copy permalink: {err}");
11692
11693                    Err::<(), anyhow::Error>(err).log_err();
11694
11695                    if let Some(workspace) = workspace {
11696                        workspace
11697                            .update(&mut cx, |workspace, cx| {
11698                                struct CopyPermalinkToLine;
11699
11700                                workspace.show_toast(
11701                                    Toast::new(
11702                                        NotificationId::unique::<CopyPermalinkToLine>(),
11703                                        message,
11704                                    ),
11705                                    cx,
11706                                )
11707                            })
11708                            .ok();
11709                    }
11710                }
11711            }
11712        })
11713        .detach();
11714    }
11715
11716    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11717        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11718        if let Some(file) = self.target_file(cx) {
11719            if let Some(path) = file.path().to_str() {
11720                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11721            }
11722        }
11723    }
11724
11725    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11726        let permalink_task = self.get_permalink_to_line(cx);
11727        let workspace = self.workspace();
11728
11729        cx.spawn(|_, mut cx| async move {
11730            match permalink_task.await {
11731                Ok(permalink) => {
11732                    cx.update(|cx| {
11733                        cx.open_url(permalink.as_ref());
11734                    })
11735                    .ok();
11736                }
11737                Err(err) => {
11738                    let message = format!("Failed to open permalink: {err}");
11739
11740                    Err::<(), anyhow::Error>(err).log_err();
11741
11742                    if let Some(workspace) = workspace {
11743                        workspace
11744                            .update(&mut cx, |workspace, cx| {
11745                                struct OpenPermalinkToLine;
11746
11747                                workspace.show_toast(
11748                                    Toast::new(
11749                                        NotificationId::unique::<OpenPermalinkToLine>(),
11750                                        message,
11751                                    ),
11752                                    cx,
11753                                )
11754                            })
11755                            .ok();
11756                    }
11757                }
11758            }
11759        })
11760        .detach();
11761    }
11762
11763    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11764        self.insert_uuid(UuidVersion::V4, cx);
11765    }
11766
11767    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11768        self.insert_uuid(UuidVersion::V7, cx);
11769    }
11770
11771    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11772        self.transact(cx, |this, cx| {
11773            let edits = this
11774                .selections
11775                .all::<Point>(cx)
11776                .into_iter()
11777                .map(|selection| {
11778                    let uuid = match version {
11779                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11780                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11781                    };
11782
11783                    (selection.range(), uuid.to_string())
11784                });
11785            this.edit(edits, cx);
11786            this.refresh_inline_completion(true, false, cx);
11787        });
11788    }
11789
11790    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11791    /// last highlight added will be used.
11792    ///
11793    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11794    pub fn highlight_rows<T: 'static>(
11795        &mut self,
11796        range: Range<Anchor>,
11797        color: Hsla,
11798        should_autoscroll: bool,
11799        cx: &mut ViewContext<Self>,
11800    ) {
11801        let snapshot = self.buffer().read(cx).snapshot(cx);
11802        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11803        let ix = row_highlights.binary_search_by(|highlight| {
11804            Ordering::Equal
11805                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11806                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11807        });
11808
11809        if let Err(mut ix) = ix {
11810            let index = post_inc(&mut self.highlight_order);
11811
11812            // If this range intersects with the preceding highlight, then merge it with
11813            // the preceding highlight. Otherwise insert a new highlight.
11814            let mut merged = false;
11815            if ix > 0 {
11816                let prev_highlight = &mut row_highlights[ix - 1];
11817                if prev_highlight
11818                    .range
11819                    .end
11820                    .cmp(&range.start, &snapshot)
11821                    .is_ge()
11822                {
11823                    ix -= 1;
11824                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11825                        prev_highlight.range.end = range.end;
11826                    }
11827                    merged = true;
11828                    prev_highlight.index = index;
11829                    prev_highlight.color = color;
11830                    prev_highlight.should_autoscroll = should_autoscroll;
11831                }
11832            }
11833
11834            if !merged {
11835                row_highlights.insert(
11836                    ix,
11837                    RowHighlight {
11838                        range: range.clone(),
11839                        index,
11840                        color,
11841                        should_autoscroll,
11842                    },
11843                );
11844            }
11845
11846            // If any of the following highlights intersect with this one, merge them.
11847            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11848                let highlight = &row_highlights[ix];
11849                if next_highlight
11850                    .range
11851                    .start
11852                    .cmp(&highlight.range.end, &snapshot)
11853                    .is_le()
11854                {
11855                    if next_highlight
11856                        .range
11857                        .end
11858                        .cmp(&highlight.range.end, &snapshot)
11859                        .is_gt()
11860                    {
11861                        row_highlights[ix].range.end = next_highlight.range.end;
11862                    }
11863                    row_highlights.remove(ix + 1);
11864                } else {
11865                    break;
11866                }
11867            }
11868        }
11869    }
11870
11871    /// Remove any highlighted row ranges of the given type that intersect the
11872    /// given ranges.
11873    pub fn remove_highlighted_rows<T: 'static>(
11874        &mut self,
11875        ranges_to_remove: Vec<Range<Anchor>>,
11876        cx: &mut ViewContext<Self>,
11877    ) {
11878        let snapshot = self.buffer().read(cx).snapshot(cx);
11879        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11880        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11881        row_highlights.retain(|highlight| {
11882            while let Some(range_to_remove) = ranges_to_remove.peek() {
11883                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11884                    Ordering::Less | Ordering::Equal => {
11885                        ranges_to_remove.next();
11886                    }
11887                    Ordering::Greater => {
11888                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11889                            Ordering::Less | Ordering::Equal => {
11890                                return false;
11891                            }
11892                            Ordering::Greater => break,
11893                        }
11894                    }
11895                }
11896            }
11897
11898            true
11899        })
11900    }
11901
11902    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11903    pub fn clear_row_highlights<T: 'static>(&mut self) {
11904        self.highlighted_rows.remove(&TypeId::of::<T>());
11905    }
11906
11907    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11908    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11909        self.highlighted_rows
11910            .get(&TypeId::of::<T>())
11911            .map_or(&[] as &[_], |vec| vec.as_slice())
11912            .iter()
11913            .map(|highlight| (highlight.range.clone(), highlight.color))
11914    }
11915
11916    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11917    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11918    /// Allows to ignore certain kinds of highlights.
11919    pub fn highlighted_display_rows(
11920        &mut self,
11921        cx: &mut WindowContext,
11922    ) -> BTreeMap<DisplayRow, Hsla> {
11923        let snapshot = self.snapshot(cx);
11924        let mut used_highlight_orders = HashMap::default();
11925        self.highlighted_rows
11926            .iter()
11927            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11928            .fold(
11929                BTreeMap::<DisplayRow, Hsla>::new(),
11930                |mut unique_rows, highlight| {
11931                    let start = highlight.range.start.to_display_point(&snapshot);
11932                    let end = highlight.range.end.to_display_point(&snapshot);
11933                    let start_row = start.row().0;
11934                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11935                        && end.column() == 0
11936                    {
11937                        end.row().0.saturating_sub(1)
11938                    } else {
11939                        end.row().0
11940                    };
11941                    for row in start_row..=end_row {
11942                        let used_index =
11943                            used_highlight_orders.entry(row).or_insert(highlight.index);
11944                        if highlight.index >= *used_index {
11945                            *used_index = highlight.index;
11946                            unique_rows.insert(DisplayRow(row), highlight.color);
11947                        }
11948                    }
11949                    unique_rows
11950                },
11951            )
11952    }
11953
11954    pub fn highlighted_display_row_for_autoscroll(
11955        &self,
11956        snapshot: &DisplaySnapshot,
11957    ) -> Option<DisplayRow> {
11958        self.highlighted_rows
11959            .values()
11960            .flat_map(|highlighted_rows| highlighted_rows.iter())
11961            .filter_map(|highlight| {
11962                if highlight.should_autoscroll {
11963                    Some(highlight.range.start.to_display_point(snapshot).row())
11964                } else {
11965                    None
11966                }
11967            })
11968            .min()
11969    }
11970
11971    pub fn set_search_within_ranges(
11972        &mut self,
11973        ranges: &[Range<Anchor>],
11974        cx: &mut ViewContext<Self>,
11975    ) {
11976        self.highlight_background::<SearchWithinRange>(
11977            ranges,
11978            |colors| colors.editor_document_highlight_read_background,
11979            cx,
11980        )
11981    }
11982
11983    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11984        self.breadcrumb_header = Some(new_header);
11985    }
11986
11987    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11988        self.clear_background_highlights::<SearchWithinRange>(cx);
11989    }
11990
11991    pub fn highlight_background<T: 'static>(
11992        &mut self,
11993        ranges: &[Range<Anchor>],
11994        color_fetcher: fn(&ThemeColors) -> Hsla,
11995        cx: &mut ViewContext<Self>,
11996    ) {
11997        self.background_highlights
11998            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11999        self.scrollbar_marker_state.dirty = true;
12000        cx.notify();
12001    }
12002
12003    pub fn clear_background_highlights<T: 'static>(
12004        &mut self,
12005        cx: &mut ViewContext<Self>,
12006    ) -> Option<BackgroundHighlight> {
12007        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12008        if !text_highlights.1.is_empty() {
12009            self.scrollbar_marker_state.dirty = true;
12010            cx.notify();
12011        }
12012        Some(text_highlights)
12013    }
12014
12015    pub fn highlight_gutter<T: 'static>(
12016        &mut self,
12017        ranges: &[Range<Anchor>],
12018        color_fetcher: fn(&AppContext) -> Hsla,
12019        cx: &mut ViewContext<Self>,
12020    ) {
12021        self.gutter_highlights
12022            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12023        cx.notify();
12024    }
12025
12026    pub fn clear_gutter_highlights<T: 'static>(
12027        &mut self,
12028        cx: &mut ViewContext<Self>,
12029    ) -> Option<GutterHighlight> {
12030        cx.notify();
12031        self.gutter_highlights.remove(&TypeId::of::<T>())
12032    }
12033
12034    #[cfg(feature = "test-support")]
12035    pub fn all_text_background_highlights(
12036        &mut self,
12037        cx: &mut ViewContext<Self>,
12038    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12039        let snapshot = self.snapshot(cx);
12040        let buffer = &snapshot.buffer_snapshot;
12041        let start = buffer.anchor_before(0);
12042        let end = buffer.anchor_after(buffer.len());
12043        let theme = cx.theme().colors();
12044        self.background_highlights_in_range(start..end, &snapshot, theme)
12045    }
12046
12047    #[cfg(feature = "test-support")]
12048    pub fn search_background_highlights(
12049        &mut self,
12050        cx: &mut ViewContext<Self>,
12051    ) -> Vec<Range<Point>> {
12052        let snapshot = self.buffer().read(cx).snapshot(cx);
12053
12054        let highlights = self
12055            .background_highlights
12056            .get(&TypeId::of::<items::BufferSearchHighlights>());
12057
12058        if let Some((_color, ranges)) = highlights {
12059            ranges
12060                .iter()
12061                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12062                .collect_vec()
12063        } else {
12064            vec![]
12065        }
12066    }
12067
12068    fn document_highlights_for_position<'a>(
12069        &'a self,
12070        position: Anchor,
12071        buffer: &'a MultiBufferSnapshot,
12072    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12073        let read_highlights = self
12074            .background_highlights
12075            .get(&TypeId::of::<DocumentHighlightRead>())
12076            .map(|h| &h.1);
12077        let write_highlights = self
12078            .background_highlights
12079            .get(&TypeId::of::<DocumentHighlightWrite>())
12080            .map(|h| &h.1);
12081        let left_position = position.bias_left(buffer);
12082        let right_position = position.bias_right(buffer);
12083        read_highlights
12084            .into_iter()
12085            .chain(write_highlights)
12086            .flat_map(move |ranges| {
12087                let start_ix = match ranges.binary_search_by(|probe| {
12088                    let cmp = probe.end.cmp(&left_position, buffer);
12089                    if cmp.is_ge() {
12090                        Ordering::Greater
12091                    } else {
12092                        Ordering::Less
12093                    }
12094                }) {
12095                    Ok(i) | Err(i) => i,
12096                };
12097
12098                ranges[start_ix..]
12099                    .iter()
12100                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12101            })
12102    }
12103
12104    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12105        self.background_highlights
12106            .get(&TypeId::of::<T>())
12107            .map_or(false, |(_, highlights)| !highlights.is_empty())
12108    }
12109
12110    pub fn background_highlights_in_range(
12111        &self,
12112        search_range: Range<Anchor>,
12113        display_snapshot: &DisplaySnapshot,
12114        theme: &ThemeColors,
12115    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12116        let mut results = Vec::new();
12117        for (color_fetcher, ranges) in self.background_highlights.values() {
12118            let color = color_fetcher(theme);
12119            let start_ix = match ranges.binary_search_by(|probe| {
12120                let cmp = probe
12121                    .end
12122                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12123                if cmp.is_gt() {
12124                    Ordering::Greater
12125                } else {
12126                    Ordering::Less
12127                }
12128            }) {
12129                Ok(i) | Err(i) => i,
12130            };
12131            for range in &ranges[start_ix..] {
12132                if range
12133                    .start
12134                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12135                    .is_ge()
12136                {
12137                    break;
12138                }
12139
12140                let start = range.start.to_display_point(display_snapshot);
12141                let end = range.end.to_display_point(display_snapshot);
12142                results.push((start..end, color))
12143            }
12144        }
12145        results
12146    }
12147
12148    pub fn background_highlight_row_ranges<T: 'static>(
12149        &self,
12150        search_range: Range<Anchor>,
12151        display_snapshot: &DisplaySnapshot,
12152        count: usize,
12153    ) -> Vec<RangeInclusive<DisplayPoint>> {
12154        let mut results = Vec::new();
12155        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12156            return vec![];
12157        };
12158
12159        let start_ix = match ranges.binary_search_by(|probe| {
12160            let cmp = probe
12161                .end
12162                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12163            if cmp.is_gt() {
12164                Ordering::Greater
12165            } else {
12166                Ordering::Less
12167            }
12168        }) {
12169            Ok(i) | Err(i) => i,
12170        };
12171        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12172            if let (Some(start_display), Some(end_display)) = (start, end) {
12173                results.push(
12174                    start_display.to_display_point(display_snapshot)
12175                        ..=end_display.to_display_point(display_snapshot),
12176                );
12177            }
12178        };
12179        let mut start_row: Option<Point> = None;
12180        let mut end_row: Option<Point> = None;
12181        if ranges.len() > count {
12182            return Vec::new();
12183        }
12184        for range in &ranges[start_ix..] {
12185            if range
12186                .start
12187                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12188                .is_ge()
12189            {
12190                break;
12191            }
12192            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12193            if let Some(current_row) = &end_row {
12194                if end.row == current_row.row {
12195                    continue;
12196                }
12197            }
12198            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12199            if start_row.is_none() {
12200                assert_eq!(end_row, None);
12201                start_row = Some(start);
12202                end_row = Some(end);
12203                continue;
12204            }
12205            if let Some(current_end) = end_row.as_mut() {
12206                if start.row > current_end.row + 1 {
12207                    push_region(start_row, end_row);
12208                    start_row = Some(start);
12209                    end_row = Some(end);
12210                } else {
12211                    // Merge two hunks.
12212                    *current_end = end;
12213                }
12214            } else {
12215                unreachable!();
12216            }
12217        }
12218        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12219        push_region(start_row, end_row);
12220        results
12221    }
12222
12223    pub fn gutter_highlights_in_range(
12224        &self,
12225        search_range: Range<Anchor>,
12226        display_snapshot: &DisplaySnapshot,
12227        cx: &AppContext,
12228    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12229        let mut results = Vec::new();
12230        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12231            let color = color_fetcher(cx);
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            for range in &ranges[start_ix..] {
12245                if range
12246                    .start
12247                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12248                    .is_ge()
12249                {
12250                    break;
12251                }
12252
12253                let start = range.start.to_display_point(display_snapshot);
12254                let end = range.end.to_display_point(display_snapshot);
12255                results.push((start..end, color))
12256            }
12257        }
12258        results
12259    }
12260
12261    /// Get the text ranges corresponding to the redaction query
12262    pub fn redacted_ranges(
12263        &self,
12264        search_range: Range<Anchor>,
12265        display_snapshot: &DisplaySnapshot,
12266        cx: &WindowContext,
12267    ) -> Vec<Range<DisplayPoint>> {
12268        display_snapshot
12269            .buffer_snapshot
12270            .redacted_ranges(search_range, |file| {
12271                if let Some(file) = file {
12272                    file.is_private()
12273                        && EditorSettings::get(
12274                            Some(SettingsLocation {
12275                                worktree_id: file.worktree_id(cx),
12276                                path: file.path().as_ref(),
12277                            }),
12278                            cx,
12279                        )
12280                        .redact_private_values
12281                } else {
12282                    false
12283                }
12284            })
12285            .map(|range| {
12286                range.start.to_display_point(display_snapshot)
12287                    ..range.end.to_display_point(display_snapshot)
12288            })
12289            .collect()
12290    }
12291
12292    pub fn highlight_text<T: 'static>(
12293        &mut self,
12294        ranges: Vec<Range<Anchor>>,
12295        style: HighlightStyle,
12296        cx: &mut ViewContext<Self>,
12297    ) {
12298        self.display_map.update(cx, |map, _| {
12299            map.highlight_text(TypeId::of::<T>(), ranges, style)
12300        });
12301        cx.notify();
12302    }
12303
12304    pub(crate) fn highlight_inlays<T: 'static>(
12305        &mut self,
12306        highlights: Vec<InlayHighlight>,
12307        style: HighlightStyle,
12308        cx: &mut ViewContext<Self>,
12309    ) {
12310        self.display_map.update(cx, |map, _| {
12311            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12312        });
12313        cx.notify();
12314    }
12315
12316    pub fn text_highlights<'a, T: 'static>(
12317        &'a self,
12318        cx: &'a AppContext,
12319    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12320        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12321    }
12322
12323    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12324        let cleared = self
12325            .display_map
12326            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12327        if cleared {
12328            cx.notify();
12329        }
12330    }
12331
12332    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12333        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12334            && self.focus_handle.is_focused(cx)
12335    }
12336
12337    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12338        self.show_cursor_when_unfocused = is_enabled;
12339        cx.notify();
12340    }
12341
12342    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12343        self.project
12344            .as_ref()
12345            .map(|project| project.read(cx).lsp_store())
12346    }
12347
12348    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12349        cx.notify();
12350    }
12351
12352    fn on_buffer_event(
12353        &mut self,
12354        multibuffer: Model<MultiBuffer>,
12355        event: &multi_buffer::Event,
12356        cx: &mut ViewContext<Self>,
12357    ) {
12358        match event {
12359            multi_buffer::Event::Edited {
12360                singleton_buffer_edited,
12361                edited_buffer: buffer_edited,
12362            } => {
12363                self.scrollbar_marker_state.dirty = true;
12364                self.active_indent_guides_state.dirty = true;
12365                self.refresh_active_diagnostics(cx);
12366                self.refresh_code_actions(cx);
12367                if self.has_active_inline_completion() {
12368                    self.update_visible_inline_completion(cx);
12369                }
12370                if let Some(buffer) = buffer_edited {
12371                    let buffer_id = buffer.read(cx).remote_id();
12372                    if !self.registered_buffers.contains_key(&buffer_id) {
12373                        if let Some(lsp_store) = self.lsp_store(cx) {
12374                            lsp_store.update(cx, |lsp_store, cx| {
12375                                self.registered_buffers.insert(
12376                                    buffer_id,
12377                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
12378                                );
12379                            })
12380                        }
12381                    }
12382                }
12383                cx.emit(EditorEvent::BufferEdited);
12384                cx.emit(SearchEvent::MatchesInvalidated);
12385                if *singleton_buffer_edited {
12386                    if let Some(project) = &self.project {
12387                        let project = project.read(cx);
12388                        #[allow(clippy::mutable_key_type)]
12389                        let languages_affected = multibuffer
12390                            .read(cx)
12391                            .all_buffers()
12392                            .into_iter()
12393                            .filter_map(|buffer| {
12394                                let buffer = buffer.read(cx);
12395                                let language = buffer.language()?;
12396                                if project.is_local()
12397                                    && project
12398                                        .language_servers_for_local_buffer(buffer, cx)
12399                                        .count()
12400                                        == 0
12401                                {
12402                                    None
12403                                } else {
12404                                    Some(language)
12405                                }
12406                            })
12407                            .cloned()
12408                            .collect::<HashSet<_>>();
12409                        if !languages_affected.is_empty() {
12410                            self.refresh_inlay_hints(
12411                                InlayHintRefreshReason::BufferEdited(languages_affected),
12412                                cx,
12413                            );
12414                        }
12415                    }
12416                }
12417
12418                let Some(project) = &self.project else { return };
12419                let (telemetry, is_via_ssh) = {
12420                    let project = project.read(cx);
12421                    let telemetry = project.client().telemetry().clone();
12422                    let is_via_ssh = project.is_via_ssh();
12423                    (telemetry, is_via_ssh)
12424                };
12425                refresh_linked_ranges(self, cx);
12426                telemetry.log_edit_event("editor", is_via_ssh);
12427            }
12428            multi_buffer::Event::ExcerptsAdded {
12429                buffer,
12430                predecessor,
12431                excerpts,
12432            } => {
12433                self.tasks_update_task = Some(self.refresh_runnables(cx));
12434                let buffer_id = buffer.read(cx).remote_id();
12435                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12436                    if let Some(project) = &self.project {
12437                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12438                    }
12439                }
12440                cx.emit(EditorEvent::ExcerptsAdded {
12441                    buffer: buffer.clone(),
12442                    predecessor: *predecessor,
12443                    excerpts: excerpts.clone(),
12444                });
12445                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12446            }
12447            multi_buffer::Event::ExcerptsRemoved { ids } => {
12448                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12449                let buffer = self.buffer.read(cx);
12450                self.registered_buffers
12451                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12452                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12453            }
12454            multi_buffer::Event::ExcerptsEdited { ids } => {
12455                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12456            }
12457            multi_buffer::Event::ExcerptsExpanded { ids } => {
12458                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12459                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12460            }
12461            multi_buffer::Event::Reparsed(buffer_id) => {
12462                self.tasks_update_task = Some(self.refresh_runnables(cx));
12463
12464                cx.emit(EditorEvent::Reparsed(*buffer_id));
12465            }
12466            multi_buffer::Event::LanguageChanged(buffer_id) => {
12467                linked_editing_ranges::refresh_linked_ranges(self, cx);
12468                cx.emit(EditorEvent::Reparsed(*buffer_id));
12469                cx.notify();
12470            }
12471            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12472            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12473            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12474                cx.emit(EditorEvent::TitleChanged)
12475            }
12476            // multi_buffer::Event::DiffBaseChanged => {
12477            //     self.scrollbar_marker_state.dirty = true;
12478            //     cx.emit(EditorEvent::DiffBaseChanged);
12479            //     cx.notify();
12480            // }
12481            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12482            multi_buffer::Event::DiagnosticsUpdated => {
12483                self.refresh_active_diagnostics(cx);
12484                self.scrollbar_marker_state.dirty = true;
12485                cx.notify();
12486            }
12487            _ => {}
12488        };
12489    }
12490
12491    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12492        cx.notify();
12493    }
12494
12495    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12496        self.tasks_update_task = Some(self.refresh_runnables(cx));
12497        self.refresh_inline_completion(true, false, cx);
12498        self.refresh_inlay_hints(
12499            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12500                self.selections.newest_anchor().head(),
12501                &self.buffer.read(cx).snapshot(cx),
12502                cx,
12503            )),
12504            cx,
12505        );
12506
12507        let old_cursor_shape = self.cursor_shape;
12508
12509        {
12510            let editor_settings = EditorSettings::get_global(cx);
12511            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12512            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12513            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12514        }
12515
12516        if old_cursor_shape != self.cursor_shape {
12517            cx.emit(EditorEvent::CursorShapeChanged);
12518        }
12519
12520        let project_settings = ProjectSettings::get_global(cx);
12521        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12522
12523        if self.mode == EditorMode::Full {
12524            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12525            if self.git_blame_inline_enabled != inline_blame_enabled {
12526                self.toggle_git_blame_inline_internal(false, cx);
12527            }
12528        }
12529
12530        cx.notify();
12531    }
12532
12533    pub fn set_searchable(&mut self, searchable: bool) {
12534        self.searchable = searchable;
12535    }
12536
12537    pub fn searchable(&self) -> bool {
12538        self.searchable
12539    }
12540
12541    fn open_proposed_changes_editor(
12542        &mut self,
12543        _: &OpenProposedChangesEditor,
12544        cx: &mut ViewContext<Self>,
12545    ) {
12546        let Some(workspace) = self.workspace() else {
12547            cx.propagate();
12548            return;
12549        };
12550
12551        let selections = self.selections.all::<usize>(cx);
12552        let multi_buffer = self.buffer.read(cx);
12553        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12554        let mut new_selections_by_buffer = HashMap::default();
12555        for selection in selections {
12556            for (excerpt, range) in
12557                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12558            {
12559                let mut range = range.to_point(excerpt.buffer());
12560                range.start.column = 0;
12561                range.end.column = excerpt.buffer().line_len(range.end.row);
12562                new_selections_by_buffer
12563                    .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12564                    .or_insert(Vec::new())
12565                    .push(range)
12566            }
12567        }
12568
12569        let proposed_changes_buffers = new_selections_by_buffer
12570            .into_iter()
12571            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12572            .collect::<Vec<_>>();
12573        let proposed_changes_editor = cx.new_view(|cx| {
12574            ProposedChangesEditor::new(
12575                "Proposed changes",
12576                proposed_changes_buffers,
12577                self.project.clone(),
12578                cx,
12579            )
12580        });
12581
12582        cx.window_context().defer(move |cx| {
12583            workspace.update(cx, |workspace, cx| {
12584                workspace.active_pane().update(cx, |pane, cx| {
12585                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12586                });
12587            });
12588        });
12589    }
12590
12591    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12592        self.open_excerpts_common(None, true, cx)
12593    }
12594
12595    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12596        self.open_excerpts_common(None, false, cx)
12597    }
12598
12599    fn open_excerpts_common(
12600        &mut self,
12601        jump_data: Option<JumpData>,
12602        split: bool,
12603        cx: &mut ViewContext<Self>,
12604    ) {
12605        let Some(workspace) = self.workspace() else {
12606            cx.propagate();
12607            return;
12608        };
12609
12610        if self.buffer.read(cx).is_singleton() {
12611            cx.propagate();
12612            return;
12613        }
12614
12615        let mut new_selections_by_buffer = HashMap::default();
12616        match &jump_data {
12617            Some(JumpData::MultiBufferPoint {
12618                excerpt_id,
12619                position,
12620                anchor,
12621                line_offset_from_top,
12622            }) => {
12623                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12624                if let Some(buffer) = multi_buffer_snapshot
12625                    .buffer_id_for_excerpt(*excerpt_id)
12626                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12627                {
12628                    let buffer_snapshot = buffer.read(cx).snapshot();
12629                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12630                        language::ToPoint::to_point(anchor, &buffer_snapshot)
12631                    } else {
12632                        buffer_snapshot.clip_point(*position, Bias::Left)
12633                    };
12634                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12635                    new_selections_by_buffer.insert(
12636                        buffer,
12637                        (
12638                            vec![jump_to_offset..jump_to_offset],
12639                            Some(*line_offset_from_top),
12640                        ),
12641                    );
12642                }
12643            }
12644            Some(JumpData::MultiBufferRow {
12645                row,
12646                line_offset_from_top,
12647            }) => {
12648                let point = MultiBufferPoint::new(row.0, 0);
12649                if let Some((buffer, buffer_point, _)) =
12650                    self.buffer.read(cx).point_to_buffer_point(point, cx)
12651                {
12652                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12653                    new_selections_by_buffer
12654                        .entry(buffer)
12655                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
12656                        .0
12657                        .push(buffer_offset..buffer_offset)
12658                }
12659            }
12660            None => {
12661                let selections = self.selections.all::<usize>(cx);
12662                let multi_buffer = self.buffer.read(cx);
12663                for selection in selections {
12664                    for (excerpt, mut range) in multi_buffer
12665                        .snapshot(cx)
12666                        .range_to_buffer_ranges(selection.range())
12667                    {
12668                        // When editing branch buffers, jump to the corresponding location
12669                        // in their base buffer.
12670                        let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12671                        let buffer = buffer_handle.read(cx);
12672                        if let Some(base_buffer) = buffer.base_buffer() {
12673                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12674                            buffer_handle = base_buffer;
12675                        }
12676
12677                        if selection.reversed {
12678                            mem::swap(&mut range.start, &mut range.end);
12679                        }
12680                        new_selections_by_buffer
12681                            .entry(buffer_handle)
12682                            .or_insert((Vec::new(), None))
12683                            .0
12684                            .push(range)
12685                    }
12686                }
12687            }
12688        }
12689
12690        if new_selections_by_buffer.is_empty() {
12691            return;
12692        }
12693
12694        // We defer the pane interaction because we ourselves are a workspace item
12695        // and activating a new item causes the pane to call a method on us reentrantly,
12696        // which panics if we're on the stack.
12697        cx.window_context().defer(move |cx| {
12698            workspace.update(cx, |workspace, cx| {
12699                let pane = if split {
12700                    workspace.adjacent_pane(cx)
12701                } else {
12702                    workspace.active_pane().clone()
12703                };
12704
12705                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12706                    let editor = buffer
12707                        .read(cx)
12708                        .file()
12709                        .is_none()
12710                        .then(|| {
12711                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12712                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12713                            // Instead, we try to activate the existing editor in the pane first.
12714                            let (editor, pane_item_index) =
12715                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12716                                    let editor = item.downcast::<Editor>()?;
12717                                    let singleton_buffer =
12718                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12719                                    if singleton_buffer == buffer {
12720                                        Some((editor, i))
12721                                    } else {
12722                                        None
12723                                    }
12724                                })?;
12725                            pane.update(cx, |pane, cx| {
12726                                pane.activate_item(pane_item_index, true, true, cx)
12727                            });
12728                            Some(editor)
12729                        })
12730                        .flatten()
12731                        .unwrap_or_else(|| {
12732                            workspace.open_project_item::<Self>(
12733                                pane.clone(),
12734                                buffer,
12735                                true,
12736                                true,
12737                                cx,
12738                            )
12739                        });
12740
12741                    editor.update(cx, |editor, cx| {
12742                        let autoscroll = match scroll_offset {
12743                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12744                            None => Autoscroll::newest(),
12745                        };
12746                        let nav_history = editor.nav_history.take();
12747                        editor.change_selections(Some(autoscroll), cx, |s| {
12748                            s.select_ranges(ranges);
12749                        });
12750                        editor.nav_history = nav_history;
12751                    });
12752                }
12753            })
12754        });
12755    }
12756
12757    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12758        let snapshot = self.buffer.read(cx).read(cx);
12759        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12760        Some(
12761            ranges
12762                .iter()
12763                .map(move |range| {
12764                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12765                })
12766                .collect(),
12767        )
12768    }
12769
12770    fn selection_replacement_ranges(
12771        &self,
12772        range: Range<OffsetUtf16>,
12773        cx: &mut AppContext,
12774    ) -> Vec<Range<OffsetUtf16>> {
12775        let selections = self.selections.all::<OffsetUtf16>(cx);
12776        let newest_selection = selections
12777            .iter()
12778            .max_by_key(|selection| selection.id)
12779            .unwrap();
12780        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12781        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12782        let snapshot = self.buffer.read(cx).read(cx);
12783        selections
12784            .into_iter()
12785            .map(|mut selection| {
12786                selection.start.0 =
12787                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12788                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12789                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12790                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12791            })
12792            .collect()
12793    }
12794
12795    fn report_editor_event(
12796        &self,
12797        event_type: &'static str,
12798        file_extension: Option<String>,
12799        cx: &AppContext,
12800    ) {
12801        if cfg!(any(test, feature = "test-support")) {
12802            return;
12803        }
12804
12805        let Some(project) = &self.project else { return };
12806
12807        // If None, we are in a file without an extension
12808        let file = self
12809            .buffer
12810            .read(cx)
12811            .as_singleton()
12812            .and_then(|b| b.read(cx).file());
12813        let file_extension = file_extension.or(file
12814            .as_ref()
12815            .and_then(|file| Path::new(file.file_name(cx)).extension())
12816            .and_then(|e| e.to_str())
12817            .map(|a| a.to_string()));
12818
12819        let vim_mode = cx
12820            .global::<SettingsStore>()
12821            .raw_user_settings()
12822            .get("vim_mode")
12823            == Some(&serde_json::Value::Bool(true));
12824
12825        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12826            == language::language_settings::InlineCompletionProvider::Copilot;
12827        let copilot_enabled_for_language = self
12828            .buffer
12829            .read(cx)
12830            .settings_at(0, cx)
12831            .show_inline_completions;
12832
12833        let project = project.read(cx);
12834        telemetry::event!(
12835            event_type,
12836            file_extension,
12837            vim_mode,
12838            copilot_enabled,
12839            copilot_enabled_for_language,
12840            is_via_ssh = project.is_via_ssh(),
12841        );
12842    }
12843
12844    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12845    /// with each line being an array of {text, highlight} objects.
12846    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12847        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12848            return;
12849        };
12850
12851        #[derive(Serialize)]
12852        struct Chunk<'a> {
12853            text: String,
12854            highlight: Option<&'a str>,
12855        }
12856
12857        let snapshot = buffer.read(cx).snapshot();
12858        let range = self
12859            .selected_text_range(false, cx)
12860            .and_then(|selection| {
12861                if selection.range.is_empty() {
12862                    None
12863                } else {
12864                    Some(selection.range)
12865                }
12866            })
12867            .unwrap_or_else(|| 0..snapshot.len());
12868
12869        let chunks = snapshot.chunks(range, true);
12870        let mut lines = Vec::new();
12871        let mut line: VecDeque<Chunk> = VecDeque::new();
12872
12873        let Some(style) = self.style.as_ref() else {
12874            return;
12875        };
12876
12877        for chunk in chunks {
12878            let highlight = chunk
12879                .syntax_highlight_id
12880                .and_then(|id| id.name(&style.syntax));
12881            let mut chunk_lines = chunk.text.split('\n').peekable();
12882            while let Some(text) = chunk_lines.next() {
12883                let mut merged_with_last_token = false;
12884                if let Some(last_token) = line.back_mut() {
12885                    if last_token.highlight == highlight {
12886                        last_token.text.push_str(text);
12887                        merged_with_last_token = true;
12888                    }
12889                }
12890
12891                if !merged_with_last_token {
12892                    line.push_back(Chunk {
12893                        text: text.into(),
12894                        highlight,
12895                    });
12896                }
12897
12898                if chunk_lines.peek().is_some() {
12899                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12900                        line.pop_front();
12901                    }
12902                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12903                        line.pop_back();
12904                    }
12905
12906                    lines.push(mem::take(&mut line));
12907                }
12908            }
12909        }
12910
12911        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12912            return;
12913        };
12914        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12915    }
12916
12917    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12918        self.request_autoscroll(Autoscroll::newest(), cx);
12919        let position = self.selections.newest_display(cx).start;
12920        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12921    }
12922
12923    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12924        &self.inlay_hint_cache
12925    }
12926
12927    pub fn replay_insert_event(
12928        &mut self,
12929        text: &str,
12930        relative_utf16_range: Option<Range<isize>>,
12931        cx: &mut ViewContext<Self>,
12932    ) {
12933        if !self.input_enabled {
12934            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12935            return;
12936        }
12937        if let Some(relative_utf16_range) = relative_utf16_range {
12938            let selections = self.selections.all::<OffsetUtf16>(cx);
12939            self.change_selections(None, cx, |s| {
12940                let new_ranges = selections.into_iter().map(|range| {
12941                    let start = OffsetUtf16(
12942                        range
12943                            .head()
12944                            .0
12945                            .saturating_add_signed(relative_utf16_range.start),
12946                    );
12947                    let end = OffsetUtf16(
12948                        range
12949                            .head()
12950                            .0
12951                            .saturating_add_signed(relative_utf16_range.end),
12952                    );
12953                    start..end
12954                });
12955                s.select_ranges(new_ranges);
12956            });
12957        }
12958
12959        self.handle_input(text, cx);
12960    }
12961
12962    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12963        let Some(provider) = self.semantics_provider.as_ref() else {
12964            return false;
12965        };
12966
12967        let mut supports = false;
12968        self.buffer().read(cx).for_each_buffer(|buffer| {
12969            supports |= provider.supports_inlay_hints(buffer, cx);
12970        });
12971        supports
12972    }
12973
12974    pub fn focus(&self, cx: &mut WindowContext) {
12975        cx.focus(&self.focus_handle)
12976    }
12977
12978    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12979        self.focus_handle.is_focused(cx)
12980    }
12981
12982    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12983        cx.emit(EditorEvent::Focused);
12984
12985        if let Some(descendant) = self
12986            .last_focused_descendant
12987            .take()
12988            .and_then(|descendant| descendant.upgrade())
12989        {
12990            cx.focus(&descendant);
12991        } else {
12992            if let Some(blame) = self.blame.as_ref() {
12993                blame.update(cx, GitBlame::focus)
12994            }
12995
12996            self.blink_manager.update(cx, BlinkManager::enable);
12997            self.show_cursor_names(cx);
12998            self.buffer.update(cx, |buffer, cx| {
12999                buffer.finalize_last_transaction(cx);
13000                if self.leader_peer_id.is_none() {
13001                    buffer.set_active_selections(
13002                        &self.selections.disjoint_anchors(),
13003                        self.selections.line_mode,
13004                        self.cursor_shape,
13005                        cx,
13006                    );
13007                }
13008            });
13009        }
13010    }
13011
13012    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13013        cx.emit(EditorEvent::FocusedIn)
13014    }
13015
13016    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13017        if event.blurred != self.focus_handle {
13018            self.last_focused_descendant = Some(event.blurred);
13019        }
13020    }
13021
13022    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13023        self.blink_manager.update(cx, BlinkManager::disable);
13024        self.buffer
13025            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13026
13027        if let Some(blame) = self.blame.as_ref() {
13028            blame.update(cx, GitBlame::blur)
13029        }
13030        if !self.hover_state.focused(cx) {
13031            hide_hover(self, cx);
13032        }
13033
13034        self.hide_context_menu(cx);
13035        cx.emit(EditorEvent::Blurred);
13036        cx.notify();
13037    }
13038
13039    pub fn register_action<A: Action>(
13040        &mut self,
13041        listener: impl Fn(&A, &mut WindowContext) + 'static,
13042    ) -> Subscription {
13043        let id = self.next_editor_action_id.post_inc();
13044        let listener = Arc::new(listener);
13045        self.editor_actions.borrow_mut().insert(
13046            id,
13047            Box::new(move |cx| {
13048                let cx = cx.window_context();
13049                let listener = listener.clone();
13050                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13051                    let action = action.downcast_ref().unwrap();
13052                    if phase == DispatchPhase::Bubble {
13053                        listener(action, cx)
13054                    }
13055                })
13056            }),
13057        );
13058
13059        let editor_actions = self.editor_actions.clone();
13060        Subscription::new(move || {
13061            editor_actions.borrow_mut().remove(&id);
13062        })
13063    }
13064
13065    pub fn file_header_size(&self) -> u32 {
13066        FILE_HEADER_HEIGHT
13067    }
13068
13069    pub fn revert(
13070        &mut self,
13071        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13072        cx: &mut ViewContext<Self>,
13073    ) {
13074        self.buffer().update(cx, |multi_buffer, cx| {
13075            for (buffer_id, changes) in revert_changes {
13076                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13077                    buffer.update(cx, |buffer, cx| {
13078                        buffer.edit(
13079                            changes.into_iter().map(|(range, text)| {
13080                                (range, text.to_string().map(Arc::<str>::from))
13081                            }),
13082                            None,
13083                            cx,
13084                        );
13085                    });
13086                }
13087            }
13088        });
13089        self.change_selections(None, cx, |selections| selections.refresh());
13090    }
13091
13092    pub fn to_pixel_point(
13093        &mut self,
13094        source: multi_buffer::Anchor,
13095        editor_snapshot: &EditorSnapshot,
13096        cx: &mut ViewContext<Self>,
13097    ) -> Option<gpui::Point<Pixels>> {
13098        let source_point = source.to_display_point(editor_snapshot);
13099        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13100    }
13101
13102    pub fn display_to_pixel_point(
13103        &self,
13104        source: DisplayPoint,
13105        editor_snapshot: &EditorSnapshot,
13106        cx: &WindowContext,
13107    ) -> Option<gpui::Point<Pixels>> {
13108        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13109        let text_layout_details = self.text_layout_details(cx);
13110        let scroll_top = text_layout_details
13111            .scroll_anchor
13112            .scroll_position(editor_snapshot)
13113            .y;
13114
13115        if source.row().as_f32() < scroll_top.floor() {
13116            return None;
13117        }
13118        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13119        let source_y = line_height * (source.row().as_f32() - scroll_top);
13120        Some(gpui::Point::new(source_x, source_y))
13121    }
13122
13123    pub fn has_active_completions_menu(&self) -> bool {
13124        self.context_menu.borrow().as_ref().map_or(false, |menu| {
13125            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13126        })
13127    }
13128
13129    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13130        self.addons
13131            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13132    }
13133
13134    pub fn unregister_addon<T: Addon>(&mut self) {
13135        self.addons.remove(&std::any::TypeId::of::<T>());
13136    }
13137
13138    pub fn addon<T: Addon>(&self) -> Option<&T> {
13139        let type_id = std::any::TypeId::of::<T>();
13140        self.addons
13141            .get(&type_id)
13142            .and_then(|item| item.to_any().downcast_ref::<T>())
13143    }
13144
13145    pub fn add_change_set(
13146        &mut self,
13147        change_set: Model<BufferChangeSet>,
13148        cx: &mut ViewContext<Self>,
13149    ) {
13150        self.diff_map.add_change_set(change_set, cx);
13151    }
13152
13153    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13154        let text_layout_details = self.text_layout_details(cx);
13155        let style = &text_layout_details.editor_style;
13156        let font_id = cx.text_system().resolve_font(&style.text.font());
13157        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13158        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13159
13160        let em_width = cx
13161            .text_system()
13162            .typographic_bounds(font_id, font_size, 'm')
13163            .unwrap()
13164            .size
13165            .width;
13166
13167        gpui::Point::new(em_width, line_height)
13168    }
13169}
13170
13171fn get_unstaged_changes_for_buffers(
13172    project: &Model<Project>,
13173    buffers: impl IntoIterator<Item = Model<Buffer>>,
13174    cx: &mut ViewContext<Editor>,
13175) {
13176    let mut tasks = Vec::new();
13177    project.update(cx, |project, cx| {
13178        for buffer in buffers {
13179            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13180        }
13181    });
13182    cx.spawn(|this, mut cx| async move {
13183        let change_sets = futures::future::join_all(tasks).await;
13184        this.update(&mut cx, |this, cx| {
13185            for change_set in change_sets {
13186                if let Some(change_set) = change_set.log_err() {
13187                    this.diff_map.add_change_set(change_set, cx);
13188                }
13189            }
13190        })
13191        .ok();
13192    })
13193    .detach();
13194}
13195
13196fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13197    let tab_size = tab_size.get() as usize;
13198    let mut width = offset;
13199
13200    for ch in text.chars() {
13201        width += if ch == '\t' {
13202            tab_size - (width % tab_size)
13203        } else {
13204            1
13205        };
13206    }
13207
13208    width - offset
13209}
13210
13211#[cfg(test)]
13212mod tests {
13213    use super::*;
13214
13215    #[test]
13216    fn test_string_size_with_expanded_tabs() {
13217        let nz = |val| NonZeroU32::new(val).unwrap();
13218        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13219        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13220        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13221        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13222        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13223        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13224        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13225        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13226    }
13227}
13228
13229/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13230struct WordBreakingTokenizer<'a> {
13231    input: &'a str,
13232}
13233
13234impl<'a> WordBreakingTokenizer<'a> {
13235    fn new(input: &'a str) -> Self {
13236        Self { input }
13237    }
13238}
13239
13240fn is_char_ideographic(ch: char) -> bool {
13241    use unicode_script::Script::*;
13242    use unicode_script::UnicodeScript;
13243    matches!(ch.script(), Han | Tangut | Yi)
13244}
13245
13246fn is_grapheme_ideographic(text: &str) -> bool {
13247    text.chars().any(is_char_ideographic)
13248}
13249
13250fn is_grapheme_whitespace(text: &str) -> bool {
13251    text.chars().any(|x| x.is_whitespace())
13252}
13253
13254fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13255    text.chars().next().map_or(false, |ch| {
13256        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13257    })
13258}
13259
13260#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13261struct WordBreakToken<'a> {
13262    token: &'a str,
13263    grapheme_len: usize,
13264    is_whitespace: bool,
13265}
13266
13267impl<'a> Iterator for WordBreakingTokenizer<'a> {
13268    /// Yields a span, the count of graphemes in the token, and whether it was
13269    /// whitespace. Note that it also breaks at word boundaries.
13270    type Item = WordBreakToken<'a>;
13271
13272    fn next(&mut self) -> Option<Self::Item> {
13273        use unicode_segmentation::UnicodeSegmentation;
13274        if self.input.is_empty() {
13275            return None;
13276        }
13277
13278        let mut iter = self.input.graphemes(true).peekable();
13279        let mut offset = 0;
13280        let mut graphemes = 0;
13281        if let Some(first_grapheme) = iter.next() {
13282            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13283            offset += first_grapheme.len();
13284            graphemes += 1;
13285            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13286                if let Some(grapheme) = iter.peek().copied() {
13287                    if should_stay_with_preceding_ideograph(grapheme) {
13288                        offset += grapheme.len();
13289                        graphemes += 1;
13290                    }
13291                }
13292            } else {
13293                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13294                let mut next_word_bound = words.peek().copied();
13295                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13296                    next_word_bound = words.next();
13297                }
13298                while let Some(grapheme) = iter.peek().copied() {
13299                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13300                        break;
13301                    };
13302                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13303                        break;
13304                    };
13305                    offset += grapheme.len();
13306                    graphemes += 1;
13307                    iter.next();
13308                }
13309            }
13310            let token = &self.input[..offset];
13311            self.input = &self.input[offset..];
13312            if is_whitespace {
13313                Some(WordBreakToken {
13314                    token: " ",
13315                    grapheme_len: 1,
13316                    is_whitespace: true,
13317                })
13318            } else {
13319                Some(WordBreakToken {
13320                    token,
13321                    grapheme_len: graphemes,
13322                    is_whitespace: false,
13323                })
13324            }
13325        } else {
13326            None
13327        }
13328    }
13329}
13330
13331#[test]
13332fn test_word_breaking_tokenizer() {
13333    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13334        ("", &[]),
13335        ("  ", &[(" ", 1, true)]),
13336        ("Ʒ", &[("Ʒ", 1, false)]),
13337        ("Ǽ", &[("Ǽ", 1, false)]),
13338        ("", &[("", 1, false)]),
13339        ("⋑⋑", &[("⋑⋑", 2, false)]),
13340        (
13341            "原理,进而",
13342            &[
13343                ("", 1, false),
13344                ("理,", 2, false),
13345                ("", 1, false),
13346                ("", 1, false),
13347            ],
13348        ),
13349        (
13350            "hello world",
13351            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13352        ),
13353        (
13354            "hello, world",
13355            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13356        ),
13357        (
13358            "  hello world",
13359            &[
13360                (" ", 1, true),
13361                ("hello", 5, false),
13362                (" ", 1, true),
13363                ("world", 5, false),
13364            ],
13365        ),
13366        (
13367            "这是什么 \n 钢笔",
13368            &[
13369                ("", 1, false),
13370                ("", 1, false),
13371                ("", 1, false),
13372                ("", 1, false),
13373                (" ", 1, true),
13374                ("", 1, false),
13375                ("", 1, false),
13376            ],
13377        ),
13378        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13379    ];
13380
13381    for (input, result) in tests {
13382        assert_eq!(
13383            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13384            result
13385                .iter()
13386                .copied()
13387                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13388                    token,
13389                    grapheme_len,
13390                    is_whitespace,
13391                })
13392                .collect::<Vec<_>>()
13393        );
13394    }
13395}
13396
13397fn wrap_with_prefix(
13398    line_prefix: String,
13399    unwrapped_text: String,
13400    wrap_column: usize,
13401    tab_size: NonZeroU32,
13402) -> String {
13403    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13404    let mut wrapped_text = String::new();
13405    let mut current_line = line_prefix.clone();
13406
13407    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13408    let mut current_line_len = line_prefix_len;
13409    for WordBreakToken {
13410        token,
13411        grapheme_len,
13412        is_whitespace,
13413    } in tokenizer
13414    {
13415        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13416            wrapped_text.push_str(current_line.trim_end());
13417            wrapped_text.push('\n');
13418            current_line.truncate(line_prefix.len());
13419            current_line_len = line_prefix_len;
13420            if !is_whitespace {
13421                current_line.push_str(token);
13422                current_line_len += grapheme_len;
13423            }
13424        } else if !is_whitespace {
13425            current_line.push_str(token);
13426            current_line_len += grapheme_len;
13427        } else if current_line_len != line_prefix_len {
13428            current_line.push(' ');
13429            current_line_len += 1;
13430        }
13431    }
13432
13433    if !current_line.is_empty() {
13434        wrapped_text.push_str(&current_line);
13435    }
13436    wrapped_text
13437}
13438
13439#[test]
13440fn test_wrap_with_prefix() {
13441    assert_eq!(
13442        wrap_with_prefix(
13443            "# ".to_string(),
13444            "abcdefg".to_string(),
13445            4,
13446            NonZeroU32::new(4).unwrap()
13447        ),
13448        "# abcdefg"
13449    );
13450    assert_eq!(
13451        wrap_with_prefix(
13452            "".to_string(),
13453            "\thello world".to_string(),
13454            8,
13455            NonZeroU32::new(4).unwrap()
13456        ),
13457        "hello\nworld"
13458    );
13459    assert_eq!(
13460        wrap_with_prefix(
13461            "// ".to_string(),
13462            "xx \nyy zz aa bb cc".to_string(),
13463            12,
13464            NonZeroU32::new(4).unwrap()
13465        ),
13466        "// xx yy zz\n// aa bb cc"
13467    );
13468    assert_eq!(
13469        wrap_with_prefix(
13470            String::new(),
13471            "这是什么 \n 钢笔".to_string(),
13472            3,
13473            NonZeroU32::new(4).unwrap()
13474        ),
13475        "这是什\n么 钢\n"
13476    );
13477}
13478
13479fn hunks_for_selections(
13480    snapshot: &EditorSnapshot,
13481    selections: &[Selection<Point>],
13482) -> Vec<MultiBufferDiffHunk> {
13483    hunks_for_ranges(
13484        selections.iter().map(|selection| selection.range()),
13485        snapshot,
13486    )
13487}
13488
13489pub fn hunks_for_ranges(
13490    ranges: impl Iterator<Item = Range<Point>>,
13491    snapshot: &EditorSnapshot,
13492) -> Vec<MultiBufferDiffHunk> {
13493    let mut hunks = Vec::new();
13494    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13495        HashMap::default();
13496    for query_range in ranges {
13497        let query_rows =
13498            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13499        for hunk in snapshot.diff_map.diff_hunks_in_range(
13500            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13501            &snapshot.buffer_snapshot,
13502        ) {
13503            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13504            // when the caret is just above or just below the deleted hunk.
13505            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13506            let related_to_selection = if allow_adjacent {
13507                hunk.row_range.overlaps(&query_rows)
13508                    || hunk.row_range.start == query_rows.end
13509                    || hunk.row_range.end == query_rows.start
13510            } else {
13511                hunk.row_range.overlaps(&query_rows)
13512            };
13513            if related_to_selection {
13514                if !processed_buffer_rows
13515                    .entry(hunk.buffer_id)
13516                    .or_default()
13517                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13518                {
13519                    continue;
13520                }
13521                hunks.push(hunk);
13522            }
13523        }
13524    }
13525
13526    hunks
13527}
13528
13529pub trait CollaborationHub {
13530    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13531    fn user_participant_indices<'a>(
13532        &self,
13533        cx: &'a AppContext,
13534    ) -> &'a HashMap<u64, ParticipantIndex>;
13535    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13536}
13537
13538impl CollaborationHub for Model<Project> {
13539    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13540        self.read(cx).collaborators()
13541    }
13542
13543    fn user_participant_indices<'a>(
13544        &self,
13545        cx: &'a AppContext,
13546    ) -> &'a HashMap<u64, ParticipantIndex> {
13547        self.read(cx).user_store().read(cx).participant_indices()
13548    }
13549
13550    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13551        let this = self.read(cx);
13552        let user_ids = this.collaborators().values().map(|c| c.user_id);
13553        this.user_store().read_with(cx, |user_store, cx| {
13554            user_store.participant_names(user_ids, cx)
13555        })
13556    }
13557}
13558
13559pub trait SemanticsProvider {
13560    fn hover(
13561        &self,
13562        buffer: &Model<Buffer>,
13563        position: text::Anchor,
13564        cx: &mut AppContext,
13565    ) -> Option<Task<Vec<project::Hover>>>;
13566
13567    fn inlay_hints(
13568        &self,
13569        buffer_handle: Model<Buffer>,
13570        range: Range<text::Anchor>,
13571        cx: &mut AppContext,
13572    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13573
13574    fn resolve_inlay_hint(
13575        &self,
13576        hint: InlayHint,
13577        buffer_handle: Model<Buffer>,
13578        server_id: LanguageServerId,
13579        cx: &mut AppContext,
13580    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13581
13582    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13583
13584    fn document_highlights(
13585        &self,
13586        buffer: &Model<Buffer>,
13587        position: text::Anchor,
13588        cx: &mut AppContext,
13589    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13590
13591    fn definitions(
13592        &self,
13593        buffer: &Model<Buffer>,
13594        position: text::Anchor,
13595        kind: GotoDefinitionKind,
13596        cx: &mut AppContext,
13597    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13598
13599    fn range_for_rename(
13600        &self,
13601        buffer: &Model<Buffer>,
13602        position: text::Anchor,
13603        cx: &mut AppContext,
13604    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13605
13606    fn perform_rename(
13607        &self,
13608        buffer: &Model<Buffer>,
13609        position: text::Anchor,
13610        new_name: String,
13611        cx: &mut AppContext,
13612    ) -> Option<Task<Result<ProjectTransaction>>>;
13613}
13614
13615pub trait CompletionProvider {
13616    fn completions(
13617        &self,
13618        buffer: &Model<Buffer>,
13619        buffer_position: text::Anchor,
13620        trigger: CompletionContext,
13621        cx: &mut ViewContext<Editor>,
13622    ) -> Task<Result<Vec<Completion>>>;
13623
13624    fn resolve_completions(
13625        &self,
13626        buffer: Model<Buffer>,
13627        completion_indices: Vec<usize>,
13628        completions: Rc<RefCell<Box<[Completion]>>>,
13629        cx: &mut ViewContext<Editor>,
13630    ) -> Task<Result<bool>>;
13631
13632    fn apply_additional_edits_for_completion(
13633        &self,
13634        _buffer: Model<Buffer>,
13635        _completions: Rc<RefCell<Box<[Completion]>>>,
13636        _completion_index: usize,
13637        _push_to_history: bool,
13638        _cx: &mut ViewContext<Editor>,
13639    ) -> Task<Result<Option<language::Transaction>>> {
13640        Task::ready(Ok(None))
13641    }
13642
13643    fn is_completion_trigger(
13644        &self,
13645        buffer: &Model<Buffer>,
13646        position: language::Anchor,
13647        text: &str,
13648        trigger_in_words: bool,
13649        cx: &mut ViewContext<Editor>,
13650    ) -> bool;
13651
13652    fn sort_completions(&self) -> bool {
13653        true
13654    }
13655}
13656
13657pub trait CodeActionProvider {
13658    fn id(&self) -> Arc<str>;
13659
13660    fn code_actions(
13661        &self,
13662        buffer: &Model<Buffer>,
13663        range: Range<text::Anchor>,
13664        cx: &mut WindowContext,
13665    ) -> Task<Result<Vec<CodeAction>>>;
13666
13667    fn apply_code_action(
13668        &self,
13669        buffer_handle: Model<Buffer>,
13670        action: CodeAction,
13671        excerpt_id: ExcerptId,
13672        push_to_history: bool,
13673        cx: &mut WindowContext,
13674    ) -> Task<Result<ProjectTransaction>>;
13675}
13676
13677impl CodeActionProvider for Model<Project> {
13678    fn id(&self) -> Arc<str> {
13679        "project".into()
13680    }
13681
13682    fn code_actions(
13683        &self,
13684        buffer: &Model<Buffer>,
13685        range: Range<text::Anchor>,
13686        cx: &mut WindowContext,
13687    ) -> Task<Result<Vec<CodeAction>>> {
13688        self.update(cx, |project, cx| {
13689            project.code_actions(buffer, range, None, cx)
13690        })
13691    }
13692
13693    fn apply_code_action(
13694        &self,
13695        buffer_handle: Model<Buffer>,
13696        action: CodeAction,
13697        _excerpt_id: ExcerptId,
13698        push_to_history: bool,
13699        cx: &mut WindowContext,
13700    ) -> Task<Result<ProjectTransaction>> {
13701        self.update(cx, |project, cx| {
13702            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13703        })
13704    }
13705}
13706
13707fn snippet_completions(
13708    project: &Project,
13709    buffer: &Model<Buffer>,
13710    buffer_position: text::Anchor,
13711    cx: &mut AppContext,
13712) -> Task<Result<Vec<Completion>>> {
13713    let language = buffer.read(cx).language_at(buffer_position);
13714    let language_name = language.as_ref().map(|language| language.lsp_id());
13715    let snippet_store = project.snippets().read(cx);
13716    let snippets = snippet_store.snippets_for(language_name, cx);
13717
13718    if snippets.is_empty() {
13719        return Task::ready(Ok(vec![]));
13720    }
13721    let snapshot = buffer.read(cx).text_snapshot();
13722    let chars: String = snapshot
13723        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13724        .collect();
13725
13726    let scope = language.map(|language| language.default_scope());
13727    let executor = cx.background_executor().clone();
13728
13729    cx.background_executor().spawn(async move {
13730        let classifier = CharClassifier::new(scope).for_completion(true);
13731        let mut last_word = chars
13732            .chars()
13733            .take_while(|c| classifier.is_word(*c))
13734            .collect::<String>();
13735        last_word = last_word.chars().rev().collect();
13736
13737        if last_word.is_empty() {
13738            return Ok(vec![]);
13739        }
13740
13741        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13742        let to_lsp = |point: &text::Anchor| {
13743            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13744            point_to_lsp(end)
13745        };
13746        let lsp_end = to_lsp(&buffer_position);
13747
13748        let candidates = snippets
13749            .iter()
13750            .enumerate()
13751            .flat_map(|(ix, snippet)| {
13752                snippet
13753                    .prefix
13754                    .iter()
13755                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13756            })
13757            .collect::<Vec<StringMatchCandidate>>();
13758
13759        let mut matches = fuzzy::match_strings(
13760            &candidates,
13761            &last_word,
13762            last_word.chars().any(|c| c.is_uppercase()),
13763            100,
13764            &Default::default(),
13765            executor,
13766        )
13767        .await;
13768
13769        // Remove all candidates where the query's start does not match the start of any word in the candidate
13770        if let Some(query_start) = last_word.chars().next() {
13771            matches.retain(|string_match| {
13772                split_words(&string_match.string).any(|word| {
13773                    // Check that the first codepoint of the word as lowercase matches the first
13774                    // codepoint of the query as lowercase
13775                    word.chars()
13776                        .flat_map(|codepoint| codepoint.to_lowercase())
13777                        .zip(query_start.to_lowercase())
13778                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13779                })
13780            });
13781        }
13782
13783        let matched_strings = matches
13784            .into_iter()
13785            .map(|m| m.string)
13786            .collect::<HashSet<_>>();
13787
13788        let result: Vec<Completion> = snippets
13789            .into_iter()
13790            .filter_map(|snippet| {
13791                let matching_prefix = snippet
13792                    .prefix
13793                    .iter()
13794                    .find(|prefix| matched_strings.contains(*prefix))?;
13795                let start = as_offset - last_word.len();
13796                let start = snapshot.anchor_before(start);
13797                let range = start..buffer_position;
13798                let lsp_start = to_lsp(&start);
13799                let lsp_range = lsp::Range {
13800                    start: lsp_start,
13801                    end: lsp_end,
13802                };
13803                Some(Completion {
13804                    old_range: range,
13805                    new_text: snippet.body.clone(),
13806                    resolved: false,
13807                    label: CodeLabel {
13808                        text: matching_prefix.clone(),
13809                        runs: vec![],
13810                        filter_range: 0..matching_prefix.len(),
13811                    },
13812                    server_id: LanguageServerId(usize::MAX),
13813                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13814                    lsp_completion: lsp::CompletionItem {
13815                        label: snippet.prefix.first().unwrap().clone(),
13816                        kind: Some(CompletionItemKind::SNIPPET),
13817                        label_details: snippet.description.as_ref().map(|description| {
13818                            lsp::CompletionItemLabelDetails {
13819                                detail: Some(description.clone()),
13820                                description: None,
13821                            }
13822                        }),
13823                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13824                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13825                            lsp::InsertReplaceEdit {
13826                                new_text: snippet.body.clone(),
13827                                insert: lsp_range,
13828                                replace: lsp_range,
13829                            },
13830                        )),
13831                        filter_text: Some(snippet.body.clone()),
13832                        sort_text: Some(char::MAX.to_string()),
13833                        ..Default::default()
13834                    },
13835                    confirm: None,
13836                })
13837            })
13838            .collect();
13839
13840        Ok(result)
13841    })
13842}
13843
13844impl CompletionProvider for Model<Project> {
13845    fn completions(
13846        &self,
13847        buffer: &Model<Buffer>,
13848        buffer_position: text::Anchor,
13849        options: CompletionContext,
13850        cx: &mut ViewContext<Editor>,
13851    ) -> Task<Result<Vec<Completion>>> {
13852        self.update(cx, |project, cx| {
13853            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13854            let project_completions = project.completions(buffer, buffer_position, options, cx);
13855            cx.background_executor().spawn(async move {
13856                let mut completions = project_completions.await?;
13857                let snippets_completions = snippets.await?;
13858                completions.extend(snippets_completions);
13859                Ok(completions)
13860            })
13861        })
13862    }
13863
13864    fn resolve_completions(
13865        &self,
13866        buffer: Model<Buffer>,
13867        completion_indices: Vec<usize>,
13868        completions: Rc<RefCell<Box<[Completion]>>>,
13869        cx: &mut ViewContext<Editor>,
13870    ) -> Task<Result<bool>> {
13871        self.update(cx, |project, cx| {
13872            project.lsp_store().update(cx, |lsp_store, cx| {
13873                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13874            })
13875        })
13876    }
13877
13878    fn apply_additional_edits_for_completion(
13879        &self,
13880        buffer: Model<Buffer>,
13881        completions: Rc<RefCell<Box<[Completion]>>>,
13882        completion_index: usize,
13883        push_to_history: bool,
13884        cx: &mut ViewContext<Editor>,
13885    ) -> Task<Result<Option<language::Transaction>>> {
13886        self.update(cx, |project, cx| {
13887            project.lsp_store().update(cx, |lsp_store, cx| {
13888                lsp_store.apply_additional_edits_for_completion(
13889                    buffer,
13890                    completions,
13891                    completion_index,
13892                    push_to_history,
13893                    cx,
13894                )
13895            })
13896        })
13897    }
13898
13899    fn is_completion_trigger(
13900        &self,
13901        buffer: &Model<Buffer>,
13902        position: language::Anchor,
13903        text: &str,
13904        trigger_in_words: bool,
13905        cx: &mut ViewContext<Editor>,
13906    ) -> bool {
13907        let mut chars = text.chars();
13908        let char = if let Some(char) = chars.next() {
13909            char
13910        } else {
13911            return false;
13912        };
13913        if chars.next().is_some() {
13914            return false;
13915        }
13916
13917        let buffer = buffer.read(cx);
13918        let snapshot = buffer.snapshot();
13919        if !snapshot.settings_at(position, cx).show_completions_on_input {
13920            return false;
13921        }
13922        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13923        if trigger_in_words && classifier.is_word(char) {
13924            return true;
13925        }
13926
13927        buffer.completion_triggers().contains(text)
13928    }
13929}
13930
13931impl SemanticsProvider for Model<Project> {
13932    fn hover(
13933        &self,
13934        buffer: &Model<Buffer>,
13935        position: text::Anchor,
13936        cx: &mut AppContext,
13937    ) -> Option<Task<Vec<project::Hover>>> {
13938        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13939    }
13940
13941    fn document_highlights(
13942        &self,
13943        buffer: &Model<Buffer>,
13944        position: text::Anchor,
13945        cx: &mut AppContext,
13946    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13947        Some(self.update(cx, |project, cx| {
13948            project.document_highlights(buffer, position, cx)
13949        }))
13950    }
13951
13952    fn definitions(
13953        &self,
13954        buffer: &Model<Buffer>,
13955        position: text::Anchor,
13956        kind: GotoDefinitionKind,
13957        cx: &mut AppContext,
13958    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13959        Some(self.update(cx, |project, cx| match kind {
13960            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13961            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13962            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13963            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13964        }))
13965    }
13966
13967    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13968        // TODO: make this work for remote projects
13969        self.read(cx)
13970            .language_servers_for_local_buffer(buffer.read(cx), cx)
13971            .any(
13972                |(_, server)| match server.capabilities().inlay_hint_provider {
13973                    Some(lsp::OneOf::Left(enabled)) => enabled,
13974                    Some(lsp::OneOf::Right(_)) => true,
13975                    None => false,
13976                },
13977            )
13978    }
13979
13980    fn inlay_hints(
13981        &self,
13982        buffer_handle: Model<Buffer>,
13983        range: Range<text::Anchor>,
13984        cx: &mut AppContext,
13985    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13986        Some(self.update(cx, |project, cx| {
13987            project.inlay_hints(buffer_handle, range, cx)
13988        }))
13989    }
13990
13991    fn resolve_inlay_hint(
13992        &self,
13993        hint: InlayHint,
13994        buffer_handle: Model<Buffer>,
13995        server_id: LanguageServerId,
13996        cx: &mut AppContext,
13997    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13998        Some(self.update(cx, |project, cx| {
13999            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14000        }))
14001    }
14002
14003    fn range_for_rename(
14004        &self,
14005        buffer: &Model<Buffer>,
14006        position: text::Anchor,
14007        cx: &mut AppContext,
14008    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14009        Some(self.update(cx, |project, cx| {
14010            let buffer = buffer.clone();
14011            let task = project.prepare_rename(buffer.clone(), position, cx);
14012            cx.spawn(|_, mut cx| async move {
14013                Ok(match task.await? {
14014                    PrepareRenameResponse::Success(range) => Some(range),
14015                    PrepareRenameResponse::InvalidPosition => None,
14016                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
14017                        // Fallback on using TreeSitter info to determine identifier range
14018                        buffer.update(&mut cx, |buffer, _| {
14019                            let snapshot = buffer.snapshot();
14020                            let (range, kind) = snapshot.surrounding_word(position);
14021                            if kind != Some(CharKind::Word) {
14022                                return None;
14023                            }
14024                            Some(
14025                                snapshot.anchor_before(range.start)
14026                                    ..snapshot.anchor_after(range.end),
14027                            )
14028                        })?
14029                    }
14030                })
14031            })
14032        }))
14033    }
14034
14035    fn perform_rename(
14036        &self,
14037        buffer: &Model<Buffer>,
14038        position: text::Anchor,
14039        new_name: String,
14040        cx: &mut AppContext,
14041    ) -> Option<Task<Result<ProjectTransaction>>> {
14042        Some(self.update(cx, |project, cx| {
14043            project.perform_rename(buffer.clone(), position, new_name, cx)
14044        }))
14045    }
14046}
14047
14048fn inlay_hint_settings(
14049    location: Anchor,
14050    snapshot: &MultiBufferSnapshot,
14051    cx: &mut ViewContext<Editor>,
14052) -> InlayHintSettings {
14053    let file = snapshot.file_at(location);
14054    let language = snapshot.language_at(location).map(|l| l.name());
14055    language_settings(language, file, cx).inlay_hints
14056}
14057
14058fn consume_contiguous_rows(
14059    contiguous_row_selections: &mut Vec<Selection<Point>>,
14060    selection: &Selection<Point>,
14061    display_map: &DisplaySnapshot,
14062    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14063) -> (MultiBufferRow, MultiBufferRow) {
14064    contiguous_row_selections.push(selection.clone());
14065    let start_row = MultiBufferRow(selection.start.row);
14066    let mut end_row = ending_row(selection, display_map);
14067
14068    while let Some(next_selection) = selections.peek() {
14069        if next_selection.start.row <= end_row.0 {
14070            end_row = ending_row(next_selection, display_map);
14071            contiguous_row_selections.push(selections.next().unwrap().clone());
14072        } else {
14073            break;
14074        }
14075    }
14076    (start_row, end_row)
14077}
14078
14079fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14080    if next_selection.end.column > 0 || next_selection.is_empty() {
14081        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14082    } else {
14083        MultiBufferRow(next_selection.end.row)
14084    }
14085}
14086
14087impl EditorSnapshot {
14088    pub fn remote_selections_in_range<'a>(
14089        &'a self,
14090        range: &'a Range<Anchor>,
14091        collaboration_hub: &dyn CollaborationHub,
14092        cx: &'a AppContext,
14093    ) -> impl 'a + Iterator<Item = RemoteSelection> {
14094        let participant_names = collaboration_hub.user_names(cx);
14095        let participant_indices = collaboration_hub.user_participant_indices(cx);
14096        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14097        let collaborators_by_replica_id = collaborators_by_peer_id
14098            .iter()
14099            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14100            .collect::<HashMap<_, _>>();
14101        self.buffer_snapshot
14102            .selections_in_range(range, false)
14103            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14104                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14105                let participant_index = participant_indices.get(&collaborator.user_id).copied();
14106                let user_name = participant_names.get(&collaborator.user_id).cloned();
14107                Some(RemoteSelection {
14108                    replica_id,
14109                    selection,
14110                    cursor_shape,
14111                    line_mode,
14112                    participant_index,
14113                    peer_id: collaborator.peer_id,
14114                    user_name,
14115                })
14116            })
14117    }
14118
14119    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14120        self.display_snapshot.buffer_snapshot.language_at(position)
14121    }
14122
14123    pub fn is_focused(&self) -> bool {
14124        self.is_focused
14125    }
14126
14127    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14128        self.placeholder_text.as_ref()
14129    }
14130
14131    pub fn scroll_position(&self) -> gpui::Point<f32> {
14132        self.scroll_anchor.scroll_position(&self.display_snapshot)
14133    }
14134
14135    fn gutter_dimensions(
14136        &self,
14137        font_id: FontId,
14138        font_size: Pixels,
14139        em_width: Pixels,
14140        em_advance: Pixels,
14141        max_line_number_width: Pixels,
14142        cx: &AppContext,
14143    ) -> GutterDimensions {
14144        if !self.show_gutter {
14145            return GutterDimensions::default();
14146        }
14147        let descent = cx.text_system().descent(font_id, font_size);
14148
14149        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14150            matches!(
14151                ProjectSettings::get_global(cx).git.git_gutter,
14152                Some(GitGutterSetting::TrackedFiles)
14153            )
14154        });
14155        let gutter_settings = EditorSettings::get_global(cx).gutter;
14156        let show_line_numbers = self
14157            .show_line_numbers
14158            .unwrap_or(gutter_settings.line_numbers);
14159        let line_gutter_width = if show_line_numbers {
14160            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14161            let min_width_for_number_on_gutter = em_advance * 4.0;
14162            max_line_number_width.max(min_width_for_number_on_gutter)
14163        } else {
14164            0.0.into()
14165        };
14166
14167        let show_code_actions = self
14168            .show_code_actions
14169            .unwrap_or(gutter_settings.code_actions);
14170
14171        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14172
14173        let git_blame_entries_width =
14174            self.git_blame_gutter_max_author_length
14175                .map(|max_author_length| {
14176                    // Length of the author name, but also space for the commit hash,
14177                    // the spacing and the timestamp.
14178                    let max_char_count = max_author_length
14179                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14180                        + 7 // length of commit sha
14181                        + 14 // length of max relative timestamp ("60 minutes ago")
14182                        + 4; // gaps and margins
14183
14184                    em_advance * max_char_count
14185                });
14186
14187        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14188        left_padding += if show_code_actions || show_runnables {
14189            em_width * 3.0
14190        } else if show_git_gutter && show_line_numbers {
14191            em_width * 2.0
14192        } else if show_git_gutter || show_line_numbers {
14193            em_width
14194        } else {
14195            px(0.)
14196        };
14197
14198        let right_padding = if gutter_settings.folds && show_line_numbers {
14199            em_width * 4.0
14200        } else if gutter_settings.folds {
14201            em_width * 3.0
14202        } else if show_line_numbers {
14203            em_width
14204        } else {
14205            px(0.)
14206        };
14207
14208        GutterDimensions {
14209            left_padding,
14210            right_padding,
14211            width: line_gutter_width + left_padding + right_padding,
14212            margin: -descent,
14213            git_blame_entries_width,
14214        }
14215    }
14216
14217    pub fn render_crease_toggle(
14218        &self,
14219        buffer_row: MultiBufferRow,
14220        row_contains_cursor: bool,
14221        editor: View<Editor>,
14222        cx: &mut WindowContext,
14223    ) -> Option<AnyElement> {
14224        let folded = self.is_line_folded(buffer_row);
14225        let mut is_foldable = false;
14226
14227        if let Some(crease) = self
14228            .crease_snapshot
14229            .query_row(buffer_row, &self.buffer_snapshot)
14230        {
14231            is_foldable = true;
14232            match crease {
14233                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14234                    if let Some(render_toggle) = render_toggle {
14235                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14236                            if folded {
14237                                editor.update(cx, |editor, cx| {
14238                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14239                                });
14240                            } else {
14241                                editor.update(cx, |editor, cx| {
14242                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14243                                });
14244                            }
14245                        });
14246                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14247                    }
14248                }
14249            }
14250        }
14251
14252        is_foldable |= self.starts_indent(buffer_row);
14253
14254        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14255            Some(
14256                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14257                    .toggle_state(folded)
14258                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14259                        if folded {
14260                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14261                        } else {
14262                            this.fold_at(&FoldAt { buffer_row }, cx);
14263                        }
14264                    }))
14265                    .into_any_element(),
14266            )
14267        } else {
14268            None
14269        }
14270    }
14271
14272    pub fn render_crease_trailer(
14273        &self,
14274        buffer_row: MultiBufferRow,
14275        cx: &mut WindowContext,
14276    ) -> Option<AnyElement> {
14277        let folded = self.is_line_folded(buffer_row);
14278        if let Crease::Inline { render_trailer, .. } = self
14279            .crease_snapshot
14280            .query_row(buffer_row, &self.buffer_snapshot)?
14281        {
14282            let render_trailer = render_trailer.as_ref()?;
14283            Some(render_trailer(buffer_row, folded, cx))
14284        } else {
14285            None
14286        }
14287    }
14288}
14289
14290impl Deref for EditorSnapshot {
14291    type Target = DisplaySnapshot;
14292
14293    fn deref(&self) -> &Self::Target {
14294        &self.display_snapshot
14295    }
14296}
14297
14298#[derive(Clone, Debug, PartialEq, Eq)]
14299pub enum EditorEvent {
14300    InputIgnored {
14301        text: Arc<str>,
14302    },
14303    InputHandled {
14304        utf16_range_to_replace: Option<Range<isize>>,
14305        text: Arc<str>,
14306    },
14307    ExcerptsAdded {
14308        buffer: Model<Buffer>,
14309        predecessor: ExcerptId,
14310        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14311    },
14312    ExcerptsRemoved {
14313        ids: Vec<ExcerptId>,
14314    },
14315    BufferFoldToggled {
14316        ids: Vec<ExcerptId>,
14317        folded: bool,
14318    },
14319    ExcerptsEdited {
14320        ids: Vec<ExcerptId>,
14321    },
14322    ExcerptsExpanded {
14323        ids: Vec<ExcerptId>,
14324    },
14325    BufferEdited,
14326    Edited {
14327        transaction_id: clock::Lamport,
14328    },
14329    Reparsed(BufferId),
14330    Focused,
14331    FocusedIn,
14332    Blurred,
14333    DirtyChanged,
14334    Saved,
14335    TitleChanged,
14336    DiffBaseChanged,
14337    SelectionsChanged {
14338        local: bool,
14339    },
14340    ScrollPositionChanged {
14341        local: bool,
14342        autoscroll: bool,
14343    },
14344    Closed,
14345    TransactionUndone {
14346        transaction_id: clock::Lamport,
14347    },
14348    TransactionBegun {
14349        transaction_id: clock::Lamport,
14350    },
14351    Reloaded,
14352    CursorShapeChanged,
14353}
14354
14355impl EventEmitter<EditorEvent> for Editor {}
14356
14357impl FocusableView for Editor {
14358    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14359        self.focus_handle.clone()
14360    }
14361}
14362
14363impl Render for Editor {
14364    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14365        let settings = ThemeSettings::get_global(cx);
14366
14367        let mut text_style = match self.mode {
14368            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14369                color: cx.theme().colors().editor_foreground,
14370                font_family: settings.ui_font.family.clone(),
14371                font_features: settings.ui_font.features.clone(),
14372                font_fallbacks: settings.ui_font.fallbacks.clone(),
14373                font_size: rems(0.875).into(),
14374                font_weight: settings.ui_font.weight,
14375                line_height: relative(settings.buffer_line_height.value()),
14376                ..Default::default()
14377            },
14378            EditorMode::Full => TextStyle {
14379                color: cx.theme().colors().editor_foreground,
14380                font_family: settings.buffer_font.family.clone(),
14381                font_features: settings.buffer_font.features.clone(),
14382                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14383                font_size: settings.buffer_font_size().into(),
14384                font_weight: settings.buffer_font.weight,
14385                line_height: relative(settings.buffer_line_height.value()),
14386                ..Default::default()
14387            },
14388        };
14389        if let Some(text_style_refinement) = &self.text_style_refinement {
14390            text_style.refine(text_style_refinement)
14391        }
14392
14393        let background = match self.mode {
14394            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14395            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14396            EditorMode::Full => cx.theme().colors().editor_background,
14397        };
14398
14399        EditorElement::new(
14400            cx.view(),
14401            EditorStyle {
14402                background,
14403                local_player: cx.theme().players().local(),
14404                text: text_style,
14405                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14406                syntax: cx.theme().syntax().clone(),
14407                status: cx.theme().status().clone(),
14408                inlay_hints_style: make_inlay_hints_style(cx),
14409                inline_completion_styles: make_suggestion_styles(cx),
14410                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14411            },
14412        )
14413    }
14414}
14415
14416impl ViewInputHandler for Editor {
14417    fn text_for_range(
14418        &mut self,
14419        range_utf16: Range<usize>,
14420        adjusted_range: &mut Option<Range<usize>>,
14421        cx: &mut ViewContext<Self>,
14422    ) -> Option<String> {
14423        let snapshot = self.buffer.read(cx).read(cx);
14424        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14425        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14426        if (start.0..end.0) != range_utf16 {
14427            adjusted_range.replace(start.0..end.0);
14428        }
14429        Some(snapshot.text_for_range(start..end).collect())
14430    }
14431
14432    fn selected_text_range(
14433        &mut self,
14434        ignore_disabled_input: bool,
14435        cx: &mut ViewContext<Self>,
14436    ) -> Option<UTF16Selection> {
14437        // Prevent the IME menu from appearing when holding down an alphabetic key
14438        // while input is disabled.
14439        if !ignore_disabled_input && !self.input_enabled {
14440            return None;
14441        }
14442
14443        let selection = self.selections.newest::<OffsetUtf16>(cx);
14444        let range = selection.range();
14445
14446        Some(UTF16Selection {
14447            range: range.start.0..range.end.0,
14448            reversed: selection.reversed,
14449        })
14450    }
14451
14452    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14453        let snapshot = self.buffer.read(cx).read(cx);
14454        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14455        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14456    }
14457
14458    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14459        self.clear_highlights::<InputComposition>(cx);
14460        self.ime_transaction.take();
14461    }
14462
14463    fn replace_text_in_range(
14464        &mut self,
14465        range_utf16: Option<Range<usize>>,
14466        text: &str,
14467        cx: &mut ViewContext<Self>,
14468    ) {
14469        if !self.input_enabled {
14470            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14471            return;
14472        }
14473
14474        self.transact(cx, |this, cx| {
14475            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14476                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14477                Some(this.selection_replacement_ranges(range_utf16, cx))
14478            } else {
14479                this.marked_text_ranges(cx)
14480            };
14481
14482            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14483                let newest_selection_id = this.selections.newest_anchor().id;
14484                this.selections
14485                    .all::<OffsetUtf16>(cx)
14486                    .iter()
14487                    .zip(ranges_to_replace.iter())
14488                    .find_map(|(selection, range)| {
14489                        if selection.id == newest_selection_id {
14490                            Some(
14491                                (range.start.0 as isize - selection.head().0 as isize)
14492                                    ..(range.end.0 as isize - selection.head().0 as isize),
14493                            )
14494                        } else {
14495                            None
14496                        }
14497                    })
14498            });
14499
14500            cx.emit(EditorEvent::InputHandled {
14501                utf16_range_to_replace: range_to_replace,
14502                text: text.into(),
14503            });
14504
14505            if let Some(new_selected_ranges) = new_selected_ranges {
14506                this.change_selections(None, cx, |selections| {
14507                    selections.select_ranges(new_selected_ranges)
14508                });
14509                this.backspace(&Default::default(), cx);
14510            }
14511
14512            this.handle_input(text, cx);
14513        });
14514
14515        if let Some(transaction) = self.ime_transaction {
14516            self.buffer.update(cx, |buffer, cx| {
14517                buffer.group_until_transaction(transaction, cx);
14518            });
14519        }
14520
14521        self.unmark_text(cx);
14522    }
14523
14524    fn replace_and_mark_text_in_range(
14525        &mut self,
14526        range_utf16: Option<Range<usize>>,
14527        text: &str,
14528        new_selected_range_utf16: Option<Range<usize>>,
14529        cx: &mut ViewContext<Self>,
14530    ) {
14531        if !self.input_enabled {
14532            return;
14533        }
14534
14535        let transaction = self.transact(cx, |this, cx| {
14536            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14537                let snapshot = this.buffer.read(cx).read(cx);
14538                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14539                    for marked_range in &mut marked_ranges {
14540                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14541                        marked_range.start.0 += relative_range_utf16.start;
14542                        marked_range.start =
14543                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14544                        marked_range.end =
14545                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14546                    }
14547                }
14548                Some(marked_ranges)
14549            } else if let Some(range_utf16) = range_utf16 {
14550                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14551                Some(this.selection_replacement_ranges(range_utf16, cx))
14552            } else {
14553                None
14554            };
14555
14556            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14557                let newest_selection_id = this.selections.newest_anchor().id;
14558                this.selections
14559                    .all::<OffsetUtf16>(cx)
14560                    .iter()
14561                    .zip(ranges_to_replace.iter())
14562                    .find_map(|(selection, range)| {
14563                        if selection.id == newest_selection_id {
14564                            Some(
14565                                (range.start.0 as isize - selection.head().0 as isize)
14566                                    ..(range.end.0 as isize - selection.head().0 as isize),
14567                            )
14568                        } else {
14569                            None
14570                        }
14571                    })
14572            });
14573
14574            cx.emit(EditorEvent::InputHandled {
14575                utf16_range_to_replace: range_to_replace,
14576                text: text.into(),
14577            });
14578
14579            if let Some(ranges) = ranges_to_replace {
14580                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14581            }
14582
14583            let marked_ranges = {
14584                let snapshot = this.buffer.read(cx).read(cx);
14585                this.selections
14586                    .disjoint_anchors()
14587                    .iter()
14588                    .map(|selection| {
14589                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14590                    })
14591                    .collect::<Vec<_>>()
14592            };
14593
14594            if text.is_empty() {
14595                this.unmark_text(cx);
14596            } else {
14597                this.highlight_text::<InputComposition>(
14598                    marked_ranges.clone(),
14599                    HighlightStyle {
14600                        underline: Some(UnderlineStyle {
14601                            thickness: px(1.),
14602                            color: None,
14603                            wavy: false,
14604                        }),
14605                        ..Default::default()
14606                    },
14607                    cx,
14608                );
14609            }
14610
14611            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14612            let use_autoclose = this.use_autoclose;
14613            let use_auto_surround = this.use_auto_surround;
14614            this.set_use_autoclose(false);
14615            this.set_use_auto_surround(false);
14616            this.handle_input(text, cx);
14617            this.set_use_autoclose(use_autoclose);
14618            this.set_use_auto_surround(use_auto_surround);
14619
14620            if let Some(new_selected_range) = new_selected_range_utf16 {
14621                let snapshot = this.buffer.read(cx).read(cx);
14622                let new_selected_ranges = marked_ranges
14623                    .into_iter()
14624                    .map(|marked_range| {
14625                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14626                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14627                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14628                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14629                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14630                    })
14631                    .collect::<Vec<_>>();
14632
14633                drop(snapshot);
14634                this.change_selections(None, cx, |selections| {
14635                    selections.select_ranges(new_selected_ranges)
14636                });
14637            }
14638        });
14639
14640        self.ime_transaction = self.ime_transaction.or(transaction);
14641        if let Some(transaction) = self.ime_transaction {
14642            self.buffer.update(cx, |buffer, cx| {
14643                buffer.group_until_transaction(transaction, cx);
14644            });
14645        }
14646
14647        if self.text_highlights::<InputComposition>(cx).is_none() {
14648            self.ime_transaction.take();
14649        }
14650    }
14651
14652    fn bounds_for_range(
14653        &mut self,
14654        range_utf16: Range<usize>,
14655        element_bounds: gpui::Bounds<Pixels>,
14656        cx: &mut ViewContext<Self>,
14657    ) -> Option<gpui::Bounds<Pixels>> {
14658        let text_layout_details = self.text_layout_details(cx);
14659        let gpui::Point {
14660            x: em_width,
14661            y: line_height,
14662        } = self.character_size(cx);
14663
14664        let snapshot = self.snapshot(cx);
14665        let scroll_position = snapshot.scroll_position();
14666        let scroll_left = scroll_position.x * em_width;
14667
14668        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14669        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14670            + self.gutter_dimensions.width
14671            + self.gutter_dimensions.margin;
14672        let y = line_height * (start.row().as_f32() - scroll_position.y);
14673
14674        Some(Bounds {
14675            origin: element_bounds.origin + point(x, y),
14676            size: size(em_width, line_height),
14677        })
14678    }
14679}
14680
14681trait SelectionExt {
14682    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14683    fn spanned_rows(
14684        &self,
14685        include_end_if_at_line_start: bool,
14686        map: &DisplaySnapshot,
14687    ) -> Range<MultiBufferRow>;
14688}
14689
14690impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14691    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14692        let start = self
14693            .start
14694            .to_point(&map.buffer_snapshot)
14695            .to_display_point(map);
14696        let end = self
14697            .end
14698            .to_point(&map.buffer_snapshot)
14699            .to_display_point(map);
14700        if self.reversed {
14701            end..start
14702        } else {
14703            start..end
14704        }
14705    }
14706
14707    fn spanned_rows(
14708        &self,
14709        include_end_if_at_line_start: bool,
14710        map: &DisplaySnapshot,
14711    ) -> Range<MultiBufferRow> {
14712        let start = self.start.to_point(&map.buffer_snapshot);
14713        let mut end = self.end.to_point(&map.buffer_snapshot);
14714        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14715            end.row -= 1;
14716        }
14717
14718        let buffer_start = map.prev_line_boundary(start).0;
14719        let buffer_end = map.next_line_boundary(end).0;
14720        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14721    }
14722}
14723
14724impl<T: InvalidationRegion> InvalidationStack<T> {
14725    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14726    where
14727        S: Clone + ToOffset,
14728    {
14729        while let Some(region) = self.last() {
14730            let all_selections_inside_invalidation_ranges =
14731                if selections.len() == region.ranges().len() {
14732                    selections
14733                        .iter()
14734                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14735                        .all(|(selection, invalidation_range)| {
14736                            let head = selection.head().to_offset(buffer);
14737                            invalidation_range.start <= head && invalidation_range.end >= head
14738                        })
14739                } else {
14740                    false
14741                };
14742
14743            if all_selections_inside_invalidation_ranges {
14744                break;
14745            } else {
14746                self.pop();
14747            }
14748        }
14749    }
14750}
14751
14752impl<T> Default for InvalidationStack<T> {
14753    fn default() -> Self {
14754        Self(Default::default())
14755    }
14756}
14757
14758impl<T> Deref for InvalidationStack<T> {
14759    type Target = Vec<T>;
14760
14761    fn deref(&self) -> &Self::Target {
14762        &self.0
14763    }
14764}
14765
14766impl<T> DerefMut for InvalidationStack<T> {
14767    fn deref_mut(&mut self) -> &mut Self::Target {
14768        &mut self.0
14769    }
14770}
14771
14772impl InvalidationRegion for SnippetState {
14773    fn ranges(&self) -> &[Range<Anchor>] {
14774        &self.ranges[self.active_index]
14775    }
14776}
14777
14778pub fn diagnostic_block_renderer(
14779    diagnostic: Diagnostic,
14780    max_message_rows: Option<u8>,
14781    allow_closing: bool,
14782    _is_valid: bool,
14783) -> RenderBlock {
14784    let (text_without_backticks, code_ranges) =
14785        highlight_diagnostic_message(&diagnostic, max_message_rows);
14786
14787    Arc::new(move |cx: &mut BlockContext| {
14788        let group_id: SharedString = cx.block_id.to_string().into();
14789
14790        let mut text_style = cx.text_style().clone();
14791        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14792        let theme_settings = ThemeSettings::get_global(cx);
14793        text_style.font_family = theme_settings.buffer_font.family.clone();
14794        text_style.font_style = theme_settings.buffer_font.style;
14795        text_style.font_features = theme_settings.buffer_font.features.clone();
14796        text_style.font_weight = theme_settings.buffer_font.weight;
14797
14798        let multi_line_diagnostic = diagnostic.message.contains('\n');
14799
14800        let buttons = |diagnostic: &Diagnostic| {
14801            if multi_line_diagnostic {
14802                v_flex()
14803            } else {
14804                h_flex()
14805            }
14806            .when(allow_closing, |div| {
14807                div.children(diagnostic.is_primary.then(|| {
14808                    IconButton::new("close-block", IconName::XCircle)
14809                        .icon_color(Color::Muted)
14810                        .size(ButtonSize::Compact)
14811                        .style(ButtonStyle::Transparent)
14812                        .visible_on_hover(group_id.clone())
14813                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14814                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14815                }))
14816            })
14817            .child(
14818                IconButton::new("copy-block", IconName::Copy)
14819                    .icon_color(Color::Muted)
14820                    .size(ButtonSize::Compact)
14821                    .style(ButtonStyle::Transparent)
14822                    .visible_on_hover(group_id.clone())
14823                    .on_click({
14824                        let message = diagnostic.message.clone();
14825                        move |_click, cx| {
14826                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14827                        }
14828                    })
14829                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14830            )
14831        };
14832
14833        let icon_size = buttons(&diagnostic)
14834            .into_any_element()
14835            .layout_as_root(AvailableSpace::min_size(), cx);
14836
14837        h_flex()
14838            .id(cx.block_id)
14839            .group(group_id.clone())
14840            .relative()
14841            .size_full()
14842            .block_mouse_down()
14843            .pl(cx.gutter_dimensions.width)
14844            .w(cx.max_width - cx.gutter_dimensions.full_width())
14845            .child(
14846                div()
14847                    .flex()
14848                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14849                    .flex_shrink(),
14850            )
14851            .child(buttons(&diagnostic))
14852            .child(div().flex().flex_shrink_0().child(
14853                StyledText::new(text_without_backticks.clone()).with_highlights(
14854                    &text_style,
14855                    code_ranges.iter().map(|range| {
14856                        (
14857                            range.clone(),
14858                            HighlightStyle {
14859                                font_weight: Some(FontWeight::BOLD),
14860                                ..Default::default()
14861                            },
14862                        )
14863                    }),
14864                ),
14865            ))
14866            .into_any_element()
14867    })
14868}
14869
14870fn inline_completion_edit_text(
14871    editor_snapshot: &EditorSnapshot,
14872    edits: &Vec<(Range<Anchor>, String)>,
14873    include_deletions: bool,
14874    cx: &WindowContext,
14875) -> InlineCompletionText {
14876    let edit_start = edits
14877        .first()
14878        .unwrap()
14879        .0
14880        .start
14881        .to_display_point(editor_snapshot);
14882
14883    let mut text = String::new();
14884    let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14885    let mut highlights = Vec::new();
14886    for (old_range, new_text) in edits {
14887        let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14888        text.extend(
14889            editor_snapshot
14890                .buffer_snapshot
14891                .chunks(offset..old_offset_range.start, false)
14892                .map(|chunk| chunk.text),
14893        );
14894        offset = old_offset_range.end;
14895
14896        let start = text.len();
14897        let color = if include_deletions && new_text.is_empty() {
14898            text.extend(
14899                editor_snapshot
14900                    .buffer_snapshot
14901                    .chunks(old_offset_range.start..offset, false)
14902                    .map(|chunk| chunk.text),
14903            );
14904            cx.theme().status().deleted_background
14905        } else {
14906            text.push_str(new_text);
14907            cx.theme().status().created_background
14908        };
14909        let end = text.len();
14910
14911        highlights.push((
14912            start..end,
14913            HighlightStyle {
14914                background_color: Some(color),
14915                ..Default::default()
14916            },
14917        ));
14918    }
14919
14920    let edit_end = edits
14921        .last()
14922        .unwrap()
14923        .0
14924        .end
14925        .to_display_point(editor_snapshot);
14926    let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14927        .to_offset(editor_snapshot, Bias::Right);
14928    text.extend(
14929        editor_snapshot
14930            .buffer_snapshot
14931            .chunks(offset..end_of_line, false)
14932            .map(|chunk| chunk.text),
14933    );
14934
14935    InlineCompletionText::Edit {
14936        text: text.into(),
14937        highlights,
14938    }
14939}
14940
14941pub fn highlight_diagnostic_message(
14942    diagnostic: &Diagnostic,
14943    mut max_message_rows: Option<u8>,
14944) -> (SharedString, Vec<Range<usize>>) {
14945    let mut text_without_backticks = String::new();
14946    let mut code_ranges = Vec::new();
14947
14948    if let Some(source) = &diagnostic.source {
14949        text_without_backticks.push_str(source);
14950        code_ranges.push(0..source.len());
14951        text_without_backticks.push_str(": ");
14952    }
14953
14954    let mut prev_offset = 0;
14955    let mut in_code_block = false;
14956    let has_row_limit = max_message_rows.is_some();
14957    let mut newline_indices = diagnostic
14958        .message
14959        .match_indices('\n')
14960        .filter(|_| has_row_limit)
14961        .map(|(ix, _)| ix)
14962        .fuse()
14963        .peekable();
14964
14965    for (quote_ix, _) in diagnostic
14966        .message
14967        .match_indices('`')
14968        .chain([(diagnostic.message.len(), "")])
14969    {
14970        let mut first_newline_ix = None;
14971        let mut last_newline_ix = None;
14972        while let Some(newline_ix) = newline_indices.peek() {
14973            if *newline_ix < quote_ix {
14974                if first_newline_ix.is_none() {
14975                    first_newline_ix = Some(*newline_ix);
14976                }
14977                last_newline_ix = Some(*newline_ix);
14978
14979                if let Some(rows_left) = &mut max_message_rows {
14980                    if *rows_left == 0 {
14981                        break;
14982                    } else {
14983                        *rows_left -= 1;
14984                    }
14985                }
14986                let _ = newline_indices.next();
14987            } else {
14988                break;
14989            }
14990        }
14991        let prev_len = text_without_backticks.len();
14992        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14993        text_without_backticks.push_str(new_text);
14994        if in_code_block {
14995            code_ranges.push(prev_len..text_without_backticks.len());
14996        }
14997        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14998        in_code_block = !in_code_block;
14999        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15000            text_without_backticks.push_str("...");
15001            break;
15002        }
15003    }
15004
15005    (text_without_backticks.into(), code_ranges)
15006}
15007
15008fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15009    match severity {
15010        DiagnosticSeverity::ERROR => colors.error,
15011        DiagnosticSeverity::WARNING => colors.warning,
15012        DiagnosticSeverity::INFORMATION => colors.info,
15013        DiagnosticSeverity::HINT => colors.info,
15014        _ => colors.ignored,
15015    }
15016}
15017
15018pub fn styled_runs_for_code_label<'a>(
15019    label: &'a CodeLabel,
15020    syntax_theme: &'a theme::SyntaxTheme,
15021) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15022    let fade_out = HighlightStyle {
15023        fade_out: Some(0.35),
15024        ..Default::default()
15025    };
15026
15027    let mut prev_end = label.filter_range.end;
15028    label
15029        .runs
15030        .iter()
15031        .enumerate()
15032        .flat_map(move |(ix, (range, highlight_id))| {
15033            let style = if let Some(style) = highlight_id.style(syntax_theme) {
15034                style
15035            } else {
15036                return Default::default();
15037            };
15038            let mut muted_style = style;
15039            muted_style.highlight(fade_out);
15040
15041            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15042            if range.start >= label.filter_range.end {
15043                if range.start > prev_end {
15044                    runs.push((prev_end..range.start, fade_out));
15045                }
15046                runs.push((range.clone(), muted_style));
15047            } else if range.end <= label.filter_range.end {
15048                runs.push((range.clone(), style));
15049            } else {
15050                runs.push((range.start..label.filter_range.end, style));
15051                runs.push((label.filter_range.end..range.end, muted_style));
15052            }
15053            prev_end = cmp::max(prev_end, range.end);
15054
15055            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15056                runs.push((prev_end..label.text.len(), fade_out));
15057            }
15058
15059            runs
15060        })
15061}
15062
15063pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15064    let mut prev_index = 0;
15065    let mut prev_codepoint: Option<char> = None;
15066    text.char_indices()
15067        .chain([(text.len(), '\0')])
15068        .filter_map(move |(index, codepoint)| {
15069            let prev_codepoint = prev_codepoint.replace(codepoint)?;
15070            let is_boundary = index == text.len()
15071                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15072                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15073            if is_boundary {
15074                let chunk = &text[prev_index..index];
15075                prev_index = index;
15076                Some(chunk)
15077            } else {
15078                None
15079            }
15080        })
15081}
15082
15083pub trait RangeToAnchorExt: Sized {
15084    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15085
15086    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15087        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15088        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15089    }
15090}
15091
15092impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15093    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15094        let start_offset = self.start.to_offset(snapshot);
15095        let end_offset = self.end.to_offset(snapshot);
15096        if start_offset == end_offset {
15097            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15098        } else {
15099            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15100        }
15101    }
15102}
15103
15104pub trait RowExt {
15105    fn as_f32(&self) -> f32;
15106
15107    fn next_row(&self) -> Self;
15108
15109    fn previous_row(&self) -> Self;
15110
15111    fn minus(&self, other: Self) -> u32;
15112}
15113
15114impl RowExt for DisplayRow {
15115    fn as_f32(&self) -> f32 {
15116        self.0 as f32
15117    }
15118
15119    fn next_row(&self) -> Self {
15120        Self(self.0 + 1)
15121    }
15122
15123    fn previous_row(&self) -> Self {
15124        Self(self.0.saturating_sub(1))
15125    }
15126
15127    fn minus(&self, other: Self) -> u32 {
15128        self.0 - other.0
15129    }
15130}
15131
15132impl RowExt for MultiBufferRow {
15133    fn as_f32(&self) -> f32 {
15134        self.0 as f32
15135    }
15136
15137    fn next_row(&self) -> Self {
15138        Self(self.0 + 1)
15139    }
15140
15141    fn previous_row(&self) -> Self {
15142        Self(self.0.saturating_sub(1))
15143    }
15144
15145    fn minus(&self, other: Self) -> u32 {
15146        self.0 - other.0
15147    }
15148}
15149
15150trait RowRangeExt {
15151    type Row;
15152
15153    fn len(&self) -> usize;
15154
15155    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15156}
15157
15158impl RowRangeExt for Range<MultiBufferRow> {
15159    type Row = MultiBufferRow;
15160
15161    fn len(&self) -> usize {
15162        (self.end.0 - self.start.0) as usize
15163    }
15164
15165    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15166        (self.start.0..self.end.0).map(MultiBufferRow)
15167    }
15168}
15169
15170impl RowRangeExt for Range<DisplayRow> {
15171    type Row = DisplayRow;
15172
15173    fn len(&self) -> usize {
15174        (self.end.0 - self.start.0) as usize
15175    }
15176
15177    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15178        (self.start.0..self.end.0).map(DisplayRow)
15179    }
15180}
15181
15182fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15183    if hunk.diff_base_byte_range.is_empty() {
15184        DiffHunkStatus::Added
15185    } else if hunk.row_range.is_empty() {
15186        DiffHunkStatus::Removed
15187    } else {
15188        DiffHunkStatus::Modified
15189    }
15190}
15191
15192/// If select range has more than one line, we
15193/// just point the cursor to range.start.
15194fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15195    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15196        range
15197    } else {
15198        range.start..range.start
15199    }
15200}
15201
15202pub struct KillRing(ClipboardItem);
15203impl Global for KillRing {}
15204
15205const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);