editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod code_context_menus;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50use ::git::diff::DiffHunkStatus;
   51pub(crate) use actions::*;
   52pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   53use aho_corasick::AhoCorasick;
   54use anyhow::{anyhow, Context as _, Result};
   55use blink_manager::BlinkManager;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::LineWithInvisibles;
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{future, FutureExt};
   71use fuzzy::StringMatchCandidate;
   72use zed_predict_tos::ZedPredictTos;
   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};
   91use indent_guides::ActiveIndentGuidesState;
   92use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   93pub use inline_completion::Direction;
   94use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
   95pub use items::MAX_TAB_TITLE_LEN;
   96use itertools::Itertools;
   97use language::{
   98    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
   99    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  100    CursorShape, Diagnostic, Documentation, EditPreview, HighlightedEdits, IndentKind, IndentSize,
  101    Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject, TransactionId,
  102    TreeSitterOptions,
  103};
  104use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  105use linked_editing_ranges::refresh_linked_ranges;
  106use mouse_context_menu::MouseContextMenu;
  107pub use proposed_changes_editor::{
  108    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  109};
  110use similar::{ChangeTag, TextDiff};
  111use std::iter::Peekable;
  112use task::{ResolvedTask, TaskTemplate, TaskVariables};
  113
  114use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  115pub use lsp::CompletionContext;
  116use lsp::{
  117    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  118    LanguageServerId, LanguageServerName,
  119};
  120
  121use language::BufferSnapshot;
  122use movement::TextLayoutDetails;
  123pub use multi_buffer::{
  124    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  125    ToOffset, ToPoint,
  126};
  127use multi_buffer::{
  128    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  129};
  130use project::{
  131    lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  132    project_settings::{GitGutterSetting, ProjectSettings},
  133    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  134    LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  135};
  136use rand::prelude::*;
  137use rpc::{proto::*, ErrorExt};
  138use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  139use selections_collection::{
  140    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  141};
  142use serde::{Deserialize, Serialize};
  143use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  144use smallvec::SmallVec;
  145use snippet::Snippet;
  146use std::{
  147    any::TypeId,
  148    borrow::Cow,
  149    cell::RefCell,
  150    cmp::{self, Ordering, Reverse},
  151    mem,
  152    num::NonZeroU32,
  153    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  154    path::{Path, PathBuf},
  155    rc::Rc,
  156    sync::Arc,
  157    time::{Duration, Instant},
  158};
  159pub use sum_tree::Bias;
  160use sum_tree::TreeMap;
  161use text::{BufferId, OffsetUtf16, Rope};
  162use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
  163use ui::{
  164    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  165    Tooltip,
  166};
  167use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  168use workspace::item::{ItemHandle, PreviewTabsSettings};
  169use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  170use workspace::{
  171    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  172};
  173use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  174
  175use crate::hover_links::{find_url, find_url_from_range};
  176use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  177
  178pub const FILE_HEADER_HEIGHT: u32 = 2;
  179pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  180pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  181pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  182const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  183const MAX_LINE_LEN: usize = 1024;
  184const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  185const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  186pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  187#[doc(hidden)]
  188pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  189
  190pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  191pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  192
  193pub fn render_parsed_markdown(
  194    element_id: impl Into<ElementId>,
  195    parsed: &language::ParsedMarkdown,
  196    editor_style: &EditorStyle,
  197    workspace: Option<WeakView<Workspace>>,
  198    cx: &mut WindowContext,
  199) -> InteractiveText {
  200    let code_span_background_color = cx
  201        .theme()
  202        .colors()
  203        .editor_document_highlight_read_background;
  204
  205    let highlights = gpui::combine_highlights(
  206        parsed.highlights.iter().filter_map(|(range, highlight)| {
  207            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  208            Some((range.clone(), highlight))
  209        }),
  210        parsed
  211            .regions
  212            .iter()
  213            .zip(&parsed.region_ranges)
  214            .filter_map(|(region, range)| {
  215                if region.code {
  216                    Some((
  217                        range.clone(),
  218                        HighlightStyle {
  219                            background_color: Some(code_span_background_color),
  220                            ..Default::default()
  221                        },
  222                    ))
  223                } else {
  224                    None
  225                }
  226            }),
  227    );
  228
  229    let mut links = Vec::new();
  230    let mut link_ranges = Vec::new();
  231    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  232        if let Some(link) = region.link.clone() {
  233            links.push(link);
  234            link_ranges.push(range.clone());
  235        }
  236    }
  237
  238    InteractiveText::new(
  239        element_id,
  240        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  241    )
  242    .on_click(link_ranges, move |clicked_range_ix, cx| {
  243        match &links[clicked_range_ix] {
  244            markdown::Link::Web { url } => cx.open_url(url),
  245            markdown::Link::Path { path } => {
  246                if let Some(workspace) = &workspace {
  247                    _ = workspace.update(cx, |workspace, cx| {
  248                        workspace.open_abs_path(path.clone(), false, cx).detach();
  249                    });
  250                }
  251            }
  252        }
  253    })
  254}
  255
  256#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  257pub enum InlayId {
  258    InlineCompletion(usize),
  259    Hint(usize),
  260}
  261
  262impl InlayId {
  263    fn id(&self) -> usize {
  264        match self {
  265            Self::InlineCompletion(id) => *id,
  266            Self::Hint(id) => *id,
  267        }
  268    }
  269}
  270
  271enum DocumentHighlightRead {}
  272enum DocumentHighlightWrite {}
  273enum InputComposition {}
  274
  275#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  276pub enum Navigated {
  277    Yes,
  278    No,
  279}
  280
  281impl Navigated {
  282    pub fn from_bool(yes: bool) -> Navigated {
  283        if yes {
  284            Navigated::Yes
  285        } else {
  286            Navigated::No
  287        }
  288    }
  289}
  290
  291pub fn init_settings(cx: &mut AppContext) {
  292    EditorSettings::register(cx);
  293}
  294
  295pub fn init(cx: &mut AppContext) {
  296    init_settings(cx);
  297
  298    workspace::register_project_item::<Editor>(cx);
  299    workspace::FollowableViewRegistry::register::<Editor>(cx);
  300    workspace::register_serializable_item::<Editor>(cx);
  301
  302    cx.observe_new_views(
  303        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  304            workspace.register_action(Editor::new_file);
  305            workspace.register_action(Editor::new_file_vertical);
  306            workspace.register_action(Editor::new_file_horizontal);
  307        },
  308    )
  309    .detach();
  310
  311    cx.on_action(move |_: &workspace::NewFile, cx| {
  312        let app_state = workspace::AppState::global(cx);
  313        if let Some(app_state) = app_state.upgrade() {
  314            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  315                Editor::new_file(workspace, &Default::default(), cx)
  316            })
  317            .detach();
  318        }
  319    });
  320    cx.on_action(move |_: &workspace::NewWindow, cx| {
  321        let app_state = workspace::AppState::global(cx);
  322        if let Some(app_state) = app_state.upgrade() {
  323            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  324                Editor::new_file(workspace, &Default::default(), cx)
  325            })
  326            .detach();
  327        }
  328    });
  329    git::project_diff::init(cx);
  330}
  331
  332pub struct SearchWithinRange;
  333
  334trait InvalidationRegion {
  335    fn ranges(&self) -> &[Range<Anchor>];
  336}
  337
  338#[derive(Clone, Debug, PartialEq)]
  339pub enum SelectPhase {
  340    Begin {
  341        position: DisplayPoint,
  342        add: bool,
  343        click_count: usize,
  344    },
  345    BeginColumnar {
  346        position: DisplayPoint,
  347        reset: bool,
  348        goal_column: u32,
  349    },
  350    Extend {
  351        position: DisplayPoint,
  352        click_count: usize,
  353    },
  354    Update {
  355        position: DisplayPoint,
  356        goal_column: u32,
  357        scroll_delta: gpui::Point<f32>,
  358    },
  359    End,
  360}
  361
  362#[derive(Clone, Debug)]
  363pub enum SelectMode {
  364    Character,
  365    Word(Range<Anchor>),
  366    Line(Range<Anchor>),
  367    All,
  368}
  369
  370#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  371pub enum EditorMode {
  372    SingleLine { auto_width: bool },
  373    AutoHeight { max_lines: usize },
  374    Full,
  375}
  376
  377#[derive(Copy, Clone, Debug)]
  378pub enum SoftWrap {
  379    /// Prefer not to wrap at all.
  380    ///
  381    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  382    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  383    GitDiff,
  384    /// Prefer a single line generally, unless an overly long line is encountered.
  385    None,
  386    /// Soft wrap lines that exceed the editor width.
  387    EditorWidth,
  388    /// Soft wrap lines at the preferred line length.
  389    Column(u32),
  390    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  391    Bounded(u32),
  392}
  393
  394#[derive(Clone)]
  395pub struct EditorStyle {
  396    pub background: Hsla,
  397    pub local_player: PlayerColor,
  398    pub text: TextStyle,
  399    pub scrollbar_width: Pixels,
  400    pub syntax: Arc<SyntaxTheme>,
  401    pub status: StatusColors,
  402    pub inlay_hints_style: HighlightStyle,
  403    pub inline_completion_styles: InlineCompletionStyles,
  404    pub unnecessary_code_fade: f32,
  405}
  406
  407impl Default for EditorStyle {
  408    fn default() -> Self {
  409        Self {
  410            background: Hsla::default(),
  411            local_player: PlayerColor::default(),
  412            text: TextStyle::default(),
  413            scrollbar_width: Pixels::default(),
  414            syntax: Default::default(),
  415            // HACK: Status colors don't have a real default.
  416            // We should look into removing the status colors from the editor
  417            // style and retrieve them directly from the theme.
  418            status: StatusColors::dark(),
  419            inlay_hints_style: HighlightStyle::default(),
  420            inline_completion_styles: InlineCompletionStyles {
  421                insertion: HighlightStyle::default(),
  422                whitespace: HighlightStyle::default(),
  423            },
  424            unnecessary_code_fade: Default::default(),
  425        }
  426    }
  427}
  428
  429pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  430    let show_background = language_settings::language_settings(None, None, cx)
  431        .inlay_hints
  432        .show_background;
  433
  434    HighlightStyle {
  435        color: Some(cx.theme().status().hint),
  436        background_color: show_background.then(|| cx.theme().status().hint_background),
  437        ..HighlightStyle::default()
  438    }
  439}
  440
  441pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
  442    InlineCompletionStyles {
  443        insertion: HighlightStyle {
  444            color: Some(cx.theme().status().predictive),
  445            ..HighlightStyle::default()
  446        },
  447        whitespace: HighlightStyle {
  448            background_color: Some(cx.theme().status().created_background),
  449            ..HighlightStyle::default()
  450        },
  451    }
  452}
  453
  454type CompletionId = usize;
  455
  456#[derive(Debug, Clone)]
  457enum InlineCompletionMenuHint {
  458    Loading,
  459    Loaded { text: InlineCompletionText },
  460    PendingTermsAcceptance,
  461    None,
  462}
  463
  464impl InlineCompletionMenuHint {
  465    pub fn label(&self) -> &'static str {
  466        match self {
  467            InlineCompletionMenuHint::Loading | InlineCompletionMenuHint::Loaded { .. } => {
  468                "Edit Prediction"
  469            }
  470            InlineCompletionMenuHint::PendingTermsAcceptance => "Accept Terms of Service",
  471            InlineCompletionMenuHint::None => "No Prediction",
  472        }
  473    }
  474}
  475
  476#[derive(Clone, Debug)]
  477enum InlineCompletionText {
  478    Move(SharedString),
  479    Edit(HighlightedEdits),
  480}
  481
  482pub(crate) enum EditDisplayMode {
  483    TabAccept,
  484    DiffPopover,
  485    Inline,
  486}
  487
  488enum InlineCompletion {
  489    Edit {
  490        edits: Vec<(Range<Anchor>, String)>,
  491        edit_preview: Option<EditPreview>,
  492        display_mode: EditDisplayMode,
  493        snapshot: BufferSnapshot,
  494    },
  495    Move(Anchor),
  496}
  497
  498struct InlineCompletionState {
  499    inlay_ids: Vec<InlayId>,
  500    completion: InlineCompletion,
  501    invalidation_range: Range<Anchor>,
  502}
  503
  504enum InlineCompletionHighlight {}
  505
  506pub enum MenuInlineCompletionsPolicy {
  507    Never,
  508    ByProvider,
  509}
  510
  511#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  512struct EditorActionId(usize);
  513
  514impl EditorActionId {
  515    pub fn post_inc(&mut self) -> Self {
  516        let answer = self.0;
  517
  518        *self = Self(answer + 1);
  519
  520        Self(answer)
  521    }
  522}
  523
  524// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  525// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  526
  527type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  528type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  529
  530#[derive(Default)]
  531struct ScrollbarMarkerState {
  532    scrollbar_size: Size<Pixels>,
  533    dirty: bool,
  534    markers: Arc<[PaintQuad]>,
  535    pending_refresh: Option<Task<Result<()>>>,
  536}
  537
  538impl ScrollbarMarkerState {
  539    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  540        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  541    }
  542}
  543
  544#[derive(Clone, Debug)]
  545struct RunnableTasks {
  546    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  547    offset: MultiBufferOffset,
  548    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  549    column: u32,
  550    // Values of all named captures, including those starting with '_'
  551    extra_variables: HashMap<String, String>,
  552    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  553    context_range: Range<BufferOffset>,
  554}
  555
  556impl RunnableTasks {
  557    fn resolve<'a>(
  558        &'a self,
  559        cx: &'a task::TaskContext,
  560    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  561        self.templates.iter().filter_map(|(kind, template)| {
  562            template
  563                .resolve_task(&kind.to_id_base(), cx)
  564                .map(|task| (kind.clone(), task))
  565        })
  566    }
  567}
  568
  569#[derive(Clone)]
  570struct ResolvedTasks {
  571    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  572    position: Anchor,
  573}
  574#[derive(Copy, Clone, Debug)]
  575struct MultiBufferOffset(usize);
  576#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  577struct BufferOffset(usize);
  578
  579// Addons allow storing per-editor state in other crates (e.g. Vim)
  580pub trait Addon: 'static {
  581    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  582
  583    fn to_any(&self) -> &dyn std::any::Any;
  584}
  585
  586#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  587pub enum IsVimMode {
  588    Yes,
  589    No,
  590}
  591
  592/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  593///
  594/// See the [module level documentation](self) for more information.
  595pub struct Editor {
  596    focus_handle: FocusHandle,
  597    last_focused_descendant: Option<WeakFocusHandle>,
  598    /// The text buffer being edited
  599    buffer: Model<MultiBuffer>,
  600    /// Map of how text in the buffer should be displayed.
  601    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  602    pub display_map: Model<DisplayMap>,
  603    pub selections: SelectionsCollection,
  604    pub scroll_manager: ScrollManager,
  605    /// When inline assist editors are linked, they all render cursors because
  606    /// typing enters text into each of them, even the ones that aren't focused.
  607    pub(crate) show_cursor_when_unfocused: bool,
  608    columnar_selection_tail: Option<Anchor>,
  609    add_selections_state: Option<AddSelectionsState>,
  610    select_next_state: Option<SelectNextState>,
  611    select_prev_state: Option<SelectNextState>,
  612    selection_history: SelectionHistory,
  613    autoclose_regions: Vec<AutocloseRegion>,
  614    snippet_stack: InvalidationStack<SnippetState>,
  615    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  616    ime_transaction: Option<TransactionId>,
  617    active_diagnostics: Option<ActiveDiagnosticGroup>,
  618    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  619
  620    project: Option<Model<Project>>,
  621    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  622    completion_provider: Option<Box<dyn CompletionProvider>>,
  623    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  624    blink_manager: Model<BlinkManager>,
  625    show_cursor_names: bool,
  626    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  627    pub show_local_selections: bool,
  628    mode: EditorMode,
  629    show_breadcrumbs: bool,
  630    show_gutter: bool,
  631    show_scrollbars: bool,
  632    show_line_numbers: Option<bool>,
  633    use_relative_line_numbers: Option<bool>,
  634    show_git_diff_gutter: Option<bool>,
  635    show_code_actions: Option<bool>,
  636    show_runnables: Option<bool>,
  637    show_wrap_guides: Option<bool>,
  638    show_indent_guides: Option<bool>,
  639    placeholder_text: Option<Arc<str>>,
  640    highlight_order: usize,
  641    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  642    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  643    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  644    scrollbar_marker_state: ScrollbarMarkerState,
  645    active_indent_guides_state: ActiveIndentGuidesState,
  646    nav_history: Option<ItemNavHistory>,
  647    context_menu: RefCell<Option<CodeContextMenu>>,
  648    mouse_context_menu: Option<MouseContextMenu>,
  649    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  650    signature_help_state: SignatureHelpState,
  651    auto_signature_help: Option<bool>,
  652    find_all_references_task_sources: Vec<Anchor>,
  653    next_completion_id: CompletionId,
  654    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  655    code_actions_task: Option<Task<Result<()>>>,
  656    document_highlights_task: Option<Task<()>>,
  657    linked_editing_range_task: Option<Task<Option<()>>>,
  658    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  659    pending_rename: Option<RenameState>,
  660    searchable: bool,
  661    cursor_shape: CursorShape,
  662    current_line_highlight: Option<CurrentLineHighlight>,
  663    collapse_matches: bool,
  664    autoindent_mode: Option<AutoindentMode>,
  665    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  666    input_enabled: bool,
  667    use_modal_editing: bool,
  668    read_only: bool,
  669    leader_peer_id: Option<PeerId>,
  670    remote_id: Option<ViewId>,
  671    hover_state: HoverState,
  672    gutter_hovered: bool,
  673    hovered_link_state: Option<HoveredLinkState>,
  674    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  675    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  676    active_inline_completion: Option<InlineCompletionState>,
  677    // enable_inline_completions is a switch that Vim can use to disable
  678    // inline completions based on its mode.
  679    enable_inline_completions: bool,
  680    show_inline_completions_override: Option<bool>,
  681    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  682    inlay_hint_cache: InlayHintCache,
  683    next_inlay_id: usize,
  684    _subscriptions: Vec<Subscription>,
  685    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  686    gutter_dimensions: GutterDimensions,
  687    style: Option<EditorStyle>,
  688    text_style_refinement: Option<TextStyleRefinement>,
  689    next_editor_action_id: EditorActionId,
  690    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  691    use_autoclose: bool,
  692    use_auto_surround: bool,
  693    auto_replace_emoji_shortcode: bool,
  694    show_git_blame_gutter: bool,
  695    show_git_blame_inline: bool,
  696    show_git_blame_inline_delay_task: Option<Task<()>>,
  697    git_blame_inline_enabled: bool,
  698    serialize_dirty_buffers: bool,
  699    show_selection_menu: Option<bool>,
  700    blame: Option<Model<GitBlame>>,
  701    blame_subscription: Option<Subscription>,
  702    custom_context_menu: Option<
  703        Box<
  704            dyn 'static
  705                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  706        >,
  707    >,
  708    last_bounds: Option<Bounds<Pixels>>,
  709    expect_bounds_change: Option<Bounds<Pixels>>,
  710    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  711    tasks_update_task: Option<Task<()>>,
  712    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  713    breadcrumb_header: Option<String>,
  714    focused_block: Option<FocusedBlock>,
  715    next_scroll_position: NextScrollCursorCenterTopBottom,
  716    addons: HashMap<TypeId, Box<dyn Addon>>,
  717    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  718    selection_mark_mode: bool,
  719    toggle_fold_multiple_buffers: Task<()>,
  720    _scroll_cursor_center_top_bottom_task: Task<()>,
  721}
  722
  723#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  724enum NextScrollCursorCenterTopBottom {
  725    #[default]
  726    Center,
  727    Top,
  728    Bottom,
  729}
  730
  731impl NextScrollCursorCenterTopBottom {
  732    fn next(&self) -> Self {
  733        match self {
  734            Self::Center => Self::Top,
  735            Self::Top => Self::Bottom,
  736            Self::Bottom => Self::Center,
  737        }
  738    }
  739}
  740
  741#[derive(Clone)]
  742pub struct EditorSnapshot {
  743    pub mode: EditorMode,
  744    show_gutter: bool,
  745    show_line_numbers: Option<bool>,
  746    show_git_diff_gutter: Option<bool>,
  747    show_code_actions: Option<bool>,
  748    show_runnables: Option<bool>,
  749    git_blame_gutter_max_author_length: Option<usize>,
  750    pub display_snapshot: DisplaySnapshot,
  751    pub placeholder_text: Option<Arc<str>>,
  752    is_focused: bool,
  753    scroll_anchor: ScrollAnchor,
  754    ongoing_scroll: OngoingScroll,
  755    current_line_highlight: CurrentLineHighlight,
  756    gutter_hovered: bool,
  757}
  758
  759const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  760
  761#[derive(Default, Debug, Clone, Copy)]
  762pub struct GutterDimensions {
  763    pub left_padding: Pixels,
  764    pub right_padding: Pixels,
  765    pub width: Pixels,
  766    pub margin: Pixels,
  767    pub git_blame_entries_width: Option<Pixels>,
  768}
  769
  770impl GutterDimensions {
  771    /// The full width of the space taken up by the gutter.
  772    pub fn full_width(&self) -> Pixels {
  773        self.margin + self.width
  774    }
  775
  776    /// The width of the space reserved for the fold indicators,
  777    /// use alongside 'justify_end' and `gutter_width` to
  778    /// right align content with the line numbers
  779    pub fn fold_area_width(&self) -> Pixels {
  780        self.margin + self.right_padding
  781    }
  782}
  783
  784#[derive(Debug)]
  785pub struct RemoteSelection {
  786    pub replica_id: ReplicaId,
  787    pub selection: Selection<Anchor>,
  788    pub cursor_shape: CursorShape,
  789    pub peer_id: PeerId,
  790    pub line_mode: bool,
  791    pub participant_index: Option<ParticipantIndex>,
  792    pub user_name: Option<SharedString>,
  793}
  794
  795#[derive(Clone, Debug)]
  796struct SelectionHistoryEntry {
  797    selections: Arc<[Selection<Anchor>]>,
  798    select_next_state: Option<SelectNextState>,
  799    select_prev_state: Option<SelectNextState>,
  800    add_selections_state: Option<AddSelectionsState>,
  801}
  802
  803enum SelectionHistoryMode {
  804    Normal,
  805    Undoing,
  806    Redoing,
  807}
  808
  809#[derive(Clone, PartialEq, Eq, Hash)]
  810struct HoveredCursor {
  811    replica_id: u16,
  812    selection_id: usize,
  813}
  814
  815impl Default for SelectionHistoryMode {
  816    fn default() -> Self {
  817        Self::Normal
  818    }
  819}
  820
  821#[derive(Default)]
  822struct SelectionHistory {
  823    #[allow(clippy::type_complexity)]
  824    selections_by_transaction:
  825        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  826    mode: SelectionHistoryMode,
  827    undo_stack: VecDeque<SelectionHistoryEntry>,
  828    redo_stack: VecDeque<SelectionHistoryEntry>,
  829}
  830
  831impl SelectionHistory {
  832    fn insert_transaction(
  833        &mut self,
  834        transaction_id: TransactionId,
  835        selections: Arc<[Selection<Anchor>]>,
  836    ) {
  837        self.selections_by_transaction
  838            .insert(transaction_id, (selections, None));
  839    }
  840
  841    #[allow(clippy::type_complexity)]
  842    fn transaction(
  843        &self,
  844        transaction_id: TransactionId,
  845    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  846        self.selections_by_transaction.get(&transaction_id)
  847    }
  848
  849    #[allow(clippy::type_complexity)]
  850    fn transaction_mut(
  851        &mut self,
  852        transaction_id: TransactionId,
  853    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  854        self.selections_by_transaction.get_mut(&transaction_id)
  855    }
  856
  857    fn push(&mut self, entry: SelectionHistoryEntry) {
  858        if !entry.selections.is_empty() {
  859            match self.mode {
  860                SelectionHistoryMode::Normal => {
  861                    self.push_undo(entry);
  862                    self.redo_stack.clear();
  863                }
  864                SelectionHistoryMode::Undoing => self.push_redo(entry),
  865                SelectionHistoryMode::Redoing => self.push_undo(entry),
  866            }
  867        }
  868    }
  869
  870    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  871        if self
  872            .undo_stack
  873            .back()
  874            .map_or(true, |e| e.selections != entry.selections)
  875        {
  876            self.undo_stack.push_back(entry);
  877            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  878                self.undo_stack.pop_front();
  879            }
  880        }
  881    }
  882
  883    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  884        if self
  885            .redo_stack
  886            .back()
  887            .map_or(true, |e| e.selections != entry.selections)
  888        {
  889            self.redo_stack.push_back(entry);
  890            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  891                self.redo_stack.pop_front();
  892            }
  893        }
  894    }
  895}
  896
  897struct RowHighlight {
  898    index: usize,
  899    range: Range<Anchor>,
  900    color: Hsla,
  901    should_autoscroll: bool,
  902}
  903
  904#[derive(Clone, Debug)]
  905struct AddSelectionsState {
  906    above: bool,
  907    stack: Vec<usize>,
  908}
  909
  910#[derive(Clone)]
  911struct SelectNextState {
  912    query: AhoCorasick,
  913    wordwise: bool,
  914    done: bool,
  915}
  916
  917impl std::fmt::Debug for SelectNextState {
  918    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  919        f.debug_struct(std::any::type_name::<Self>())
  920            .field("wordwise", &self.wordwise)
  921            .field("done", &self.done)
  922            .finish()
  923    }
  924}
  925
  926#[derive(Debug)]
  927struct AutocloseRegion {
  928    selection_id: usize,
  929    range: Range<Anchor>,
  930    pair: BracketPair,
  931}
  932
  933#[derive(Debug)]
  934struct SnippetState {
  935    ranges: Vec<Vec<Range<Anchor>>>,
  936    active_index: usize,
  937    choices: Vec<Option<Vec<String>>>,
  938}
  939
  940#[doc(hidden)]
  941pub struct RenameState {
  942    pub range: Range<Anchor>,
  943    pub old_name: Arc<str>,
  944    pub editor: View<Editor>,
  945    block_id: CustomBlockId,
  946}
  947
  948struct InvalidationStack<T>(Vec<T>);
  949
  950struct RegisteredInlineCompletionProvider {
  951    provider: Arc<dyn InlineCompletionProviderHandle>,
  952    _subscription: Subscription,
  953}
  954
  955#[derive(Debug)]
  956struct ActiveDiagnosticGroup {
  957    primary_range: Range<Anchor>,
  958    primary_message: String,
  959    group_id: usize,
  960    blocks: HashMap<CustomBlockId, Diagnostic>,
  961    is_valid: bool,
  962}
  963
  964#[derive(Serialize, Deserialize, Clone, Debug)]
  965pub struct ClipboardSelection {
  966    pub len: usize,
  967    pub is_entire_line: bool,
  968    pub first_line_indent: u32,
  969}
  970
  971#[derive(Debug)]
  972pub(crate) struct NavigationData {
  973    cursor_anchor: Anchor,
  974    cursor_position: Point,
  975    scroll_anchor: ScrollAnchor,
  976    scroll_top_row: u32,
  977}
  978
  979#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  980pub enum GotoDefinitionKind {
  981    Symbol,
  982    Declaration,
  983    Type,
  984    Implementation,
  985}
  986
  987#[derive(Debug, Clone)]
  988enum InlayHintRefreshReason {
  989    Toggle(bool),
  990    SettingsChange(InlayHintSettings),
  991    NewLinesShown,
  992    BufferEdited(HashSet<Arc<Language>>),
  993    RefreshRequested,
  994    ExcerptsRemoved(Vec<ExcerptId>),
  995}
  996
  997impl InlayHintRefreshReason {
  998    fn description(&self) -> &'static str {
  999        match self {
 1000            Self::Toggle(_) => "toggle",
 1001            Self::SettingsChange(_) => "settings change",
 1002            Self::NewLinesShown => "new lines shown",
 1003            Self::BufferEdited(_) => "buffer edited",
 1004            Self::RefreshRequested => "refresh requested",
 1005            Self::ExcerptsRemoved(_) => "excerpts removed",
 1006        }
 1007    }
 1008}
 1009
 1010pub enum FormatTarget {
 1011    Buffers,
 1012    Ranges(Vec<Range<MultiBufferPoint>>),
 1013}
 1014
 1015pub(crate) struct FocusedBlock {
 1016    id: BlockId,
 1017    focus_handle: WeakFocusHandle,
 1018}
 1019
 1020#[derive(Clone)]
 1021enum JumpData {
 1022    MultiBufferRow {
 1023        row: MultiBufferRow,
 1024        line_offset_from_top: u32,
 1025    },
 1026    MultiBufferPoint {
 1027        excerpt_id: ExcerptId,
 1028        position: Point,
 1029        anchor: text::Anchor,
 1030        line_offset_from_top: u32,
 1031    },
 1032}
 1033
 1034impl Editor {
 1035    pub fn single_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(
 1039            EditorMode::SingleLine { auto_width: false },
 1040            buffer,
 1041            None,
 1042            false,
 1043            cx,
 1044        )
 1045    }
 1046
 1047    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1048        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1049        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1050        Self::new(EditorMode::Full, buffer, None, false, cx)
 1051    }
 1052
 1053    pub fn auto_width(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::SingleLine { auto_width: true },
 1058            buffer,
 1059            None,
 1060            false,
 1061            cx,
 1062        )
 1063    }
 1064
 1065    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1066        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1067        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1068        Self::new(
 1069            EditorMode::AutoHeight { max_lines },
 1070            buffer,
 1071            None,
 1072            false,
 1073            cx,
 1074        )
 1075    }
 1076
 1077    pub fn for_buffer(
 1078        buffer: Model<Buffer>,
 1079        project: Option<Model<Project>>,
 1080        cx: &mut ViewContext<Self>,
 1081    ) -> Self {
 1082        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1083        Self::new(EditorMode::Full, buffer, project, false, cx)
 1084    }
 1085
 1086    pub fn for_multibuffer(
 1087        buffer: Model<MultiBuffer>,
 1088        project: Option<Model<Project>>,
 1089        show_excerpt_controls: bool,
 1090        cx: &mut ViewContext<Self>,
 1091    ) -> Self {
 1092        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1093    }
 1094
 1095    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1096        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1097        let mut clone = Self::new(
 1098            self.mode,
 1099            self.buffer.clone(),
 1100            self.project.clone(),
 1101            show_excerpt_controls,
 1102            cx,
 1103        );
 1104        self.display_map.update(cx, |display_map, cx| {
 1105            let snapshot = display_map.snapshot(cx);
 1106            clone.display_map.update(cx, |display_map, cx| {
 1107                display_map.set_state(&snapshot, cx);
 1108            });
 1109        });
 1110        clone.selections.clone_state(&self.selections);
 1111        clone.scroll_manager.clone_state(&self.scroll_manager);
 1112        clone.searchable = self.searchable;
 1113        clone
 1114    }
 1115
 1116    pub fn new(
 1117        mode: EditorMode,
 1118        buffer: Model<MultiBuffer>,
 1119        project: Option<Model<Project>>,
 1120        show_excerpt_controls: bool,
 1121        cx: &mut ViewContext<Self>,
 1122    ) -> Self {
 1123        let style = cx.text_style();
 1124        let font_size = style.font_size.to_pixels(cx.rem_size());
 1125        let editor = cx.view().downgrade();
 1126        let fold_placeholder = FoldPlaceholder {
 1127            constrain_width: true,
 1128            render: Arc::new(move |fold_id, fold_range, cx| {
 1129                let editor = editor.clone();
 1130                div()
 1131                    .id(fold_id)
 1132                    .bg(cx.theme().colors().ghost_element_background)
 1133                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1134                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1135                    .rounded_sm()
 1136                    .size_full()
 1137                    .cursor_pointer()
 1138                    .child("")
 1139                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1140                    .on_click(move |_, cx| {
 1141                        editor
 1142                            .update(cx, |editor, cx| {
 1143                                editor.unfold_ranges(
 1144                                    &[fold_range.start..fold_range.end],
 1145                                    true,
 1146                                    false,
 1147                                    cx,
 1148                                );
 1149                                cx.stop_propagation();
 1150                            })
 1151                            .ok();
 1152                    })
 1153                    .into_any()
 1154            }),
 1155            merge_adjacent: true,
 1156            ..Default::default()
 1157        };
 1158        let display_map = cx.new_model(|cx| {
 1159            DisplayMap::new(
 1160                buffer.clone(),
 1161                style.font(),
 1162                font_size,
 1163                None,
 1164                show_excerpt_controls,
 1165                FILE_HEADER_HEIGHT,
 1166                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1167                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1168                fold_placeholder,
 1169                cx,
 1170            )
 1171        });
 1172
 1173        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1174
 1175        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1176
 1177        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1178            .then(|| language_settings::SoftWrap::None);
 1179
 1180        let mut project_subscriptions = Vec::new();
 1181        if mode == EditorMode::Full {
 1182            if let Some(project) = project.as_ref() {
 1183                if buffer.read(cx).is_singleton() {
 1184                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1185                        cx.emit(EditorEvent::TitleChanged);
 1186                    }));
 1187                }
 1188                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1189                    if let project::Event::RefreshInlayHints = event {
 1190                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1191                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1192                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1193                            let focus_handle = editor.focus_handle(cx);
 1194                            if focus_handle.is_focused(cx) {
 1195                                let snapshot = buffer.read(cx).snapshot();
 1196                                for (range, snippet) in snippet_edits {
 1197                                    let editor_range =
 1198                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1199                                    editor
 1200                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1201                                        .ok();
 1202                                }
 1203                            }
 1204                        }
 1205                    }
 1206                }));
 1207                if let Some(task_inventory) = project
 1208                    .read(cx)
 1209                    .task_store()
 1210                    .read(cx)
 1211                    .task_inventory()
 1212                    .cloned()
 1213                {
 1214                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1215                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1216                    }));
 1217                }
 1218            }
 1219        }
 1220
 1221        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1222
 1223        let inlay_hint_settings =
 1224            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1225        let focus_handle = cx.focus_handle();
 1226        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1227        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1228            .detach();
 1229        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1230            .detach();
 1231        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1232
 1233        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1234            Some(false)
 1235        } else {
 1236            None
 1237        };
 1238
 1239        let mut code_action_providers = Vec::new();
 1240        if let Some(project) = project.clone() {
 1241            get_unstaged_changes_for_buffers(
 1242                &project,
 1243                buffer.read(cx).all_buffers(),
 1244                buffer.clone(),
 1245                cx,
 1246            );
 1247            code_action_providers.push(Rc::new(project) as Rc<_>);
 1248        }
 1249
 1250        let mut this = Self {
 1251            focus_handle,
 1252            show_cursor_when_unfocused: false,
 1253            last_focused_descendant: None,
 1254            buffer: buffer.clone(),
 1255            display_map: display_map.clone(),
 1256            selections,
 1257            scroll_manager: ScrollManager::new(cx),
 1258            columnar_selection_tail: None,
 1259            add_selections_state: None,
 1260            select_next_state: None,
 1261            select_prev_state: None,
 1262            selection_history: Default::default(),
 1263            autoclose_regions: Default::default(),
 1264            snippet_stack: Default::default(),
 1265            select_larger_syntax_node_stack: Vec::new(),
 1266            ime_transaction: Default::default(),
 1267            active_diagnostics: None,
 1268            soft_wrap_mode_override,
 1269            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1270            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1271            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1272            project,
 1273            blink_manager: blink_manager.clone(),
 1274            show_local_selections: true,
 1275            show_scrollbars: true,
 1276            mode,
 1277            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1278            show_gutter: mode == EditorMode::Full,
 1279            show_line_numbers: None,
 1280            use_relative_line_numbers: None,
 1281            show_git_diff_gutter: None,
 1282            show_code_actions: None,
 1283            show_runnables: None,
 1284            show_wrap_guides: None,
 1285            show_indent_guides,
 1286            placeholder_text: None,
 1287            highlight_order: 0,
 1288            highlighted_rows: HashMap::default(),
 1289            background_highlights: Default::default(),
 1290            gutter_highlights: TreeMap::default(),
 1291            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1292            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1293            nav_history: None,
 1294            context_menu: RefCell::new(None),
 1295            mouse_context_menu: None,
 1296            completion_tasks: Default::default(),
 1297            signature_help_state: SignatureHelpState::default(),
 1298            auto_signature_help: None,
 1299            find_all_references_task_sources: Vec::new(),
 1300            next_completion_id: 0,
 1301            next_inlay_id: 0,
 1302            code_action_providers,
 1303            available_code_actions: Default::default(),
 1304            code_actions_task: Default::default(),
 1305            document_highlights_task: Default::default(),
 1306            linked_editing_range_task: Default::default(),
 1307            pending_rename: Default::default(),
 1308            searchable: true,
 1309            cursor_shape: EditorSettings::get_global(cx)
 1310                .cursor_shape
 1311                .unwrap_or_default(),
 1312            current_line_highlight: None,
 1313            autoindent_mode: Some(AutoindentMode::EachLine),
 1314            collapse_matches: false,
 1315            workspace: None,
 1316            input_enabled: true,
 1317            use_modal_editing: mode == EditorMode::Full,
 1318            read_only: false,
 1319            use_autoclose: true,
 1320            use_auto_surround: true,
 1321            auto_replace_emoji_shortcode: false,
 1322            leader_peer_id: None,
 1323            remote_id: None,
 1324            hover_state: Default::default(),
 1325            hovered_link_state: Default::default(),
 1326            inline_completion_provider: None,
 1327            active_inline_completion: None,
 1328            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1329
 1330            gutter_hovered: false,
 1331            pixel_position_of_newest_cursor: None,
 1332            last_bounds: None,
 1333            expect_bounds_change: None,
 1334            gutter_dimensions: GutterDimensions::default(),
 1335            style: None,
 1336            show_cursor_names: false,
 1337            hovered_cursors: Default::default(),
 1338            next_editor_action_id: EditorActionId::default(),
 1339            editor_actions: Rc::default(),
 1340            show_inline_completions_override: None,
 1341            enable_inline_completions: true,
 1342            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1343            custom_context_menu: None,
 1344            show_git_blame_gutter: false,
 1345            show_git_blame_inline: false,
 1346            show_selection_menu: None,
 1347            show_git_blame_inline_delay_task: None,
 1348            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1349            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1350                .session
 1351                .restore_unsaved_buffers,
 1352            blame: None,
 1353            blame_subscription: None,
 1354            tasks: Default::default(),
 1355            _subscriptions: vec![
 1356                cx.observe(&buffer, Self::on_buffer_changed),
 1357                cx.subscribe(&buffer, Self::on_buffer_event),
 1358                cx.observe(&display_map, Self::on_display_map_changed),
 1359                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1360                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1361                cx.observe_window_activation(|editor, cx| {
 1362                    let active = cx.is_window_active();
 1363                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1364                        if active {
 1365                            blink_manager.enable(cx);
 1366                        } else {
 1367                            blink_manager.disable(cx);
 1368                        }
 1369                    });
 1370                }),
 1371            ],
 1372            tasks_update_task: None,
 1373            linked_edit_ranges: Default::default(),
 1374            previous_search_ranges: None,
 1375            breadcrumb_header: None,
 1376            focused_block: None,
 1377            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1378            addons: HashMap::default(),
 1379            registered_buffers: HashMap::default(),
 1380            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1381            selection_mark_mode: false,
 1382            toggle_fold_multiple_buffers: Task::ready(()),
 1383            text_style_refinement: None,
 1384        };
 1385        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1386        this._subscriptions.extend(project_subscriptions);
 1387
 1388        this.end_selection(cx);
 1389        this.scroll_manager.show_scrollbar(cx);
 1390
 1391        if mode == EditorMode::Full {
 1392            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1393            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1394
 1395            if this.git_blame_inline_enabled {
 1396                this.git_blame_inline_enabled = true;
 1397                this.start_git_blame_inline(false, cx);
 1398            }
 1399
 1400            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1401                if let Some(project) = this.project.as_ref() {
 1402                    let lsp_store = project.read(cx).lsp_store();
 1403                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1404                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1405                    });
 1406                    this.registered_buffers
 1407                        .insert(buffer.read(cx).remote_id(), handle);
 1408                }
 1409            }
 1410        }
 1411
 1412        this.report_editor_event("Editor Opened", None, cx);
 1413        this
 1414    }
 1415
 1416    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 1417        self.mouse_context_menu
 1418            .as_ref()
 1419            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1420    }
 1421
 1422    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 1423        let mut key_context = KeyContext::new_with_defaults();
 1424        key_context.add("Editor");
 1425        let mode = match self.mode {
 1426            EditorMode::SingleLine { .. } => "single_line",
 1427            EditorMode::AutoHeight { .. } => "auto_height",
 1428            EditorMode::Full => "full",
 1429        };
 1430
 1431        if EditorSettings::jupyter_enabled(cx) {
 1432            key_context.add("jupyter");
 1433        }
 1434
 1435        key_context.set("mode", mode);
 1436        if self.pending_rename.is_some() {
 1437            key_context.add("renaming");
 1438        }
 1439        match self.context_menu.borrow().as_ref() {
 1440            Some(CodeContextMenu::Completions(_)) => {
 1441                key_context.add("menu");
 1442                key_context.add("showing_completions")
 1443            }
 1444            Some(CodeContextMenu::CodeActions(_)) => {
 1445                key_context.add("menu");
 1446                key_context.add("showing_code_actions")
 1447            }
 1448            None => {}
 1449        }
 1450
 1451        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1452        if !self.focus_handle(cx).contains_focused(cx)
 1453            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 1454        {
 1455            for addon in self.addons.values() {
 1456                addon.extend_key_context(&mut key_context, cx)
 1457            }
 1458        }
 1459
 1460        if let Some(extension) = self
 1461            .buffer
 1462            .read(cx)
 1463            .as_singleton()
 1464            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1465        {
 1466            key_context.set("extension", extension.to_string());
 1467        }
 1468
 1469        if self.has_active_inline_completion() {
 1470            key_context.add("copilot_suggestion");
 1471            key_context.add("inline_completion");
 1472        }
 1473
 1474        if self.selection_mark_mode {
 1475            key_context.add("selection_mode");
 1476        }
 1477
 1478        key_context
 1479    }
 1480
 1481    pub fn new_file(
 1482        workspace: &mut Workspace,
 1483        _: &workspace::NewFile,
 1484        cx: &mut ViewContext<Workspace>,
 1485    ) {
 1486        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1487            "Failed to create buffer",
 1488            cx,
 1489            |e, _| match e.error_code() {
 1490                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1491                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1492                e.error_tag("required").unwrap_or("the latest version")
 1493            )),
 1494                _ => None,
 1495            },
 1496        );
 1497    }
 1498
 1499    pub fn new_in_workspace(
 1500        workspace: &mut Workspace,
 1501        cx: &mut ViewContext<Workspace>,
 1502    ) -> Task<Result<View<Editor>>> {
 1503        let project = workspace.project().clone();
 1504        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1505
 1506        cx.spawn(|workspace, mut cx| async move {
 1507            let buffer = create.await?;
 1508            workspace.update(&mut cx, |workspace, cx| {
 1509                let editor =
 1510                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 1511                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 1512                editor
 1513            })
 1514        })
 1515    }
 1516
 1517    fn new_file_vertical(
 1518        workspace: &mut Workspace,
 1519        _: &workspace::NewFileSplitVertical,
 1520        cx: &mut ViewContext<Workspace>,
 1521    ) {
 1522        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 1523    }
 1524
 1525    fn new_file_horizontal(
 1526        workspace: &mut Workspace,
 1527        _: &workspace::NewFileSplitHorizontal,
 1528        cx: &mut ViewContext<Workspace>,
 1529    ) {
 1530        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 1531    }
 1532
 1533    fn new_file_in_direction(
 1534        workspace: &mut Workspace,
 1535        direction: SplitDirection,
 1536        cx: &mut ViewContext<Workspace>,
 1537    ) {
 1538        let project = workspace.project().clone();
 1539        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1540
 1541        cx.spawn(|workspace, mut cx| async move {
 1542            let buffer = create.await?;
 1543            workspace.update(&mut cx, move |workspace, cx| {
 1544                workspace.split_item(
 1545                    direction,
 1546                    Box::new(
 1547                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1548                    ),
 1549                    cx,
 1550                )
 1551            })?;
 1552            anyhow::Ok(())
 1553        })
 1554        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1555            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1556                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1557                e.error_tag("required").unwrap_or("the latest version")
 1558            )),
 1559            _ => None,
 1560        });
 1561    }
 1562
 1563    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1564        self.leader_peer_id
 1565    }
 1566
 1567    pub fn buffer(&self) -> &Model<MultiBuffer> {
 1568        &self.buffer
 1569    }
 1570
 1571    pub fn workspace(&self) -> Option<View<Workspace>> {
 1572        self.workspace.as_ref()?.0.upgrade()
 1573    }
 1574
 1575    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 1576        self.buffer().read(cx).title(cx)
 1577    }
 1578
 1579    pub fn snapshot(&self, cx: &mut WindowContext) -> EditorSnapshot {
 1580        let git_blame_gutter_max_author_length = self
 1581            .render_git_blame_gutter(cx)
 1582            .then(|| {
 1583                if let Some(blame) = self.blame.as_ref() {
 1584                    let max_author_length =
 1585                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1586                    Some(max_author_length)
 1587                } else {
 1588                    None
 1589                }
 1590            })
 1591            .flatten();
 1592
 1593        EditorSnapshot {
 1594            mode: self.mode,
 1595            show_gutter: self.show_gutter,
 1596            show_line_numbers: self.show_line_numbers,
 1597            show_git_diff_gutter: self.show_git_diff_gutter,
 1598            show_code_actions: self.show_code_actions,
 1599            show_runnables: self.show_runnables,
 1600            git_blame_gutter_max_author_length,
 1601            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1602            scroll_anchor: self.scroll_manager.anchor(),
 1603            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1604            placeholder_text: self.placeholder_text.clone(),
 1605            is_focused: self.focus_handle.is_focused(cx),
 1606            current_line_highlight: self
 1607                .current_line_highlight
 1608                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1609            gutter_hovered: self.gutter_hovered,
 1610        }
 1611    }
 1612
 1613    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 1614        self.buffer.read(cx).language_at(point, cx)
 1615    }
 1616
 1617    pub fn file_at<T: ToOffset>(
 1618        &self,
 1619        point: T,
 1620        cx: &AppContext,
 1621    ) -> Option<Arc<dyn language::File>> {
 1622        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1623    }
 1624
 1625    pub fn active_excerpt(
 1626        &self,
 1627        cx: &AppContext,
 1628    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 1629        self.buffer
 1630            .read(cx)
 1631            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1632    }
 1633
 1634    pub fn mode(&self) -> EditorMode {
 1635        self.mode
 1636    }
 1637
 1638    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1639        self.collaboration_hub.as_deref()
 1640    }
 1641
 1642    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1643        self.collaboration_hub = Some(hub);
 1644    }
 1645
 1646    pub fn set_custom_context_menu(
 1647        &mut self,
 1648        f: impl 'static
 1649            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 1650    ) {
 1651        self.custom_context_menu = Some(Box::new(f))
 1652    }
 1653
 1654    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1655        self.completion_provider = provider;
 1656    }
 1657
 1658    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1659        self.semantics_provider.clone()
 1660    }
 1661
 1662    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1663        self.semantics_provider = provider;
 1664    }
 1665
 1666    pub fn set_inline_completion_provider<T>(
 1667        &mut self,
 1668        provider: Option<Model<T>>,
 1669        cx: &mut ViewContext<Self>,
 1670    ) where
 1671        T: InlineCompletionProvider,
 1672    {
 1673        self.inline_completion_provider =
 1674            provider.map(|provider| RegisteredInlineCompletionProvider {
 1675                _subscription: cx.observe(&provider, |this, _, cx| {
 1676                    if this.focus_handle.is_focused(cx) {
 1677                        this.update_visible_inline_completion(cx);
 1678                    }
 1679                }),
 1680                provider: Arc::new(provider),
 1681            });
 1682        self.refresh_inline_completion(false, false, cx);
 1683    }
 1684
 1685    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 1686        self.placeholder_text.as_deref()
 1687    }
 1688
 1689    pub fn set_placeholder_text(
 1690        &mut self,
 1691        placeholder_text: impl Into<Arc<str>>,
 1692        cx: &mut ViewContext<Self>,
 1693    ) {
 1694        let placeholder_text = Some(placeholder_text.into());
 1695        if self.placeholder_text != placeholder_text {
 1696            self.placeholder_text = placeholder_text;
 1697            cx.notify();
 1698        }
 1699    }
 1700
 1701    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 1702        self.cursor_shape = cursor_shape;
 1703
 1704        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1705        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1706
 1707        cx.notify();
 1708    }
 1709
 1710    pub fn set_current_line_highlight(
 1711        &mut self,
 1712        current_line_highlight: Option<CurrentLineHighlight>,
 1713    ) {
 1714        self.current_line_highlight = current_line_highlight;
 1715    }
 1716
 1717    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1718        self.collapse_matches = collapse_matches;
 1719    }
 1720
 1721    pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
 1722        let buffers = self.buffer.read(cx).all_buffers();
 1723        let Some(lsp_store) = self.lsp_store(cx) else {
 1724            return;
 1725        };
 1726        lsp_store.update(cx, |lsp_store, cx| {
 1727            for buffer in buffers {
 1728                self.registered_buffers
 1729                    .entry(buffer.read(cx).remote_id())
 1730                    .or_insert_with(|| {
 1731                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1732                    });
 1733            }
 1734        })
 1735    }
 1736
 1737    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1738        if self.collapse_matches {
 1739            return range.start..range.start;
 1740        }
 1741        range.clone()
 1742    }
 1743
 1744    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 1745        if self.display_map.read(cx).clip_at_line_ends != clip {
 1746            self.display_map
 1747                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1748        }
 1749    }
 1750
 1751    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1752        self.input_enabled = input_enabled;
 1753    }
 1754
 1755    pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut ViewContext<Self>) {
 1756        self.enable_inline_completions = enabled;
 1757        if !self.enable_inline_completions {
 1758            self.take_active_inline_completion(cx);
 1759            cx.notify();
 1760        }
 1761    }
 1762
 1763    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1764        self.menu_inline_completions_policy = value;
 1765    }
 1766
 1767    pub fn set_autoindent(&mut self, autoindent: bool) {
 1768        if autoindent {
 1769            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1770        } else {
 1771            self.autoindent_mode = None;
 1772        }
 1773    }
 1774
 1775    pub fn read_only(&self, cx: &AppContext) -> bool {
 1776        self.read_only || self.buffer.read(cx).read_only()
 1777    }
 1778
 1779    pub fn set_read_only(&mut self, read_only: bool) {
 1780        self.read_only = read_only;
 1781    }
 1782
 1783    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1784        self.use_autoclose = autoclose;
 1785    }
 1786
 1787    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1788        self.use_auto_surround = auto_surround;
 1789    }
 1790
 1791    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1792        self.auto_replace_emoji_shortcode = auto_replace;
 1793    }
 1794
 1795    pub fn toggle_inline_completions(
 1796        &mut self,
 1797        _: &ToggleInlineCompletions,
 1798        cx: &mut ViewContext<Self>,
 1799    ) {
 1800        if self.show_inline_completions_override.is_some() {
 1801            self.set_show_inline_completions(None, cx);
 1802        } else {
 1803            let cursor = self.selections.newest_anchor().head();
 1804            if let Some((buffer, cursor_buffer_position)) =
 1805                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1806            {
 1807                let show_inline_completions =
 1808                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1809                self.set_show_inline_completions(Some(show_inline_completions), cx);
 1810            }
 1811        }
 1812    }
 1813
 1814    pub fn set_show_inline_completions(
 1815        &mut self,
 1816        show_inline_completions: Option<bool>,
 1817        cx: &mut ViewContext<Self>,
 1818    ) {
 1819        self.show_inline_completions_override = show_inline_completions;
 1820        self.refresh_inline_completion(false, true, cx);
 1821    }
 1822
 1823    pub fn inline_completions_enabled(&self, cx: &AppContext) -> bool {
 1824        let cursor = self.selections.newest_anchor().head();
 1825        if let Some((buffer, buffer_position)) =
 1826            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1827        {
 1828            self.should_show_inline_completions(&buffer, buffer_position, cx)
 1829        } else {
 1830            false
 1831        }
 1832    }
 1833
 1834    fn should_show_inline_completions(
 1835        &self,
 1836        buffer: &Model<Buffer>,
 1837        buffer_position: language::Anchor,
 1838        cx: &AppContext,
 1839    ) -> bool {
 1840        if !self.snippet_stack.is_empty() {
 1841            return false;
 1842        }
 1843
 1844        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1845            return false;
 1846        }
 1847
 1848        if let Some(provider) = self.inline_completion_provider() {
 1849            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1850                show_inline_completions
 1851            } else {
 1852                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1853            }
 1854        } else {
 1855            false
 1856        }
 1857    }
 1858
 1859    fn inline_completions_disabled_in_scope(
 1860        &self,
 1861        buffer: &Model<Buffer>,
 1862        buffer_position: language::Anchor,
 1863        cx: &AppContext,
 1864    ) -> bool {
 1865        let snapshot = buffer.read(cx).snapshot();
 1866        let settings = snapshot.settings_at(buffer_position, cx);
 1867
 1868        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1869            return false;
 1870        };
 1871
 1872        scope.override_name().map_or(false, |scope_name| {
 1873            settings
 1874                .inline_completions_disabled_in
 1875                .iter()
 1876                .any(|s| s == scope_name)
 1877        })
 1878    }
 1879
 1880    pub fn set_use_modal_editing(&mut self, to: bool) {
 1881        self.use_modal_editing = to;
 1882    }
 1883
 1884    pub fn use_modal_editing(&self) -> bool {
 1885        self.use_modal_editing
 1886    }
 1887
 1888    fn selections_did_change(
 1889        &mut self,
 1890        local: bool,
 1891        old_cursor_position: &Anchor,
 1892        show_completions: bool,
 1893        cx: &mut ViewContext<Self>,
 1894    ) {
 1895        cx.invalidate_character_coordinates();
 1896
 1897        // Copy selections to primary selection buffer
 1898        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1899        if local {
 1900            let selections = self.selections.all::<usize>(cx);
 1901            let buffer_handle = self.buffer.read(cx).read(cx);
 1902
 1903            let mut text = String::new();
 1904            for (index, selection) in selections.iter().enumerate() {
 1905                let text_for_selection = buffer_handle
 1906                    .text_for_range(selection.start..selection.end)
 1907                    .collect::<String>();
 1908
 1909                text.push_str(&text_for_selection);
 1910                if index != selections.len() - 1 {
 1911                    text.push('\n');
 1912                }
 1913            }
 1914
 1915            if !text.is_empty() {
 1916                cx.write_to_primary(ClipboardItem::new_string(text));
 1917            }
 1918        }
 1919
 1920        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 1921            self.buffer.update(cx, |buffer, cx| {
 1922                buffer.set_active_selections(
 1923                    &self.selections.disjoint_anchors(),
 1924                    self.selections.line_mode,
 1925                    self.cursor_shape,
 1926                    cx,
 1927                )
 1928            });
 1929        }
 1930        let display_map = self
 1931            .display_map
 1932            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1933        let buffer = &display_map.buffer_snapshot;
 1934        self.add_selections_state = None;
 1935        self.select_next_state = None;
 1936        self.select_prev_state = None;
 1937        self.select_larger_syntax_node_stack.clear();
 1938        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 1939        self.snippet_stack
 1940            .invalidate(&self.selections.disjoint_anchors(), buffer);
 1941        self.take_rename(false, cx);
 1942
 1943        let new_cursor_position = self.selections.newest_anchor().head();
 1944
 1945        self.push_to_nav_history(
 1946            *old_cursor_position,
 1947            Some(new_cursor_position.to_point(buffer)),
 1948            cx,
 1949        );
 1950
 1951        if local {
 1952            let new_cursor_position = self.selections.newest_anchor().head();
 1953            let mut context_menu = self.context_menu.borrow_mut();
 1954            let completion_menu = match context_menu.as_ref() {
 1955                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 1956                _ => {
 1957                    *context_menu = None;
 1958                    None
 1959                }
 1960            };
 1961
 1962            if let Some(completion_menu) = completion_menu {
 1963                let cursor_position = new_cursor_position.to_offset(buffer);
 1964                let (word_range, kind) =
 1965                    buffer.surrounding_word(completion_menu.initial_position, true);
 1966                if kind == Some(CharKind::Word)
 1967                    && word_range.to_inclusive().contains(&cursor_position)
 1968                {
 1969                    let mut completion_menu = completion_menu.clone();
 1970                    drop(context_menu);
 1971
 1972                    let query = Self::completion_query(buffer, cursor_position);
 1973                    cx.spawn(move |this, mut cx| async move {
 1974                        completion_menu
 1975                            .filter(query.as_deref(), cx.background_executor().clone())
 1976                            .await;
 1977
 1978                        this.update(&mut cx, |this, cx| {
 1979                            let mut context_menu = this.context_menu.borrow_mut();
 1980                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 1981                            else {
 1982                                return;
 1983                            };
 1984
 1985                            if menu.id > completion_menu.id {
 1986                                return;
 1987                            }
 1988
 1989                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 1990                            drop(context_menu);
 1991                            cx.notify();
 1992                        })
 1993                    })
 1994                    .detach();
 1995
 1996                    if show_completions {
 1997                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 1998                    }
 1999                } else {
 2000                    drop(context_menu);
 2001                    self.hide_context_menu(cx);
 2002                }
 2003            } else {
 2004                drop(context_menu);
 2005            }
 2006
 2007            hide_hover(self, cx);
 2008
 2009            if old_cursor_position.to_display_point(&display_map).row()
 2010                != new_cursor_position.to_display_point(&display_map).row()
 2011            {
 2012                self.available_code_actions.take();
 2013            }
 2014            self.refresh_code_actions(cx);
 2015            self.refresh_document_highlights(cx);
 2016            refresh_matching_bracket_highlights(self, cx);
 2017            self.update_visible_inline_completion(cx);
 2018            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2019            if self.git_blame_inline_enabled {
 2020                self.start_inline_blame_timer(cx);
 2021            }
 2022        }
 2023
 2024        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2025        cx.emit(EditorEvent::SelectionsChanged { local });
 2026
 2027        if self.selections.disjoint_anchors().len() == 1 {
 2028            cx.emit(SearchEvent::ActiveMatchChanged)
 2029        }
 2030        cx.notify();
 2031    }
 2032
 2033    pub fn change_selections<R>(
 2034        &mut self,
 2035        autoscroll: Option<Autoscroll>,
 2036        cx: &mut ViewContext<Self>,
 2037        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2038    ) -> R {
 2039        self.change_selections_inner(autoscroll, true, cx, change)
 2040    }
 2041
 2042    pub fn change_selections_inner<R>(
 2043        &mut self,
 2044        autoscroll: Option<Autoscroll>,
 2045        request_completions: bool,
 2046        cx: &mut ViewContext<Self>,
 2047        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2048    ) -> R {
 2049        let old_cursor_position = self.selections.newest_anchor().head();
 2050        self.push_to_selection_history();
 2051
 2052        let (changed, result) = self.selections.change_with(cx, change);
 2053
 2054        if changed {
 2055            if let Some(autoscroll) = autoscroll {
 2056                self.request_autoscroll(autoscroll, cx);
 2057            }
 2058            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2059
 2060            if self.should_open_signature_help_automatically(
 2061                &old_cursor_position,
 2062                self.signature_help_state.backspace_pressed(),
 2063                cx,
 2064            ) {
 2065                self.show_signature_help(&ShowSignatureHelp, cx);
 2066            }
 2067            self.signature_help_state.set_backspace_pressed(false);
 2068        }
 2069
 2070        result
 2071    }
 2072
 2073    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2074    where
 2075        I: IntoIterator<Item = (Range<S>, T)>,
 2076        S: ToOffset,
 2077        T: Into<Arc<str>>,
 2078    {
 2079        if self.read_only(cx) {
 2080            return;
 2081        }
 2082
 2083        self.buffer
 2084            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2085    }
 2086
 2087    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2088    where
 2089        I: IntoIterator<Item = (Range<S>, T)>,
 2090        S: ToOffset,
 2091        T: Into<Arc<str>>,
 2092    {
 2093        if self.read_only(cx) {
 2094            return;
 2095        }
 2096
 2097        self.buffer.update(cx, |buffer, cx| {
 2098            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2099        });
 2100    }
 2101
 2102    pub fn edit_with_block_indent<I, S, T>(
 2103        &mut self,
 2104        edits: I,
 2105        original_indent_columns: Vec<u32>,
 2106        cx: &mut ViewContext<Self>,
 2107    ) where
 2108        I: IntoIterator<Item = (Range<S>, T)>,
 2109        S: ToOffset,
 2110        T: Into<Arc<str>>,
 2111    {
 2112        if self.read_only(cx) {
 2113            return;
 2114        }
 2115
 2116        self.buffer.update(cx, |buffer, cx| {
 2117            buffer.edit(
 2118                edits,
 2119                Some(AutoindentMode::Block {
 2120                    original_indent_columns,
 2121                }),
 2122                cx,
 2123            )
 2124        });
 2125    }
 2126
 2127    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2128        self.hide_context_menu(cx);
 2129
 2130        match phase {
 2131            SelectPhase::Begin {
 2132                position,
 2133                add,
 2134                click_count,
 2135            } => self.begin_selection(position, add, click_count, cx),
 2136            SelectPhase::BeginColumnar {
 2137                position,
 2138                goal_column,
 2139                reset,
 2140            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2141            SelectPhase::Extend {
 2142                position,
 2143                click_count,
 2144            } => self.extend_selection(position, click_count, cx),
 2145            SelectPhase::Update {
 2146                position,
 2147                goal_column,
 2148                scroll_delta,
 2149            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2150            SelectPhase::End => self.end_selection(cx),
 2151        }
 2152    }
 2153
 2154    fn extend_selection(
 2155        &mut self,
 2156        position: DisplayPoint,
 2157        click_count: usize,
 2158        cx: &mut ViewContext<Self>,
 2159    ) {
 2160        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2161        let tail = self.selections.newest::<usize>(cx).tail();
 2162        self.begin_selection(position, false, click_count, cx);
 2163
 2164        let position = position.to_offset(&display_map, Bias::Left);
 2165        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2166
 2167        let mut pending_selection = self
 2168            .selections
 2169            .pending_anchor()
 2170            .expect("extend_selection not called with pending selection");
 2171        if position >= tail {
 2172            pending_selection.start = tail_anchor;
 2173        } else {
 2174            pending_selection.end = tail_anchor;
 2175            pending_selection.reversed = true;
 2176        }
 2177
 2178        let mut pending_mode = self.selections.pending_mode().unwrap();
 2179        match &mut pending_mode {
 2180            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2181            _ => {}
 2182        }
 2183
 2184        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2185            s.set_pending(pending_selection, pending_mode)
 2186        });
 2187    }
 2188
 2189    fn begin_selection(
 2190        &mut self,
 2191        position: DisplayPoint,
 2192        add: bool,
 2193        click_count: usize,
 2194        cx: &mut ViewContext<Self>,
 2195    ) {
 2196        if !self.focus_handle.is_focused(cx) {
 2197            self.last_focused_descendant = None;
 2198            cx.focus(&self.focus_handle);
 2199        }
 2200
 2201        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2202        let buffer = &display_map.buffer_snapshot;
 2203        let newest_selection = self.selections.newest_anchor().clone();
 2204        let position = display_map.clip_point(position, Bias::Left);
 2205
 2206        let start;
 2207        let end;
 2208        let mode;
 2209        let mut auto_scroll;
 2210        match click_count {
 2211            1 => {
 2212                start = buffer.anchor_before(position.to_point(&display_map));
 2213                end = start;
 2214                mode = SelectMode::Character;
 2215                auto_scroll = true;
 2216            }
 2217            2 => {
 2218                let range = movement::surrounding_word(&display_map, position);
 2219                start = buffer.anchor_before(range.start.to_point(&display_map));
 2220                end = buffer.anchor_before(range.end.to_point(&display_map));
 2221                mode = SelectMode::Word(start..end);
 2222                auto_scroll = true;
 2223            }
 2224            3 => {
 2225                let position = display_map
 2226                    .clip_point(position, Bias::Left)
 2227                    .to_point(&display_map);
 2228                let line_start = display_map.prev_line_boundary(position).0;
 2229                let next_line_start = buffer.clip_point(
 2230                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2231                    Bias::Left,
 2232                );
 2233                start = buffer.anchor_before(line_start);
 2234                end = buffer.anchor_before(next_line_start);
 2235                mode = SelectMode::Line(start..end);
 2236                auto_scroll = true;
 2237            }
 2238            _ => {
 2239                start = buffer.anchor_before(0);
 2240                end = buffer.anchor_before(buffer.len());
 2241                mode = SelectMode::All;
 2242                auto_scroll = false;
 2243            }
 2244        }
 2245        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2246
 2247        let point_to_delete: Option<usize> = {
 2248            let selected_points: Vec<Selection<Point>> =
 2249                self.selections.disjoint_in_range(start..end, cx);
 2250
 2251            if !add || click_count > 1 {
 2252                None
 2253            } else if !selected_points.is_empty() {
 2254                Some(selected_points[0].id)
 2255            } else {
 2256                let clicked_point_already_selected =
 2257                    self.selections.disjoint.iter().find(|selection| {
 2258                        selection.start.to_point(buffer) == start.to_point(buffer)
 2259                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2260                    });
 2261
 2262                clicked_point_already_selected.map(|selection| selection.id)
 2263            }
 2264        };
 2265
 2266        let selections_count = self.selections.count();
 2267
 2268        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2269            if let Some(point_to_delete) = point_to_delete {
 2270                s.delete(point_to_delete);
 2271
 2272                if selections_count == 1 {
 2273                    s.set_pending_anchor_range(start..end, mode);
 2274                }
 2275            } else {
 2276                if !add {
 2277                    s.clear_disjoint();
 2278                } else if click_count > 1 {
 2279                    s.delete(newest_selection.id)
 2280                }
 2281
 2282                s.set_pending_anchor_range(start..end, mode);
 2283            }
 2284        });
 2285    }
 2286
 2287    fn begin_columnar_selection(
 2288        &mut self,
 2289        position: DisplayPoint,
 2290        goal_column: u32,
 2291        reset: bool,
 2292        cx: &mut ViewContext<Self>,
 2293    ) {
 2294        if !self.focus_handle.is_focused(cx) {
 2295            self.last_focused_descendant = None;
 2296            cx.focus(&self.focus_handle);
 2297        }
 2298
 2299        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2300
 2301        if reset {
 2302            let pointer_position = display_map
 2303                .buffer_snapshot
 2304                .anchor_before(position.to_point(&display_map));
 2305
 2306            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2307                s.clear_disjoint();
 2308                s.set_pending_anchor_range(
 2309                    pointer_position..pointer_position,
 2310                    SelectMode::Character,
 2311                );
 2312            });
 2313        }
 2314
 2315        let tail = self.selections.newest::<Point>(cx).tail();
 2316        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2317
 2318        if !reset {
 2319            self.select_columns(
 2320                tail.to_display_point(&display_map),
 2321                position,
 2322                goal_column,
 2323                &display_map,
 2324                cx,
 2325            );
 2326        }
 2327    }
 2328
 2329    fn update_selection(
 2330        &mut self,
 2331        position: DisplayPoint,
 2332        goal_column: u32,
 2333        scroll_delta: gpui::Point<f32>,
 2334        cx: &mut ViewContext<Self>,
 2335    ) {
 2336        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2337
 2338        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2339            let tail = tail.to_display_point(&display_map);
 2340            self.select_columns(tail, position, goal_column, &display_map, cx);
 2341        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2342            let buffer = self.buffer.read(cx).snapshot(cx);
 2343            let head;
 2344            let tail;
 2345            let mode = self.selections.pending_mode().unwrap();
 2346            match &mode {
 2347                SelectMode::Character => {
 2348                    head = position.to_point(&display_map);
 2349                    tail = pending.tail().to_point(&buffer);
 2350                }
 2351                SelectMode::Word(original_range) => {
 2352                    let original_display_range = original_range.start.to_display_point(&display_map)
 2353                        ..original_range.end.to_display_point(&display_map);
 2354                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2355                        ..original_display_range.end.to_point(&display_map);
 2356                    if movement::is_inside_word(&display_map, position)
 2357                        || original_display_range.contains(&position)
 2358                    {
 2359                        let word_range = movement::surrounding_word(&display_map, position);
 2360                        if word_range.start < original_display_range.start {
 2361                            head = word_range.start.to_point(&display_map);
 2362                        } else {
 2363                            head = word_range.end.to_point(&display_map);
 2364                        }
 2365                    } else {
 2366                        head = position.to_point(&display_map);
 2367                    }
 2368
 2369                    if head <= original_buffer_range.start {
 2370                        tail = original_buffer_range.end;
 2371                    } else {
 2372                        tail = original_buffer_range.start;
 2373                    }
 2374                }
 2375                SelectMode::Line(original_range) => {
 2376                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2377
 2378                    let position = display_map
 2379                        .clip_point(position, Bias::Left)
 2380                        .to_point(&display_map);
 2381                    let line_start = display_map.prev_line_boundary(position).0;
 2382                    let next_line_start = buffer.clip_point(
 2383                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2384                        Bias::Left,
 2385                    );
 2386
 2387                    if line_start < original_range.start {
 2388                        head = line_start
 2389                    } else {
 2390                        head = next_line_start
 2391                    }
 2392
 2393                    if head <= original_range.start {
 2394                        tail = original_range.end;
 2395                    } else {
 2396                        tail = original_range.start;
 2397                    }
 2398                }
 2399                SelectMode::All => {
 2400                    return;
 2401                }
 2402            };
 2403
 2404            if head < tail {
 2405                pending.start = buffer.anchor_before(head);
 2406                pending.end = buffer.anchor_before(tail);
 2407                pending.reversed = true;
 2408            } else {
 2409                pending.start = buffer.anchor_before(tail);
 2410                pending.end = buffer.anchor_before(head);
 2411                pending.reversed = false;
 2412            }
 2413
 2414            self.change_selections(None, cx, |s| {
 2415                s.set_pending(pending, mode);
 2416            });
 2417        } else {
 2418            log::error!("update_selection dispatched with no pending selection");
 2419            return;
 2420        }
 2421
 2422        self.apply_scroll_delta(scroll_delta, cx);
 2423        cx.notify();
 2424    }
 2425
 2426    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2427        self.columnar_selection_tail.take();
 2428        if self.selections.pending_anchor().is_some() {
 2429            let selections = self.selections.all::<usize>(cx);
 2430            self.change_selections(None, cx, |s| {
 2431                s.select(selections);
 2432                s.clear_pending();
 2433            });
 2434        }
 2435    }
 2436
 2437    fn select_columns(
 2438        &mut self,
 2439        tail: DisplayPoint,
 2440        head: DisplayPoint,
 2441        goal_column: u32,
 2442        display_map: &DisplaySnapshot,
 2443        cx: &mut ViewContext<Self>,
 2444    ) {
 2445        let start_row = cmp::min(tail.row(), head.row());
 2446        let end_row = cmp::max(tail.row(), head.row());
 2447        let start_column = cmp::min(tail.column(), goal_column);
 2448        let end_column = cmp::max(tail.column(), goal_column);
 2449        let reversed = start_column < tail.column();
 2450
 2451        let selection_ranges = (start_row.0..=end_row.0)
 2452            .map(DisplayRow)
 2453            .filter_map(|row| {
 2454                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2455                    let start = display_map
 2456                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2457                        .to_point(display_map);
 2458                    let end = display_map
 2459                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2460                        .to_point(display_map);
 2461                    if reversed {
 2462                        Some(end..start)
 2463                    } else {
 2464                        Some(start..end)
 2465                    }
 2466                } else {
 2467                    None
 2468                }
 2469            })
 2470            .collect::<Vec<_>>();
 2471
 2472        self.change_selections(None, cx, |s| {
 2473            s.select_ranges(selection_ranges);
 2474        });
 2475        cx.notify();
 2476    }
 2477
 2478    pub fn has_pending_nonempty_selection(&self) -> bool {
 2479        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2480            Some(Selection { start, end, .. }) => start != end,
 2481            None => false,
 2482        };
 2483
 2484        pending_nonempty_selection
 2485            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2486    }
 2487
 2488    pub fn has_pending_selection(&self) -> bool {
 2489        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2490    }
 2491
 2492    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2493        self.selection_mark_mode = false;
 2494
 2495        if self.clear_expanded_diff_hunks(cx) {
 2496            cx.notify();
 2497            return;
 2498        }
 2499        if self.dismiss_menus_and_popups(true, cx) {
 2500            return;
 2501        }
 2502
 2503        if self.mode == EditorMode::Full
 2504            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 2505        {
 2506            return;
 2507        }
 2508
 2509        cx.propagate();
 2510    }
 2511
 2512    pub fn dismiss_menus_and_popups(
 2513        &mut self,
 2514        should_report_inline_completion_event: bool,
 2515        cx: &mut ViewContext<Self>,
 2516    ) -> bool {
 2517        if self.take_rename(false, cx).is_some() {
 2518            return true;
 2519        }
 2520
 2521        if hide_hover(self, cx) {
 2522            return true;
 2523        }
 2524
 2525        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2526            return true;
 2527        }
 2528
 2529        if self.hide_context_menu(cx).is_some() {
 2530            if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
 2531                self.update_visible_inline_completion(cx);
 2532            }
 2533            return true;
 2534        }
 2535
 2536        if self.mouse_context_menu.take().is_some() {
 2537            return true;
 2538        }
 2539
 2540        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2541            return true;
 2542        }
 2543
 2544        if self.snippet_stack.pop().is_some() {
 2545            return true;
 2546        }
 2547
 2548        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2549            self.dismiss_diagnostics(cx);
 2550            return true;
 2551        }
 2552
 2553        false
 2554    }
 2555
 2556    fn linked_editing_ranges_for(
 2557        &self,
 2558        selection: Range<text::Anchor>,
 2559        cx: &AppContext,
 2560    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2561        if self.linked_edit_ranges.is_empty() {
 2562            return None;
 2563        }
 2564        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2565            selection.end.buffer_id.and_then(|end_buffer_id| {
 2566                if selection.start.buffer_id != Some(end_buffer_id) {
 2567                    return None;
 2568                }
 2569                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2570                let snapshot = buffer.read(cx).snapshot();
 2571                self.linked_edit_ranges
 2572                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2573                    .map(|ranges| (ranges, snapshot, buffer))
 2574            })?;
 2575        use text::ToOffset as TO;
 2576        // find offset from the start of current range to current cursor position
 2577        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2578
 2579        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2580        let start_difference = start_offset - start_byte_offset;
 2581        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2582        let end_difference = end_offset - start_byte_offset;
 2583        // Current range has associated linked ranges.
 2584        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2585        for range in linked_ranges.iter() {
 2586            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2587            let end_offset = start_offset + end_difference;
 2588            let start_offset = start_offset + start_difference;
 2589            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2590                continue;
 2591            }
 2592            if self.selections.disjoint_anchor_ranges().any(|s| {
 2593                if s.start.buffer_id != selection.start.buffer_id
 2594                    || s.end.buffer_id != selection.end.buffer_id
 2595                {
 2596                    return false;
 2597                }
 2598                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2599                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2600            }) {
 2601                continue;
 2602            }
 2603            let start = buffer_snapshot.anchor_after(start_offset);
 2604            let end = buffer_snapshot.anchor_after(end_offset);
 2605            linked_edits
 2606                .entry(buffer.clone())
 2607                .or_default()
 2608                .push(start..end);
 2609        }
 2610        Some(linked_edits)
 2611    }
 2612
 2613    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2614        let text: Arc<str> = text.into();
 2615
 2616        if self.read_only(cx) {
 2617            return;
 2618        }
 2619
 2620        let selections = self.selections.all_adjusted(cx);
 2621        let mut bracket_inserted = false;
 2622        let mut edits = Vec::new();
 2623        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2624        let mut new_selections = Vec::with_capacity(selections.len());
 2625        let mut new_autoclose_regions = Vec::new();
 2626        let snapshot = self.buffer.read(cx).read(cx);
 2627
 2628        for (selection, autoclose_region) in
 2629            self.selections_with_autoclose_regions(selections, &snapshot)
 2630        {
 2631            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2632                // Determine if the inserted text matches the opening or closing
 2633                // bracket of any of this language's bracket pairs.
 2634                let mut bracket_pair = None;
 2635                let mut is_bracket_pair_start = false;
 2636                let mut is_bracket_pair_end = false;
 2637                if !text.is_empty() {
 2638                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2639                    //  and they are removing the character that triggered IME popup.
 2640                    for (pair, enabled) in scope.brackets() {
 2641                        if !pair.close && !pair.surround {
 2642                            continue;
 2643                        }
 2644
 2645                        if enabled && pair.start.ends_with(text.as_ref()) {
 2646                            let prefix_len = pair.start.len() - text.len();
 2647                            let preceding_text_matches_prefix = prefix_len == 0
 2648                                || (selection.start.column >= (prefix_len as u32)
 2649                                    && snapshot.contains_str_at(
 2650                                        Point::new(
 2651                                            selection.start.row,
 2652                                            selection.start.column - (prefix_len as u32),
 2653                                        ),
 2654                                        &pair.start[..prefix_len],
 2655                                    ));
 2656                            if preceding_text_matches_prefix {
 2657                                bracket_pair = Some(pair.clone());
 2658                                is_bracket_pair_start = true;
 2659                                break;
 2660                            }
 2661                        }
 2662                        if pair.end.as_str() == text.as_ref() {
 2663                            bracket_pair = Some(pair.clone());
 2664                            is_bracket_pair_end = true;
 2665                            break;
 2666                        }
 2667                    }
 2668                }
 2669
 2670                if let Some(bracket_pair) = bracket_pair {
 2671                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2672                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2673                    let auto_surround =
 2674                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2675                    if selection.is_empty() {
 2676                        if is_bracket_pair_start {
 2677                            // If the inserted text is a suffix of an opening bracket and the
 2678                            // selection is preceded by the rest of the opening bracket, then
 2679                            // insert the closing bracket.
 2680                            let following_text_allows_autoclose = snapshot
 2681                                .chars_at(selection.start)
 2682                                .next()
 2683                                .map_or(true, |c| scope.should_autoclose_before(c));
 2684
 2685                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2686                                && bracket_pair.start.len() == 1
 2687                            {
 2688                                let target = bracket_pair.start.chars().next().unwrap();
 2689                                let current_line_count = snapshot
 2690                                    .reversed_chars_at(selection.start)
 2691                                    .take_while(|&c| c != '\n')
 2692                                    .filter(|&c| c == target)
 2693                                    .count();
 2694                                current_line_count % 2 == 1
 2695                            } else {
 2696                                false
 2697                            };
 2698
 2699                            if autoclose
 2700                                && bracket_pair.close
 2701                                && following_text_allows_autoclose
 2702                                && !is_closing_quote
 2703                            {
 2704                                let anchor = snapshot.anchor_before(selection.end);
 2705                                new_selections.push((selection.map(|_| anchor), text.len()));
 2706                                new_autoclose_regions.push((
 2707                                    anchor,
 2708                                    text.len(),
 2709                                    selection.id,
 2710                                    bracket_pair.clone(),
 2711                                ));
 2712                                edits.push((
 2713                                    selection.range(),
 2714                                    format!("{}{}", text, bracket_pair.end).into(),
 2715                                ));
 2716                                bracket_inserted = true;
 2717                                continue;
 2718                            }
 2719                        }
 2720
 2721                        if let Some(region) = autoclose_region {
 2722                            // If the selection is followed by an auto-inserted closing bracket,
 2723                            // then don't insert that closing bracket again; just move the selection
 2724                            // past the closing bracket.
 2725                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2726                                && text.as_ref() == region.pair.end.as_str();
 2727                            if should_skip {
 2728                                let anchor = snapshot.anchor_after(selection.end);
 2729                                new_selections
 2730                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2731                                continue;
 2732                            }
 2733                        }
 2734
 2735                        let always_treat_brackets_as_autoclosed = snapshot
 2736                            .settings_at(selection.start, cx)
 2737                            .always_treat_brackets_as_autoclosed;
 2738                        if always_treat_brackets_as_autoclosed
 2739                            && is_bracket_pair_end
 2740                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2741                        {
 2742                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2743                            // and the inserted text is a closing bracket and the selection is followed
 2744                            // by the closing bracket then move the selection past the closing bracket.
 2745                            let anchor = snapshot.anchor_after(selection.end);
 2746                            new_selections.push((selection.map(|_| anchor), text.len()));
 2747                            continue;
 2748                        }
 2749                    }
 2750                    // If an opening bracket is 1 character long and is typed while
 2751                    // text is selected, then surround that text with the bracket pair.
 2752                    else if auto_surround
 2753                        && bracket_pair.surround
 2754                        && is_bracket_pair_start
 2755                        && bracket_pair.start.chars().count() == 1
 2756                    {
 2757                        edits.push((selection.start..selection.start, text.clone()));
 2758                        edits.push((
 2759                            selection.end..selection.end,
 2760                            bracket_pair.end.as_str().into(),
 2761                        ));
 2762                        bracket_inserted = true;
 2763                        new_selections.push((
 2764                            Selection {
 2765                                id: selection.id,
 2766                                start: snapshot.anchor_after(selection.start),
 2767                                end: snapshot.anchor_before(selection.end),
 2768                                reversed: selection.reversed,
 2769                                goal: selection.goal,
 2770                            },
 2771                            0,
 2772                        ));
 2773                        continue;
 2774                    }
 2775                }
 2776            }
 2777
 2778            if self.auto_replace_emoji_shortcode
 2779                && selection.is_empty()
 2780                && text.as_ref().ends_with(':')
 2781            {
 2782                if let Some(possible_emoji_short_code) =
 2783                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2784                {
 2785                    if !possible_emoji_short_code.is_empty() {
 2786                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2787                            let emoji_shortcode_start = Point::new(
 2788                                selection.start.row,
 2789                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2790                            );
 2791
 2792                            // Remove shortcode from buffer
 2793                            edits.push((
 2794                                emoji_shortcode_start..selection.start,
 2795                                "".to_string().into(),
 2796                            ));
 2797                            new_selections.push((
 2798                                Selection {
 2799                                    id: selection.id,
 2800                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2801                                    end: snapshot.anchor_before(selection.start),
 2802                                    reversed: selection.reversed,
 2803                                    goal: selection.goal,
 2804                                },
 2805                                0,
 2806                            ));
 2807
 2808                            // Insert emoji
 2809                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2810                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2811                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2812
 2813                            continue;
 2814                        }
 2815                    }
 2816                }
 2817            }
 2818
 2819            // If not handling any auto-close operation, then just replace the selected
 2820            // text with the given input and move the selection to the end of the
 2821            // newly inserted text.
 2822            let anchor = snapshot.anchor_after(selection.end);
 2823            if !self.linked_edit_ranges.is_empty() {
 2824                let start_anchor = snapshot.anchor_before(selection.start);
 2825
 2826                let is_word_char = text.chars().next().map_or(true, |char| {
 2827                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2828                    classifier.is_word(char)
 2829                });
 2830
 2831                if is_word_char {
 2832                    if let Some(ranges) = self
 2833                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2834                    {
 2835                        for (buffer, edits) in ranges {
 2836                            linked_edits
 2837                                .entry(buffer.clone())
 2838                                .or_default()
 2839                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2840                        }
 2841                    }
 2842                }
 2843            }
 2844
 2845            new_selections.push((selection.map(|_| anchor), 0));
 2846            edits.push((selection.start..selection.end, text.clone()));
 2847        }
 2848
 2849        drop(snapshot);
 2850
 2851        self.transact(cx, |this, cx| {
 2852            this.buffer.update(cx, |buffer, cx| {
 2853                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2854            });
 2855            for (buffer, edits) in linked_edits {
 2856                buffer.update(cx, |buffer, cx| {
 2857                    let snapshot = buffer.snapshot();
 2858                    let edits = edits
 2859                        .into_iter()
 2860                        .map(|(range, text)| {
 2861                            use text::ToPoint as TP;
 2862                            let end_point = TP::to_point(&range.end, &snapshot);
 2863                            let start_point = TP::to_point(&range.start, &snapshot);
 2864                            (start_point..end_point, text)
 2865                        })
 2866                        .sorted_by_key(|(range, _)| range.start)
 2867                        .collect::<Vec<_>>();
 2868                    buffer.edit(edits, None, cx);
 2869                })
 2870            }
 2871            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2872            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2873            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2874            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2875                .zip(new_selection_deltas)
 2876                .map(|(selection, delta)| Selection {
 2877                    id: selection.id,
 2878                    start: selection.start + delta,
 2879                    end: selection.end + delta,
 2880                    reversed: selection.reversed,
 2881                    goal: SelectionGoal::None,
 2882                })
 2883                .collect::<Vec<_>>();
 2884
 2885            let mut i = 0;
 2886            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2887                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2888                let start = map.buffer_snapshot.anchor_before(position);
 2889                let end = map.buffer_snapshot.anchor_after(position);
 2890                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2891                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2892                        Ordering::Less => i += 1,
 2893                        Ordering::Greater => break,
 2894                        Ordering::Equal => {
 2895                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2896                                Ordering::Less => i += 1,
 2897                                Ordering::Equal => break,
 2898                                Ordering::Greater => break,
 2899                            }
 2900                        }
 2901                    }
 2902                }
 2903                this.autoclose_regions.insert(
 2904                    i,
 2905                    AutocloseRegion {
 2906                        selection_id,
 2907                        range: start..end,
 2908                        pair,
 2909                    },
 2910                );
 2911            }
 2912
 2913            let had_active_inline_completion = this.has_active_inline_completion();
 2914            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 2915                s.select(new_selections)
 2916            });
 2917
 2918            if !bracket_inserted {
 2919                if let Some(on_type_format_task) =
 2920                    this.trigger_on_type_formatting(text.to_string(), cx)
 2921                {
 2922                    on_type_format_task.detach_and_log_err(cx);
 2923                }
 2924            }
 2925
 2926            let editor_settings = EditorSettings::get_global(cx);
 2927            if bracket_inserted
 2928                && (editor_settings.auto_signature_help
 2929                    || editor_settings.show_signature_help_after_edits)
 2930            {
 2931                this.show_signature_help(&ShowSignatureHelp, cx);
 2932            }
 2933
 2934            let trigger_in_words =
 2935                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 2936            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 2937            linked_editing_ranges::refresh_linked_ranges(this, cx);
 2938            this.refresh_inline_completion(true, false, cx);
 2939        });
 2940    }
 2941
 2942    fn find_possible_emoji_shortcode_at_position(
 2943        snapshot: &MultiBufferSnapshot,
 2944        position: Point,
 2945    ) -> Option<String> {
 2946        let mut chars = Vec::new();
 2947        let mut found_colon = false;
 2948        for char in snapshot.reversed_chars_at(position).take(100) {
 2949            // Found a possible emoji shortcode in the middle of the buffer
 2950            if found_colon {
 2951                if char.is_whitespace() {
 2952                    chars.reverse();
 2953                    return Some(chars.iter().collect());
 2954                }
 2955                // If the previous character is not a whitespace, we are in the middle of a word
 2956                // and we only want to complete the shortcode if the word is made up of other emojis
 2957                let mut containing_word = String::new();
 2958                for ch in snapshot
 2959                    .reversed_chars_at(position)
 2960                    .skip(chars.len() + 1)
 2961                    .take(100)
 2962                {
 2963                    if ch.is_whitespace() {
 2964                        break;
 2965                    }
 2966                    containing_word.push(ch);
 2967                }
 2968                let containing_word = containing_word.chars().rev().collect::<String>();
 2969                if util::word_consists_of_emojis(containing_word.as_str()) {
 2970                    chars.reverse();
 2971                    return Some(chars.iter().collect());
 2972                }
 2973            }
 2974
 2975            if char.is_whitespace() || !char.is_ascii() {
 2976                return None;
 2977            }
 2978            if char == ':' {
 2979                found_colon = true;
 2980            } else {
 2981                chars.push(char);
 2982            }
 2983        }
 2984        // Found a possible emoji shortcode at the beginning of the buffer
 2985        chars.reverse();
 2986        Some(chars.iter().collect())
 2987    }
 2988
 2989    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 2990        self.transact(cx, |this, cx| {
 2991            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 2992                let selections = this.selections.all::<usize>(cx);
 2993                let multi_buffer = this.buffer.read(cx);
 2994                let buffer = multi_buffer.snapshot(cx);
 2995                selections
 2996                    .iter()
 2997                    .map(|selection| {
 2998                        let start_point = selection.start.to_point(&buffer);
 2999                        let mut indent =
 3000                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3001                        indent.len = cmp::min(indent.len, start_point.column);
 3002                        let start = selection.start;
 3003                        let end = selection.end;
 3004                        let selection_is_empty = start == end;
 3005                        let language_scope = buffer.language_scope_at(start);
 3006                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3007                            &language_scope
 3008                        {
 3009                            let leading_whitespace_len = buffer
 3010                                .reversed_chars_at(start)
 3011                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3012                                .map(|c| c.len_utf8())
 3013                                .sum::<usize>();
 3014
 3015                            let trailing_whitespace_len = buffer
 3016                                .chars_at(end)
 3017                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3018                                .map(|c| c.len_utf8())
 3019                                .sum::<usize>();
 3020
 3021                            let insert_extra_newline =
 3022                                language.brackets().any(|(pair, enabled)| {
 3023                                    let pair_start = pair.start.trim_end();
 3024                                    let pair_end = pair.end.trim_start();
 3025
 3026                                    enabled
 3027                                        && pair.newline
 3028                                        && buffer.contains_str_at(
 3029                                            end + trailing_whitespace_len,
 3030                                            pair_end,
 3031                                        )
 3032                                        && buffer.contains_str_at(
 3033                                            (start - leading_whitespace_len)
 3034                                                .saturating_sub(pair_start.len()),
 3035                                            pair_start,
 3036                                        )
 3037                                });
 3038
 3039                            // Comment extension on newline is allowed only for cursor selections
 3040                            let comment_delimiter = maybe!({
 3041                                if !selection_is_empty {
 3042                                    return None;
 3043                                }
 3044
 3045                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3046                                    return None;
 3047                                }
 3048
 3049                                let delimiters = language.line_comment_prefixes();
 3050                                let max_len_of_delimiter =
 3051                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3052                                let (snapshot, range) =
 3053                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3054
 3055                                let mut index_of_first_non_whitespace = 0;
 3056                                let comment_candidate = snapshot
 3057                                    .chars_for_range(range)
 3058                                    .skip_while(|c| {
 3059                                        let should_skip = c.is_whitespace();
 3060                                        if should_skip {
 3061                                            index_of_first_non_whitespace += 1;
 3062                                        }
 3063                                        should_skip
 3064                                    })
 3065                                    .take(max_len_of_delimiter)
 3066                                    .collect::<String>();
 3067                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3068                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3069                                })?;
 3070                                let cursor_is_placed_after_comment_marker =
 3071                                    index_of_first_non_whitespace + comment_prefix.len()
 3072                                        <= start_point.column as usize;
 3073                                if cursor_is_placed_after_comment_marker {
 3074                                    Some(comment_prefix.clone())
 3075                                } else {
 3076                                    None
 3077                                }
 3078                            });
 3079                            (comment_delimiter, insert_extra_newline)
 3080                        } else {
 3081                            (None, false)
 3082                        };
 3083
 3084                        let capacity_for_delimiter = comment_delimiter
 3085                            .as_deref()
 3086                            .map(str::len)
 3087                            .unwrap_or_default();
 3088                        let mut new_text =
 3089                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3090                        new_text.push('\n');
 3091                        new_text.extend(indent.chars());
 3092                        if let Some(delimiter) = &comment_delimiter {
 3093                            new_text.push_str(delimiter);
 3094                        }
 3095                        if insert_extra_newline {
 3096                            new_text = new_text.repeat(2);
 3097                        }
 3098
 3099                        let anchor = buffer.anchor_after(end);
 3100                        let new_selection = selection.map(|_| anchor);
 3101                        (
 3102                            (start..end, new_text),
 3103                            (insert_extra_newline, new_selection),
 3104                        )
 3105                    })
 3106                    .unzip()
 3107            };
 3108
 3109            this.edit_with_autoindent(edits, cx);
 3110            let buffer = this.buffer.read(cx).snapshot(cx);
 3111            let new_selections = selection_fixup_info
 3112                .into_iter()
 3113                .map(|(extra_newline_inserted, new_selection)| {
 3114                    let mut cursor = new_selection.end.to_point(&buffer);
 3115                    if extra_newline_inserted {
 3116                        cursor.row -= 1;
 3117                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3118                    }
 3119                    new_selection.map(|_| cursor)
 3120                })
 3121                .collect();
 3122
 3123            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3124            this.refresh_inline_completion(true, false, cx);
 3125        });
 3126    }
 3127
 3128    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3129        let buffer = self.buffer.read(cx);
 3130        let snapshot = buffer.snapshot(cx);
 3131
 3132        let mut edits = Vec::new();
 3133        let mut rows = Vec::new();
 3134
 3135        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3136            let cursor = selection.head();
 3137            let row = cursor.row;
 3138
 3139            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3140
 3141            let newline = "\n".to_string();
 3142            edits.push((start_of_line..start_of_line, newline));
 3143
 3144            rows.push(row + rows_inserted as u32);
 3145        }
 3146
 3147        self.transact(cx, |editor, cx| {
 3148            editor.edit(edits, cx);
 3149
 3150            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3151                let mut index = 0;
 3152                s.move_cursors_with(|map, _, _| {
 3153                    let row = rows[index];
 3154                    index += 1;
 3155
 3156                    let point = Point::new(row, 0);
 3157                    let boundary = map.next_line_boundary(point).1;
 3158                    let clipped = map.clip_point(boundary, Bias::Left);
 3159
 3160                    (clipped, SelectionGoal::None)
 3161                });
 3162            });
 3163
 3164            let mut indent_edits = Vec::new();
 3165            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3166            for row in rows {
 3167                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3168                for (row, indent) in indents {
 3169                    if indent.len == 0 {
 3170                        continue;
 3171                    }
 3172
 3173                    let text = match indent.kind {
 3174                        IndentKind::Space => " ".repeat(indent.len as usize),
 3175                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3176                    };
 3177                    let point = Point::new(row.0, 0);
 3178                    indent_edits.push((point..point, text));
 3179                }
 3180            }
 3181            editor.edit(indent_edits, cx);
 3182        });
 3183    }
 3184
 3185    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3186        let buffer = self.buffer.read(cx);
 3187        let snapshot = buffer.snapshot(cx);
 3188
 3189        let mut edits = Vec::new();
 3190        let mut rows = Vec::new();
 3191        let mut rows_inserted = 0;
 3192
 3193        for selection in self.selections.all_adjusted(cx) {
 3194            let cursor = selection.head();
 3195            let row = cursor.row;
 3196
 3197            let point = Point::new(row + 1, 0);
 3198            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3199
 3200            let newline = "\n".to_string();
 3201            edits.push((start_of_line..start_of_line, newline));
 3202
 3203            rows_inserted += 1;
 3204            rows.push(row + rows_inserted);
 3205        }
 3206
 3207        self.transact(cx, |editor, cx| {
 3208            editor.edit(edits, cx);
 3209
 3210            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3211                let mut index = 0;
 3212                s.move_cursors_with(|map, _, _| {
 3213                    let row = rows[index];
 3214                    index += 1;
 3215
 3216                    let point = Point::new(row, 0);
 3217                    let boundary = map.next_line_boundary(point).1;
 3218                    let clipped = map.clip_point(boundary, Bias::Left);
 3219
 3220                    (clipped, SelectionGoal::None)
 3221                });
 3222            });
 3223
 3224            let mut indent_edits = Vec::new();
 3225            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3226            for row in rows {
 3227                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3228                for (row, indent) in indents {
 3229                    if indent.len == 0 {
 3230                        continue;
 3231                    }
 3232
 3233                    let text = match indent.kind {
 3234                        IndentKind::Space => " ".repeat(indent.len as usize),
 3235                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3236                    };
 3237                    let point = Point::new(row.0, 0);
 3238                    indent_edits.push((point..point, text));
 3239                }
 3240            }
 3241            editor.edit(indent_edits, cx);
 3242        });
 3243    }
 3244
 3245    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3246        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3247            original_indent_columns: Vec::new(),
 3248        });
 3249        self.insert_with_autoindent_mode(text, autoindent, cx);
 3250    }
 3251
 3252    fn insert_with_autoindent_mode(
 3253        &mut self,
 3254        text: &str,
 3255        autoindent_mode: Option<AutoindentMode>,
 3256        cx: &mut ViewContext<Self>,
 3257    ) {
 3258        if self.read_only(cx) {
 3259            return;
 3260        }
 3261
 3262        let text: Arc<str> = text.into();
 3263        self.transact(cx, |this, cx| {
 3264            let old_selections = this.selections.all_adjusted(cx);
 3265            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3266                let anchors = {
 3267                    let snapshot = buffer.read(cx);
 3268                    old_selections
 3269                        .iter()
 3270                        .map(|s| {
 3271                            let anchor = snapshot.anchor_after(s.head());
 3272                            s.map(|_| anchor)
 3273                        })
 3274                        .collect::<Vec<_>>()
 3275                };
 3276                buffer.edit(
 3277                    old_selections
 3278                        .iter()
 3279                        .map(|s| (s.start..s.end, text.clone())),
 3280                    autoindent_mode,
 3281                    cx,
 3282                );
 3283                anchors
 3284            });
 3285
 3286            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3287                s.select_anchors(selection_anchors);
 3288            })
 3289        });
 3290    }
 3291
 3292    fn trigger_completion_on_input(
 3293        &mut self,
 3294        text: &str,
 3295        trigger_in_words: bool,
 3296        cx: &mut ViewContext<Self>,
 3297    ) {
 3298        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3299            self.show_completions(
 3300                &ShowCompletions {
 3301                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3302                },
 3303                cx,
 3304            );
 3305        } else {
 3306            self.hide_context_menu(cx);
 3307        }
 3308    }
 3309
 3310    fn is_completion_trigger(
 3311        &self,
 3312        text: &str,
 3313        trigger_in_words: bool,
 3314        cx: &mut ViewContext<Self>,
 3315    ) -> bool {
 3316        let position = self.selections.newest_anchor().head();
 3317        let multibuffer = self.buffer.read(cx);
 3318        let Some(buffer) = position
 3319            .buffer_id
 3320            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3321        else {
 3322            return false;
 3323        };
 3324
 3325        if let Some(completion_provider) = &self.completion_provider {
 3326            completion_provider.is_completion_trigger(
 3327                &buffer,
 3328                position.text_anchor,
 3329                text,
 3330                trigger_in_words,
 3331                cx,
 3332            )
 3333        } else {
 3334            false
 3335        }
 3336    }
 3337
 3338    /// If any empty selections is touching the start of its innermost containing autoclose
 3339    /// region, expand it to select the brackets.
 3340    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3341        let selections = self.selections.all::<usize>(cx);
 3342        let buffer = self.buffer.read(cx).read(cx);
 3343        let new_selections = self
 3344            .selections_with_autoclose_regions(selections, &buffer)
 3345            .map(|(mut selection, region)| {
 3346                if !selection.is_empty() {
 3347                    return selection;
 3348                }
 3349
 3350                if let Some(region) = region {
 3351                    let mut range = region.range.to_offset(&buffer);
 3352                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3353                        range.start -= region.pair.start.len();
 3354                        if buffer.contains_str_at(range.start, &region.pair.start)
 3355                            && buffer.contains_str_at(range.end, &region.pair.end)
 3356                        {
 3357                            range.end += region.pair.end.len();
 3358                            selection.start = range.start;
 3359                            selection.end = range.end;
 3360
 3361                            return selection;
 3362                        }
 3363                    }
 3364                }
 3365
 3366                let always_treat_brackets_as_autoclosed = buffer
 3367                    .settings_at(selection.start, cx)
 3368                    .always_treat_brackets_as_autoclosed;
 3369
 3370                if !always_treat_brackets_as_autoclosed {
 3371                    return selection;
 3372                }
 3373
 3374                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3375                    for (pair, enabled) in scope.brackets() {
 3376                        if !enabled || !pair.close {
 3377                            continue;
 3378                        }
 3379
 3380                        if buffer.contains_str_at(selection.start, &pair.end) {
 3381                            let pair_start_len = pair.start.len();
 3382                            if buffer.contains_str_at(
 3383                                selection.start.saturating_sub(pair_start_len),
 3384                                &pair.start,
 3385                            ) {
 3386                                selection.start -= pair_start_len;
 3387                                selection.end += pair.end.len();
 3388
 3389                                return selection;
 3390                            }
 3391                        }
 3392                    }
 3393                }
 3394
 3395                selection
 3396            })
 3397            .collect();
 3398
 3399        drop(buffer);
 3400        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3401    }
 3402
 3403    /// Iterate the given selections, and for each one, find the smallest surrounding
 3404    /// autoclose region. This uses the ordering of the selections and the autoclose
 3405    /// regions to avoid repeated comparisons.
 3406    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3407        &'a self,
 3408        selections: impl IntoIterator<Item = Selection<D>>,
 3409        buffer: &'a MultiBufferSnapshot,
 3410    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3411        let mut i = 0;
 3412        let mut regions = self.autoclose_regions.as_slice();
 3413        selections.into_iter().map(move |selection| {
 3414            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3415
 3416            let mut enclosing = None;
 3417            while let Some(pair_state) = regions.get(i) {
 3418                if pair_state.range.end.to_offset(buffer) < range.start {
 3419                    regions = &regions[i + 1..];
 3420                    i = 0;
 3421                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3422                    break;
 3423                } else {
 3424                    if pair_state.selection_id == selection.id {
 3425                        enclosing = Some(pair_state);
 3426                    }
 3427                    i += 1;
 3428                }
 3429            }
 3430
 3431            (selection, enclosing)
 3432        })
 3433    }
 3434
 3435    /// Remove any autoclose regions that no longer contain their selection.
 3436    fn invalidate_autoclose_regions(
 3437        &mut self,
 3438        mut selections: &[Selection<Anchor>],
 3439        buffer: &MultiBufferSnapshot,
 3440    ) {
 3441        self.autoclose_regions.retain(|state| {
 3442            let mut i = 0;
 3443            while let Some(selection) = selections.get(i) {
 3444                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3445                    selections = &selections[1..];
 3446                    continue;
 3447                }
 3448                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3449                    break;
 3450                }
 3451                if selection.id == state.selection_id {
 3452                    return true;
 3453                } else {
 3454                    i += 1;
 3455                }
 3456            }
 3457            false
 3458        });
 3459    }
 3460
 3461    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3462        let offset = position.to_offset(buffer);
 3463        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3464        if offset > word_range.start && kind == Some(CharKind::Word) {
 3465            Some(
 3466                buffer
 3467                    .text_for_range(word_range.start..offset)
 3468                    .collect::<String>(),
 3469            )
 3470        } else {
 3471            None
 3472        }
 3473    }
 3474
 3475    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3476        self.refresh_inlay_hints(
 3477            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3478            cx,
 3479        );
 3480    }
 3481
 3482    pub fn inlay_hints_enabled(&self) -> bool {
 3483        self.inlay_hint_cache.enabled
 3484    }
 3485
 3486    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3487        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3488            return;
 3489        }
 3490
 3491        let reason_description = reason.description();
 3492        let ignore_debounce = matches!(
 3493            reason,
 3494            InlayHintRefreshReason::SettingsChange(_)
 3495                | InlayHintRefreshReason::Toggle(_)
 3496                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3497        );
 3498        let (invalidate_cache, required_languages) = match reason {
 3499            InlayHintRefreshReason::Toggle(enabled) => {
 3500                self.inlay_hint_cache.enabled = enabled;
 3501                if enabled {
 3502                    (InvalidationStrategy::RefreshRequested, None)
 3503                } else {
 3504                    self.inlay_hint_cache.clear();
 3505                    self.splice_inlays(
 3506                        self.visible_inlay_hints(cx)
 3507                            .iter()
 3508                            .map(|inlay| inlay.id)
 3509                            .collect(),
 3510                        Vec::new(),
 3511                        cx,
 3512                    );
 3513                    return;
 3514                }
 3515            }
 3516            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3517                match self.inlay_hint_cache.update_settings(
 3518                    &self.buffer,
 3519                    new_settings,
 3520                    self.visible_inlay_hints(cx),
 3521                    cx,
 3522                ) {
 3523                    ControlFlow::Break(Some(InlaySplice {
 3524                        to_remove,
 3525                        to_insert,
 3526                    })) => {
 3527                        self.splice_inlays(to_remove, to_insert, cx);
 3528                        return;
 3529                    }
 3530                    ControlFlow::Break(None) => return,
 3531                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3532                }
 3533            }
 3534            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3535                if let Some(InlaySplice {
 3536                    to_remove,
 3537                    to_insert,
 3538                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3539                {
 3540                    self.splice_inlays(to_remove, to_insert, cx);
 3541                }
 3542                return;
 3543            }
 3544            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3545            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3546                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3547            }
 3548            InlayHintRefreshReason::RefreshRequested => {
 3549                (InvalidationStrategy::RefreshRequested, None)
 3550            }
 3551        };
 3552
 3553        if let Some(InlaySplice {
 3554            to_remove,
 3555            to_insert,
 3556        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3557            reason_description,
 3558            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3559            invalidate_cache,
 3560            ignore_debounce,
 3561            cx,
 3562        ) {
 3563            self.splice_inlays(to_remove, to_insert, cx);
 3564        }
 3565    }
 3566
 3567    fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
 3568        self.display_map
 3569            .read(cx)
 3570            .current_inlays()
 3571            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3572            .cloned()
 3573            .collect()
 3574    }
 3575
 3576    pub fn excerpts_for_inlay_hints_query(
 3577        &self,
 3578        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3579        cx: &mut ViewContext<Editor>,
 3580    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3581        let Some(project) = self.project.as_ref() else {
 3582            return HashMap::default();
 3583        };
 3584        let project = project.read(cx);
 3585        let multi_buffer = self.buffer().read(cx);
 3586        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3587        let multi_buffer_visible_start = self
 3588            .scroll_manager
 3589            .anchor()
 3590            .anchor
 3591            .to_point(&multi_buffer_snapshot);
 3592        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3593            multi_buffer_visible_start
 3594                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3595            Bias::Left,
 3596        );
 3597        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3598        multi_buffer_snapshot
 3599            .range_to_buffer_ranges(multi_buffer_visible_range)
 3600            .into_iter()
 3601            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3602            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3603                let buffer_file = project::File::from_dyn(buffer.file())?;
 3604                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3605                let worktree_entry = buffer_worktree
 3606                    .read(cx)
 3607                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3608                if worktree_entry.is_ignored {
 3609                    return None;
 3610                }
 3611
 3612                let language = buffer.language()?;
 3613                if let Some(restrict_to_languages) = restrict_to_languages {
 3614                    if !restrict_to_languages.contains(language) {
 3615                        return None;
 3616                    }
 3617                }
 3618                Some((
 3619                    excerpt_id,
 3620                    (
 3621                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3622                        buffer.version().clone(),
 3623                        excerpt_visible_range,
 3624                    ),
 3625                ))
 3626            })
 3627            .collect()
 3628    }
 3629
 3630    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3631        TextLayoutDetails {
 3632            text_system: cx.text_system().clone(),
 3633            editor_style: self.style.clone().unwrap(),
 3634            rem_size: cx.rem_size(),
 3635            scroll_anchor: self.scroll_manager.anchor(),
 3636            visible_rows: self.visible_line_count(),
 3637            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3638        }
 3639    }
 3640
 3641    pub fn splice_inlays(
 3642        &self,
 3643        to_remove: Vec<InlayId>,
 3644        to_insert: Vec<Inlay>,
 3645        cx: &mut ViewContext<Self>,
 3646    ) {
 3647        self.display_map.update(cx, |display_map, cx| {
 3648            display_map.splice_inlays(to_remove, to_insert, cx)
 3649        });
 3650        cx.notify();
 3651    }
 3652
 3653    fn trigger_on_type_formatting(
 3654        &self,
 3655        input: String,
 3656        cx: &mut ViewContext<Self>,
 3657    ) -> Option<Task<Result<()>>> {
 3658        if input.len() != 1 {
 3659            return None;
 3660        }
 3661
 3662        let project = self.project.as_ref()?;
 3663        let position = self.selections.newest_anchor().head();
 3664        let (buffer, buffer_position) = self
 3665            .buffer
 3666            .read(cx)
 3667            .text_anchor_for_position(position, cx)?;
 3668
 3669        let settings = language_settings::language_settings(
 3670            buffer
 3671                .read(cx)
 3672                .language_at(buffer_position)
 3673                .map(|l| l.name()),
 3674            buffer.read(cx).file(),
 3675            cx,
 3676        );
 3677        if !settings.use_on_type_format {
 3678            return None;
 3679        }
 3680
 3681        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3682        // hence we do LSP request & edit on host side only — add formats to host's history.
 3683        let push_to_lsp_host_history = true;
 3684        // If this is not the host, append its history with new edits.
 3685        let push_to_client_history = project.read(cx).is_via_collab();
 3686
 3687        let on_type_formatting = project.update(cx, |project, cx| {
 3688            project.on_type_format(
 3689                buffer.clone(),
 3690                buffer_position,
 3691                input,
 3692                push_to_lsp_host_history,
 3693                cx,
 3694            )
 3695        });
 3696        Some(cx.spawn(|editor, mut cx| async move {
 3697            if let Some(transaction) = on_type_formatting.await? {
 3698                if push_to_client_history {
 3699                    buffer
 3700                        .update(&mut cx, |buffer, _| {
 3701                            buffer.push_transaction(transaction, Instant::now());
 3702                        })
 3703                        .ok();
 3704                }
 3705                editor.update(&mut cx, |editor, cx| {
 3706                    editor.refresh_document_highlights(cx);
 3707                })?;
 3708            }
 3709            Ok(())
 3710        }))
 3711    }
 3712
 3713    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3714        if self.pending_rename.is_some() {
 3715            return;
 3716        }
 3717
 3718        let Some(provider) = self.completion_provider.as_ref() else {
 3719            return;
 3720        };
 3721
 3722        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3723            return;
 3724        }
 3725
 3726        let position = self.selections.newest_anchor().head();
 3727        if position.diff_base_anchor.is_some() {
 3728            return;
 3729        }
 3730        let (buffer, buffer_position) =
 3731            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3732                output
 3733            } else {
 3734                return;
 3735            };
 3736        let show_completion_documentation = buffer
 3737            .read(cx)
 3738            .snapshot()
 3739            .settings_at(buffer_position, cx)
 3740            .show_completion_documentation;
 3741
 3742        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3743
 3744        let trigger_kind = match &options.trigger {
 3745            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3746                CompletionTriggerKind::TRIGGER_CHARACTER
 3747            }
 3748            _ => CompletionTriggerKind::INVOKED,
 3749        };
 3750        let completion_context = CompletionContext {
 3751            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3752                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3753                    Some(String::from(trigger))
 3754                } else {
 3755                    None
 3756                }
 3757            }),
 3758            trigger_kind,
 3759        };
 3760        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 3761        let sort_completions = provider.sort_completions();
 3762
 3763        let id = post_inc(&mut self.next_completion_id);
 3764        let task = cx.spawn(|editor, mut cx| {
 3765            async move {
 3766                editor.update(&mut cx, |this, _| {
 3767                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3768                })?;
 3769                let completions = completions.await.log_err();
 3770                let menu = if let Some(completions) = completions {
 3771                    let mut menu = CompletionsMenu::new(
 3772                        id,
 3773                        sort_completions,
 3774                        show_completion_documentation,
 3775                        position,
 3776                        buffer.clone(),
 3777                        completions.into(),
 3778                    );
 3779
 3780                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3781                        .await;
 3782
 3783                    menu.visible().then_some(menu)
 3784                } else {
 3785                    None
 3786                };
 3787
 3788                editor.update(&mut cx, |editor, cx| {
 3789                    match editor.context_menu.borrow().as_ref() {
 3790                        None => {}
 3791                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3792                            if prev_menu.id > id {
 3793                                return;
 3794                            }
 3795                        }
 3796                        _ => return,
 3797                    }
 3798
 3799                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 3800                        let mut menu = menu.unwrap();
 3801                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3802
 3803                        if editor.show_inline_completions_in_menu(cx) {
 3804                            if let Some(hint) = editor.inline_completion_menu_hint(cx) {
 3805                                menu.show_inline_completion_hint(hint);
 3806                            }
 3807                        } else {
 3808                            editor.discard_inline_completion(false, cx);
 3809                        }
 3810
 3811                        *editor.context_menu.borrow_mut() =
 3812                            Some(CodeContextMenu::Completions(menu));
 3813
 3814                        cx.notify();
 3815                    } else if editor.completion_tasks.len() <= 1 {
 3816                        // If there are no more completion tasks and the last menu was
 3817                        // empty, we should hide it.
 3818                        let was_hidden = editor.hide_context_menu(cx).is_none();
 3819                        // If it was already hidden and we don't show inline
 3820                        // completions in the menu, we should also show the
 3821                        // inline-completion when available.
 3822                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3823                            editor.update_visible_inline_completion(cx);
 3824                        }
 3825                    }
 3826                })?;
 3827
 3828                Ok::<_, anyhow::Error>(())
 3829            }
 3830            .log_err()
 3831        });
 3832
 3833        self.completion_tasks.push((id, task));
 3834    }
 3835
 3836    pub fn confirm_completion(
 3837        &mut self,
 3838        action: &ConfirmCompletion,
 3839        cx: &mut ViewContext<Self>,
 3840    ) -> Option<Task<Result<()>>> {
 3841        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 3842    }
 3843
 3844    pub fn compose_completion(
 3845        &mut self,
 3846        action: &ComposeCompletion,
 3847        cx: &mut ViewContext<Self>,
 3848    ) -> Option<Task<Result<()>>> {
 3849        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 3850    }
 3851
 3852    fn toggle_zed_predict_tos(&mut self, cx: &mut ViewContext<Self>) {
 3853        let (Some(workspace), Some(project)) = (self.workspace(), self.project.as_ref()) else {
 3854            return;
 3855        };
 3856
 3857        ZedPredictTos::toggle(workspace, project.read(cx).user_store().clone(), cx);
 3858    }
 3859
 3860    fn do_completion(
 3861        &mut self,
 3862        item_ix: Option<usize>,
 3863        intent: CompletionIntent,
 3864        cx: &mut ViewContext<Editor>,
 3865    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3866        use language::ToOffset as _;
 3867
 3868        {
 3869            let context_menu = self.context_menu.borrow();
 3870            if let CodeContextMenu::Completions(menu) = context_menu.as_ref()? {
 3871                let entries = menu.entries.borrow();
 3872                let entry = entries.get(item_ix.unwrap_or(menu.selected_item));
 3873                match entry {
 3874                    Some(CompletionEntry::InlineCompletionHint(
 3875                        InlineCompletionMenuHint::Loading,
 3876                    )) => return Some(Task::ready(Ok(()))),
 3877                    Some(CompletionEntry::InlineCompletionHint(InlineCompletionMenuHint::None)) => {
 3878                        drop(entries);
 3879                        drop(context_menu);
 3880                        self.context_menu_next(&Default::default(), cx);
 3881                        return Some(Task::ready(Ok(())));
 3882                    }
 3883                    Some(CompletionEntry::InlineCompletionHint(
 3884                        InlineCompletionMenuHint::PendingTermsAcceptance,
 3885                    )) => {
 3886                        drop(entries);
 3887                        drop(context_menu);
 3888                        self.toggle_zed_predict_tos(cx);
 3889                        return Some(Task::ready(Ok(())));
 3890                    }
 3891                    _ => {}
 3892                }
 3893            }
 3894        }
 3895
 3896        let completions_menu =
 3897            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3898                menu
 3899            } else {
 3900                return None;
 3901            };
 3902
 3903        let entries = completions_menu.entries.borrow();
 3904        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3905        let mat = match mat {
 3906            CompletionEntry::InlineCompletionHint(_) => {
 3907                self.accept_inline_completion(&AcceptInlineCompletion, cx);
 3908                cx.stop_propagation();
 3909                return Some(Task::ready(Ok(())));
 3910            }
 3911            CompletionEntry::Match(mat) => {
 3912                if self.show_inline_completions_in_menu(cx) {
 3913                    self.discard_inline_completion(true, cx);
 3914                }
 3915                mat
 3916            }
 3917        };
 3918        let candidate_id = mat.candidate_id;
 3919        drop(entries);
 3920
 3921        let buffer_handle = completions_menu.buffer;
 3922        let completion = completions_menu
 3923            .completions
 3924            .borrow()
 3925            .get(candidate_id)?
 3926            .clone();
 3927        cx.stop_propagation();
 3928
 3929        let snippet;
 3930        let text;
 3931
 3932        if completion.is_snippet() {
 3933            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3934            text = snippet.as_ref().unwrap().text.clone();
 3935        } else {
 3936            snippet = None;
 3937            text = completion.new_text.clone();
 3938        };
 3939        let selections = self.selections.all::<usize>(cx);
 3940        let buffer = buffer_handle.read(cx);
 3941        let old_range = completion.old_range.to_offset(buffer);
 3942        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3943
 3944        let newest_selection = self.selections.newest_anchor();
 3945        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3946            return None;
 3947        }
 3948
 3949        let lookbehind = newest_selection
 3950            .start
 3951            .text_anchor
 3952            .to_offset(buffer)
 3953            .saturating_sub(old_range.start);
 3954        let lookahead = old_range
 3955            .end
 3956            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3957        let mut common_prefix_len = old_text
 3958            .bytes()
 3959            .zip(text.bytes())
 3960            .take_while(|(a, b)| a == b)
 3961            .count();
 3962
 3963        let snapshot = self.buffer.read(cx).snapshot(cx);
 3964        let mut range_to_replace: Option<Range<isize>> = None;
 3965        let mut ranges = Vec::new();
 3966        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3967        for selection in &selections {
 3968            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3969                let start = selection.start.saturating_sub(lookbehind);
 3970                let end = selection.end + lookahead;
 3971                if selection.id == newest_selection.id {
 3972                    range_to_replace = Some(
 3973                        ((start + common_prefix_len) as isize - selection.start as isize)
 3974                            ..(end as isize - selection.start as isize),
 3975                    );
 3976                }
 3977                ranges.push(start + common_prefix_len..end);
 3978            } else {
 3979                common_prefix_len = 0;
 3980                ranges.clear();
 3981                ranges.extend(selections.iter().map(|s| {
 3982                    if s.id == newest_selection.id {
 3983                        range_to_replace = Some(
 3984                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3985                                - selection.start as isize
 3986                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3987                                    - selection.start as isize,
 3988                        );
 3989                        old_range.clone()
 3990                    } else {
 3991                        s.start..s.end
 3992                    }
 3993                }));
 3994                break;
 3995            }
 3996            if !self.linked_edit_ranges.is_empty() {
 3997                let start_anchor = snapshot.anchor_before(selection.head());
 3998                let end_anchor = snapshot.anchor_after(selection.tail());
 3999                if let Some(ranges) = self
 4000                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4001                {
 4002                    for (buffer, edits) in ranges {
 4003                        linked_edits.entry(buffer.clone()).or_default().extend(
 4004                            edits
 4005                                .into_iter()
 4006                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4007                        );
 4008                    }
 4009                }
 4010            }
 4011        }
 4012        let text = &text[common_prefix_len..];
 4013
 4014        cx.emit(EditorEvent::InputHandled {
 4015            utf16_range_to_replace: range_to_replace,
 4016            text: text.into(),
 4017        });
 4018
 4019        self.transact(cx, |this, cx| {
 4020            if let Some(mut snippet) = snippet {
 4021                snippet.text = text.to_string();
 4022                for tabstop in snippet
 4023                    .tabstops
 4024                    .iter_mut()
 4025                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4026                {
 4027                    tabstop.start -= common_prefix_len as isize;
 4028                    tabstop.end -= common_prefix_len as isize;
 4029                }
 4030
 4031                this.insert_snippet(&ranges, snippet, cx).log_err();
 4032            } else {
 4033                this.buffer.update(cx, |buffer, cx| {
 4034                    buffer.edit(
 4035                        ranges.iter().map(|range| (range.clone(), text)),
 4036                        this.autoindent_mode.clone(),
 4037                        cx,
 4038                    );
 4039                });
 4040            }
 4041            for (buffer, edits) in linked_edits {
 4042                buffer.update(cx, |buffer, cx| {
 4043                    let snapshot = buffer.snapshot();
 4044                    let edits = edits
 4045                        .into_iter()
 4046                        .map(|(range, text)| {
 4047                            use text::ToPoint as TP;
 4048                            let end_point = TP::to_point(&range.end, &snapshot);
 4049                            let start_point = TP::to_point(&range.start, &snapshot);
 4050                            (start_point..end_point, text)
 4051                        })
 4052                        .sorted_by_key(|(range, _)| range.start)
 4053                        .collect::<Vec<_>>();
 4054                    buffer.edit(edits, None, cx);
 4055                })
 4056            }
 4057
 4058            this.refresh_inline_completion(true, false, cx);
 4059        });
 4060
 4061        let show_new_completions_on_confirm = completion
 4062            .confirm
 4063            .as_ref()
 4064            .map_or(false, |confirm| confirm(intent, cx));
 4065        if show_new_completions_on_confirm {
 4066            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4067        }
 4068
 4069        let provider = self.completion_provider.as_ref()?;
 4070        drop(completion);
 4071        let apply_edits = provider.apply_additional_edits_for_completion(
 4072            buffer_handle,
 4073            completions_menu.completions.clone(),
 4074            candidate_id,
 4075            true,
 4076            cx,
 4077        );
 4078
 4079        let editor_settings = EditorSettings::get_global(cx);
 4080        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4081            // After the code completion is finished, users often want to know what signatures are needed.
 4082            // so we should automatically call signature_help
 4083            self.show_signature_help(&ShowSignatureHelp, cx);
 4084        }
 4085
 4086        Some(cx.foreground_executor().spawn(async move {
 4087            apply_edits.await?;
 4088            Ok(())
 4089        }))
 4090    }
 4091
 4092    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4093        let mut context_menu = self.context_menu.borrow_mut();
 4094        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4095            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4096                // Toggle if we're selecting the same one
 4097                *context_menu = None;
 4098                cx.notify();
 4099                return;
 4100            } else {
 4101                // Otherwise, clear it and start a new one
 4102                *context_menu = None;
 4103                cx.notify();
 4104            }
 4105        }
 4106        drop(context_menu);
 4107        let snapshot = self.snapshot(cx);
 4108        let deployed_from_indicator = action.deployed_from_indicator;
 4109        let mut task = self.code_actions_task.take();
 4110        let action = action.clone();
 4111        cx.spawn(|editor, mut cx| async move {
 4112            while let Some(prev_task) = task {
 4113                prev_task.await.log_err();
 4114                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4115            }
 4116
 4117            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4118                if editor.focus_handle.is_focused(cx) {
 4119                    let multibuffer_point = action
 4120                        .deployed_from_indicator
 4121                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4122                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4123                    let (buffer, buffer_row) = snapshot
 4124                        .buffer_snapshot
 4125                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4126                        .and_then(|(buffer_snapshot, range)| {
 4127                            editor
 4128                                .buffer
 4129                                .read(cx)
 4130                                .buffer(buffer_snapshot.remote_id())
 4131                                .map(|buffer| (buffer, range.start.row))
 4132                        })?;
 4133                    let (_, code_actions) = editor
 4134                        .available_code_actions
 4135                        .clone()
 4136                        .and_then(|(location, code_actions)| {
 4137                            let snapshot = location.buffer.read(cx).snapshot();
 4138                            let point_range = location.range.to_point(&snapshot);
 4139                            let point_range = point_range.start.row..=point_range.end.row;
 4140                            if point_range.contains(&buffer_row) {
 4141                                Some((location, code_actions))
 4142                            } else {
 4143                                None
 4144                            }
 4145                        })
 4146                        .unzip();
 4147                    let buffer_id = buffer.read(cx).remote_id();
 4148                    let tasks = editor
 4149                        .tasks
 4150                        .get(&(buffer_id, buffer_row))
 4151                        .map(|t| Arc::new(t.to_owned()));
 4152                    if tasks.is_none() && code_actions.is_none() {
 4153                        return None;
 4154                    }
 4155
 4156                    editor.completion_tasks.clear();
 4157                    editor.discard_inline_completion(false, cx);
 4158                    let task_context =
 4159                        tasks
 4160                            .as_ref()
 4161                            .zip(editor.project.clone())
 4162                            .map(|(tasks, project)| {
 4163                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4164                            });
 4165
 4166                    Some(cx.spawn(|editor, mut cx| async move {
 4167                        let task_context = match task_context {
 4168                            Some(task_context) => task_context.await,
 4169                            None => None,
 4170                        };
 4171                        let resolved_tasks =
 4172                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4173                                Rc::new(ResolvedTasks {
 4174                                    templates: tasks.resolve(&task_context).collect(),
 4175                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4176                                        multibuffer_point.row,
 4177                                        tasks.column,
 4178                                    )),
 4179                                })
 4180                            });
 4181                        let spawn_straight_away = resolved_tasks
 4182                            .as_ref()
 4183                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4184                            && code_actions
 4185                                .as_ref()
 4186                                .map_or(true, |actions| actions.is_empty());
 4187                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4188                            *editor.context_menu.borrow_mut() =
 4189                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4190                                    buffer,
 4191                                    actions: CodeActionContents {
 4192                                        tasks: resolved_tasks,
 4193                                        actions: code_actions,
 4194                                    },
 4195                                    selected_item: Default::default(),
 4196                                    scroll_handle: UniformListScrollHandle::default(),
 4197                                    deployed_from_indicator,
 4198                                }));
 4199                            if spawn_straight_away {
 4200                                if let Some(task) = editor.confirm_code_action(
 4201                                    &ConfirmCodeAction { item_ix: Some(0) },
 4202                                    cx,
 4203                                ) {
 4204                                    cx.notify();
 4205                                    return task;
 4206                                }
 4207                            }
 4208                            cx.notify();
 4209                            Task::ready(Ok(()))
 4210                        }) {
 4211                            task.await
 4212                        } else {
 4213                            Ok(())
 4214                        }
 4215                    }))
 4216                } else {
 4217                    Some(Task::ready(Ok(())))
 4218                }
 4219            })?;
 4220            if let Some(task) = spawned_test_task {
 4221                task.await?;
 4222            }
 4223
 4224            Ok::<_, anyhow::Error>(())
 4225        })
 4226        .detach_and_log_err(cx);
 4227    }
 4228
 4229    pub fn confirm_code_action(
 4230        &mut self,
 4231        action: &ConfirmCodeAction,
 4232        cx: &mut ViewContext<Self>,
 4233    ) -> Option<Task<Result<()>>> {
 4234        let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4235            menu
 4236        } else {
 4237            return None;
 4238        };
 4239        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4240        let action = actions_menu.actions.get(action_ix)?;
 4241        let title = action.label();
 4242        let buffer = actions_menu.buffer;
 4243        let workspace = self.workspace()?;
 4244
 4245        match action {
 4246            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4247                workspace.update(cx, |workspace, cx| {
 4248                    workspace::tasks::schedule_resolved_task(
 4249                        workspace,
 4250                        task_source_kind,
 4251                        resolved_task,
 4252                        false,
 4253                        cx,
 4254                    );
 4255
 4256                    Some(Task::ready(Ok(())))
 4257                })
 4258            }
 4259            CodeActionsItem::CodeAction {
 4260                excerpt_id,
 4261                action,
 4262                provider,
 4263            } => {
 4264                let apply_code_action =
 4265                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4266                let workspace = workspace.downgrade();
 4267                Some(cx.spawn(|editor, cx| async move {
 4268                    let project_transaction = apply_code_action.await?;
 4269                    Self::open_project_transaction(
 4270                        &editor,
 4271                        workspace,
 4272                        project_transaction,
 4273                        title,
 4274                        cx,
 4275                    )
 4276                    .await
 4277                }))
 4278            }
 4279        }
 4280    }
 4281
 4282    pub async fn open_project_transaction(
 4283        this: &WeakView<Editor>,
 4284        workspace: WeakView<Workspace>,
 4285        transaction: ProjectTransaction,
 4286        title: String,
 4287        mut cx: AsyncWindowContext,
 4288    ) -> Result<()> {
 4289        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4290        cx.update(|cx| {
 4291            entries.sort_unstable_by_key(|(buffer, _)| {
 4292                buffer.read(cx).file().map(|f| f.path().clone())
 4293            });
 4294        })?;
 4295
 4296        // If the project transaction's edits are all contained within this editor, then
 4297        // avoid opening a new editor to display them.
 4298
 4299        if let Some((buffer, transaction)) = entries.first() {
 4300            if entries.len() == 1 {
 4301                let excerpt = this.update(&mut cx, |editor, cx| {
 4302                    editor
 4303                        .buffer()
 4304                        .read(cx)
 4305                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4306                })?;
 4307                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4308                    if excerpted_buffer == *buffer {
 4309                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4310                            let excerpt_range = excerpt_range.to_offset(buffer);
 4311                            buffer
 4312                                .edited_ranges_for_transaction::<usize>(transaction)
 4313                                .all(|range| {
 4314                                    excerpt_range.start <= range.start
 4315                                        && excerpt_range.end >= range.end
 4316                                })
 4317                        })?;
 4318
 4319                        if all_edits_within_excerpt {
 4320                            return Ok(());
 4321                        }
 4322                    }
 4323                }
 4324            }
 4325        } else {
 4326            return Ok(());
 4327        }
 4328
 4329        let mut ranges_to_highlight = Vec::new();
 4330        let excerpt_buffer = cx.new_model(|cx| {
 4331            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4332            for (buffer_handle, transaction) in &entries {
 4333                let buffer = buffer_handle.read(cx);
 4334                ranges_to_highlight.extend(
 4335                    multibuffer.push_excerpts_with_context_lines(
 4336                        buffer_handle.clone(),
 4337                        buffer
 4338                            .edited_ranges_for_transaction::<usize>(transaction)
 4339                            .collect(),
 4340                        DEFAULT_MULTIBUFFER_CONTEXT,
 4341                        cx,
 4342                    ),
 4343                );
 4344            }
 4345            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4346            multibuffer
 4347        })?;
 4348
 4349        workspace.update(&mut cx, |workspace, cx| {
 4350            let project = workspace.project().clone();
 4351            let editor =
 4352                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4353            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4354            editor.update(cx, |editor, cx| {
 4355                editor.highlight_background::<Self>(
 4356                    &ranges_to_highlight,
 4357                    |theme| theme.editor_highlighted_line_background,
 4358                    cx,
 4359                );
 4360            });
 4361        })?;
 4362
 4363        Ok(())
 4364    }
 4365
 4366    pub fn clear_code_action_providers(&mut self) {
 4367        self.code_action_providers.clear();
 4368        self.available_code_actions.take();
 4369    }
 4370
 4371    pub fn add_code_action_provider(
 4372        &mut self,
 4373        provider: Rc<dyn CodeActionProvider>,
 4374        cx: &mut ViewContext<Self>,
 4375    ) {
 4376        if self
 4377            .code_action_providers
 4378            .iter()
 4379            .any(|existing_provider| existing_provider.id() == provider.id())
 4380        {
 4381            return;
 4382        }
 4383
 4384        self.code_action_providers.push(provider);
 4385        self.refresh_code_actions(cx);
 4386    }
 4387
 4388    pub fn remove_code_action_provider(&mut self, id: Arc<str>, cx: &mut ViewContext<Self>) {
 4389        self.code_action_providers
 4390            .retain(|provider| provider.id() != id);
 4391        self.refresh_code_actions(cx);
 4392    }
 4393
 4394    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4395        let buffer = self.buffer.read(cx);
 4396        let newest_selection = self.selections.newest_anchor().clone();
 4397        if newest_selection.head().diff_base_anchor.is_some() {
 4398            return None;
 4399        }
 4400        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4401        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4402        if start_buffer != end_buffer {
 4403            return None;
 4404        }
 4405
 4406        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4407            cx.background_executor()
 4408                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4409                .await;
 4410
 4411            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4412                let providers = this.code_action_providers.clone();
 4413                let tasks = this
 4414                    .code_action_providers
 4415                    .iter()
 4416                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4417                    .collect::<Vec<_>>();
 4418                (providers, tasks)
 4419            })?;
 4420
 4421            let mut actions = Vec::new();
 4422            for (provider, provider_actions) in
 4423                providers.into_iter().zip(future::join_all(tasks).await)
 4424            {
 4425                if let Some(provider_actions) = provider_actions.log_err() {
 4426                    actions.extend(provider_actions.into_iter().map(|action| {
 4427                        AvailableCodeAction {
 4428                            excerpt_id: newest_selection.start.excerpt_id,
 4429                            action,
 4430                            provider: provider.clone(),
 4431                        }
 4432                    }));
 4433                }
 4434            }
 4435
 4436            this.update(&mut cx, |this, cx| {
 4437                this.available_code_actions = if actions.is_empty() {
 4438                    None
 4439                } else {
 4440                    Some((
 4441                        Location {
 4442                            buffer: start_buffer,
 4443                            range: start..end,
 4444                        },
 4445                        actions.into(),
 4446                    ))
 4447                };
 4448                cx.notify();
 4449            })
 4450        }));
 4451        None
 4452    }
 4453
 4454    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4455        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4456            self.show_git_blame_inline = false;
 4457
 4458            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4459                cx.background_executor().timer(delay).await;
 4460
 4461                this.update(&mut cx, |this, cx| {
 4462                    this.show_git_blame_inline = true;
 4463                    cx.notify();
 4464                })
 4465                .log_err();
 4466            }));
 4467        }
 4468    }
 4469
 4470    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4471        if self.pending_rename.is_some() {
 4472            return None;
 4473        }
 4474
 4475        let provider = self.semantics_provider.clone()?;
 4476        let buffer = self.buffer.read(cx);
 4477        let newest_selection = self.selections.newest_anchor().clone();
 4478        let cursor_position = newest_selection.head();
 4479        let (cursor_buffer, cursor_buffer_position) =
 4480            buffer.text_anchor_for_position(cursor_position, cx)?;
 4481        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4482        if cursor_buffer != tail_buffer {
 4483            return None;
 4484        }
 4485        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4486        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4487            cx.background_executor()
 4488                .timer(Duration::from_millis(debounce))
 4489                .await;
 4490
 4491            let highlights = if let Some(highlights) = cx
 4492                .update(|cx| {
 4493                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4494                })
 4495                .ok()
 4496                .flatten()
 4497            {
 4498                highlights.await.log_err()
 4499            } else {
 4500                None
 4501            };
 4502
 4503            if let Some(highlights) = highlights {
 4504                this.update(&mut cx, |this, cx| {
 4505                    if this.pending_rename.is_some() {
 4506                        return;
 4507                    }
 4508
 4509                    let buffer_id = cursor_position.buffer_id;
 4510                    let buffer = this.buffer.read(cx);
 4511                    if !buffer
 4512                        .text_anchor_for_position(cursor_position, cx)
 4513                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4514                    {
 4515                        return;
 4516                    }
 4517
 4518                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4519                    let mut write_ranges = Vec::new();
 4520                    let mut read_ranges = Vec::new();
 4521                    for highlight in highlights {
 4522                        for (excerpt_id, excerpt_range) in
 4523                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4524                        {
 4525                            let start = highlight
 4526                                .range
 4527                                .start
 4528                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4529                            let end = highlight
 4530                                .range
 4531                                .end
 4532                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4533                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4534                                continue;
 4535                            }
 4536
 4537                            let range = Anchor {
 4538                                buffer_id,
 4539                                excerpt_id,
 4540                                text_anchor: start,
 4541                                diff_base_anchor: None,
 4542                            }..Anchor {
 4543                                buffer_id,
 4544                                excerpt_id,
 4545                                text_anchor: end,
 4546                                diff_base_anchor: None,
 4547                            };
 4548                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4549                                write_ranges.push(range);
 4550                            } else {
 4551                                read_ranges.push(range);
 4552                            }
 4553                        }
 4554                    }
 4555
 4556                    this.highlight_background::<DocumentHighlightRead>(
 4557                        &read_ranges,
 4558                        |theme| theme.editor_document_highlight_read_background,
 4559                        cx,
 4560                    );
 4561                    this.highlight_background::<DocumentHighlightWrite>(
 4562                        &write_ranges,
 4563                        |theme| theme.editor_document_highlight_write_background,
 4564                        cx,
 4565                    );
 4566                    cx.notify();
 4567                })
 4568                .log_err();
 4569            }
 4570        }));
 4571        None
 4572    }
 4573
 4574    pub fn refresh_inline_completion(
 4575        &mut self,
 4576        debounce: bool,
 4577        user_requested: bool,
 4578        cx: &mut ViewContext<Self>,
 4579    ) -> Option<()> {
 4580        let provider = self.inline_completion_provider()?;
 4581        let cursor = self.selections.newest_anchor().head();
 4582        let (buffer, cursor_buffer_position) =
 4583            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4584
 4585        if !user_requested
 4586            && (!self.enable_inline_completions
 4587                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4588                || !self.is_focused(cx)
 4589                || buffer.read(cx).is_empty())
 4590        {
 4591            self.discard_inline_completion(false, cx);
 4592            return None;
 4593        }
 4594
 4595        self.update_visible_inline_completion(cx);
 4596        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4597        Some(())
 4598    }
 4599
 4600    fn cycle_inline_completion(
 4601        &mut self,
 4602        direction: Direction,
 4603        cx: &mut ViewContext<Self>,
 4604    ) -> Option<()> {
 4605        let provider = self.inline_completion_provider()?;
 4606        let cursor = self.selections.newest_anchor().head();
 4607        let (buffer, cursor_buffer_position) =
 4608            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4609        if !self.enable_inline_completions
 4610            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4611        {
 4612            return None;
 4613        }
 4614
 4615        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4616        self.update_visible_inline_completion(cx);
 4617
 4618        Some(())
 4619    }
 4620
 4621    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4622        if !self.has_active_inline_completion() {
 4623            self.refresh_inline_completion(false, true, cx);
 4624            return;
 4625        }
 4626
 4627        self.update_visible_inline_completion(cx);
 4628    }
 4629
 4630    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4631        self.show_cursor_names(cx);
 4632    }
 4633
 4634    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4635        self.show_cursor_names = true;
 4636        cx.notify();
 4637        cx.spawn(|this, mut cx| async move {
 4638            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4639            this.update(&mut cx, |this, cx| {
 4640                this.show_cursor_names = false;
 4641                cx.notify()
 4642            })
 4643            .ok()
 4644        })
 4645        .detach();
 4646    }
 4647
 4648    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4649        if self.has_active_inline_completion() {
 4650            self.cycle_inline_completion(Direction::Next, cx);
 4651        } else {
 4652            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4653            if is_copilot_disabled {
 4654                cx.propagate();
 4655            }
 4656        }
 4657    }
 4658
 4659    pub fn previous_inline_completion(
 4660        &mut self,
 4661        _: &PreviousInlineCompletion,
 4662        cx: &mut ViewContext<Self>,
 4663    ) {
 4664        if self.has_active_inline_completion() {
 4665            self.cycle_inline_completion(Direction::Prev, cx);
 4666        } else {
 4667            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4668            if is_copilot_disabled {
 4669                cx.propagate();
 4670            }
 4671        }
 4672    }
 4673
 4674    pub fn accept_inline_completion(
 4675        &mut self,
 4676        _: &AcceptInlineCompletion,
 4677        cx: &mut ViewContext<Self>,
 4678    ) {
 4679        let buffer = self.buffer.read(cx);
 4680        let snapshot = buffer.snapshot(cx);
 4681        let selection = self.selections.newest_adjusted(cx);
 4682        let cursor = selection.head();
 4683        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4684        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4685        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4686        {
 4687            if cursor.column < suggested_indent.len
 4688                && cursor.column <= current_indent.len
 4689                && current_indent.len <= suggested_indent.len
 4690            {
 4691                self.tab(&Default::default(), cx);
 4692                return;
 4693            }
 4694        }
 4695
 4696        if self.show_inline_completions_in_menu(cx) {
 4697            self.hide_context_menu(cx);
 4698        }
 4699
 4700        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4701            return;
 4702        };
 4703
 4704        self.report_inline_completion_event(true, cx);
 4705
 4706        match &active_inline_completion.completion {
 4707            InlineCompletion::Move(position) => {
 4708                let position = *position;
 4709                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4710                    selections.select_anchor_ranges([position..position]);
 4711                });
 4712            }
 4713            InlineCompletion::Edit { edits, .. } => {
 4714                if let Some(provider) = self.inline_completion_provider() {
 4715                    provider.accept(cx);
 4716                }
 4717
 4718                let snapshot = self.buffer.read(cx).snapshot(cx);
 4719                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4720
 4721                self.buffer.update(cx, |buffer, cx| {
 4722                    buffer.edit(edits.iter().cloned(), None, cx)
 4723                });
 4724
 4725                self.change_selections(None, cx, |s| {
 4726                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4727                });
 4728
 4729                self.update_visible_inline_completion(cx);
 4730                if self.active_inline_completion.is_none() {
 4731                    self.refresh_inline_completion(true, true, cx);
 4732                }
 4733
 4734                cx.notify();
 4735            }
 4736        }
 4737    }
 4738
 4739    pub fn accept_partial_inline_completion(
 4740        &mut self,
 4741        _: &AcceptPartialInlineCompletion,
 4742        cx: &mut ViewContext<Self>,
 4743    ) {
 4744        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4745            return;
 4746        };
 4747        if self.selections.count() != 1 {
 4748            return;
 4749        }
 4750
 4751        self.report_inline_completion_event(true, cx);
 4752
 4753        match &active_inline_completion.completion {
 4754            InlineCompletion::Move(position) => {
 4755                let position = *position;
 4756                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4757                    selections.select_anchor_ranges([position..position]);
 4758                });
 4759            }
 4760            InlineCompletion::Edit { edits, .. } => {
 4761                // Find an insertion that starts at the cursor position.
 4762                let snapshot = self.buffer.read(cx).snapshot(cx);
 4763                let cursor_offset = self.selections.newest::<usize>(cx).head();
 4764                let insertion = edits.iter().find_map(|(range, text)| {
 4765                    let range = range.to_offset(&snapshot);
 4766                    if range.is_empty() && range.start == cursor_offset {
 4767                        Some(text)
 4768                    } else {
 4769                        None
 4770                    }
 4771                });
 4772
 4773                if let Some(text) = insertion {
 4774                    let mut partial_completion = text
 4775                        .chars()
 4776                        .by_ref()
 4777                        .take_while(|c| c.is_alphabetic())
 4778                        .collect::<String>();
 4779                    if partial_completion.is_empty() {
 4780                        partial_completion = text
 4781                            .chars()
 4782                            .by_ref()
 4783                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4784                            .collect::<String>();
 4785                    }
 4786
 4787                    cx.emit(EditorEvent::InputHandled {
 4788                        utf16_range_to_replace: None,
 4789                        text: partial_completion.clone().into(),
 4790                    });
 4791
 4792                    self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4793
 4794                    self.refresh_inline_completion(true, true, cx);
 4795                    cx.notify();
 4796                } else {
 4797                    self.accept_inline_completion(&Default::default(), cx);
 4798                }
 4799            }
 4800        }
 4801    }
 4802
 4803    fn discard_inline_completion(
 4804        &mut self,
 4805        should_report_inline_completion_event: bool,
 4806        cx: &mut ViewContext<Self>,
 4807    ) -> bool {
 4808        if should_report_inline_completion_event {
 4809            self.report_inline_completion_event(false, cx);
 4810        }
 4811
 4812        if let Some(provider) = self.inline_completion_provider() {
 4813            provider.discard(cx);
 4814        }
 4815
 4816        self.take_active_inline_completion(cx).is_some()
 4817    }
 4818
 4819    fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
 4820        let Some(provider) = self.inline_completion_provider() else {
 4821            return;
 4822        };
 4823
 4824        let Some((_, buffer, _)) = self
 4825            .buffer
 4826            .read(cx)
 4827            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4828        else {
 4829            return;
 4830        };
 4831
 4832        let extension = buffer
 4833            .read(cx)
 4834            .file()
 4835            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4836
 4837        let event_type = match accepted {
 4838            true => "Inline Completion Accepted",
 4839            false => "Inline Completion Discarded",
 4840        };
 4841        telemetry::event!(
 4842            event_type,
 4843            provider = provider.name(),
 4844            suggestion_accepted = accepted,
 4845            file_extension = extension,
 4846        );
 4847    }
 4848
 4849    pub fn has_active_inline_completion(&self) -> bool {
 4850        self.active_inline_completion.is_some()
 4851    }
 4852
 4853    fn take_active_inline_completion(
 4854        &mut self,
 4855        cx: &mut ViewContext<Self>,
 4856    ) -> Option<InlineCompletion> {
 4857        let active_inline_completion = self.active_inline_completion.take()?;
 4858        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 4859        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4860        Some(active_inline_completion.completion)
 4861    }
 4862
 4863    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4864        let selection = self.selections.newest_anchor();
 4865        let cursor = selection.head();
 4866        let multibuffer = self.buffer.read(cx).snapshot(cx);
 4867        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 4868        let excerpt_id = cursor.excerpt_id;
 4869
 4870        let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
 4871            && (self.context_menu.borrow().is_some()
 4872                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 4873        if completions_menu_has_precedence
 4874            || !offset_selection.is_empty()
 4875            || !self.enable_inline_completions
 4876            || self
 4877                .active_inline_completion
 4878                .as_ref()
 4879                .map_or(false, |completion| {
 4880                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 4881                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 4882                    !invalidation_range.contains(&offset_selection.head())
 4883                })
 4884        {
 4885            self.discard_inline_completion(false, cx);
 4886            return None;
 4887        }
 4888
 4889        self.take_active_inline_completion(cx);
 4890        let provider = self.inline_completion_provider()?;
 4891
 4892        let (buffer, cursor_buffer_position) =
 4893            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4894
 4895        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 4896        let edits = inline_completion
 4897            .edits
 4898            .into_iter()
 4899            .flat_map(|(range, new_text)| {
 4900                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 4901                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 4902                Some((start..end, new_text))
 4903            })
 4904            .collect::<Vec<_>>();
 4905        if edits.is_empty() {
 4906            return None;
 4907        }
 4908
 4909        let first_edit_start = edits.first().unwrap().0.start;
 4910        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 4911        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 4912
 4913        let last_edit_end = edits.last().unwrap().0.end;
 4914        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 4915        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 4916
 4917        let cursor_row = cursor.to_point(&multibuffer).row;
 4918
 4919        let mut inlay_ids = Vec::new();
 4920        let invalidation_row_range;
 4921        let completion = if cursor_row < edit_start_row {
 4922            invalidation_row_range = cursor_row..edit_end_row;
 4923            InlineCompletion::Move(first_edit_start)
 4924        } else if cursor_row > edit_end_row {
 4925            invalidation_row_range = edit_start_row..cursor_row;
 4926            InlineCompletion::Move(first_edit_start)
 4927        } else {
 4928            if edits
 4929                .iter()
 4930                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 4931            {
 4932                let mut inlays = Vec::new();
 4933                for (range, new_text) in &edits {
 4934                    let inlay = Inlay::inline_completion(
 4935                        post_inc(&mut self.next_inlay_id),
 4936                        range.start,
 4937                        new_text.as_str(),
 4938                    );
 4939                    inlay_ids.push(inlay.id);
 4940                    inlays.push(inlay);
 4941                }
 4942
 4943                self.splice_inlays(vec![], inlays, cx);
 4944            } else {
 4945                let background_color = cx.theme().status().deleted_background;
 4946                self.highlight_text::<InlineCompletionHighlight>(
 4947                    edits.iter().map(|(range, _)| range.clone()).collect(),
 4948                    HighlightStyle {
 4949                        background_color: Some(background_color),
 4950                        ..Default::default()
 4951                    },
 4952                    cx,
 4953                );
 4954            }
 4955
 4956            invalidation_row_range = edit_start_row..edit_end_row;
 4957
 4958            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 4959                if provider.show_tab_accept_marker()
 4960                    && first_edit_start_point.row == last_edit_end_point.row
 4961                    && !edits.iter().any(|(_, edit)| edit.contains('\n'))
 4962                {
 4963                    EditDisplayMode::TabAccept
 4964                } else {
 4965                    EditDisplayMode::Inline
 4966                }
 4967            } else {
 4968                EditDisplayMode::DiffPopover
 4969            };
 4970
 4971            let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 4972
 4973            InlineCompletion::Edit {
 4974                edits,
 4975                edit_preview: inline_completion.edit_preview,
 4976                display_mode,
 4977                snapshot,
 4978            }
 4979        };
 4980
 4981        let invalidation_range = multibuffer
 4982            .anchor_before(Point::new(invalidation_row_range.start, 0))
 4983            ..multibuffer.anchor_after(Point::new(
 4984                invalidation_row_range.end,
 4985                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 4986            ));
 4987
 4988        self.active_inline_completion = Some(InlineCompletionState {
 4989            inlay_ids,
 4990            completion,
 4991            invalidation_range,
 4992        });
 4993
 4994        if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
 4995            if let Some(hint) = self.inline_completion_menu_hint(cx) {
 4996                match self.context_menu.borrow_mut().as_mut() {
 4997                    Some(CodeContextMenu::Completions(menu)) => {
 4998                        menu.show_inline_completion_hint(hint);
 4999                    }
 5000                    _ => {}
 5001                }
 5002            }
 5003        }
 5004
 5005        cx.notify();
 5006
 5007        Some(())
 5008    }
 5009
 5010    fn inline_completion_menu_hint(
 5011        &self,
 5012        cx: &mut ViewContext<Self>,
 5013    ) -> Option<InlineCompletionMenuHint> {
 5014        let provider = self.inline_completion_provider()?;
 5015        if self.has_active_inline_completion() {
 5016            let editor_snapshot = self.snapshot(cx);
 5017
 5018            let text = match &self.active_inline_completion.as_ref()?.completion {
 5019                InlineCompletion::Edit {
 5020                    edits,
 5021                    edit_preview,
 5022                    display_mode: _,
 5023                    snapshot,
 5024                } => edit_preview
 5025                    .as_ref()
 5026                    .and_then(|edit_preview| {
 5027                        inline_completion_edit_text(&snapshot, &edits, edit_preview, true, cx)
 5028                    })
 5029                    .map(InlineCompletionText::Edit),
 5030                InlineCompletion::Move(target) => {
 5031                    let target_point =
 5032                        target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
 5033                    let target_line = target_point.row + 1;
 5034                    Some(InlineCompletionText::Move(
 5035                        format!("Jump to edit in line {}", target_line).into(),
 5036                    ))
 5037                }
 5038            };
 5039
 5040            Some(InlineCompletionMenuHint::Loaded { text: text? })
 5041        } else if provider.is_refreshing(cx) {
 5042            Some(InlineCompletionMenuHint::Loading)
 5043        } else if provider.needs_terms_acceptance(cx) {
 5044            Some(InlineCompletionMenuHint::PendingTermsAcceptance)
 5045        } else {
 5046            Some(InlineCompletionMenuHint::None)
 5047        }
 5048    }
 5049
 5050    pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5051        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5052    }
 5053
 5054    fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
 5055        let by_provider = matches!(
 5056            self.menu_inline_completions_policy,
 5057            MenuInlineCompletionsPolicy::ByProvider
 5058        );
 5059
 5060        by_provider
 5061            && EditorSettings::get_global(cx).show_inline_completions_in_menu
 5062            && self
 5063                .inline_completion_provider()
 5064                .map_or(false, |provider| provider.show_completions_in_menu())
 5065    }
 5066
 5067    fn render_code_actions_indicator(
 5068        &self,
 5069        _style: &EditorStyle,
 5070        row: DisplayRow,
 5071        is_active: bool,
 5072        cx: &mut ViewContext<Self>,
 5073    ) -> Option<IconButton> {
 5074        if self.available_code_actions.is_some() {
 5075            Some(
 5076                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5077                    .shape(ui::IconButtonShape::Square)
 5078                    .icon_size(IconSize::XSmall)
 5079                    .icon_color(Color::Muted)
 5080                    .toggle_state(is_active)
 5081                    .tooltip({
 5082                        let focus_handle = self.focus_handle.clone();
 5083                        move |cx| {
 5084                            Tooltip::for_action_in(
 5085                                "Toggle Code Actions",
 5086                                &ToggleCodeActions {
 5087                                    deployed_from_indicator: None,
 5088                                },
 5089                                &focus_handle,
 5090                                cx,
 5091                            )
 5092                        }
 5093                    })
 5094                    .on_click(cx.listener(move |editor, _e, cx| {
 5095                        editor.focus(cx);
 5096                        editor.toggle_code_actions(
 5097                            &ToggleCodeActions {
 5098                                deployed_from_indicator: Some(row),
 5099                            },
 5100                            cx,
 5101                        );
 5102                    })),
 5103            )
 5104        } else {
 5105            None
 5106        }
 5107    }
 5108
 5109    fn clear_tasks(&mut self) {
 5110        self.tasks.clear()
 5111    }
 5112
 5113    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5114        if self.tasks.insert(key, value).is_some() {
 5115            // This case should hopefully be rare, but just in case...
 5116            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5117        }
 5118    }
 5119
 5120    fn build_tasks_context(
 5121        project: &Model<Project>,
 5122        buffer: &Model<Buffer>,
 5123        buffer_row: u32,
 5124        tasks: &Arc<RunnableTasks>,
 5125        cx: &mut ViewContext<Self>,
 5126    ) -> Task<Option<task::TaskContext>> {
 5127        let position = Point::new(buffer_row, tasks.column);
 5128        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5129        let location = Location {
 5130            buffer: buffer.clone(),
 5131            range: range_start..range_start,
 5132        };
 5133        // Fill in the environmental variables from the tree-sitter captures
 5134        let mut captured_task_variables = TaskVariables::default();
 5135        for (capture_name, value) in tasks.extra_variables.clone() {
 5136            captured_task_variables.insert(
 5137                task::VariableName::Custom(capture_name.into()),
 5138                value.clone(),
 5139            );
 5140        }
 5141        project.update(cx, |project, cx| {
 5142            project.task_store().update(cx, |task_store, cx| {
 5143                task_store.task_context_for_location(captured_task_variables, location, cx)
 5144            })
 5145        })
 5146    }
 5147
 5148    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5149        let Some((workspace, _)) = self.workspace.clone() else {
 5150            return;
 5151        };
 5152        let Some(project) = self.project.clone() else {
 5153            return;
 5154        };
 5155
 5156        // Try to find a closest, enclosing node using tree-sitter that has a
 5157        // task
 5158        let Some((buffer, buffer_row, tasks)) = self
 5159            .find_enclosing_node_task(cx)
 5160            // Or find the task that's closest in row-distance.
 5161            .or_else(|| self.find_closest_task(cx))
 5162        else {
 5163            return;
 5164        };
 5165
 5166        let reveal_strategy = action.reveal;
 5167        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5168        cx.spawn(|_, mut cx| async move {
 5169            let context = task_context.await?;
 5170            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5171
 5172            let resolved = resolved_task.resolved.as_mut()?;
 5173            resolved.reveal = reveal_strategy;
 5174
 5175            workspace
 5176                .update(&mut cx, |workspace, cx| {
 5177                    workspace::tasks::schedule_resolved_task(
 5178                        workspace,
 5179                        task_source_kind,
 5180                        resolved_task,
 5181                        false,
 5182                        cx,
 5183                    );
 5184                })
 5185                .ok()
 5186        })
 5187        .detach();
 5188    }
 5189
 5190    fn find_closest_task(
 5191        &mut self,
 5192        cx: &mut ViewContext<Self>,
 5193    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5194        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5195
 5196        let ((buffer_id, row), tasks) = self
 5197            .tasks
 5198            .iter()
 5199            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5200
 5201        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5202        let tasks = Arc::new(tasks.to_owned());
 5203        Some((buffer, *row, tasks))
 5204    }
 5205
 5206    fn find_enclosing_node_task(
 5207        &mut self,
 5208        cx: &mut ViewContext<Self>,
 5209    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5210        let snapshot = self.buffer.read(cx).snapshot(cx);
 5211        let offset = self.selections.newest::<usize>(cx).head();
 5212        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5213        let buffer_id = excerpt.buffer().remote_id();
 5214
 5215        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5216        let mut cursor = layer.node().walk();
 5217
 5218        while cursor.goto_first_child_for_byte(offset).is_some() {
 5219            if cursor.node().end_byte() == offset {
 5220                cursor.goto_next_sibling();
 5221            }
 5222        }
 5223
 5224        // Ascend to the smallest ancestor that contains the range and has a task.
 5225        loop {
 5226            let node = cursor.node();
 5227            let node_range = node.byte_range();
 5228            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5229
 5230            // Check if this node contains our offset
 5231            if node_range.start <= offset && node_range.end >= offset {
 5232                // If it contains offset, check for task
 5233                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5234                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5235                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5236                }
 5237            }
 5238
 5239            if !cursor.goto_parent() {
 5240                break;
 5241            }
 5242        }
 5243        None
 5244    }
 5245
 5246    fn render_run_indicator(
 5247        &self,
 5248        _style: &EditorStyle,
 5249        is_active: bool,
 5250        row: DisplayRow,
 5251        cx: &mut ViewContext<Self>,
 5252    ) -> IconButton {
 5253        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5254            .shape(ui::IconButtonShape::Square)
 5255            .icon_size(IconSize::XSmall)
 5256            .icon_color(Color::Muted)
 5257            .toggle_state(is_active)
 5258            .on_click(cx.listener(move |editor, _e, cx| {
 5259                editor.focus(cx);
 5260                editor.toggle_code_actions(
 5261                    &ToggleCodeActions {
 5262                        deployed_from_indicator: Some(row),
 5263                    },
 5264                    cx,
 5265                );
 5266            }))
 5267    }
 5268
 5269    #[cfg(any(test, feature = "test-support"))]
 5270    pub fn context_menu_visible(&self) -> bool {
 5271        self.context_menu
 5272            .borrow()
 5273            .as_ref()
 5274            .map_or(false, |menu| menu.visible())
 5275    }
 5276
 5277    #[cfg(feature = "test-support")]
 5278    pub fn context_menu_contains_inline_completion(&self) -> bool {
 5279        self.context_menu
 5280            .borrow()
 5281            .as_ref()
 5282            .map_or(false, |menu| match menu {
 5283                CodeContextMenu::Completions(menu) => {
 5284                    menu.entries.borrow().first().map_or(false, |entry| {
 5285                        matches!(entry, CompletionEntry::InlineCompletionHint(_))
 5286                    })
 5287                }
 5288                CodeContextMenu::CodeActions(_) => false,
 5289            })
 5290    }
 5291
 5292    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5293        self.context_menu
 5294            .borrow()
 5295            .as_ref()
 5296            .map(|menu| menu.origin(cursor_position))
 5297    }
 5298
 5299    fn render_context_menu(
 5300        &self,
 5301        style: &EditorStyle,
 5302        max_height_in_lines: u32,
 5303        y_flipped: bool,
 5304        cx: &mut ViewContext<Editor>,
 5305    ) -> Option<AnyElement> {
 5306        self.context_menu.borrow().as_ref().and_then(|menu| {
 5307            if menu.visible() {
 5308                Some(menu.render(style, max_height_in_lines, y_flipped, cx))
 5309            } else {
 5310                None
 5311            }
 5312        })
 5313    }
 5314
 5315    fn render_context_menu_aside(
 5316        &self,
 5317        style: &EditorStyle,
 5318        max_size: Size<Pixels>,
 5319        cx: &mut ViewContext<Editor>,
 5320    ) -> Option<AnyElement> {
 5321        self.context_menu.borrow().as_ref().and_then(|menu| {
 5322            if menu.visible() {
 5323                menu.render_aside(
 5324                    style,
 5325                    max_size,
 5326                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5327                    cx,
 5328                )
 5329            } else {
 5330                None
 5331            }
 5332        })
 5333    }
 5334
 5335    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
 5336        cx.notify();
 5337        self.completion_tasks.clear();
 5338        let context_menu = self.context_menu.borrow_mut().take();
 5339        if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
 5340            self.update_visible_inline_completion(cx);
 5341        }
 5342        context_menu
 5343    }
 5344
 5345    fn show_snippet_choices(
 5346        &mut self,
 5347        choices: &Vec<String>,
 5348        selection: Range<Anchor>,
 5349        cx: &mut ViewContext<Self>,
 5350    ) {
 5351        if selection.start.buffer_id.is_none() {
 5352            return;
 5353        }
 5354        let buffer_id = selection.start.buffer_id.unwrap();
 5355        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5356        let id = post_inc(&mut self.next_completion_id);
 5357
 5358        if let Some(buffer) = buffer {
 5359            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5360                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5361            ));
 5362        }
 5363    }
 5364
 5365    pub fn insert_snippet(
 5366        &mut self,
 5367        insertion_ranges: &[Range<usize>],
 5368        snippet: Snippet,
 5369        cx: &mut ViewContext<Self>,
 5370    ) -> Result<()> {
 5371        struct Tabstop<T> {
 5372            is_end_tabstop: bool,
 5373            ranges: Vec<Range<T>>,
 5374            choices: Option<Vec<String>>,
 5375        }
 5376
 5377        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5378            let snippet_text: Arc<str> = snippet.text.clone().into();
 5379            buffer.edit(
 5380                insertion_ranges
 5381                    .iter()
 5382                    .cloned()
 5383                    .map(|range| (range, snippet_text.clone())),
 5384                Some(AutoindentMode::EachLine),
 5385                cx,
 5386            );
 5387
 5388            let snapshot = &*buffer.read(cx);
 5389            let snippet = &snippet;
 5390            snippet
 5391                .tabstops
 5392                .iter()
 5393                .map(|tabstop| {
 5394                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5395                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5396                    });
 5397                    let mut tabstop_ranges = tabstop
 5398                        .ranges
 5399                        .iter()
 5400                        .flat_map(|tabstop_range| {
 5401                            let mut delta = 0_isize;
 5402                            insertion_ranges.iter().map(move |insertion_range| {
 5403                                let insertion_start = insertion_range.start as isize + delta;
 5404                                delta +=
 5405                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5406
 5407                                let start = ((insertion_start + tabstop_range.start) as usize)
 5408                                    .min(snapshot.len());
 5409                                let end = ((insertion_start + tabstop_range.end) as usize)
 5410                                    .min(snapshot.len());
 5411                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5412                            })
 5413                        })
 5414                        .collect::<Vec<_>>();
 5415                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5416
 5417                    Tabstop {
 5418                        is_end_tabstop,
 5419                        ranges: tabstop_ranges,
 5420                        choices: tabstop.choices.clone(),
 5421                    }
 5422                })
 5423                .collect::<Vec<_>>()
 5424        });
 5425        if let Some(tabstop) = tabstops.first() {
 5426            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5427                s.select_ranges(tabstop.ranges.iter().cloned());
 5428            });
 5429
 5430            if let Some(choices) = &tabstop.choices {
 5431                if let Some(selection) = tabstop.ranges.first() {
 5432                    self.show_snippet_choices(choices, selection.clone(), cx)
 5433                }
 5434            }
 5435
 5436            // If we're already at the last tabstop and it's at the end of the snippet,
 5437            // we're done, we don't need to keep the state around.
 5438            if !tabstop.is_end_tabstop {
 5439                let choices = tabstops
 5440                    .iter()
 5441                    .map(|tabstop| tabstop.choices.clone())
 5442                    .collect();
 5443
 5444                let ranges = tabstops
 5445                    .into_iter()
 5446                    .map(|tabstop| tabstop.ranges)
 5447                    .collect::<Vec<_>>();
 5448
 5449                self.snippet_stack.push(SnippetState {
 5450                    active_index: 0,
 5451                    ranges,
 5452                    choices,
 5453                });
 5454            }
 5455
 5456            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5457            if self.autoclose_regions.is_empty() {
 5458                let snapshot = self.buffer.read(cx).snapshot(cx);
 5459                for selection in &mut self.selections.all::<Point>(cx) {
 5460                    let selection_head = selection.head();
 5461                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5462                        continue;
 5463                    };
 5464
 5465                    let mut bracket_pair = None;
 5466                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5467                    let prev_chars = snapshot
 5468                        .reversed_chars_at(selection_head)
 5469                        .collect::<String>();
 5470                    for (pair, enabled) in scope.brackets() {
 5471                        if enabled
 5472                            && pair.close
 5473                            && prev_chars.starts_with(pair.start.as_str())
 5474                            && next_chars.starts_with(pair.end.as_str())
 5475                        {
 5476                            bracket_pair = Some(pair.clone());
 5477                            break;
 5478                        }
 5479                    }
 5480                    if let Some(pair) = bracket_pair {
 5481                        let start = snapshot.anchor_after(selection_head);
 5482                        let end = snapshot.anchor_after(selection_head);
 5483                        self.autoclose_regions.push(AutocloseRegion {
 5484                            selection_id: selection.id,
 5485                            range: start..end,
 5486                            pair,
 5487                        });
 5488                    }
 5489                }
 5490            }
 5491        }
 5492        Ok(())
 5493    }
 5494
 5495    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5496        self.move_to_snippet_tabstop(Bias::Right, cx)
 5497    }
 5498
 5499    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5500        self.move_to_snippet_tabstop(Bias::Left, cx)
 5501    }
 5502
 5503    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5504        if let Some(mut snippet) = self.snippet_stack.pop() {
 5505            match bias {
 5506                Bias::Left => {
 5507                    if snippet.active_index > 0 {
 5508                        snippet.active_index -= 1;
 5509                    } else {
 5510                        self.snippet_stack.push(snippet);
 5511                        return false;
 5512                    }
 5513                }
 5514                Bias::Right => {
 5515                    if snippet.active_index + 1 < snippet.ranges.len() {
 5516                        snippet.active_index += 1;
 5517                    } else {
 5518                        self.snippet_stack.push(snippet);
 5519                        return false;
 5520                    }
 5521                }
 5522            }
 5523            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5524                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5525                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5526                });
 5527
 5528                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5529                    if let Some(selection) = current_ranges.first() {
 5530                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5531                    }
 5532                }
 5533
 5534                // If snippet state is not at the last tabstop, push it back on the stack
 5535                if snippet.active_index + 1 < snippet.ranges.len() {
 5536                    self.snippet_stack.push(snippet);
 5537                }
 5538                return true;
 5539            }
 5540        }
 5541
 5542        false
 5543    }
 5544
 5545    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5546        self.transact(cx, |this, cx| {
 5547            this.select_all(&SelectAll, cx);
 5548            this.insert("", cx);
 5549        });
 5550    }
 5551
 5552    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5553        self.transact(cx, |this, cx| {
 5554            this.select_autoclose_pair(cx);
 5555            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5556            if !this.linked_edit_ranges.is_empty() {
 5557                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5558                let snapshot = this.buffer.read(cx).snapshot(cx);
 5559
 5560                for selection in selections.iter() {
 5561                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5562                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5563                    if selection_start.buffer_id != selection_end.buffer_id {
 5564                        continue;
 5565                    }
 5566                    if let Some(ranges) =
 5567                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5568                    {
 5569                        for (buffer, entries) in ranges {
 5570                            linked_ranges.entry(buffer).or_default().extend(entries);
 5571                        }
 5572                    }
 5573                }
 5574            }
 5575
 5576            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5577            if !this.selections.line_mode {
 5578                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5579                for selection in &mut selections {
 5580                    if selection.is_empty() {
 5581                        let old_head = selection.head();
 5582                        let mut new_head =
 5583                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5584                                .to_point(&display_map);
 5585                        if let Some((buffer, line_buffer_range)) = display_map
 5586                            .buffer_snapshot
 5587                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5588                        {
 5589                            let indent_size =
 5590                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5591                            let indent_len = match indent_size.kind {
 5592                                IndentKind::Space => {
 5593                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5594                                }
 5595                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5596                            };
 5597                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5598                                let indent_len = indent_len.get();
 5599                                new_head = cmp::min(
 5600                                    new_head,
 5601                                    MultiBufferPoint::new(
 5602                                        old_head.row,
 5603                                        ((old_head.column - 1) / indent_len) * indent_len,
 5604                                    ),
 5605                                );
 5606                            }
 5607                        }
 5608
 5609                        selection.set_head(new_head, SelectionGoal::None);
 5610                    }
 5611                }
 5612            }
 5613
 5614            this.signature_help_state.set_backspace_pressed(true);
 5615            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5616            this.insert("", cx);
 5617            let empty_str: Arc<str> = Arc::from("");
 5618            for (buffer, edits) in linked_ranges {
 5619                let snapshot = buffer.read(cx).snapshot();
 5620                use text::ToPoint as TP;
 5621
 5622                let edits = edits
 5623                    .into_iter()
 5624                    .map(|range| {
 5625                        let end_point = TP::to_point(&range.end, &snapshot);
 5626                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5627
 5628                        if end_point == start_point {
 5629                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5630                                .saturating_sub(1);
 5631                            start_point =
 5632                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5633                        };
 5634
 5635                        (start_point..end_point, empty_str.clone())
 5636                    })
 5637                    .sorted_by_key(|(range, _)| range.start)
 5638                    .collect::<Vec<_>>();
 5639                buffer.update(cx, |this, cx| {
 5640                    this.edit(edits, None, cx);
 5641                })
 5642            }
 5643            this.refresh_inline_completion(true, false, cx);
 5644            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5645        });
 5646    }
 5647
 5648    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5649        self.transact(cx, |this, cx| {
 5650            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5651                let line_mode = s.line_mode;
 5652                s.move_with(|map, selection| {
 5653                    if selection.is_empty() && !line_mode {
 5654                        let cursor = movement::right(map, selection.head());
 5655                        selection.end = cursor;
 5656                        selection.reversed = true;
 5657                        selection.goal = SelectionGoal::None;
 5658                    }
 5659                })
 5660            });
 5661            this.insert("", cx);
 5662            this.refresh_inline_completion(true, false, cx);
 5663        });
 5664    }
 5665
 5666    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5667        if self.move_to_prev_snippet_tabstop(cx) {
 5668            return;
 5669        }
 5670
 5671        self.outdent(&Outdent, cx);
 5672    }
 5673
 5674    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5675        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5676            return;
 5677        }
 5678
 5679        let mut selections = self.selections.all_adjusted(cx);
 5680        let buffer = self.buffer.read(cx);
 5681        let snapshot = buffer.snapshot(cx);
 5682        let rows_iter = selections.iter().map(|s| s.head().row);
 5683        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5684
 5685        let mut edits = Vec::new();
 5686        let mut prev_edited_row = 0;
 5687        let mut row_delta = 0;
 5688        for selection in &mut selections {
 5689            if selection.start.row != prev_edited_row {
 5690                row_delta = 0;
 5691            }
 5692            prev_edited_row = selection.end.row;
 5693
 5694            // If the selection is non-empty, then increase the indentation of the selected lines.
 5695            if !selection.is_empty() {
 5696                row_delta =
 5697                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5698                continue;
 5699            }
 5700
 5701            // If the selection is empty and the cursor is in the leading whitespace before the
 5702            // suggested indentation, then auto-indent the line.
 5703            let cursor = selection.head();
 5704            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5705            if let Some(suggested_indent) =
 5706                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5707            {
 5708                if cursor.column < suggested_indent.len
 5709                    && cursor.column <= current_indent.len
 5710                    && current_indent.len <= suggested_indent.len
 5711                {
 5712                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5713                    selection.end = selection.start;
 5714                    if row_delta == 0 {
 5715                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5716                            cursor.row,
 5717                            current_indent,
 5718                            suggested_indent,
 5719                        ));
 5720                        row_delta = suggested_indent.len - current_indent.len;
 5721                    }
 5722                    continue;
 5723                }
 5724            }
 5725
 5726            // Otherwise, insert a hard or soft tab.
 5727            let settings = buffer.settings_at(cursor, cx);
 5728            let tab_size = if settings.hard_tabs {
 5729                IndentSize::tab()
 5730            } else {
 5731                let tab_size = settings.tab_size.get();
 5732                let char_column = snapshot
 5733                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5734                    .flat_map(str::chars)
 5735                    .count()
 5736                    + row_delta as usize;
 5737                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5738                IndentSize::spaces(chars_to_next_tab_stop)
 5739            };
 5740            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5741            selection.end = selection.start;
 5742            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5743            row_delta += tab_size.len;
 5744        }
 5745
 5746        self.transact(cx, |this, cx| {
 5747            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5748            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5749            this.refresh_inline_completion(true, false, cx);
 5750        });
 5751    }
 5752
 5753    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5754        if self.read_only(cx) {
 5755            return;
 5756        }
 5757        let mut selections = self.selections.all::<Point>(cx);
 5758        let mut prev_edited_row = 0;
 5759        let mut row_delta = 0;
 5760        let mut edits = Vec::new();
 5761        let buffer = self.buffer.read(cx);
 5762        let snapshot = buffer.snapshot(cx);
 5763        for selection in &mut selections {
 5764            if selection.start.row != prev_edited_row {
 5765                row_delta = 0;
 5766            }
 5767            prev_edited_row = selection.end.row;
 5768
 5769            row_delta =
 5770                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5771        }
 5772
 5773        self.transact(cx, |this, cx| {
 5774            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5775            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5776        });
 5777    }
 5778
 5779    fn indent_selection(
 5780        buffer: &MultiBuffer,
 5781        snapshot: &MultiBufferSnapshot,
 5782        selection: &mut Selection<Point>,
 5783        edits: &mut Vec<(Range<Point>, String)>,
 5784        delta_for_start_row: u32,
 5785        cx: &AppContext,
 5786    ) -> u32 {
 5787        let settings = buffer.settings_at(selection.start, cx);
 5788        let tab_size = settings.tab_size.get();
 5789        let indent_kind = if settings.hard_tabs {
 5790            IndentKind::Tab
 5791        } else {
 5792            IndentKind::Space
 5793        };
 5794        let mut start_row = selection.start.row;
 5795        let mut end_row = selection.end.row + 1;
 5796
 5797        // If a selection ends at the beginning of a line, don't indent
 5798        // that last line.
 5799        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5800            end_row -= 1;
 5801        }
 5802
 5803        // Avoid re-indenting a row that has already been indented by a
 5804        // previous selection, but still update this selection's column
 5805        // to reflect that indentation.
 5806        if delta_for_start_row > 0 {
 5807            start_row += 1;
 5808            selection.start.column += delta_for_start_row;
 5809            if selection.end.row == selection.start.row {
 5810                selection.end.column += delta_for_start_row;
 5811            }
 5812        }
 5813
 5814        let mut delta_for_end_row = 0;
 5815        let has_multiple_rows = start_row + 1 != end_row;
 5816        for row in start_row..end_row {
 5817            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5818            let indent_delta = match (current_indent.kind, indent_kind) {
 5819                (IndentKind::Space, IndentKind::Space) => {
 5820                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5821                    IndentSize::spaces(columns_to_next_tab_stop)
 5822                }
 5823                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5824                (_, IndentKind::Tab) => IndentSize::tab(),
 5825            };
 5826
 5827            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5828                0
 5829            } else {
 5830                selection.start.column
 5831            };
 5832            let row_start = Point::new(row, start);
 5833            edits.push((
 5834                row_start..row_start,
 5835                indent_delta.chars().collect::<String>(),
 5836            ));
 5837
 5838            // Update this selection's endpoints to reflect the indentation.
 5839            if row == selection.start.row {
 5840                selection.start.column += indent_delta.len;
 5841            }
 5842            if row == selection.end.row {
 5843                selection.end.column += indent_delta.len;
 5844                delta_for_end_row = indent_delta.len;
 5845            }
 5846        }
 5847
 5848        if selection.start.row == selection.end.row {
 5849            delta_for_start_row + delta_for_end_row
 5850        } else {
 5851            delta_for_end_row
 5852        }
 5853    }
 5854
 5855    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5856        if self.read_only(cx) {
 5857            return;
 5858        }
 5859        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5860        let selections = self.selections.all::<Point>(cx);
 5861        let mut deletion_ranges = Vec::new();
 5862        let mut last_outdent = None;
 5863        {
 5864            let buffer = self.buffer.read(cx);
 5865            let snapshot = buffer.snapshot(cx);
 5866            for selection in &selections {
 5867                let settings = buffer.settings_at(selection.start, cx);
 5868                let tab_size = settings.tab_size.get();
 5869                let mut rows = selection.spanned_rows(false, &display_map);
 5870
 5871                // Avoid re-outdenting a row that has already been outdented by a
 5872                // previous selection.
 5873                if let Some(last_row) = last_outdent {
 5874                    if last_row == rows.start {
 5875                        rows.start = rows.start.next_row();
 5876                    }
 5877                }
 5878                let has_multiple_rows = rows.len() > 1;
 5879                for row in rows.iter_rows() {
 5880                    let indent_size = snapshot.indent_size_for_line(row);
 5881                    if indent_size.len > 0 {
 5882                        let deletion_len = match indent_size.kind {
 5883                            IndentKind::Space => {
 5884                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5885                                if columns_to_prev_tab_stop == 0 {
 5886                                    tab_size
 5887                                } else {
 5888                                    columns_to_prev_tab_stop
 5889                                }
 5890                            }
 5891                            IndentKind::Tab => 1,
 5892                        };
 5893                        let start = if has_multiple_rows
 5894                            || deletion_len > selection.start.column
 5895                            || indent_size.len < selection.start.column
 5896                        {
 5897                            0
 5898                        } else {
 5899                            selection.start.column - deletion_len
 5900                        };
 5901                        deletion_ranges.push(
 5902                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5903                        );
 5904                        last_outdent = Some(row);
 5905                    }
 5906                }
 5907            }
 5908        }
 5909
 5910        self.transact(cx, |this, cx| {
 5911            this.buffer.update(cx, |buffer, cx| {
 5912                let empty_str: Arc<str> = Arc::default();
 5913                buffer.edit(
 5914                    deletion_ranges
 5915                        .into_iter()
 5916                        .map(|range| (range, empty_str.clone())),
 5917                    None,
 5918                    cx,
 5919                );
 5920            });
 5921            let selections = this.selections.all::<usize>(cx);
 5922            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5923        });
 5924    }
 5925
 5926    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 5927        if self.read_only(cx) {
 5928            return;
 5929        }
 5930        let selections = self
 5931            .selections
 5932            .all::<usize>(cx)
 5933            .into_iter()
 5934            .map(|s| s.range());
 5935
 5936        self.transact(cx, |this, cx| {
 5937            this.buffer.update(cx, |buffer, cx| {
 5938                buffer.autoindent_ranges(selections, cx);
 5939            });
 5940            let selections = this.selections.all::<usize>(cx);
 5941            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5942        });
 5943    }
 5944
 5945    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5946        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5947        let selections = self.selections.all::<Point>(cx);
 5948
 5949        let mut new_cursors = Vec::new();
 5950        let mut edit_ranges = Vec::new();
 5951        let mut selections = selections.iter().peekable();
 5952        while let Some(selection) = selections.next() {
 5953            let mut rows = selection.spanned_rows(false, &display_map);
 5954            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5955
 5956            // Accumulate contiguous regions of rows that we want to delete.
 5957            while let Some(next_selection) = selections.peek() {
 5958                let next_rows = next_selection.spanned_rows(false, &display_map);
 5959                if next_rows.start <= rows.end {
 5960                    rows.end = next_rows.end;
 5961                    selections.next().unwrap();
 5962                } else {
 5963                    break;
 5964                }
 5965            }
 5966
 5967            let buffer = &display_map.buffer_snapshot;
 5968            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5969            let edit_end;
 5970            let cursor_buffer_row;
 5971            if buffer.max_point().row >= rows.end.0 {
 5972                // If there's a line after the range, delete the \n from the end of the row range
 5973                // and position the cursor on the next line.
 5974                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5975                cursor_buffer_row = rows.end;
 5976            } else {
 5977                // If there isn't a line after the range, delete the \n from the line before the
 5978                // start of the row range and position the cursor there.
 5979                edit_start = edit_start.saturating_sub(1);
 5980                edit_end = buffer.len();
 5981                cursor_buffer_row = rows.start.previous_row();
 5982            }
 5983
 5984            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5985            *cursor.column_mut() =
 5986                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5987
 5988            new_cursors.push((
 5989                selection.id,
 5990                buffer.anchor_after(cursor.to_point(&display_map)),
 5991            ));
 5992            edit_ranges.push(edit_start..edit_end);
 5993        }
 5994
 5995        self.transact(cx, |this, cx| {
 5996            let buffer = this.buffer.update(cx, |buffer, cx| {
 5997                let empty_str: Arc<str> = Arc::default();
 5998                buffer.edit(
 5999                    edit_ranges
 6000                        .into_iter()
 6001                        .map(|range| (range, empty_str.clone())),
 6002                    None,
 6003                    cx,
 6004                );
 6005                buffer.snapshot(cx)
 6006            });
 6007            let new_selections = new_cursors
 6008                .into_iter()
 6009                .map(|(id, cursor)| {
 6010                    let cursor = cursor.to_point(&buffer);
 6011                    Selection {
 6012                        id,
 6013                        start: cursor,
 6014                        end: cursor,
 6015                        reversed: false,
 6016                        goal: SelectionGoal::None,
 6017                    }
 6018                })
 6019                .collect();
 6020
 6021            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6022                s.select(new_selections);
 6023            });
 6024        });
 6025    }
 6026
 6027    pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
 6028        if self.read_only(cx) {
 6029            return;
 6030        }
 6031        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6032        for selection in self.selections.all::<Point>(cx) {
 6033            let start = MultiBufferRow(selection.start.row);
 6034            // Treat single line selections as if they include the next line. Otherwise this action
 6035            // would do nothing for single line selections individual cursors.
 6036            let end = if selection.start.row == selection.end.row {
 6037                MultiBufferRow(selection.start.row + 1)
 6038            } else {
 6039                MultiBufferRow(selection.end.row)
 6040            };
 6041
 6042            if let Some(last_row_range) = row_ranges.last_mut() {
 6043                if start <= last_row_range.end {
 6044                    last_row_range.end = end;
 6045                    continue;
 6046                }
 6047            }
 6048            row_ranges.push(start..end);
 6049        }
 6050
 6051        let snapshot = self.buffer.read(cx).snapshot(cx);
 6052        let mut cursor_positions = Vec::new();
 6053        for row_range in &row_ranges {
 6054            let anchor = snapshot.anchor_before(Point::new(
 6055                row_range.end.previous_row().0,
 6056                snapshot.line_len(row_range.end.previous_row()),
 6057            ));
 6058            cursor_positions.push(anchor..anchor);
 6059        }
 6060
 6061        self.transact(cx, |this, cx| {
 6062            for row_range in row_ranges.into_iter().rev() {
 6063                for row in row_range.iter_rows().rev() {
 6064                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6065                    let next_line_row = row.next_row();
 6066                    let indent = snapshot.indent_size_for_line(next_line_row);
 6067                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6068
 6069                    let replace =
 6070                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6071                            " "
 6072                        } else {
 6073                            ""
 6074                        };
 6075
 6076                    this.buffer.update(cx, |buffer, cx| {
 6077                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6078                    });
 6079                }
 6080            }
 6081
 6082            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6083                s.select_anchor_ranges(cursor_positions)
 6084            });
 6085        });
 6086    }
 6087
 6088    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6089        self.join_lines_impl(true, cx);
 6090    }
 6091
 6092    pub fn sort_lines_case_sensitive(
 6093        &mut self,
 6094        _: &SortLinesCaseSensitive,
 6095        cx: &mut ViewContext<Self>,
 6096    ) {
 6097        self.manipulate_lines(cx, |lines| lines.sort())
 6098    }
 6099
 6100    pub fn sort_lines_case_insensitive(
 6101        &mut self,
 6102        _: &SortLinesCaseInsensitive,
 6103        cx: &mut ViewContext<Self>,
 6104    ) {
 6105        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6106    }
 6107
 6108    pub fn unique_lines_case_insensitive(
 6109        &mut self,
 6110        _: &UniqueLinesCaseInsensitive,
 6111        cx: &mut ViewContext<Self>,
 6112    ) {
 6113        self.manipulate_lines(cx, |lines| {
 6114            let mut seen = HashSet::default();
 6115            lines.retain(|line| seen.insert(line.to_lowercase()));
 6116        })
 6117    }
 6118
 6119    pub fn unique_lines_case_sensitive(
 6120        &mut self,
 6121        _: &UniqueLinesCaseSensitive,
 6122        cx: &mut ViewContext<Self>,
 6123    ) {
 6124        self.manipulate_lines(cx, |lines| {
 6125            let mut seen = HashSet::default();
 6126            lines.retain(|line| seen.insert(*line));
 6127        })
 6128    }
 6129
 6130    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6131        let mut revert_changes = HashMap::default();
 6132        let snapshot = self.snapshot(cx);
 6133        for hunk in snapshot
 6134            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6135        {
 6136            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6137        }
 6138        if !revert_changes.is_empty() {
 6139            self.transact(cx, |editor, cx| {
 6140                editor.revert(revert_changes, cx);
 6141            });
 6142        }
 6143    }
 6144
 6145    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6146        let Some(project) = self.project.clone() else {
 6147            return;
 6148        };
 6149        self.reload(project, cx).detach_and_notify_err(cx);
 6150    }
 6151
 6152    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6153        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6154        self.revert_hunks_in_ranges(selections, cx);
 6155    }
 6156
 6157    fn revert_hunks_in_ranges(
 6158        &mut self,
 6159        ranges: impl Iterator<Item = Range<Point>>,
 6160        cx: &mut ViewContext<Editor>,
 6161    ) {
 6162        let mut revert_changes = HashMap::default();
 6163        let snapshot = self.snapshot(cx);
 6164        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6165            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6166        }
 6167        if !revert_changes.is_empty() {
 6168            self.transact(cx, |editor, cx| {
 6169                editor.revert(revert_changes, cx);
 6170            });
 6171        }
 6172    }
 6173
 6174    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6175        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6176            let project_path = buffer.read(cx).project_path(cx)?;
 6177            let project = self.project.as_ref()?.read(cx);
 6178            let entry = project.entry_for_path(&project_path, cx)?;
 6179            let parent = match &entry.canonical_path {
 6180                Some(canonical_path) => canonical_path.to_path_buf(),
 6181                None => project.absolute_path(&project_path, cx)?,
 6182            }
 6183            .parent()?
 6184            .to_path_buf();
 6185            Some(parent)
 6186        }) {
 6187            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6188        }
 6189    }
 6190
 6191    pub fn prepare_revert_change(
 6192        &self,
 6193        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6194        hunk: &MultiBufferDiffHunk,
 6195        cx: &mut WindowContext,
 6196    ) -> Option<()> {
 6197        let buffer = self.buffer.read(cx);
 6198        let change_set = buffer.change_set_for(hunk.buffer_id)?;
 6199        let buffer = buffer.buffer(hunk.buffer_id)?;
 6200        let buffer = buffer.read(cx);
 6201        let original_text = change_set
 6202            .read(cx)
 6203            .base_text
 6204            .as_ref()?
 6205            .as_rope()
 6206            .slice(hunk.diff_base_byte_range.clone());
 6207        let buffer_snapshot = buffer.snapshot();
 6208        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6209        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6210            probe
 6211                .0
 6212                .start
 6213                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6214                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6215        }) {
 6216            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6217            Some(())
 6218        } else {
 6219            None
 6220        }
 6221    }
 6222
 6223    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6224        self.manipulate_lines(cx, |lines| lines.reverse())
 6225    }
 6226
 6227    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6228        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6229    }
 6230
 6231    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6232    where
 6233        Fn: FnMut(&mut Vec<&str>),
 6234    {
 6235        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6236        let buffer = self.buffer.read(cx).snapshot(cx);
 6237
 6238        let mut edits = Vec::new();
 6239
 6240        let selections = self.selections.all::<Point>(cx);
 6241        let mut selections = selections.iter().peekable();
 6242        let mut contiguous_row_selections = Vec::new();
 6243        let mut new_selections = Vec::new();
 6244        let mut added_lines = 0;
 6245        let mut removed_lines = 0;
 6246
 6247        while let Some(selection) = selections.next() {
 6248            let (start_row, end_row) = consume_contiguous_rows(
 6249                &mut contiguous_row_selections,
 6250                selection,
 6251                &display_map,
 6252                &mut selections,
 6253            );
 6254
 6255            let start_point = Point::new(start_row.0, 0);
 6256            let end_point = Point::new(
 6257                end_row.previous_row().0,
 6258                buffer.line_len(end_row.previous_row()),
 6259            );
 6260            let text = buffer
 6261                .text_for_range(start_point..end_point)
 6262                .collect::<String>();
 6263
 6264            let mut lines = text.split('\n').collect_vec();
 6265
 6266            let lines_before = lines.len();
 6267            callback(&mut lines);
 6268            let lines_after = lines.len();
 6269
 6270            edits.push((start_point..end_point, lines.join("\n")));
 6271
 6272            // Selections must change based on added and removed line count
 6273            let start_row =
 6274                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6275            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6276            new_selections.push(Selection {
 6277                id: selection.id,
 6278                start: start_row,
 6279                end: end_row,
 6280                goal: SelectionGoal::None,
 6281                reversed: selection.reversed,
 6282            });
 6283
 6284            if lines_after > lines_before {
 6285                added_lines += lines_after - lines_before;
 6286            } else if lines_before > lines_after {
 6287                removed_lines += lines_before - lines_after;
 6288            }
 6289        }
 6290
 6291        self.transact(cx, |this, cx| {
 6292            let buffer = this.buffer.update(cx, |buffer, cx| {
 6293                buffer.edit(edits, None, cx);
 6294                buffer.snapshot(cx)
 6295            });
 6296
 6297            // Recalculate offsets on newly edited buffer
 6298            let new_selections = new_selections
 6299                .iter()
 6300                .map(|s| {
 6301                    let start_point = Point::new(s.start.0, 0);
 6302                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6303                    Selection {
 6304                        id: s.id,
 6305                        start: buffer.point_to_offset(start_point),
 6306                        end: buffer.point_to_offset(end_point),
 6307                        goal: s.goal,
 6308                        reversed: s.reversed,
 6309                    }
 6310                })
 6311                .collect();
 6312
 6313            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6314                s.select(new_selections);
 6315            });
 6316
 6317            this.request_autoscroll(Autoscroll::fit(), cx);
 6318        });
 6319    }
 6320
 6321    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6322        self.manipulate_text(cx, |text| text.to_uppercase())
 6323    }
 6324
 6325    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6326        self.manipulate_text(cx, |text| text.to_lowercase())
 6327    }
 6328
 6329    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6330        self.manipulate_text(cx, |text| {
 6331            text.split('\n')
 6332                .map(|line| line.to_case(Case::Title))
 6333                .join("\n")
 6334        })
 6335    }
 6336
 6337    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6338        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6339    }
 6340
 6341    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6342        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6343    }
 6344
 6345    pub fn convert_to_upper_camel_case(
 6346        &mut self,
 6347        _: &ConvertToUpperCamelCase,
 6348        cx: &mut ViewContext<Self>,
 6349    ) {
 6350        self.manipulate_text(cx, |text| {
 6351            text.split('\n')
 6352                .map(|line| line.to_case(Case::UpperCamel))
 6353                .join("\n")
 6354        })
 6355    }
 6356
 6357    pub fn convert_to_lower_camel_case(
 6358        &mut self,
 6359        _: &ConvertToLowerCamelCase,
 6360        cx: &mut ViewContext<Self>,
 6361    ) {
 6362        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6363    }
 6364
 6365    pub fn convert_to_opposite_case(
 6366        &mut self,
 6367        _: &ConvertToOppositeCase,
 6368        cx: &mut ViewContext<Self>,
 6369    ) {
 6370        self.manipulate_text(cx, |text| {
 6371            text.chars()
 6372                .fold(String::with_capacity(text.len()), |mut t, c| {
 6373                    if c.is_uppercase() {
 6374                        t.extend(c.to_lowercase());
 6375                    } else {
 6376                        t.extend(c.to_uppercase());
 6377                    }
 6378                    t
 6379                })
 6380        })
 6381    }
 6382
 6383    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6384    where
 6385        Fn: FnMut(&str) -> String,
 6386    {
 6387        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6388        let buffer = self.buffer.read(cx).snapshot(cx);
 6389
 6390        let mut new_selections = Vec::new();
 6391        let mut edits = Vec::new();
 6392        let mut selection_adjustment = 0i32;
 6393
 6394        for selection in self.selections.all::<usize>(cx) {
 6395            let selection_is_empty = selection.is_empty();
 6396
 6397            let (start, end) = if selection_is_empty {
 6398                let word_range = movement::surrounding_word(
 6399                    &display_map,
 6400                    selection.start.to_display_point(&display_map),
 6401                );
 6402                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6403                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6404                (start, end)
 6405            } else {
 6406                (selection.start, selection.end)
 6407            };
 6408
 6409            let text = buffer.text_for_range(start..end).collect::<String>();
 6410            let old_length = text.len() as i32;
 6411            let text = callback(&text);
 6412
 6413            new_selections.push(Selection {
 6414                start: (start as i32 - selection_adjustment) as usize,
 6415                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6416                goal: SelectionGoal::None,
 6417                ..selection
 6418            });
 6419
 6420            selection_adjustment += old_length - text.len() as i32;
 6421
 6422            edits.push((start..end, text));
 6423        }
 6424
 6425        self.transact(cx, |this, cx| {
 6426            this.buffer.update(cx, |buffer, cx| {
 6427                buffer.edit(edits, None, cx);
 6428            });
 6429
 6430            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6431                s.select(new_selections);
 6432            });
 6433
 6434            this.request_autoscroll(Autoscroll::fit(), cx);
 6435        });
 6436    }
 6437
 6438    pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
 6439        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6440        let buffer = &display_map.buffer_snapshot;
 6441        let selections = self.selections.all::<Point>(cx);
 6442
 6443        let mut edits = Vec::new();
 6444        let mut selections_iter = selections.iter().peekable();
 6445        while let Some(selection) = selections_iter.next() {
 6446            let mut rows = selection.spanned_rows(false, &display_map);
 6447            // duplicate line-wise
 6448            if whole_lines || selection.start == selection.end {
 6449                // Avoid duplicating the same lines twice.
 6450                while let Some(next_selection) = selections_iter.peek() {
 6451                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6452                    if next_rows.start < rows.end {
 6453                        rows.end = next_rows.end;
 6454                        selections_iter.next().unwrap();
 6455                    } else {
 6456                        break;
 6457                    }
 6458                }
 6459
 6460                // Copy the text from the selected row region and splice it either at the start
 6461                // or end of the region.
 6462                let start = Point::new(rows.start.0, 0);
 6463                let end = Point::new(
 6464                    rows.end.previous_row().0,
 6465                    buffer.line_len(rows.end.previous_row()),
 6466                );
 6467                let text = buffer
 6468                    .text_for_range(start..end)
 6469                    .chain(Some("\n"))
 6470                    .collect::<String>();
 6471                let insert_location = if upwards {
 6472                    Point::new(rows.end.0, 0)
 6473                } else {
 6474                    start
 6475                };
 6476                edits.push((insert_location..insert_location, text));
 6477            } else {
 6478                // duplicate character-wise
 6479                let start = selection.start;
 6480                let end = selection.end;
 6481                let text = buffer.text_for_range(start..end).collect::<String>();
 6482                edits.push((selection.end..selection.end, text));
 6483            }
 6484        }
 6485
 6486        self.transact(cx, |this, cx| {
 6487            this.buffer.update(cx, |buffer, cx| {
 6488                buffer.edit(edits, None, cx);
 6489            });
 6490
 6491            this.request_autoscroll(Autoscroll::fit(), cx);
 6492        });
 6493    }
 6494
 6495    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6496        self.duplicate(true, true, cx);
 6497    }
 6498
 6499    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6500        self.duplicate(false, true, cx);
 6501    }
 6502
 6503    pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
 6504        self.duplicate(false, false, cx);
 6505    }
 6506
 6507    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6508        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6509        let buffer = self.buffer.read(cx).snapshot(cx);
 6510
 6511        let mut edits = Vec::new();
 6512        let mut unfold_ranges = Vec::new();
 6513        let mut refold_creases = Vec::new();
 6514
 6515        let selections = self.selections.all::<Point>(cx);
 6516        let mut selections = selections.iter().peekable();
 6517        let mut contiguous_row_selections = Vec::new();
 6518        let mut new_selections = Vec::new();
 6519
 6520        while let Some(selection) = selections.next() {
 6521            // Find all the selections that span a contiguous row range
 6522            let (start_row, end_row) = consume_contiguous_rows(
 6523                &mut contiguous_row_selections,
 6524                selection,
 6525                &display_map,
 6526                &mut selections,
 6527            );
 6528
 6529            // Move the text spanned by the row range to be before the line preceding the row range
 6530            if start_row.0 > 0 {
 6531                let range_to_move = Point::new(
 6532                    start_row.previous_row().0,
 6533                    buffer.line_len(start_row.previous_row()),
 6534                )
 6535                    ..Point::new(
 6536                        end_row.previous_row().0,
 6537                        buffer.line_len(end_row.previous_row()),
 6538                    );
 6539                let insertion_point = display_map
 6540                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6541                    .0;
 6542
 6543                // Don't move lines across excerpts
 6544                if buffer
 6545                    .excerpt_containing(insertion_point..range_to_move.end)
 6546                    .is_some()
 6547                {
 6548                    let text = buffer
 6549                        .text_for_range(range_to_move.clone())
 6550                        .flat_map(|s| s.chars())
 6551                        .skip(1)
 6552                        .chain(['\n'])
 6553                        .collect::<String>();
 6554
 6555                    edits.push((
 6556                        buffer.anchor_after(range_to_move.start)
 6557                            ..buffer.anchor_before(range_to_move.end),
 6558                        String::new(),
 6559                    ));
 6560                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6561                    edits.push((insertion_anchor..insertion_anchor, text));
 6562
 6563                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6564
 6565                    // Move selections up
 6566                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6567                        |mut selection| {
 6568                            selection.start.row -= row_delta;
 6569                            selection.end.row -= row_delta;
 6570                            selection
 6571                        },
 6572                    ));
 6573
 6574                    // Move folds up
 6575                    unfold_ranges.push(range_to_move.clone());
 6576                    for fold in display_map.folds_in_range(
 6577                        buffer.anchor_before(range_to_move.start)
 6578                            ..buffer.anchor_after(range_to_move.end),
 6579                    ) {
 6580                        let mut start = fold.range.start.to_point(&buffer);
 6581                        let mut end = fold.range.end.to_point(&buffer);
 6582                        start.row -= row_delta;
 6583                        end.row -= row_delta;
 6584                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6585                    }
 6586                }
 6587            }
 6588
 6589            // If we didn't move line(s), preserve the existing selections
 6590            new_selections.append(&mut contiguous_row_selections);
 6591        }
 6592
 6593        self.transact(cx, |this, cx| {
 6594            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6595            this.buffer.update(cx, |buffer, cx| {
 6596                for (range, text) in edits {
 6597                    buffer.edit([(range, text)], None, cx);
 6598                }
 6599            });
 6600            this.fold_creases(refold_creases, true, cx);
 6601            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6602                s.select(new_selections);
 6603            })
 6604        });
 6605    }
 6606
 6607    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6608        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6609        let buffer = self.buffer.read(cx).snapshot(cx);
 6610
 6611        let mut edits = Vec::new();
 6612        let mut unfold_ranges = Vec::new();
 6613        let mut refold_creases = Vec::new();
 6614
 6615        let selections = self.selections.all::<Point>(cx);
 6616        let mut selections = selections.iter().peekable();
 6617        let mut contiguous_row_selections = Vec::new();
 6618        let mut new_selections = Vec::new();
 6619
 6620        while let Some(selection) = selections.next() {
 6621            // Find all the selections that span a contiguous row range
 6622            let (start_row, end_row) = consume_contiguous_rows(
 6623                &mut contiguous_row_selections,
 6624                selection,
 6625                &display_map,
 6626                &mut selections,
 6627            );
 6628
 6629            // Move the text spanned by the row range to be after the last line of the row range
 6630            if end_row.0 <= buffer.max_point().row {
 6631                let range_to_move =
 6632                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6633                let insertion_point = display_map
 6634                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6635                    .0;
 6636
 6637                // Don't move lines across excerpt boundaries
 6638                if buffer
 6639                    .excerpt_containing(range_to_move.start..insertion_point)
 6640                    .is_some()
 6641                {
 6642                    let mut text = String::from("\n");
 6643                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6644                    text.pop(); // Drop trailing newline
 6645                    edits.push((
 6646                        buffer.anchor_after(range_to_move.start)
 6647                            ..buffer.anchor_before(range_to_move.end),
 6648                        String::new(),
 6649                    ));
 6650                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6651                    edits.push((insertion_anchor..insertion_anchor, text));
 6652
 6653                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6654
 6655                    // Move selections down
 6656                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6657                        |mut selection| {
 6658                            selection.start.row += row_delta;
 6659                            selection.end.row += row_delta;
 6660                            selection
 6661                        },
 6662                    ));
 6663
 6664                    // Move folds down
 6665                    unfold_ranges.push(range_to_move.clone());
 6666                    for fold in display_map.folds_in_range(
 6667                        buffer.anchor_before(range_to_move.start)
 6668                            ..buffer.anchor_after(range_to_move.end),
 6669                    ) {
 6670                        let mut start = fold.range.start.to_point(&buffer);
 6671                        let mut end = fold.range.end.to_point(&buffer);
 6672                        start.row += row_delta;
 6673                        end.row += row_delta;
 6674                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6675                    }
 6676                }
 6677            }
 6678
 6679            // If we didn't move line(s), preserve the existing selections
 6680            new_selections.append(&mut contiguous_row_selections);
 6681        }
 6682
 6683        self.transact(cx, |this, cx| {
 6684            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6685            this.buffer.update(cx, |buffer, cx| {
 6686                for (range, text) in edits {
 6687                    buffer.edit([(range, text)], None, cx);
 6688                }
 6689            });
 6690            this.fold_creases(refold_creases, true, cx);
 6691            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6692        });
 6693    }
 6694
 6695    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6696        let text_layout_details = &self.text_layout_details(cx);
 6697        self.transact(cx, |this, cx| {
 6698            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6699                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6700                let line_mode = s.line_mode;
 6701                s.move_with(|display_map, selection| {
 6702                    if !selection.is_empty() || line_mode {
 6703                        return;
 6704                    }
 6705
 6706                    let mut head = selection.head();
 6707                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6708                    if head.column() == display_map.line_len(head.row()) {
 6709                        transpose_offset = display_map
 6710                            .buffer_snapshot
 6711                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6712                    }
 6713
 6714                    if transpose_offset == 0 {
 6715                        return;
 6716                    }
 6717
 6718                    *head.column_mut() += 1;
 6719                    head = display_map.clip_point(head, Bias::Right);
 6720                    let goal = SelectionGoal::HorizontalPosition(
 6721                        display_map
 6722                            .x_for_display_point(head, text_layout_details)
 6723                            .into(),
 6724                    );
 6725                    selection.collapse_to(head, goal);
 6726
 6727                    let transpose_start = display_map
 6728                        .buffer_snapshot
 6729                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6730                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6731                        let transpose_end = display_map
 6732                            .buffer_snapshot
 6733                            .clip_offset(transpose_offset + 1, Bias::Right);
 6734                        if let Some(ch) =
 6735                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6736                        {
 6737                            edits.push((transpose_start..transpose_offset, String::new()));
 6738                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6739                        }
 6740                    }
 6741                });
 6742                edits
 6743            });
 6744            this.buffer
 6745                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6746            let selections = this.selections.all::<usize>(cx);
 6747            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6748                s.select(selections);
 6749            });
 6750        });
 6751    }
 6752
 6753    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6754        self.rewrap_impl(IsVimMode::No, cx)
 6755    }
 6756
 6757    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 6758        let buffer = self.buffer.read(cx).snapshot(cx);
 6759        let selections = self.selections.all::<Point>(cx);
 6760        let mut selections = selections.iter().peekable();
 6761
 6762        let mut edits = Vec::new();
 6763        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6764
 6765        while let Some(selection) = selections.next() {
 6766            let mut start_row = selection.start.row;
 6767            let mut end_row = selection.end.row;
 6768
 6769            // Skip selections that overlap with a range that has already been rewrapped.
 6770            let selection_range = start_row..end_row;
 6771            if rewrapped_row_ranges
 6772                .iter()
 6773                .any(|range| range.overlaps(&selection_range))
 6774            {
 6775                continue;
 6776            }
 6777
 6778            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 6779
 6780            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6781                match language_scope.language_name().0.as_ref() {
 6782                    "Markdown" | "Plain Text" => {
 6783                        should_rewrap = true;
 6784                    }
 6785                    _ => {}
 6786                }
 6787            }
 6788
 6789            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 6790
 6791            // Since not all lines in the selection may be at the same indent
 6792            // level, choose the indent size that is the most common between all
 6793            // of the lines.
 6794            //
 6795            // If there is a tie, we use the deepest indent.
 6796            let (indent_size, indent_end) = {
 6797                let mut indent_size_occurrences = HashMap::default();
 6798                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6799
 6800                for row in start_row..=end_row {
 6801                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6802                    rows_by_indent_size.entry(indent).or_default().push(row);
 6803                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6804                }
 6805
 6806                let indent_size = indent_size_occurrences
 6807                    .into_iter()
 6808                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 6809                    .map(|(indent, _)| indent)
 6810                    .unwrap_or_default();
 6811                let row = rows_by_indent_size[&indent_size][0];
 6812                let indent_end = Point::new(row, indent_size.len);
 6813
 6814                (indent_size, indent_end)
 6815            };
 6816
 6817            let mut line_prefix = indent_size.chars().collect::<String>();
 6818
 6819            if let Some(comment_prefix) =
 6820                buffer
 6821                    .language_scope_at(selection.head())
 6822                    .and_then(|language| {
 6823                        language
 6824                            .line_comment_prefixes()
 6825                            .iter()
 6826                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6827                            .cloned()
 6828                    })
 6829            {
 6830                line_prefix.push_str(&comment_prefix);
 6831                should_rewrap = true;
 6832            }
 6833
 6834            if !should_rewrap {
 6835                continue;
 6836            }
 6837
 6838            if selection.is_empty() {
 6839                'expand_upwards: while start_row > 0 {
 6840                    let prev_row = start_row - 1;
 6841                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6842                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6843                    {
 6844                        start_row = prev_row;
 6845                    } else {
 6846                        break 'expand_upwards;
 6847                    }
 6848                }
 6849
 6850                'expand_downwards: while end_row < buffer.max_point().row {
 6851                    let next_row = end_row + 1;
 6852                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6853                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6854                    {
 6855                        end_row = next_row;
 6856                    } else {
 6857                        break 'expand_downwards;
 6858                    }
 6859                }
 6860            }
 6861
 6862            let start = Point::new(start_row, 0);
 6863            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6864            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6865            let Some(lines_without_prefixes) = selection_text
 6866                .lines()
 6867                .map(|line| {
 6868                    line.strip_prefix(&line_prefix)
 6869                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6870                        .ok_or_else(|| {
 6871                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6872                        })
 6873                })
 6874                .collect::<Result<Vec<_>, _>>()
 6875                .log_err()
 6876            else {
 6877                continue;
 6878            };
 6879
 6880            let wrap_column = buffer
 6881                .settings_at(Point::new(start_row, 0), cx)
 6882                .preferred_line_length as usize;
 6883            let wrapped_text = wrap_with_prefix(
 6884                line_prefix,
 6885                lines_without_prefixes.join(" "),
 6886                wrap_column,
 6887                tab_size,
 6888            );
 6889
 6890            // TODO: should always use char-based diff while still supporting cursor behavior that
 6891            // matches vim.
 6892            let diff = match is_vim_mode {
 6893                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 6894                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 6895            };
 6896            let mut offset = start.to_offset(&buffer);
 6897            let mut moved_since_edit = true;
 6898
 6899            for change in diff.iter_all_changes() {
 6900                let value = change.value();
 6901                match change.tag() {
 6902                    ChangeTag::Equal => {
 6903                        offset += value.len();
 6904                        moved_since_edit = true;
 6905                    }
 6906                    ChangeTag::Delete => {
 6907                        let start = buffer.anchor_after(offset);
 6908                        let end = buffer.anchor_before(offset + value.len());
 6909
 6910                        if moved_since_edit {
 6911                            edits.push((start..end, String::new()));
 6912                        } else {
 6913                            edits.last_mut().unwrap().0.end = end;
 6914                        }
 6915
 6916                        offset += value.len();
 6917                        moved_since_edit = false;
 6918                    }
 6919                    ChangeTag::Insert => {
 6920                        if moved_since_edit {
 6921                            let anchor = buffer.anchor_after(offset);
 6922                            edits.push((anchor..anchor, value.to_string()));
 6923                        } else {
 6924                            edits.last_mut().unwrap().1.push_str(value);
 6925                        }
 6926
 6927                        moved_since_edit = false;
 6928                    }
 6929                }
 6930            }
 6931
 6932            rewrapped_row_ranges.push(start_row..=end_row);
 6933        }
 6934
 6935        self.buffer
 6936            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6937    }
 6938
 6939    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 6940        let mut text = String::new();
 6941        let buffer = self.buffer.read(cx).snapshot(cx);
 6942        let mut selections = self.selections.all::<Point>(cx);
 6943        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6944        {
 6945            let max_point = buffer.max_point();
 6946            let mut is_first = true;
 6947            for selection in &mut selections {
 6948                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6949                if is_entire_line {
 6950                    selection.start = Point::new(selection.start.row, 0);
 6951                    if !selection.is_empty() && selection.end.column == 0 {
 6952                        selection.end = cmp::min(max_point, selection.end);
 6953                    } else {
 6954                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6955                    }
 6956                    selection.goal = SelectionGoal::None;
 6957                }
 6958                if is_first {
 6959                    is_first = false;
 6960                } else {
 6961                    text += "\n";
 6962                }
 6963                let mut len = 0;
 6964                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6965                    text.push_str(chunk);
 6966                    len += chunk.len();
 6967                }
 6968                clipboard_selections.push(ClipboardSelection {
 6969                    len,
 6970                    is_entire_line,
 6971                    first_line_indent: buffer
 6972                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6973                        .len,
 6974                });
 6975            }
 6976        }
 6977
 6978        self.transact(cx, |this, cx| {
 6979            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6980                s.select(selections);
 6981            });
 6982            this.insert("", cx);
 6983        });
 6984        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 6985    }
 6986
 6987    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6988        let item = self.cut_common(cx);
 6989        cx.write_to_clipboard(item);
 6990    }
 6991
 6992    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 6993        self.change_selections(None, cx, |s| {
 6994            s.move_with(|snapshot, sel| {
 6995                if sel.is_empty() {
 6996                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 6997                }
 6998            });
 6999        });
 7000        let item = self.cut_common(cx);
 7001        cx.set_global(KillRing(item))
 7002    }
 7003
 7004    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 7005        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7006            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7007                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7008            } else {
 7009                return;
 7010            }
 7011        } else {
 7012            return;
 7013        };
 7014        self.do_paste(&text, metadata, false, cx);
 7015    }
 7016
 7017    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7018        let selections = self.selections.all::<Point>(cx);
 7019        let buffer = self.buffer.read(cx).read(cx);
 7020        let mut text = String::new();
 7021
 7022        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7023        {
 7024            let max_point = buffer.max_point();
 7025            let mut is_first = true;
 7026            for selection in selections.iter() {
 7027                let mut start = selection.start;
 7028                let mut end = selection.end;
 7029                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7030                if is_entire_line {
 7031                    start = Point::new(start.row, 0);
 7032                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7033                }
 7034                if is_first {
 7035                    is_first = false;
 7036                } else {
 7037                    text += "\n";
 7038                }
 7039                let mut len = 0;
 7040                for chunk in buffer.text_for_range(start..end) {
 7041                    text.push_str(chunk);
 7042                    len += chunk.len();
 7043                }
 7044                clipboard_selections.push(ClipboardSelection {
 7045                    len,
 7046                    is_entire_line,
 7047                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7048                });
 7049            }
 7050        }
 7051
 7052        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7053            text,
 7054            clipboard_selections,
 7055        ));
 7056    }
 7057
 7058    pub fn do_paste(
 7059        &mut self,
 7060        text: &String,
 7061        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7062        handle_entire_lines: bool,
 7063        cx: &mut ViewContext<Self>,
 7064    ) {
 7065        if self.read_only(cx) {
 7066            return;
 7067        }
 7068
 7069        let clipboard_text = Cow::Borrowed(text);
 7070
 7071        self.transact(cx, |this, cx| {
 7072            if let Some(mut clipboard_selections) = clipboard_selections {
 7073                let old_selections = this.selections.all::<usize>(cx);
 7074                let all_selections_were_entire_line =
 7075                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7076                let first_selection_indent_column =
 7077                    clipboard_selections.first().map(|s| s.first_line_indent);
 7078                if clipboard_selections.len() != old_selections.len() {
 7079                    clipboard_selections.drain(..);
 7080                }
 7081                let cursor_offset = this.selections.last::<usize>(cx).head();
 7082                let mut auto_indent_on_paste = true;
 7083
 7084                this.buffer.update(cx, |buffer, cx| {
 7085                    let snapshot = buffer.read(cx);
 7086                    auto_indent_on_paste =
 7087                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7088
 7089                    let mut start_offset = 0;
 7090                    let mut edits = Vec::new();
 7091                    let mut original_indent_columns = Vec::new();
 7092                    for (ix, selection) in old_selections.iter().enumerate() {
 7093                        let to_insert;
 7094                        let entire_line;
 7095                        let original_indent_column;
 7096                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7097                            let end_offset = start_offset + clipboard_selection.len;
 7098                            to_insert = &clipboard_text[start_offset..end_offset];
 7099                            entire_line = clipboard_selection.is_entire_line;
 7100                            start_offset = end_offset + 1;
 7101                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7102                        } else {
 7103                            to_insert = clipboard_text.as_str();
 7104                            entire_line = all_selections_were_entire_line;
 7105                            original_indent_column = first_selection_indent_column
 7106                        }
 7107
 7108                        // If the corresponding selection was empty when this slice of the
 7109                        // clipboard text was written, then the entire line containing the
 7110                        // selection was copied. If this selection is also currently empty,
 7111                        // then paste the line before the current line of the buffer.
 7112                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7113                            let column = selection.start.to_point(&snapshot).column as usize;
 7114                            let line_start = selection.start - column;
 7115                            line_start..line_start
 7116                        } else {
 7117                            selection.range()
 7118                        };
 7119
 7120                        edits.push((range, to_insert));
 7121                        original_indent_columns.extend(original_indent_column);
 7122                    }
 7123                    drop(snapshot);
 7124
 7125                    buffer.edit(
 7126                        edits,
 7127                        if auto_indent_on_paste {
 7128                            Some(AutoindentMode::Block {
 7129                                original_indent_columns,
 7130                            })
 7131                        } else {
 7132                            None
 7133                        },
 7134                        cx,
 7135                    );
 7136                });
 7137
 7138                let selections = this.selections.all::<usize>(cx);
 7139                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7140            } else {
 7141                this.insert(&clipboard_text, cx);
 7142            }
 7143        });
 7144    }
 7145
 7146    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7147        if let Some(item) = cx.read_from_clipboard() {
 7148            let entries = item.entries();
 7149
 7150            match entries.first() {
 7151                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7152                // of all the pasted entries.
 7153                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7154                    .do_paste(
 7155                        clipboard_string.text(),
 7156                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7157                        true,
 7158                        cx,
 7159                    ),
 7160                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7161            }
 7162        }
 7163    }
 7164
 7165    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7166        if self.read_only(cx) {
 7167            return;
 7168        }
 7169
 7170        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7171            if let Some((selections, _)) =
 7172                self.selection_history.transaction(transaction_id).cloned()
 7173            {
 7174                self.change_selections(None, cx, |s| {
 7175                    s.select_anchors(selections.to_vec());
 7176                });
 7177            }
 7178            self.request_autoscroll(Autoscroll::fit(), cx);
 7179            self.unmark_text(cx);
 7180            self.refresh_inline_completion(true, false, cx);
 7181            cx.emit(EditorEvent::Edited { transaction_id });
 7182            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7183        }
 7184    }
 7185
 7186    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7187        if self.read_only(cx) {
 7188            return;
 7189        }
 7190
 7191        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7192            if let Some((_, Some(selections))) =
 7193                self.selection_history.transaction(transaction_id).cloned()
 7194            {
 7195                self.change_selections(None, cx, |s| {
 7196                    s.select_anchors(selections.to_vec());
 7197                });
 7198            }
 7199            self.request_autoscroll(Autoscroll::fit(), cx);
 7200            self.unmark_text(cx);
 7201            self.refresh_inline_completion(true, false, cx);
 7202            cx.emit(EditorEvent::Edited { transaction_id });
 7203        }
 7204    }
 7205
 7206    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7207        self.buffer
 7208            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7209    }
 7210
 7211    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7212        self.buffer
 7213            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7214    }
 7215
 7216    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7217        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7218            let line_mode = s.line_mode;
 7219            s.move_with(|map, selection| {
 7220                let cursor = if selection.is_empty() && !line_mode {
 7221                    movement::left(map, selection.start)
 7222                } else {
 7223                    selection.start
 7224                };
 7225                selection.collapse_to(cursor, SelectionGoal::None);
 7226            });
 7227        })
 7228    }
 7229
 7230    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7231        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7232            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7233        })
 7234    }
 7235
 7236    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7237        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7238            let line_mode = s.line_mode;
 7239            s.move_with(|map, selection| {
 7240                let cursor = if selection.is_empty() && !line_mode {
 7241                    movement::right(map, selection.end)
 7242                } else {
 7243                    selection.end
 7244                };
 7245                selection.collapse_to(cursor, SelectionGoal::None)
 7246            });
 7247        })
 7248    }
 7249
 7250    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7251        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7252            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7253        })
 7254    }
 7255
 7256    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7257        if self.take_rename(true, cx).is_some() {
 7258            return;
 7259        }
 7260
 7261        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7262            cx.propagate();
 7263            return;
 7264        }
 7265
 7266        let text_layout_details = &self.text_layout_details(cx);
 7267        let selection_count = self.selections.count();
 7268        let first_selection = self.selections.first_anchor();
 7269
 7270        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7271            let line_mode = s.line_mode;
 7272            s.move_with(|map, selection| {
 7273                if !selection.is_empty() && !line_mode {
 7274                    selection.goal = SelectionGoal::None;
 7275                }
 7276                let (cursor, goal) = movement::up(
 7277                    map,
 7278                    selection.start,
 7279                    selection.goal,
 7280                    false,
 7281                    text_layout_details,
 7282                );
 7283                selection.collapse_to(cursor, goal);
 7284            });
 7285        });
 7286
 7287        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7288        {
 7289            cx.propagate();
 7290        }
 7291    }
 7292
 7293    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7294        if self.take_rename(true, cx).is_some() {
 7295            return;
 7296        }
 7297
 7298        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7299            cx.propagate();
 7300            return;
 7301        }
 7302
 7303        let text_layout_details = &self.text_layout_details(cx);
 7304
 7305        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7306            let line_mode = s.line_mode;
 7307            s.move_with(|map, selection| {
 7308                if !selection.is_empty() && !line_mode {
 7309                    selection.goal = SelectionGoal::None;
 7310                }
 7311                let (cursor, goal) = movement::up_by_rows(
 7312                    map,
 7313                    selection.start,
 7314                    action.lines,
 7315                    selection.goal,
 7316                    false,
 7317                    text_layout_details,
 7318                );
 7319                selection.collapse_to(cursor, goal);
 7320            });
 7321        })
 7322    }
 7323
 7324    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7325        if self.take_rename(true, cx).is_some() {
 7326            return;
 7327        }
 7328
 7329        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7330            cx.propagate();
 7331            return;
 7332        }
 7333
 7334        let text_layout_details = &self.text_layout_details(cx);
 7335
 7336        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7337            let line_mode = s.line_mode;
 7338            s.move_with(|map, selection| {
 7339                if !selection.is_empty() && !line_mode {
 7340                    selection.goal = SelectionGoal::None;
 7341                }
 7342                let (cursor, goal) = movement::down_by_rows(
 7343                    map,
 7344                    selection.start,
 7345                    action.lines,
 7346                    selection.goal,
 7347                    false,
 7348                    text_layout_details,
 7349                );
 7350                selection.collapse_to(cursor, goal);
 7351            });
 7352        })
 7353    }
 7354
 7355    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7356        let text_layout_details = &self.text_layout_details(cx);
 7357        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7358            s.move_heads_with(|map, head, goal| {
 7359                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7360            })
 7361        })
 7362    }
 7363
 7364    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7365        let text_layout_details = &self.text_layout_details(cx);
 7366        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7367            s.move_heads_with(|map, head, goal| {
 7368                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7369            })
 7370        })
 7371    }
 7372
 7373    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7374        let Some(row_count) = self.visible_row_count() else {
 7375            return;
 7376        };
 7377
 7378        let text_layout_details = &self.text_layout_details(cx);
 7379
 7380        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7381            s.move_heads_with(|map, head, goal| {
 7382                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7383            })
 7384        })
 7385    }
 7386
 7387    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7388        if self.take_rename(true, cx).is_some() {
 7389            return;
 7390        }
 7391
 7392        if self
 7393            .context_menu
 7394            .borrow_mut()
 7395            .as_mut()
 7396            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7397            .unwrap_or(false)
 7398        {
 7399            return;
 7400        }
 7401
 7402        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7403            cx.propagate();
 7404            return;
 7405        }
 7406
 7407        let Some(row_count) = self.visible_row_count() else {
 7408            return;
 7409        };
 7410
 7411        let autoscroll = if action.center_cursor {
 7412            Autoscroll::center()
 7413        } else {
 7414            Autoscroll::fit()
 7415        };
 7416
 7417        let text_layout_details = &self.text_layout_details(cx);
 7418
 7419        self.change_selections(Some(autoscroll), cx, |s| {
 7420            let line_mode = s.line_mode;
 7421            s.move_with(|map, selection| {
 7422                if !selection.is_empty() && !line_mode {
 7423                    selection.goal = SelectionGoal::None;
 7424                }
 7425                let (cursor, goal) = movement::up_by_rows(
 7426                    map,
 7427                    selection.end,
 7428                    row_count,
 7429                    selection.goal,
 7430                    false,
 7431                    text_layout_details,
 7432                );
 7433                selection.collapse_to(cursor, goal);
 7434            });
 7435        });
 7436    }
 7437
 7438    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7439        let text_layout_details = &self.text_layout_details(cx);
 7440        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7441            s.move_heads_with(|map, head, goal| {
 7442                movement::up(map, head, goal, false, text_layout_details)
 7443            })
 7444        })
 7445    }
 7446
 7447    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7448        self.take_rename(true, cx);
 7449
 7450        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7451            cx.propagate();
 7452            return;
 7453        }
 7454
 7455        let text_layout_details = &self.text_layout_details(cx);
 7456        let selection_count = self.selections.count();
 7457        let first_selection = self.selections.first_anchor();
 7458
 7459        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7460            let line_mode = s.line_mode;
 7461            s.move_with(|map, selection| {
 7462                if !selection.is_empty() && !line_mode {
 7463                    selection.goal = SelectionGoal::None;
 7464                }
 7465                let (cursor, goal) = movement::down(
 7466                    map,
 7467                    selection.end,
 7468                    selection.goal,
 7469                    false,
 7470                    text_layout_details,
 7471                );
 7472                selection.collapse_to(cursor, goal);
 7473            });
 7474        });
 7475
 7476        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7477        {
 7478            cx.propagate();
 7479        }
 7480    }
 7481
 7482    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7483        let Some(row_count) = self.visible_row_count() else {
 7484            return;
 7485        };
 7486
 7487        let text_layout_details = &self.text_layout_details(cx);
 7488
 7489        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7490            s.move_heads_with(|map, head, goal| {
 7491                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7492            })
 7493        })
 7494    }
 7495
 7496    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7497        if self.take_rename(true, cx).is_some() {
 7498            return;
 7499        }
 7500
 7501        if self
 7502            .context_menu
 7503            .borrow_mut()
 7504            .as_mut()
 7505            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7506            .unwrap_or(false)
 7507        {
 7508            return;
 7509        }
 7510
 7511        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7512            cx.propagate();
 7513            return;
 7514        }
 7515
 7516        let Some(row_count) = self.visible_row_count() else {
 7517            return;
 7518        };
 7519
 7520        let autoscroll = if action.center_cursor {
 7521            Autoscroll::center()
 7522        } else {
 7523            Autoscroll::fit()
 7524        };
 7525
 7526        let text_layout_details = &self.text_layout_details(cx);
 7527        self.change_selections(Some(autoscroll), cx, |s| {
 7528            let line_mode = s.line_mode;
 7529            s.move_with(|map, selection| {
 7530                if !selection.is_empty() && !line_mode {
 7531                    selection.goal = SelectionGoal::None;
 7532                }
 7533                let (cursor, goal) = movement::down_by_rows(
 7534                    map,
 7535                    selection.end,
 7536                    row_count,
 7537                    selection.goal,
 7538                    false,
 7539                    text_layout_details,
 7540                );
 7541                selection.collapse_to(cursor, goal);
 7542            });
 7543        });
 7544    }
 7545
 7546    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7547        let text_layout_details = &self.text_layout_details(cx);
 7548        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7549            s.move_heads_with(|map, head, goal| {
 7550                movement::down(map, head, goal, false, text_layout_details)
 7551            })
 7552        });
 7553    }
 7554
 7555    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7556        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7557            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7558        }
 7559    }
 7560
 7561    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7562        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7563            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7564        }
 7565    }
 7566
 7567    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7568        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7569            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7570        }
 7571    }
 7572
 7573    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7574        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7575            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7576        }
 7577    }
 7578
 7579    pub fn move_to_previous_word_start(
 7580        &mut self,
 7581        _: &MoveToPreviousWordStart,
 7582        cx: &mut ViewContext<Self>,
 7583    ) {
 7584        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7585            s.move_cursors_with(|map, head, _| {
 7586                (
 7587                    movement::previous_word_start(map, head),
 7588                    SelectionGoal::None,
 7589                )
 7590            });
 7591        })
 7592    }
 7593
 7594    pub fn move_to_previous_subword_start(
 7595        &mut self,
 7596        _: &MoveToPreviousSubwordStart,
 7597        cx: &mut ViewContext<Self>,
 7598    ) {
 7599        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7600            s.move_cursors_with(|map, head, _| {
 7601                (
 7602                    movement::previous_subword_start(map, head),
 7603                    SelectionGoal::None,
 7604                )
 7605            });
 7606        })
 7607    }
 7608
 7609    pub fn select_to_previous_word_start(
 7610        &mut self,
 7611        _: &SelectToPreviousWordStart,
 7612        cx: &mut ViewContext<Self>,
 7613    ) {
 7614        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7615            s.move_heads_with(|map, head, _| {
 7616                (
 7617                    movement::previous_word_start(map, head),
 7618                    SelectionGoal::None,
 7619                )
 7620            });
 7621        })
 7622    }
 7623
 7624    pub fn select_to_previous_subword_start(
 7625        &mut self,
 7626        _: &SelectToPreviousSubwordStart,
 7627        cx: &mut ViewContext<Self>,
 7628    ) {
 7629        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7630            s.move_heads_with(|map, head, _| {
 7631                (
 7632                    movement::previous_subword_start(map, head),
 7633                    SelectionGoal::None,
 7634                )
 7635            });
 7636        })
 7637    }
 7638
 7639    pub fn delete_to_previous_word_start(
 7640        &mut self,
 7641        action: &DeleteToPreviousWordStart,
 7642        cx: &mut ViewContext<Self>,
 7643    ) {
 7644        self.transact(cx, |this, cx| {
 7645            this.select_autoclose_pair(cx);
 7646            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7647                let line_mode = s.line_mode;
 7648                s.move_with(|map, selection| {
 7649                    if selection.is_empty() && !line_mode {
 7650                        let cursor = if action.ignore_newlines {
 7651                            movement::previous_word_start(map, selection.head())
 7652                        } else {
 7653                            movement::previous_word_start_or_newline(map, selection.head())
 7654                        };
 7655                        selection.set_head(cursor, SelectionGoal::None);
 7656                    }
 7657                });
 7658            });
 7659            this.insert("", cx);
 7660        });
 7661    }
 7662
 7663    pub fn delete_to_previous_subword_start(
 7664        &mut self,
 7665        _: &DeleteToPreviousSubwordStart,
 7666        cx: &mut ViewContext<Self>,
 7667    ) {
 7668        self.transact(cx, |this, cx| {
 7669            this.select_autoclose_pair(cx);
 7670            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7671                let line_mode = s.line_mode;
 7672                s.move_with(|map, selection| {
 7673                    if selection.is_empty() && !line_mode {
 7674                        let cursor = movement::previous_subword_start(map, selection.head());
 7675                        selection.set_head(cursor, SelectionGoal::None);
 7676                    }
 7677                });
 7678            });
 7679            this.insert("", cx);
 7680        });
 7681    }
 7682
 7683    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7684        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7685            s.move_cursors_with(|map, head, _| {
 7686                (movement::next_word_end(map, head), SelectionGoal::None)
 7687            });
 7688        })
 7689    }
 7690
 7691    pub fn move_to_next_subword_end(
 7692        &mut self,
 7693        _: &MoveToNextSubwordEnd,
 7694        cx: &mut ViewContext<Self>,
 7695    ) {
 7696        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7697            s.move_cursors_with(|map, head, _| {
 7698                (movement::next_subword_end(map, head), SelectionGoal::None)
 7699            });
 7700        })
 7701    }
 7702
 7703    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7704        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7705            s.move_heads_with(|map, head, _| {
 7706                (movement::next_word_end(map, head), SelectionGoal::None)
 7707            });
 7708        })
 7709    }
 7710
 7711    pub fn select_to_next_subword_end(
 7712        &mut self,
 7713        _: &SelectToNextSubwordEnd,
 7714        cx: &mut ViewContext<Self>,
 7715    ) {
 7716        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7717            s.move_heads_with(|map, head, _| {
 7718                (movement::next_subword_end(map, head), SelectionGoal::None)
 7719            });
 7720        })
 7721    }
 7722
 7723    pub fn delete_to_next_word_end(
 7724        &mut self,
 7725        action: &DeleteToNextWordEnd,
 7726        cx: &mut ViewContext<Self>,
 7727    ) {
 7728        self.transact(cx, |this, cx| {
 7729            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7730                let line_mode = s.line_mode;
 7731                s.move_with(|map, selection| {
 7732                    if selection.is_empty() && !line_mode {
 7733                        let cursor = if action.ignore_newlines {
 7734                            movement::next_word_end(map, selection.head())
 7735                        } else {
 7736                            movement::next_word_end_or_newline(map, selection.head())
 7737                        };
 7738                        selection.set_head(cursor, SelectionGoal::None);
 7739                    }
 7740                });
 7741            });
 7742            this.insert("", cx);
 7743        });
 7744    }
 7745
 7746    pub fn delete_to_next_subword_end(
 7747        &mut self,
 7748        _: &DeleteToNextSubwordEnd,
 7749        cx: &mut ViewContext<Self>,
 7750    ) {
 7751        self.transact(cx, |this, cx| {
 7752            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7753                s.move_with(|map, selection| {
 7754                    if selection.is_empty() {
 7755                        let cursor = movement::next_subword_end(map, selection.head());
 7756                        selection.set_head(cursor, SelectionGoal::None);
 7757                    }
 7758                });
 7759            });
 7760            this.insert("", cx);
 7761        });
 7762    }
 7763
 7764    pub fn move_to_beginning_of_line(
 7765        &mut self,
 7766        action: &MoveToBeginningOfLine,
 7767        cx: &mut ViewContext<Self>,
 7768    ) {
 7769        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7770            s.move_cursors_with(|map, head, _| {
 7771                (
 7772                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7773                    SelectionGoal::None,
 7774                )
 7775            });
 7776        })
 7777    }
 7778
 7779    pub fn select_to_beginning_of_line(
 7780        &mut self,
 7781        action: &SelectToBeginningOfLine,
 7782        cx: &mut ViewContext<Self>,
 7783    ) {
 7784        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7785            s.move_heads_with(|map, head, _| {
 7786                (
 7787                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7788                    SelectionGoal::None,
 7789                )
 7790            });
 7791        });
 7792    }
 7793
 7794    pub fn delete_to_beginning_of_line(
 7795        &mut self,
 7796        _: &DeleteToBeginningOfLine,
 7797        cx: &mut ViewContext<Self>,
 7798    ) {
 7799        self.transact(cx, |this, cx| {
 7800            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7801                s.move_with(|_, selection| {
 7802                    selection.reversed = true;
 7803                });
 7804            });
 7805
 7806            this.select_to_beginning_of_line(
 7807                &SelectToBeginningOfLine {
 7808                    stop_at_soft_wraps: false,
 7809                },
 7810                cx,
 7811            );
 7812            this.backspace(&Backspace, cx);
 7813        });
 7814    }
 7815
 7816    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7817        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7818            s.move_cursors_with(|map, head, _| {
 7819                (
 7820                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7821                    SelectionGoal::None,
 7822                )
 7823            });
 7824        })
 7825    }
 7826
 7827    pub fn select_to_end_of_line(
 7828        &mut self,
 7829        action: &SelectToEndOfLine,
 7830        cx: &mut ViewContext<Self>,
 7831    ) {
 7832        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7833            s.move_heads_with(|map, head, _| {
 7834                (
 7835                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7836                    SelectionGoal::None,
 7837                )
 7838            });
 7839        })
 7840    }
 7841
 7842    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7843        self.transact(cx, |this, cx| {
 7844            this.select_to_end_of_line(
 7845                &SelectToEndOfLine {
 7846                    stop_at_soft_wraps: false,
 7847                },
 7848                cx,
 7849            );
 7850            this.delete(&Delete, cx);
 7851        });
 7852    }
 7853
 7854    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7855        self.transact(cx, |this, cx| {
 7856            this.select_to_end_of_line(
 7857                &SelectToEndOfLine {
 7858                    stop_at_soft_wraps: false,
 7859                },
 7860                cx,
 7861            );
 7862            this.cut(&Cut, cx);
 7863        });
 7864    }
 7865
 7866    pub fn move_to_start_of_paragraph(
 7867        &mut self,
 7868        _: &MoveToStartOfParagraph,
 7869        cx: &mut ViewContext<Self>,
 7870    ) {
 7871        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7872            cx.propagate();
 7873            return;
 7874        }
 7875
 7876        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7877            s.move_with(|map, selection| {
 7878                selection.collapse_to(
 7879                    movement::start_of_paragraph(map, selection.head(), 1),
 7880                    SelectionGoal::None,
 7881                )
 7882            });
 7883        })
 7884    }
 7885
 7886    pub fn move_to_end_of_paragraph(
 7887        &mut self,
 7888        _: &MoveToEndOfParagraph,
 7889        cx: &mut ViewContext<Self>,
 7890    ) {
 7891        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7892            cx.propagate();
 7893            return;
 7894        }
 7895
 7896        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7897            s.move_with(|map, selection| {
 7898                selection.collapse_to(
 7899                    movement::end_of_paragraph(map, selection.head(), 1),
 7900                    SelectionGoal::None,
 7901                )
 7902            });
 7903        })
 7904    }
 7905
 7906    pub fn select_to_start_of_paragraph(
 7907        &mut self,
 7908        _: &SelectToStartOfParagraph,
 7909        cx: &mut ViewContext<Self>,
 7910    ) {
 7911        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7912            cx.propagate();
 7913            return;
 7914        }
 7915
 7916        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7917            s.move_heads_with(|map, head, _| {
 7918                (
 7919                    movement::start_of_paragraph(map, head, 1),
 7920                    SelectionGoal::None,
 7921                )
 7922            });
 7923        })
 7924    }
 7925
 7926    pub fn select_to_end_of_paragraph(
 7927        &mut self,
 7928        _: &SelectToEndOfParagraph,
 7929        cx: &mut ViewContext<Self>,
 7930    ) {
 7931        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7932            cx.propagate();
 7933            return;
 7934        }
 7935
 7936        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7937            s.move_heads_with(|map, head, _| {
 7938                (
 7939                    movement::end_of_paragraph(map, head, 1),
 7940                    SelectionGoal::None,
 7941                )
 7942            });
 7943        })
 7944    }
 7945
 7946    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7947        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7948            cx.propagate();
 7949            return;
 7950        }
 7951
 7952        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7953            s.select_ranges(vec![0..0]);
 7954        });
 7955    }
 7956
 7957    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7958        let mut selection = self.selections.last::<Point>(cx);
 7959        selection.set_head(Point::zero(), SelectionGoal::None);
 7960
 7961        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7962            s.select(vec![selection]);
 7963        });
 7964    }
 7965
 7966    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7967        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7968            cx.propagate();
 7969            return;
 7970        }
 7971
 7972        let cursor = self.buffer.read(cx).read(cx).len();
 7973        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7974            s.select_ranges(vec![cursor..cursor])
 7975        });
 7976    }
 7977
 7978    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7979        self.nav_history = nav_history;
 7980    }
 7981
 7982    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7983        self.nav_history.as_ref()
 7984    }
 7985
 7986    fn push_to_nav_history(
 7987        &mut self,
 7988        cursor_anchor: Anchor,
 7989        new_position: Option<Point>,
 7990        cx: &mut ViewContext<Self>,
 7991    ) {
 7992        if let Some(nav_history) = self.nav_history.as_mut() {
 7993            let buffer = self.buffer.read(cx).read(cx);
 7994            let cursor_position = cursor_anchor.to_point(&buffer);
 7995            let scroll_state = self.scroll_manager.anchor();
 7996            let scroll_top_row = scroll_state.top_row(&buffer);
 7997            drop(buffer);
 7998
 7999            if let Some(new_position) = new_position {
 8000                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8001                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8002                    return;
 8003                }
 8004            }
 8005
 8006            nav_history.push(
 8007                Some(NavigationData {
 8008                    cursor_anchor,
 8009                    cursor_position,
 8010                    scroll_anchor: scroll_state,
 8011                    scroll_top_row,
 8012                }),
 8013                cx,
 8014            );
 8015        }
 8016    }
 8017
 8018    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8019        let buffer = self.buffer.read(cx).snapshot(cx);
 8020        let mut selection = self.selections.first::<usize>(cx);
 8021        selection.set_head(buffer.len(), SelectionGoal::None);
 8022        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8023            s.select(vec![selection]);
 8024        });
 8025    }
 8026
 8027    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8028        let end = self.buffer.read(cx).read(cx).len();
 8029        self.change_selections(None, cx, |s| {
 8030            s.select_ranges(vec![0..end]);
 8031        });
 8032    }
 8033
 8034    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8035        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8036        let mut selections = self.selections.all::<Point>(cx);
 8037        let max_point = display_map.buffer_snapshot.max_point();
 8038        for selection in &mut selections {
 8039            let rows = selection.spanned_rows(true, &display_map);
 8040            selection.start = Point::new(rows.start.0, 0);
 8041            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8042            selection.reversed = false;
 8043        }
 8044        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8045            s.select(selections);
 8046        });
 8047    }
 8048
 8049    pub fn split_selection_into_lines(
 8050        &mut self,
 8051        _: &SplitSelectionIntoLines,
 8052        cx: &mut ViewContext<Self>,
 8053    ) {
 8054        let mut to_unfold = Vec::new();
 8055        let mut new_selection_ranges = Vec::new();
 8056        {
 8057            let selections = self.selections.all::<Point>(cx);
 8058            let buffer = self.buffer.read(cx).read(cx);
 8059            for selection in selections {
 8060                for row in selection.start.row..selection.end.row {
 8061                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8062                    new_selection_ranges.push(cursor..cursor);
 8063                }
 8064                new_selection_ranges.push(selection.end..selection.end);
 8065                to_unfold.push(selection.start..selection.end);
 8066            }
 8067        }
 8068        self.unfold_ranges(&to_unfold, true, true, cx);
 8069        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8070            s.select_ranges(new_selection_ranges);
 8071        });
 8072    }
 8073
 8074    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8075        self.add_selection(true, cx);
 8076    }
 8077
 8078    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8079        self.add_selection(false, cx);
 8080    }
 8081
 8082    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8083        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8084        let mut selections = self.selections.all::<Point>(cx);
 8085        let text_layout_details = self.text_layout_details(cx);
 8086        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8087            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8088            let range = oldest_selection.display_range(&display_map).sorted();
 8089
 8090            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8091            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8092            let positions = start_x.min(end_x)..start_x.max(end_x);
 8093
 8094            selections.clear();
 8095            let mut stack = Vec::new();
 8096            for row in range.start.row().0..=range.end.row().0 {
 8097                if let Some(selection) = self.selections.build_columnar_selection(
 8098                    &display_map,
 8099                    DisplayRow(row),
 8100                    &positions,
 8101                    oldest_selection.reversed,
 8102                    &text_layout_details,
 8103                ) {
 8104                    stack.push(selection.id);
 8105                    selections.push(selection);
 8106                }
 8107            }
 8108
 8109            if above {
 8110                stack.reverse();
 8111            }
 8112
 8113            AddSelectionsState { above, stack }
 8114        });
 8115
 8116        let last_added_selection = *state.stack.last().unwrap();
 8117        let mut new_selections = Vec::new();
 8118        if above == state.above {
 8119            let end_row = if above {
 8120                DisplayRow(0)
 8121            } else {
 8122                display_map.max_point().row()
 8123            };
 8124
 8125            'outer: for selection in selections {
 8126                if selection.id == last_added_selection {
 8127                    let range = selection.display_range(&display_map).sorted();
 8128                    debug_assert_eq!(range.start.row(), range.end.row());
 8129                    let mut row = range.start.row();
 8130                    let positions =
 8131                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8132                            px(start)..px(end)
 8133                        } else {
 8134                            let start_x =
 8135                                display_map.x_for_display_point(range.start, &text_layout_details);
 8136                            let end_x =
 8137                                display_map.x_for_display_point(range.end, &text_layout_details);
 8138                            start_x.min(end_x)..start_x.max(end_x)
 8139                        };
 8140
 8141                    while row != end_row {
 8142                        if above {
 8143                            row.0 -= 1;
 8144                        } else {
 8145                            row.0 += 1;
 8146                        }
 8147
 8148                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8149                            &display_map,
 8150                            row,
 8151                            &positions,
 8152                            selection.reversed,
 8153                            &text_layout_details,
 8154                        ) {
 8155                            state.stack.push(new_selection.id);
 8156                            if above {
 8157                                new_selections.push(new_selection);
 8158                                new_selections.push(selection);
 8159                            } else {
 8160                                new_selections.push(selection);
 8161                                new_selections.push(new_selection);
 8162                            }
 8163
 8164                            continue 'outer;
 8165                        }
 8166                    }
 8167                }
 8168
 8169                new_selections.push(selection);
 8170            }
 8171        } else {
 8172            new_selections = selections;
 8173            new_selections.retain(|s| s.id != last_added_selection);
 8174            state.stack.pop();
 8175        }
 8176
 8177        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8178            s.select(new_selections);
 8179        });
 8180        if state.stack.len() > 1 {
 8181            self.add_selections_state = Some(state);
 8182        }
 8183    }
 8184
 8185    pub fn select_next_match_internal(
 8186        &mut self,
 8187        display_map: &DisplaySnapshot,
 8188        replace_newest: bool,
 8189        autoscroll: Option<Autoscroll>,
 8190        cx: &mut ViewContext<Self>,
 8191    ) -> Result<()> {
 8192        fn select_next_match_ranges(
 8193            this: &mut Editor,
 8194            range: Range<usize>,
 8195            replace_newest: bool,
 8196            auto_scroll: Option<Autoscroll>,
 8197            cx: &mut ViewContext<Editor>,
 8198        ) {
 8199            this.unfold_ranges(&[range.clone()], false, true, cx);
 8200            this.change_selections(auto_scroll, cx, |s| {
 8201                if replace_newest {
 8202                    s.delete(s.newest_anchor().id);
 8203                }
 8204                s.insert_range(range.clone());
 8205            });
 8206        }
 8207
 8208        let buffer = &display_map.buffer_snapshot;
 8209        let mut selections = self.selections.all::<usize>(cx);
 8210        if let Some(mut select_next_state) = self.select_next_state.take() {
 8211            let query = &select_next_state.query;
 8212            if !select_next_state.done {
 8213                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8214                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8215                let mut next_selected_range = None;
 8216
 8217                let bytes_after_last_selection =
 8218                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8219                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8220                let query_matches = query
 8221                    .stream_find_iter(bytes_after_last_selection)
 8222                    .map(|result| (last_selection.end, result))
 8223                    .chain(
 8224                        query
 8225                            .stream_find_iter(bytes_before_first_selection)
 8226                            .map(|result| (0, result)),
 8227                    );
 8228
 8229                for (start_offset, query_match) in query_matches {
 8230                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8231                    let offset_range =
 8232                        start_offset + query_match.start()..start_offset + query_match.end();
 8233                    let display_range = offset_range.start.to_display_point(display_map)
 8234                        ..offset_range.end.to_display_point(display_map);
 8235
 8236                    if !select_next_state.wordwise
 8237                        || (!movement::is_inside_word(display_map, display_range.start)
 8238                            && !movement::is_inside_word(display_map, display_range.end))
 8239                    {
 8240                        // TODO: This is n^2, because we might check all the selections
 8241                        if !selections
 8242                            .iter()
 8243                            .any(|selection| selection.range().overlaps(&offset_range))
 8244                        {
 8245                            next_selected_range = Some(offset_range);
 8246                            break;
 8247                        }
 8248                    }
 8249                }
 8250
 8251                if let Some(next_selected_range) = next_selected_range {
 8252                    select_next_match_ranges(
 8253                        self,
 8254                        next_selected_range,
 8255                        replace_newest,
 8256                        autoscroll,
 8257                        cx,
 8258                    );
 8259                } else {
 8260                    select_next_state.done = true;
 8261                }
 8262            }
 8263
 8264            self.select_next_state = Some(select_next_state);
 8265        } else {
 8266            let mut only_carets = true;
 8267            let mut same_text_selected = true;
 8268            let mut selected_text = None;
 8269
 8270            let mut selections_iter = selections.iter().peekable();
 8271            while let Some(selection) = selections_iter.next() {
 8272                if selection.start != selection.end {
 8273                    only_carets = false;
 8274                }
 8275
 8276                if same_text_selected {
 8277                    if selected_text.is_none() {
 8278                        selected_text =
 8279                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8280                    }
 8281
 8282                    if let Some(next_selection) = selections_iter.peek() {
 8283                        if next_selection.range().len() == selection.range().len() {
 8284                            let next_selected_text = buffer
 8285                                .text_for_range(next_selection.range())
 8286                                .collect::<String>();
 8287                            if Some(next_selected_text) != selected_text {
 8288                                same_text_selected = false;
 8289                                selected_text = None;
 8290                            }
 8291                        } else {
 8292                            same_text_selected = false;
 8293                            selected_text = None;
 8294                        }
 8295                    }
 8296                }
 8297            }
 8298
 8299            if only_carets {
 8300                for selection in &mut selections {
 8301                    let word_range = movement::surrounding_word(
 8302                        display_map,
 8303                        selection.start.to_display_point(display_map),
 8304                    );
 8305                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8306                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8307                    selection.goal = SelectionGoal::None;
 8308                    selection.reversed = false;
 8309                    select_next_match_ranges(
 8310                        self,
 8311                        selection.start..selection.end,
 8312                        replace_newest,
 8313                        autoscroll,
 8314                        cx,
 8315                    );
 8316                }
 8317
 8318                if selections.len() == 1 {
 8319                    let selection = selections
 8320                        .last()
 8321                        .expect("ensured that there's only one selection");
 8322                    let query = buffer
 8323                        .text_for_range(selection.start..selection.end)
 8324                        .collect::<String>();
 8325                    let is_empty = query.is_empty();
 8326                    let select_state = SelectNextState {
 8327                        query: AhoCorasick::new(&[query])?,
 8328                        wordwise: true,
 8329                        done: is_empty,
 8330                    };
 8331                    self.select_next_state = Some(select_state);
 8332                } else {
 8333                    self.select_next_state = None;
 8334                }
 8335            } else if let Some(selected_text) = selected_text {
 8336                self.select_next_state = Some(SelectNextState {
 8337                    query: AhoCorasick::new(&[selected_text])?,
 8338                    wordwise: false,
 8339                    done: false,
 8340                });
 8341                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8342            }
 8343        }
 8344        Ok(())
 8345    }
 8346
 8347    pub fn select_all_matches(
 8348        &mut self,
 8349        _action: &SelectAllMatches,
 8350        cx: &mut ViewContext<Self>,
 8351    ) -> Result<()> {
 8352        self.push_to_selection_history();
 8353        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8354
 8355        self.select_next_match_internal(&display_map, false, None, cx)?;
 8356        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8357            return Ok(());
 8358        };
 8359        if select_next_state.done {
 8360            return Ok(());
 8361        }
 8362
 8363        let mut new_selections = self.selections.all::<usize>(cx);
 8364
 8365        let buffer = &display_map.buffer_snapshot;
 8366        let query_matches = select_next_state
 8367            .query
 8368            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8369
 8370        for query_match in query_matches {
 8371            let query_match = query_match.unwrap(); // can only fail due to I/O
 8372            let offset_range = query_match.start()..query_match.end();
 8373            let display_range = offset_range.start.to_display_point(&display_map)
 8374                ..offset_range.end.to_display_point(&display_map);
 8375
 8376            if !select_next_state.wordwise
 8377                || (!movement::is_inside_word(&display_map, display_range.start)
 8378                    && !movement::is_inside_word(&display_map, display_range.end))
 8379            {
 8380                self.selections.change_with(cx, |selections| {
 8381                    new_selections.push(Selection {
 8382                        id: selections.new_selection_id(),
 8383                        start: offset_range.start,
 8384                        end: offset_range.end,
 8385                        reversed: false,
 8386                        goal: SelectionGoal::None,
 8387                    });
 8388                });
 8389            }
 8390        }
 8391
 8392        new_selections.sort_by_key(|selection| selection.start);
 8393        let mut ix = 0;
 8394        while ix + 1 < new_selections.len() {
 8395            let current_selection = &new_selections[ix];
 8396            let next_selection = &new_selections[ix + 1];
 8397            if current_selection.range().overlaps(&next_selection.range()) {
 8398                if current_selection.id < next_selection.id {
 8399                    new_selections.remove(ix + 1);
 8400                } else {
 8401                    new_selections.remove(ix);
 8402                }
 8403            } else {
 8404                ix += 1;
 8405            }
 8406        }
 8407
 8408        select_next_state.done = true;
 8409        self.unfold_ranges(
 8410            &new_selections
 8411                .iter()
 8412                .map(|selection| selection.range())
 8413                .collect::<Vec<_>>(),
 8414            false,
 8415            false,
 8416            cx,
 8417        );
 8418        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8419            selections.select(new_selections)
 8420        });
 8421
 8422        Ok(())
 8423    }
 8424
 8425    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8426        self.push_to_selection_history();
 8427        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8428        self.select_next_match_internal(
 8429            &display_map,
 8430            action.replace_newest,
 8431            Some(Autoscroll::newest()),
 8432            cx,
 8433        )?;
 8434        Ok(())
 8435    }
 8436
 8437    pub fn select_previous(
 8438        &mut self,
 8439        action: &SelectPrevious,
 8440        cx: &mut ViewContext<Self>,
 8441    ) -> Result<()> {
 8442        self.push_to_selection_history();
 8443        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8444        let buffer = &display_map.buffer_snapshot;
 8445        let mut selections = self.selections.all::<usize>(cx);
 8446        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8447            let query = &select_prev_state.query;
 8448            if !select_prev_state.done {
 8449                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8450                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8451                let mut next_selected_range = None;
 8452                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8453                let bytes_before_last_selection =
 8454                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8455                let bytes_after_first_selection =
 8456                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8457                let query_matches = query
 8458                    .stream_find_iter(bytes_before_last_selection)
 8459                    .map(|result| (last_selection.start, result))
 8460                    .chain(
 8461                        query
 8462                            .stream_find_iter(bytes_after_first_selection)
 8463                            .map(|result| (buffer.len(), result)),
 8464                    );
 8465                for (end_offset, query_match) in query_matches {
 8466                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8467                    let offset_range =
 8468                        end_offset - query_match.end()..end_offset - query_match.start();
 8469                    let display_range = offset_range.start.to_display_point(&display_map)
 8470                        ..offset_range.end.to_display_point(&display_map);
 8471
 8472                    if !select_prev_state.wordwise
 8473                        || (!movement::is_inside_word(&display_map, display_range.start)
 8474                            && !movement::is_inside_word(&display_map, display_range.end))
 8475                    {
 8476                        next_selected_range = Some(offset_range);
 8477                        break;
 8478                    }
 8479                }
 8480
 8481                if let Some(next_selected_range) = next_selected_range {
 8482                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8483                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8484                        if action.replace_newest {
 8485                            s.delete(s.newest_anchor().id);
 8486                        }
 8487                        s.insert_range(next_selected_range);
 8488                    });
 8489                } else {
 8490                    select_prev_state.done = true;
 8491                }
 8492            }
 8493
 8494            self.select_prev_state = Some(select_prev_state);
 8495        } else {
 8496            let mut only_carets = true;
 8497            let mut same_text_selected = true;
 8498            let mut selected_text = None;
 8499
 8500            let mut selections_iter = selections.iter().peekable();
 8501            while let Some(selection) = selections_iter.next() {
 8502                if selection.start != selection.end {
 8503                    only_carets = false;
 8504                }
 8505
 8506                if same_text_selected {
 8507                    if selected_text.is_none() {
 8508                        selected_text =
 8509                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8510                    }
 8511
 8512                    if let Some(next_selection) = selections_iter.peek() {
 8513                        if next_selection.range().len() == selection.range().len() {
 8514                            let next_selected_text = buffer
 8515                                .text_for_range(next_selection.range())
 8516                                .collect::<String>();
 8517                            if Some(next_selected_text) != selected_text {
 8518                                same_text_selected = false;
 8519                                selected_text = None;
 8520                            }
 8521                        } else {
 8522                            same_text_selected = false;
 8523                            selected_text = None;
 8524                        }
 8525                    }
 8526                }
 8527            }
 8528
 8529            if only_carets {
 8530                for selection in &mut selections {
 8531                    let word_range = movement::surrounding_word(
 8532                        &display_map,
 8533                        selection.start.to_display_point(&display_map),
 8534                    );
 8535                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8536                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8537                    selection.goal = SelectionGoal::None;
 8538                    selection.reversed = false;
 8539                }
 8540                if selections.len() == 1 {
 8541                    let selection = selections
 8542                        .last()
 8543                        .expect("ensured that there's only one selection");
 8544                    let query = buffer
 8545                        .text_for_range(selection.start..selection.end)
 8546                        .collect::<String>();
 8547                    let is_empty = query.is_empty();
 8548                    let select_state = SelectNextState {
 8549                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8550                        wordwise: true,
 8551                        done: is_empty,
 8552                    };
 8553                    self.select_prev_state = Some(select_state);
 8554                } else {
 8555                    self.select_prev_state = None;
 8556                }
 8557
 8558                self.unfold_ranges(
 8559                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8560                    false,
 8561                    true,
 8562                    cx,
 8563                );
 8564                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8565                    s.select(selections);
 8566                });
 8567            } else if let Some(selected_text) = selected_text {
 8568                self.select_prev_state = Some(SelectNextState {
 8569                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8570                    wordwise: false,
 8571                    done: false,
 8572                });
 8573                self.select_previous(action, cx)?;
 8574            }
 8575        }
 8576        Ok(())
 8577    }
 8578
 8579    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8580        if self.read_only(cx) {
 8581            return;
 8582        }
 8583        let text_layout_details = &self.text_layout_details(cx);
 8584        self.transact(cx, |this, cx| {
 8585            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8586            let mut edits = Vec::new();
 8587            let mut selection_edit_ranges = Vec::new();
 8588            let mut last_toggled_row = None;
 8589            let snapshot = this.buffer.read(cx).read(cx);
 8590            let empty_str: Arc<str> = Arc::default();
 8591            let mut suffixes_inserted = Vec::new();
 8592            let ignore_indent = action.ignore_indent;
 8593
 8594            fn comment_prefix_range(
 8595                snapshot: &MultiBufferSnapshot,
 8596                row: MultiBufferRow,
 8597                comment_prefix: &str,
 8598                comment_prefix_whitespace: &str,
 8599                ignore_indent: bool,
 8600            ) -> Range<Point> {
 8601                let indent_size = if ignore_indent {
 8602                    0
 8603                } else {
 8604                    snapshot.indent_size_for_line(row).len
 8605                };
 8606
 8607                let start = Point::new(row.0, indent_size);
 8608
 8609                let mut line_bytes = snapshot
 8610                    .bytes_in_range(start..snapshot.max_point())
 8611                    .flatten()
 8612                    .copied();
 8613
 8614                // If this line currently begins with the line comment prefix, then record
 8615                // the range containing the prefix.
 8616                if line_bytes
 8617                    .by_ref()
 8618                    .take(comment_prefix.len())
 8619                    .eq(comment_prefix.bytes())
 8620                {
 8621                    // Include any whitespace that matches the comment prefix.
 8622                    let matching_whitespace_len = line_bytes
 8623                        .zip(comment_prefix_whitespace.bytes())
 8624                        .take_while(|(a, b)| a == b)
 8625                        .count() as u32;
 8626                    let end = Point::new(
 8627                        start.row,
 8628                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8629                    );
 8630                    start..end
 8631                } else {
 8632                    start..start
 8633                }
 8634            }
 8635
 8636            fn comment_suffix_range(
 8637                snapshot: &MultiBufferSnapshot,
 8638                row: MultiBufferRow,
 8639                comment_suffix: &str,
 8640                comment_suffix_has_leading_space: bool,
 8641            ) -> Range<Point> {
 8642                let end = Point::new(row.0, snapshot.line_len(row));
 8643                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8644
 8645                let mut line_end_bytes = snapshot
 8646                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8647                    .flatten()
 8648                    .copied();
 8649
 8650                let leading_space_len = if suffix_start_column > 0
 8651                    && line_end_bytes.next() == Some(b' ')
 8652                    && comment_suffix_has_leading_space
 8653                {
 8654                    1
 8655                } else {
 8656                    0
 8657                };
 8658
 8659                // If this line currently begins with the line comment prefix, then record
 8660                // the range containing the prefix.
 8661                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8662                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8663                    start..end
 8664                } else {
 8665                    end..end
 8666                }
 8667            }
 8668
 8669            // TODO: Handle selections that cross excerpts
 8670            for selection in &mut selections {
 8671                let start_column = snapshot
 8672                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8673                    .len;
 8674                let language = if let Some(language) =
 8675                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8676                {
 8677                    language
 8678                } else {
 8679                    continue;
 8680                };
 8681
 8682                selection_edit_ranges.clear();
 8683
 8684                // If multiple selections contain a given row, avoid processing that
 8685                // row more than once.
 8686                let mut start_row = MultiBufferRow(selection.start.row);
 8687                if last_toggled_row == Some(start_row) {
 8688                    start_row = start_row.next_row();
 8689                }
 8690                let end_row =
 8691                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8692                        MultiBufferRow(selection.end.row - 1)
 8693                    } else {
 8694                        MultiBufferRow(selection.end.row)
 8695                    };
 8696                last_toggled_row = Some(end_row);
 8697
 8698                if start_row > end_row {
 8699                    continue;
 8700                }
 8701
 8702                // If the language has line comments, toggle those.
 8703                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8704
 8705                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8706                if ignore_indent {
 8707                    full_comment_prefixes = full_comment_prefixes
 8708                        .into_iter()
 8709                        .map(|s| Arc::from(s.trim_end()))
 8710                        .collect();
 8711                }
 8712
 8713                if !full_comment_prefixes.is_empty() {
 8714                    let first_prefix = full_comment_prefixes
 8715                        .first()
 8716                        .expect("prefixes is non-empty");
 8717                    let prefix_trimmed_lengths = full_comment_prefixes
 8718                        .iter()
 8719                        .map(|p| p.trim_end_matches(' ').len())
 8720                        .collect::<SmallVec<[usize; 4]>>();
 8721
 8722                    let mut all_selection_lines_are_comments = true;
 8723
 8724                    for row in start_row.0..=end_row.0 {
 8725                        let row = MultiBufferRow(row);
 8726                        if start_row < end_row && snapshot.is_line_blank(row) {
 8727                            continue;
 8728                        }
 8729
 8730                        let prefix_range = full_comment_prefixes
 8731                            .iter()
 8732                            .zip(prefix_trimmed_lengths.iter().copied())
 8733                            .map(|(prefix, trimmed_prefix_len)| {
 8734                                comment_prefix_range(
 8735                                    snapshot.deref(),
 8736                                    row,
 8737                                    &prefix[..trimmed_prefix_len],
 8738                                    &prefix[trimmed_prefix_len..],
 8739                                    ignore_indent,
 8740                                )
 8741                            })
 8742                            .max_by_key(|range| range.end.column - range.start.column)
 8743                            .expect("prefixes is non-empty");
 8744
 8745                        if prefix_range.is_empty() {
 8746                            all_selection_lines_are_comments = false;
 8747                        }
 8748
 8749                        selection_edit_ranges.push(prefix_range);
 8750                    }
 8751
 8752                    if all_selection_lines_are_comments {
 8753                        edits.extend(
 8754                            selection_edit_ranges
 8755                                .iter()
 8756                                .cloned()
 8757                                .map(|range| (range, empty_str.clone())),
 8758                        );
 8759                    } else {
 8760                        let min_column = selection_edit_ranges
 8761                            .iter()
 8762                            .map(|range| range.start.column)
 8763                            .min()
 8764                            .unwrap_or(0);
 8765                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8766                            let position = Point::new(range.start.row, min_column);
 8767                            (position..position, first_prefix.clone())
 8768                        }));
 8769                    }
 8770                } else if let Some((full_comment_prefix, comment_suffix)) =
 8771                    language.block_comment_delimiters()
 8772                {
 8773                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8774                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8775                    let prefix_range = comment_prefix_range(
 8776                        snapshot.deref(),
 8777                        start_row,
 8778                        comment_prefix,
 8779                        comment_prefix_whitespace,
 8780                        ignore_indent,
 8781                    );
 8782                    let suffix_range = comment_suffix_range(
 8783                        snapshot.deref(),
 8784                        end_row,
 8785                        comment_suffix.trim_start_matches(' '),
 8786                        comment_suffix.starts_with(' '),
 8787                    );
 8788
 8789                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8790                        edits.push((
 8791                            prefix_range.start..prefix_range.start,
 8792                            full_comment_prefix.clone(),
 8793                        ));
 8794                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8795                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8796                    } else {
 8797                        edits.push((prefix_range, empty_str.clone()));
 8798                        edits.push((suffix_range, empty_str.clone()));
 8799                    }
 8800                } else {
 8801                    continue;
 8802                }
 8803            }
 8804
 8805            drop(snapshot);
 8806            this.buffer.update(cx, |buffer, cx| {
 8807                buffer.edit(edits, None, cx);
 8808            });
 8809
 8810            // Adjust selections so that they end before any comment suffixes that
 8811            // were inserted.
 8812            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8813            let mut selections = this.selections.all::<Point>(cx);
 8814            let snapshot = this.buffer.read(cx).read(cx);
 8815            for selection in &mut selections {
 8816                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8817                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8818                        Ordering::Less => {
 8819                            suffixes_inserted.next();
 8820                            continue;
 8821                        }
 8822                        Ordering::Greater => break,
 8823                        Ordering::Equal => {
 8824                            if selection.end.column == snapshot.line_len(row) {
 8825                                if selection.is_empty() {
 8826                                    selection.start.column -= suffix_len as u32;
 8827                                }
 8828                                selection.end.column -= suffix_len as u32;
 8829                            }
 8830                            break;
 8831                        }
 8832                    }
 8833                }
 8834            }
 8835
 8836            drop(snapshot);
 8837            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8838
 8839            let selections = this.selections.all::<Point>(cx);
 8840            let selections_on_single_row = selections.windows(2).all(|selections| {
 8841                selections[0].start.row == selections[1].start.row
 8842                    && selections[0].end.row == selections[1].end.row
 8843                    && selections[0].start.row == selections[0].end.row
 8844            });
 8845            let selections_selecting = selections
 8846                .iter()
 8847                .any(|selection| selection.start != selection.end);
 8848            let advance_downwards = action.advance_downwards
 8849                && selections_on_single_row
 8850                && !selections_selecting
 8851                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8852
 8853            if advance_downwards {
 8854                let snapshot = this.buffer.read(cx).snapshot(cx);
 8855
 8856                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8857                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8858                        let mut point = display_point.to_point(display_snapshot);
 8859                        point.row += 1;
 8860                        point = snapshot.clip_point(point, Bias::Left);
 8861                        let display_point = point.to_display_point(display_snapshot);
 8862                        let goal = SelectionGoal::HorizontalPosition(
 8863                            display_snapshot
 8864                                .x_for_display_point(display_point, text_layout_details)
 8865                                .into(),
 8866                        );
 8867                        (display_point, goal)
 8868                    })
 8869                });
 8870            }
 8871        });
 8872    }
 8873
 8874    pub fn select_enclosing_symbol(
 8875        &mut self,
 8876        _: &SelectEnclosingSymbol,
 8877        cx: &mut ViewContext<Self>,
 8878    ) {
 8879        let buffer = self.buffer.read(cx).snapshot(cx);
 8880        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8881
 8882        fn update_selection(
 8883            selection: &Selection<usize>,
 8884            buffer_snap: &MultiBufferSnapshot,
 8885        ) -> Option<Selection<usize>> {
 8886            let cursor = selection.head();
 8887            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8888            for symbol in symbols.iter().rev() {
 8889                let start = symbol.range.start.to_offset(buffer_snap);
 8890                let end = symbol.range.end.to_offset(buffer_snap);
 8891                let new_range = start..end;
 8892                if start < selection.start || end > selection.end {
 8893                    return Some(Selection {
 8894                        id: selection.id,
 8895                        start: new_range.start,
 8896                        end: new_range.end,
 8897                        goal: SelectionGoal::None,
 8898                        reversed: selection.reversed,
 8899                    });
 8900                }
 8901            }
 8902            None
 8903        }
 8904
 8905        let mut selected_larger_symbol = false;
 8906        let new_selections = old_selections
 8907            .iter()
 8908            .map(|selection| match update_selection(selection, &buffer) {
 8909                Some(new_selection) => {
 8910                    if new_selection.range() != selection.range() {
 8911                        selected_larger_symbol = true;
 8912                    }
 8913                    new_selection
 8914                }
 8915                None => selection.clone(),
 8916            })
 8917            .collect::<Vec<_>>();
 8918
 8919        if selected_larger_symbol {
 8920            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8921                s.select(new_selections);
 8922            });
 8923        }
 8924    }
 8925
 8926    pub fn select_larger_syntax_node(
 8927        &mut self,
 8928        _: &SelectLargerSyntaxNode,
 8929        cx: &mut ViewContext<Self>,
 8930    ) {
 8931        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8932        let buffer = self.buffer.read(cx).snapshot(cx);
 8933        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8934
 8935        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8936        let mut selected_larger_node = false;
 8937        let new_selections = old_selections
 8938            .iter()
 8939            .map(|selection| {
 8940                let old_range = selection.start..selection.end;
 8941                let mut new_range = old_range.clone();
 8942                let mut new_node = None;
 8943                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 8944                {
 8945                    new_node = Some(node);
 8946                    new_range = containing_range;
 8947                    if !display_map.intersects_fold(new_range.start)
 8948                        && !display_map.intersects_fold(new_range.end)
 8949                    {
 8950                        break;
 8951                    }
 8952                }
 8953
 8954                if let Some(node) = new_node {
 8955                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 8956                    // nodes. Parent and grandparent are also logged because this operation will not
 8957                    // visit nodes that have the same range as their parent.
 8958                    log::info!("Node: {node:?}");
 8959                    let parent = node.parent();
 8960                    log::info!("Parent: {parent:?}");
 8961                    let grandparent = parent.and_then(|x| x.parent());
 8962                    log::info!("Grandparent: {grandparent:?}");
 8963                }
 8964
 8965                selected_larger_node |= new_range != old_range;
 8966                Selection {
 8967                    id: selection.id,
 8968                    start: new_range.start,
 8969                    end: new_range.end,
 8970                    goal: SelectionGoal::None,
 8971                    reversed: selection.reversed,
 8972                }
 8973            })
 8974            .collect::<Vec<_>>();
 8975
 8976        if selected_larger_node {
 8977            stack.push(old_selections);
 8978            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8979                s.select(new_selections);
 8980            });
 8981        }
 8982        self.select_larger_syntax_node_stack = stack;
 8983    }
 8984
 8985    pub fn select_smaller_syntax_node(
 8986        &mut self,
 8987        _: &SelectSmallerSyntaxNode,
 8988        cx: &mut ViewContext<Self>,
 8989    ) {
 8990        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8991        if let Some(selections) = stack.pop() {
 8992            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8993                s.select(selections.to_vec());
 8994            });
 8995        }
 8996        self.select_larger_syntax_node_stack = stack;
 8997    }
 8998
 8999    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9000        if !EditorSettings::get_global(cx).gutter.runnables {
 9001            self.clear_tasks();
 9002            return Task::ready(());
 9003        }
 9004        let project = self.project.as_ref().map(Model::downgrade);
 9005        cx.spawn(|this, mut cx| async move {
 9006            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9007            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9008                return;
 9009            };
 9010            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9011                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9012            }) else {
 9013                return;
 9014            };
 9015
 9016            let hide_runnables = project
 9017                .update(&mut cx, |project, cx| {
 9018                    // Do not display any test indicators in non-dev server remote projects.
 9019                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9020                })
 9021                .unwrap_or(true);
 9022            if hide_runnables {
 9023                return;
 9024            }
 9025            let new_rows =
 9026                cx.background_executor()
 9027                    .spawn({
 9028                        let snapshot = display_snapshot.clone();
 9029                        async move {
 9030                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9031                        }
 9032                    })
 9033                    .await;
 9034            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9035
 9036            this.update(&mut cx, |this, _| {
 9037                this.clear_tasks();
 9038                for (key, value) in rows {
 9039                    this.insert_tasks(key, value);
 9040                }
 9041            })
 9042            .ok();
 9043        })
 9044    }
 9045    fn fetch_runnable_ranges(
 9046        snapshot: &DisplaySnapshot,
 9047        range: Range<Anchor>,
 9048    ) -> Vec<language::RunnableRange> {
 9049        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9050    }
 9051
 9052    fn runnable_rows(
 9053        project: Model<Project>,
 9054        snapshot: DisplaySnapshot,
 9055        runnable_ranges: Vec<RunnableRange>,
 9056        mut cx: AsyncWindowContext,
 9057    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9058        runnable_ranges
 9059            .into_iter()
 9060            .filter_map(|mut runnable| {
 9061                let tasks = cx
 9062                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9063                    .ok()?;
 9064                if tasks.is_empty() {
 9065                    return None;
 9066                }
 9067
 9068                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9069
 9070                let row = snapshot
 9071                    .buffer_snapshot
 9072                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9073                    .1
 9074                    .start
 9075                    .row;
 9076
 9077                let context_range =
 9078                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9079                Some((
 9080                    (runnable.buffer_id, row),
 9081                    RunnableTasks {
 9082                        templates: tasks,
 9083                        offset: MultiBufferOffset(runnable.run_range.start),
 9084                        context_range,
 9085                        column: point.column,
 9086                        extra_variables: runnable.extra_captures,
 9087                    },
 9088                ))
 9089            })
 9090            .collect()
 9091    }
 9092
 9093    fn templates_with_tags(
 9094        project: &Model<Project>,
 9095        runnable: &mut Runnable,
 9096        cx: &WindowContext,
 9097    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9098        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9099            let (worktree_id, file) = project
 9100                .buffer_for_id(runnable.buffer, cx)
 9101                .and_then(|buffer| buffer.read(cx).file())
 9102                .map(|file| (file.worktree_id(cx), file.clone()))
 9103                .unzip();
 9104
 9105            (
 9106                project.task_store().read(cx).task_inventory().cloned(),
 9107                worktree_id,
 9108                file,
 9109            )
 9110        });
 9111
 9112        let tags = mem::take(&mut runnable.tags);
 9113        let mut tags: Vec<_> = tags
 9114            .into_iter()
 9115            .flat_map(|tag| {
 9116                let tag = tag.0.clone();
 9117                inventory
 9118                    .as_ref()
 9119                    .into_iter()
 9120                    .flat_map(|inventory| {
 9121                        inventory.read(cx).list_tasks(
 9122                            file.clone(),
 9123                            Some(runnable.language.clone()),
 9124                            worktree_id,
 9125                            cx,
 9126                        )
 9127                    })
 9128                    .filter(move |(_, template)| {
 9129                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9130                    })
 9131            })
 9132            .sorted_by_key(|(kind, _)| kind.to_owned())
 9133            .collect();
 9134        if let Some((leading_tag_source, _)) = tags.first() {
 9135            // Strongest source wins; if we have worktree tag binding, prefer that to
 9136            // global and language bindings;
 9137            // if we have a global binding, prefer that to language binding.
 9138            let first_mismatch = tags
 9139                .iter()
 9140                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9141            if let Some(index) = first_mismatch {
 9142                tags.truncate(index);
 9143            }
 9144        }
 9145
 9146        tags
 9147    }
 9148
 9149    pub fn move_to_enclosing_bracket(
 9150        &mut self,
 9151        _: &MoveToEnclosingBracket,
 9152        cx: &mut ViewContext<Self>,
 9153    ) {
 9154        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9155            s.move_offsets_with(|snapshot, selection| {
 9156                let Some(enclosing_bracket_ranges) =
 9157                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9158                else {
 9159                    return;
 9160                };
 9161
 9162                let mut best_length = usize::MAX;
 9163                let mut best_inside = false;
 9164                let mut best_in_bracket_range = false;
 9165                let mut best_destination = None;
 9166                for (open, close) in enclosing_bracket_ranges {
 9167                    let close = close.to_inclusive();
 9168                    let length = close.end() - open.start;
 9169                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9170                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9171                        || close.contains(&selection.head());
 9172
 9173                    // If best is next to a bracket and current isn't, skip
 9174                    if !in_bracket_range && best_in_bracket_range {
 9175                        continue;
 9176                    }
 9177
 9178                    // Prefer smaller lengths unless best is inside and current isn't
 9179                    if length > best_length && (best_inside || !inside) {
 9180                        continue;
 9181                    }
 9182
 9183                    best_length = length;
 9184                    best_inside = inside;
 9185                    best_in_bracket_range = in_bracket_range;
 9186                    best_destination = Some(
 9187                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9188                            if inside {
 9189                                open.end
 9190                            } else {
 9191                                open.start
 9192                            }
 9193                        } else if inside {
 9194                            *close.start()
 9195                        } else {
 9196                            *close.end()
 9197                        },
 9198                    );
 9199                }
 9200
 9201                if let Some(destination) = best_destination {
 9202                    selection.collapse_to(destination, SelectionGoal::None);
 9203                }
 9204            })
 9205        });
 9206    }
 9207
 9208    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9209        self.end_selection(cx);
 9210        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9211        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9212            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9213            self.select_next_state = entry.select_next_state;
 9214            self.select_prev_state = entry.select_prev_state;
 9215            self.add_selections_state = entry.add_selections_state;
 9216            self.request_autoscroll(Autoscroll::newest(), cx);
 9217        }
 9218        self.selection_history.mode = SelectionHistoryMode::Normal;
 9219    }
 9220
 9221    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9222        self.end_selection(cx);
 9223        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9224        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9225            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9226            self.select_next_state = entry.select_next_state;
 9227            self.select_prev_state = entry.select_prev_state;
 9228            self.add_selections_state = entry.add_selections_state;
 9229            self.request_autoscroll(Autoscroll::newest(), cx);
 9230        }
 9231        self.selection_history.mode = SelectionHistoryMode::Normal;
 9232    }
 9233
 9234    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9235        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9236    }
 9237
 9238    pub fn expand_excerpts_down(
 9239        &mut self,
 9240        action: &ExpandExcerptsDown,
 9241        cx: &mut ViewContext<Self>,
 9242    ) {
 9243        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9244    }
 9245
 9246    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9247        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9248    }
 9249
 9250    pub fn expand_excerpts_for_direction(
 9251        &mut self,
 9252        lines: u32,
 9253        direction: ExpandExcerptDirection,
 9254        cx: &mut ViewContext<Self>,
 9255    ) {
 9256        let selections = self.selections.disjoint_anchors();
 9257
 9258        let lines = if lines == 0 {
 9259            EditorSettings::get_global(cx).expand_excerpt_lines
 9260        } else {
 9261            lines
 9262        };
 9263
 9264        self.buffer.update(cx, |buffer, cx| {
 9265            let snapshot = buffer.snapshot(cx);
 9266            let mut excerpt_ids = selections
 9267                .iter()
 9268                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
 9269                .collect::<Vec<_>>();
 9270            excerpt_ids.sort();
 9271            excerpt_ids.dedup();
 9272            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
 9273        })
 9274    }
 9275
 9276    pub fn expand_excerpt(
 9277        &mut self,
 9278        excerpt: ExcerptId,
 9279        direction: ExpandExcerptDirection,
 9280        cx: &mut ViewContext<Self>,
 9281    ) {
 9282        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9283        self.buffer.update(cx, |buffer, cx| {
 9284            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9285        })
 9286    }
 9287
 9288    pub fn go_to_singleton_buffer_point(&mut self, point: Point, cx: &mut ViewContext<Self>) {
 9289        self.go_to_singleton_buffer_range(point..point, cx);
 9290    }
 9291
 9292    pub fn go_to_singleton_buffer_range(
 9293        &mut self,
 9294        range: Range<Point>,
 9295        cx: &mut ViewContext<Self>,
 9296    ) {
 9297        let multibuffer = self.buffer().read(cx);
 9298        let Some(buffer) = multibuffer.as_singleton() else {
 9299            return;
 9300        };
 9301        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
 9302            return;
 9303        };
 9304        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
 9305            return;
 9306        };
 9307        self.change_selections(Some(Autoscroll::center()), cx, |s| {
 9308            s.select_anchor_ranges([start..end])
 9309        });
 9310    }
 9311
 9312    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9313        self.go_to_diagnostic_impl(Direction::Next, cx)
 9314    }
 9315
 9316    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9317        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9318    }
 9319
 9320    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9321        let buffer = self.buffer.read(cx).snapshot(cx);
 9322        let selection = self.selections.newest::<usize>(cx);
 9323
 9324        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9325        if direction == Direction::Next {
 9326            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9327                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
 9328                    return;
 9329                };
 9330                self.activate_diagnostics(
 9331                    buffer_id,
 9332                    popover.local_diagnostic.diagnostic.group_id,
 9333                    cx,
 9334                );
 9335                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
 9336                    let primary_range_start = active_diagnostics.primary_range.start;
 9337                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9338                        let mut new_selection = s.newest_anchor().clone();
 9339                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
 9340                        s.select_anchors(vec![new_selection.clone()]);
 9341                    });
 9342                    self.refresh_inline_completion(false, true, cx);
 9343                }
 9344                return;
 9345            }
 9346        }
 9347
 9348        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9349            active_diagnostics
 9350                .primary_range
 9351                .to_offset(&buffer)
 9352                .to_inclusive()
 9353        });
 9354        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9355            if active_primary_range.contains(&selection.head()) {
 9356                *active_primary_range.start()
 9357            } else {
 9358                selection.head()
 9359            }
 9360        } else {
 9361            selection.head()
 9362        };
 9363        let snapshot = self.snapshot(cx);
 9364        loop {
 9365            let mut diagnostics;
 9366            if direction == Direction::Prev {
 9367                diagnostics = buffer
 9368                    .diagnostics_in_range::<_, usize>(0..search_start)
 9369                    .collect::<Vec<_>>();
 9370                diagnostics.reverse();
 9371            } else {
 9372                diagnostics = buffer
 9373                    .diagnostics_in_range::<_, usize>(search_start..buffer.len())
 9374                    .collect::<Vec<_>>();
 9375            };
 9376            let group = diagnostics
 9377                .into_iter()
 9378                .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
 9379                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9380                // be sorted in a stable way
 9381                // skip until we are at current active diagnostic, if it exists
 9382                .skip_while(|entry| {
 9383                    let is_in_range = match direction {
 9384                        Direction::Prev => entry.range.end > search_start,
 9385                        Direction::Next => entry.range.start < search_start,
 9386                    };
 9387                    is_in_range
 9388                        && self
 9389                            .active_diagnostics
 9390                            .as_ref()
 9391                            .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9392                })
 9393                .find_map(|entry| {
 9394                    if entry.diagnostic.is_primary
 9395                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9396                        && entry.range.start != entry.range.end
 9397                        // if we match with the active diagnostic, skip it
 9398                        && Some(entry.diagnostic.group_id)
 9399                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9400                    {
 9401                        Some((entry.range, entry.diagnostic.group_id))
 9402                    } else {
 9403                        None
 9404                    }
 9405                });
 9406
 9407            if let Some((primary_range, group_id)) = group {
 9408                let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
 9409                    return;
 9410                };
 9411                self.activate_diagnostics(buffer_id, group_id, cx);
 9412                if self.active_diagnostics.is_some() {
 9413                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9414                        s.select(vec![Selection {
 9415                            id: selection.id,
 9416                            start: primary_range.start,
 9417                            end: primary_range.start,
 9418                            reversed: false,
 9419                            goal: SelectionGoal::None,
 9420                        }]);
 9421                    });
 9422                    self.refresh_inline_completion(false, true, cx);
 9423                }
 9424                break;
 9425            } else {
 9426                // Cycle around to the start of the buffer, potentially moving back to the start of
 9427                // the currently active diagnostic.
 9428                active_primary_range.take();
 9429                if direction == Direction::Prev {
 9430                    if search_start == buffer.len() {
 9431                        break;
 9432                    } else {
 9433                        search_start = buffer.len();
 9434                    }
 9435                } else if search_start == 0 {
 9436                    break;
 9437                } else {
 9438                    search_start = 0;
 9439                }
 9440            }
 9441        }
 9442    }
 9443
 9444    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9445        let snapshot = self.snapshot(cx);
 9446        let selection = self.selections.newest::<Point>(cx);
 9447        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9448    }
 9449
 9450    fn go_to_hunk_after_position(
 9451        &mut self,
 9452        snapshot: &EditorSnapshot,
 9453        position: Point,
 9454        cx: &mut ViewContext<Editor>,
 9455    ) -> Option<MultiBufferDiffHunk> {
 9456        let mut hunk = snapshot
 9457            .buffer_snapshot
 9458            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
 9459            .find(|hunk| hunk.row_range.start.0 > position.row);
 9460        if hunk.is_none() {
 9461            hunk = snapshot
 9462                .buffer_snapshot
 9463                .diff_hunks_in_range(Point::zero()..position)
 9464                .find(|hunk| hunk.row_range.end.0 < position.row)
 9465        }
 9466        if let Some(hunk) = &hunk {
 9467            let destination = Point::new(hunk.row_range.start.0, 0);
 9468            self.unfold_ranges(&[destination..destination], false, false, cx);
 9469            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9470                s.select_ranges(vec![destination..destination]);
 9471            });
 9472        }
 9473
 9474        hunk
 9475    }
 9476
 9477    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9478        let snapshot = self.snapshot(cx);
 9479        let selection = self.selections.newest::<Point>(cx);
 9480        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9481    }
 9482
 9483    fn go_to_hunk_before_position(
 9484        &mut self,
 9485        snapshot: &EditorSnapshot,
 9486        position: Point,
 9487        cx: &mut ViewContext<Editor>,
 9488    ) -> Option<MultiBufferDiffHunk> {
 9489        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
 9490        if hunk.is_none() {
 9491            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
 9492        }
 9493        if let Some(hunk) = &hunk {
 9494            let destination = Point::new(hunk.row_range.start.0, 0);
 9495            self.unfold_ranges(&[destination..destination], false, false, cx);
 9496            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9497                s.select_ranges(vec![destination..destination]);
 9498            });
 9499        }
 9500
 9501        hunk
 9502    }
 9503
 9504    pub fn go_to_definition(
 9505        &mut self,
 9506        _: &GoToDefinition,
 9507        cx: &mut ViewContext<Self>,
 9508    ) -> Task<Result<Navigated>> {
 9509        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9510        cx.spawn(|editor, mut cx| async move {
 9511            if definition.await? == Navigated::Yes {
 9512                return Ok(Navigated::Yes);
 9513            }
 9514            match editor.update(&mut cx, |editor, cx| {
 9515                editor.find_all_references(&FindAllReferences, cx)
 9516            })? {
 9517                Some(references) => references.await,
 9518                None => Ok(Navigated::No),
 9519            }
 9520        })
 9521    }
 9522
 9523    pub fn go_to_declaration(
 9524        &mut self,
 9525        _: &GoToDeclaration,
 9526        cx: &mut ViewContext<Self>,
 9527    ) -> Task<Result<Navigated>> {
 9528        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9529    }
 9530
 9531    pub fn go_to_declaration_split(
 9532        &mut self,
 9533        _: &GoToDeclaration,
 9534        cx: &mut ViewContext<Self>,
 9535    ) -> Task<Result<Navigated>> {
 9536        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9537    }
 9538
 9539    pub fn go_to_implementation(
 9540        &mut self,
 9541        _: &GoToImplementation,
 9542        cx: &mut ViewContext<Self>,
 9543    ) -> Task<Result<Navigated>> {
 9544        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9545    }
 9546
 9547    pub fn go_to_implementation_split(
 9548        &mut self,
 9549        _: &GoToImplementationSplit,
 9550        cx: &mut ViewContext<Self>,
 9551    ) -> Task<Result<Navigated>> {
 9552        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9553    }
 9554
 9555    pub fn go_to_type_definition(
 9556        &mut self,
 9557        _: &GoToTypeDefinition,
 9558        cx: &mut ViewContext<Self>,
 9559    ) -> Task<Result<Navigated>> {
 9560        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9561    }
 9562
 9563    pub fn go_to_definition_split(
 9564        &mut self,
 9565        _: &GoToDefinitionSplit,
 9566        cx: &mut ViewContext<Self>,
 9567    ) -> Task<Result<Navigated>> {
 9568        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9569    }
 9570
 9571    pub fn go_to_type_definition_split(
 9572        &mut self,
 9573        _: &GoToTypeDefinitionSplit,
 9574        cx: &mut ViewContext<Self>,
 9575    ) -> Task<Result<Navigated>> {
 9576        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9577    }
 9578
 9579    fn go_to_definition_of_kind(
 9580        &mut self,
 9581        kind: GotoDefinitionKind,
 9582        split: bool,
 9583        cx: &mut ViewContext<Self>,
 9584    ) -> Task<Result<Navigated>> {
 9585        let Some(provider) = self.semantics_provider.clone() else {
 9586            return Task::ready(Ok(Navigated::No));
 9587        };
 9588        let head = self.selections.newest::<usize>(cx).head();
 9589        let buffer = self.buffer.read(cx);
 9590        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9591            text_anchor
 9592        } else {
 9593            return Task::ready(Ok(Navigated::No));
 9594        };
 9595
 9596        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9597            return Task::ready(Ok(Navigated::No));
 9598        };
 9599
 9600        cx.spawn(|editor, mut cx| async move {
 9601            let definitions = definitions.await?;
 9602            let navigated = editor
 9603                .update(&mut cx, |editor, cx| {
 9604                    editor.navigate_to_hover_links(
 9605                        Some(kind),
 9606                        definitions
 9607                            .into_iter()
 9608                            .filter(|location| {
 9609                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9610                            })
 9611                            .map(HoverLink::Text)
 9612                            .collect::<Vec<_>>(),
 9613                        split,
 9614                        cx,
 9615                    )
 9616                })?
 9617                .await?;
 9618            anyhow::Ok(navigated)
 9619        })
 9620    }
 9621
 9622    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9623        let selection = self.selections.newest_anchor();
 9624        let head = selection.head();
 9625        let tail = selection.tail();
 9626
 9627        let Some((buffer, start_position)) =
 9628            self.buffer.read(cx).text_anchor_for_position(head, cx)
 9629        else {
 9630            return;
 9631        };
 9632
 9633        let end_position = if head != tail {
 9634            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
 9635                return;
 9636            };
 9637            Some(pos)
 9638        } else {
 9639            None
 9640        };
 9641
 9642        let url_finder = cx.spawn(|editor, mut cx| async move {
 9643            let url = if let Some(end_pos) = end_position {
 9644                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
 9645            } else {
 9646                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
 9647            };
 9648
 9649            if let Some(url) = url {
 9650                editor.update(&mut cx, |_, cx| {
 9651                    cx.open_url(&url);
 9652                })
 9653            } else {
 9654                Ok(())
 9655            }
 9656        });
 9657
 9658        url_finder.detach();
 9659    }
 9660
 9661    pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
 9662        let Some(workspace) = self.workspace() else {
 9663            return;
 9664        };
 9665
 9666        let position = self.selections.newest_anchor().head();
 9667
 9668        let Some((buffer, buffer_position)) =
 9669            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9670        else {
 9671            return;
 9672        };
 9673
 9674        let project = self.project.clone();
 9675
 9676        cx.spawn(|_, mut cx| async move {
 9677            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9678
 9679            if let Some((_, path)) = result {
 9680                workspace
 9681                    .update(&mut cx, |workspace, cx| {
 9682                        workspace.open_resolved_path(path, cx)
 9683                    })?
 9684                    .await?;
 9685            }
 9686            anyhow::Ok(())
 9687        })
 9688        .detach();
 9689    }
 9690
 9691    pub(crate) fn navigate_to_hover_links(
 9692        &mut self,
 9693        kind: Option<GotoDefinitionKind>,
 9694        mut definitions: Vec<HoverLink>,
 9695        split: bool,
 9696        cx: &mut ViewContext<Editor>,
 9697    ) -> Task<Result<Navigated>> {
 9698        // If there is one definition, just open it directly
 9699        if definitions.len() == 1 {
 9700            let definition = definitions.pop().unwrap();
 9701
 9702            enum TargetTaskResult {
 9703                Location(Option<Location>),
 9704                AlreadyNavigated,
 9705            }
 9706
 9707            let target_task = match definition {
 9708                HoverLink::Text(link) => {
 9709                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9710                }
 9711                HoverLink::InlayHint(lsp_location, server_id) => {
 9712                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9713                    cx.background_executor().spawn(async move {
 9714                        let location = computation.await?;
 9715                        Ok(TargetTaskResult::Location(location))
 9716                    })
 9717                }
 9718                HoverLink::Url(url) => {
 9719                    cx.open_url(&url);
 9720                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9721                }
 9722                HoverLink::File(path) => {
 9723                    if let Some(workspace) = self.workspace() {
 9724                        cx.spawn(|_, mut cx| async move {
 9725                            workspace
 9726                                .update(&mut cx, |workspace, cx| {
 9727                                    workspace.open_resolved_path(path, cx)
 9728                                })?
 9729                                .await
 9730                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9731                        })
 9732                    } else {
 9733                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9734                    }
 9735                }
 9736            };
 9737            cx.spawn(|editor, mut cx| async move {
 9738                let target = match target_task.await.context("target resolution task")? {
 9739                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9740                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9741                    TargetTaskResult::Location(Some(target)) => target,
 9742                };
 9743
 9744                editor.update(&mut cx, |editor, cx| {
 9745                    let Some(workspace) = editor.workspace() else {
 9746                        return Navigated::No;
 9747                    };
 9748                    let pane = workspace.read(cx).active_pane().clone();
 9749
 9750                    let range = target.range.to_point(target.buffer.read(cx));
 9751                    let range = editor.range_for_match(&range);
 9752                    let range = collapse_multiline_range(range);
 9753
 9754                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9755                        editor.go_to_singleton_buffer_range(range.clone(), cx);
 9756                    } else {
 9757                        cx.window_context().defer(move |cx| {
 9758                            let target_editor: View<Self> =
 9759                                workspace.update(cx, |workspace, cx| {
 9760                                    let pane = if split {
 9761                                        workspace.adjacent_pane(cx)
 9762                                    } else {
 9763                                        workspace.active_pane().clone()
 9764                                    };
 9765
 9766                                    workspace.open_project_item(
 9767                                        pane,
 9768                                        target.buffer.clone(),
 9769                                        true,
 9770                                        true,
 9771                                        cx,
 9772                                    )
 9773                                });
 9774                            target_editor.update(cx, |target_editor, cx| {
 9775                                // When selecting a definition in a different buffer, disable the nav history
 9776                                // to avoid creating a history entry at the previous cursor location.
 9777                                pane.update(cx, |pane, _| pane.disable_history());
 9778                                target_editor.go_to_singleton_buffer_range(range, cx);
 9779                                pane.update(cx, |pane, _| pane.enable_history());
 9780                            });
 9781                        });
 9782                    }
 9783                    Navigated::Yes
 9784                })
 9785            })
 9786        } else if !definitions.is_empty() {
 9787            cx.spawn(|editor, mut cx| async move {
 9788                let (title, location_tasks, workspace) = editor
 9789                    .update(&mut cx, |editor, cx| {
 9790                        let tab_kind = match kind {
 9791                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9792                            _ => "Definitions",
 9793                        };
 9794                        let title = definitions
 9795                            .iter()
 9796                            .find_map(|definition| match definition {
 9797                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9798                                    let buffer = origin.buffer.read(cx);
 9799                                    format!(
 9800                                        "{} for {}",
 9801                                        tab_kind,
 9802                                        buffer
 9803                                            .text_for_range(origin.range.clone())
 9804                                            .collect::<String>()
 9805                                    )
 9806                                }),
 9807                                HoverLink::InlayHint(_, _) => None,
 9808                                HoverLink::Url(_) => None,
 9809                                HoverLink::File(_) => None,
 9810                            })
 9811                            .unwrap_or(tab_kind.to_string());
 9812                        let location_tasks = definitions
 9813                            .into_iter()
 9814                            .map(|definition| match definition {
 9815                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
 9816                                HoverLink::InlayHint(lsp_location, server_id) => {
 9817                                    editor.compute_target_location(lsp_location, server_id, cx)
 9818                                }
 9819                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9820                                HoverLink::File(_) => Task::ready(Ok(None)),
 9821                            })
 9822                            .collect::<Vec<_>>();
 9823                        (title, location_tasks, editor.workspace().clone())
 9824                    })
 9825                    .context("location tasks preparation")?;
 9826
 9827                let locations = future::join_all(location_tasks)
 9828                    .await
 9829                    .into_iter()
 9830                    .filter_map(|location| location.transpose())
 9831                    .collect::<Result<_>>()
 9832                    .context("location tasks")?;
 9833
 9834                let Some(workspace) = workspace else {
 9835                    return Ok(Navigated::No);
 9836                };
 9837                let opened = workspace
 9838                    .update(&mut cx, |workspace, cx| {
 9839                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9840                    })
 9841                    .ok();
 9842
 9843                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9844            })
 9845        } else {
 9846            Task::ready(Ok(Navigated::No))
 9847        }
 9848    }
 9849
 9850    fn compute_target_location(
 9851        &self,
 9852        lsp_location: lsp::Location,
 9853        server_id: LanguageServerId,
 9854        cx: &mut ViewContext<Self>,
 9855    ) -> Task<anyhow::Result<Option<Location>>> {
 9856        let Some(project) = self.project.clone() else {
 9857            return Task::ready(Ok(None));
 9858        };
 9859
 9860        cx.spawn(move |editor, mut cx| async move {
 9861            let location_task = editor.update(&mut cx, |_, cx| {
 9862                project.update(cx, |project, cx| {
 9863                    let language_server_name = project
 9864                        .language_server_statuses(cx)
 9865                        .find(|(id, _)| server_id == *id)
 9866                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9867                    language_server_name.map(|language_server_name| {
 9868                        project.open_local_buffer_via_lsp(
 9869                            lsp_location.uri.clone(),
 9870                            server_id,
 9871                            language_server_name,
 9872                            cx,
 9873                        )
 9874                    })
 9875                })
 9876            })?;
 9877            let location = match location_task {
 9878                Some(task) => Some({
 9879                    let target_buffer_handle = task.await.context("open local buffer")?;
 9880                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9881                        let target_start = target_buffer
 9882                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9883                        let target_end = target_buffer
 9884                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9885                        target_buffer.anchor_after(target_start)
 9886                            ..target_buffer.anchor_before(target_end)
 9887                    })?;
 9888                    Location {
 9889                        buffer: target_buffer_handle,
 9890                        range,
 9891                    }
 9892                }),
 9893                None => None,
 9894            };
 9895            Ok(location)
 9896        })
 9897    }
 9898
 9899    pub fn find_all_references(
 9900        &mut self,
 9901        _: &FindAllReferences,
 9902        cx: &mut ViewContext<Self>,
 9903    ) -> Option<Task<Result<Navigated>>> {
 9904        let selection = self.selections.newest::<usize>(cx);
 9905        let multi_buffer = self.buffer.read(cx);
 9906        let head = selection.head();
 9907
 9908        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9909        let head_anchor = multi_buffer_snapshot.anchor_at(
 9910            head,
 9911            if head < selection.tail() {
 9912                Bias::Right
 9913            } else {
 9914                Bias::Left
 9915            },
 9916        );
 9917
 9918        match self
 9919            .find_all_references_task_sources
 9920            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9921        {
 9922            Ok(_) => {
 9923                log::info!(
 9924                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9925                );
 9926                return None;
 9927            }
 9928            Err(i) => {
 9929                self.find_all_references_task_sources.insert(i, head_anchor);
 9930            }
 9931        }
 9932
 9933        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9934        let workspace = self.workspace()?;
 9935        let project = workspace.read(cx).project().clone();
 9936        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9937        Some(cx.spawn(|editor, mut cx| async move {
 9938            let _cleanup = defer({
 9939                let mut cx = cx.clone();
 9940                move || {
 9941                    let _ = editor.update(&mut cx, |editor, _| {
 9942                        if let Ok(i) =
 9943                            editor
 9944                                .find_all_references_task_sources
 9945                                .binary_search_by(|anchor| {
 9946                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9947                                })
 9948                        {
 9949                            editor.find_all_references_task_sources.remove(i);
 9950                        }
 9951                    });
 9952                }
 9953            });
 9954
 9955            let locations = references.await?;
 9956            if locations.is_empty() {
 9957                return anyhow::Ok(Navigated::No);
 9958            }
 9959
 9960            workspace.update(&mut cx, |workspace, cx| {
 9961                let title = locations
 9962                    .first()
 9963                    .as_ref()
 9964                    .map(|location| {
 9965                        let buffer = location.buffer.read(cx);
 9966                        format!(
 9967                            "References to `{}`",
 9968                            buffer
 9969                                .text_for_range(location.range.clone())
 9970                                .collect::<String>()
 9971                        )
 9972                    })
 9973                    .unwrap();
 9974                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9975                Navigated::Yes
 9976            })
 9977        }))
 9978    }
 9979
 9980    /// Opens a multibuffer with the given project locations in it
 9981    pub fn open_locations_in_multibuffer(
 9982        workspace: &mut Workspace,
 9983        mut locations: Vec<Location>,
 9984        title: String,
 9985        split: bool,
 9986        cx: &mut ViewContext<Workspace>,
 9987    ) {
 9988        // If there are multiple definitions, open them in a multibuffer
 9989        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9990        let mut locations = locations.into_iter().peekable();
 9991        let mut ranges_to_highlight = Vec::new();
 9992        let capability = workspace.project().read(cx).capability();
 9993
 9994        let excerpt_buffer = cx.new_model(|cx| {
 9995            let mut multibuffer = MultiBuffer::new(capability);
 9996            while let Some(location) = locations.next() {
 9997                let buffer = location.buffer.read(cx);
 9998                let mut ranges_for_buffer = Vec::new();
 9999                let range = location.range.to_offset(buffer);
10000                ranges_for_buffer.push(range.clone());
10001
10002                while let Some(next_location) = locations.peek() {
10003                    if next_location.buffer == location.buffer {
10004                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10005                        locations.next();
10006                    } else {
10007                        break;
10008                    }
10009                }
10010
10011                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10012                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10013                    location.buffer.clone(),
10014                    ranges_for_buffer,
10015                    DEFAULT_MULTIBUFFER_CONTEXT,
10016                    cx,
10017                ))
10018            }
10019
10020            multibuffer.with_title(title)
10021        });
10022
10023        let editor = cx.new_view(|cx| {
10024            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10025        });
10026        editor.update(cx, |editor, cx| {
10027            if let Some(first_range) = ranges_to_highlight.first() {
10028                editor.change_selections(None, cx, |selections| {
10029                    selections.clear_disjoint();
10030                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10031                });
10032            }
10033            editor.highlight_background::<Self>(
10034                &ranges_to_highlight,
10035                |theme| theme.editor_highlighted_line_background,
10036                cx,
10037            );
10038            editor.register_buffers_with_language_servers(cx);
10039        });
10040
10041        let item = Box::new(editor);
10042        let item_id = item.item_id();
10043
10044        if split {
10045            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10046        } else {
10047            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10048                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10049                    pane.close_current_preview_item(cx)
10050                } else {
10051                    None
10052                }
10053            });
10054            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10055        }
10056        workspace.active_pane().update(cx, |pane, cx| {
10057            pane.set_preview_item_id(Some(item_id), cx);
10058        });
10059    }
10060
10061    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10062        use language::ToOffset as _;
10063
10064        let provider = self.semantics_provider.clone()?;
10065        let selection = self.selections.newest_anchor().clone();
10066        let (cursor_buffer, cursor_buffer_position) = self
10067            .buffer
10068            .read(cx)
10069            .text_anchor_for_position(selection.head(), cx)?;
10070        let (tail_buffer, cursor_buffer_position_end) = self
10071            .buffer
10072            .read(cx)
10073            .text_anchor_for_position(selection.tail(), cx)?;
10074        if tail_buffer != cursor_buffer {
10075            return None;
10076        }
10077
10078        let snapshot = cursor_buffer.read(cx).snapshot();
10079        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10080        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10081        let prepare_rename = provider
10082            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10083            .unwrap_or_else(|| Task::ready(Ok(None)));
10084        drop(snapshot);
10085
10086        Some(cx.spawn(|this, mut cx| async move {
10087            let rename_range = if let Some(range) = prepare_rename.await? {
10088                Some(range)
10089            } else {
10090                this.update(&mut cx, |this, cx| {
10091                    let buffer = this.buffer.read(cx).snapshot(cx);
10092                    let mut buffer_highlights = this
10093                        .document_highlights_for_position(selection.head(), &buffer)
10094                        .filter(|highlight| {
10095                            highlight.start.excerpt_id == selection.head().excerpt_id
10096                                && highlight.end.excerpt_id == selection.head().excerpt_id
10097                        });
10098                    buffer_highlights
10099                        .next()
10100                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10101                })?
10102            };
10103            if let Some(rename_range) = rename_range {
10104                this.update(&mut cx, |this, cx| {
10105                    let snapshot = cursor_buffer.read(cx).snapshot();
10106                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10107                    let cursor_offset_in_rename_range =
10108                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10109                    let cursor_offset_in_rename_range_end =
10110                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10111
10112                    this.take_rename(false, cx);
10113                    let buffer = this.buffer.read(cx).read(cx);
10114                    let cursor_offset = selection.head().to_offset(&buffer);
10115                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10116                    let rename_end = rename_start + rename_buffer_range.len();
10117                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10118                    let mut old_highlight_id = None;
10119                    let old_name: Arc<str> = buffer
10120                        .chunks(rename_start..rename_end, true)
10121                        .map(|chunk| {
10122                            if old_highlight_id.is_none() {
10123                                old_highlight_id = chunk.syntax_highlight_id;
10124                            }
10125                            chunk.text
10126                        })
10127                        .collect::<String>()
10128                        .into();
10129
10130                    drop(buffer);
10131
10132                    // Position the selection in the rename editor so that it matches the current selection.
10133                    this.show_local_selections = false;
10134                    let rename_editor = cx.new_view(|cx| {
10135                        let mut editor = Editor::single_line(cx);
10136                        editor.buffer.update(cx, |buffer, cx| {
10137                            buffer.edit([(0..0, old_name.clone())], None, cx)
10138                        });
10139                        let rename_selection_range = match cursor_offset_in_rename_range
10140                            .cmp(&cursor_offset_in_rename_range_end)
10141                        {
10142                            Ordering::Equal => {
10143                                editor.select_all(&SelectAll, cx);
10144                                return editor;
10145                            }
10146                            Ordering::Less => {
10147                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10148                            }
10149                            Ordering::Greater => {
10150                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10151                            }
10152                        };
10153                        if rename_selection_range.end > old_name.len() {
10154                            editor.select_all(&SelectAll, cx);
10155                        } else {
10156                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10157                                s.select_ranges([rename_selection_range]);
10158                            });
10159                        }
10160                        editor
10161                    });
10162                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10163                        if e == &EditorEvent::Focused {
10164                            cx.emit(EditorEvent::FocusedIn)
10165                        }
10166                    })
10167                    .detach();
10168
10169                    let write_highlights =
10170                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10171                    let read_highlights =
10172                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10173                    let ranges = write_highlights
10174                        .iter()
10175                        .flat_map(|(_, ranges)| ranges.iter())
10176                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10177                        .cloned()
10178                        .collect();
10179
10180                    this.highlight_text::<Rename>(
10181                        ranges,
10182                        HighlightStyle {
10183                            fade_out: Some(0.6),
10184                            ..Default::default()
10185                        },
10186                        cx,
10187                    );
10188                    let rename_focus_handle = rename_editor.focus_handle(cx);
10189                    cx.focus(&rename_focus_handle);
10190                    let block_id = this.insert_blocks(
10191                        [BlockProperties {
10192                            style: BlockStyle::Flex,
10193                            placement: BlockPlacement::Below(range.start),
10194                            height: 1,
10195                            render: Arc::new({
10196                                let rename_editor = rename_editor.clone();
10197                                move |cx: &mut BlockContext| {
10198                                    let mut text_style = cx.editor_style.text.clone();
10199                                    if let Some(highlight_style) = old_highlight_id
10200                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10201                                    {
10202                                        text_style = text_style.highlight(highlight_style);
10203                                    }
10204                                    div()
10205                                        .block_mouse_down()
10206                                        .pl(cx.anchor_x)
10207                                        .child(EditorElement::new(
10208                                            &rename_editor,
10209                                            EditorStyle {
10210                                                background: cx.theme().system().transparent,
10211                                                local_player: cx.editor_style.local_player,
10212                                                text: text_style,
10213                                                scrollbar_width: cx.editor_style.scrollbar_width,
10214                                                syntax: cx.editor_style.syntax.clone(),
10215                                                status: cx.editor_style.status.clone(),
10216                                                inlay_hints_style: HighlightStyle {
10217                                                    font_weight: Some(FontWeight::BOLD),
10218                                                    ..make_inlay_hints_style(cx)
10219                                                },
10220                                                inline_completion_styles: make_suggestion_styles(
10221                                                    cx,
10222                                                ),
10223                                                ..EditorStyle::default()
10224                                            },
10225                                        ))
10226                                        .into_any_element()
10227                                }
10228                            }),
10229                            priority: 0,
10230                        }],
10231                        Some(Autoscroll::fit()),
10232                        cx,
10233                    )[0];
10234                    this.pending_rename = Some(RenameState {
10235                        range,
10236                        old_name,
10237                        editor: rename_editor,
10238                        block_id,
10239                    });
10240                })?;
10241            }
10242
10243            Ok(())
10244        }))
10245    }
10246
10247    pub fn confirm_rename(
10248        &mut self,
10249        _: &ConfirmRename,
10250        cx: &mut ViewContext<Self>,
10251    ) -> Option<Task<Result<()>>> {
10252        let rename = self.take_rename(false, cx)?;
10253        let workspace = self.workspace()?.downgrade();
10254        let (buffer, start) = self
10255            .buffer
10256            .read(cx)
10257            .text_anchor_for_position(rename.range.start, cx)?;
10258        let (end_buffer, _) = self
10259            .buffer
10260            .read(cx)
10261            .text_anchor_for_position(rename.range.end, cx)?;
10262        if buffer != end_buffer {
10263            return None;
10264        }
10265
10266        let old_name = rename.old_name;
10267        let new_name = rename.editor.read(cx).text(cx);
10268
10269        let rename = self.semantics_provider.as_ref()?.perform_rename(
10270            &buffer,
10271            start,
10272            new_name.clone(),
10273            cx,
10274        )?;
10275
10276        Some(cx.spawn(|editor, mut cx| async move {
10277            let project_transaction = rename.await?;
10278            Self::open_project_transaction(
10279                &editor,
10280                workspace,
10281                project_transaction,
10282                format!("Rename: {}{}", old_name, new_name),
10283                cx.clone(),
10284            )
10285            .await?;
10286
10287            editor.update(&mut cx, |editor, cx| {
10288                editor.refresh_document_highlights(cx);
10289            })?;
10290            Ok(())
10291        }))
10292    }
10293
10294    fn take_rename(
10295        &mut self,
10296        moving_cursor: bool,
10297        cx: &mut ViewContext<Self>,
10298    ) -> Option<RenameState> {
10299        let rename = self.pending_rename.take()?;
10300        if rename.editor.focus_handle(cx).is_focused(cx) {
10301            cx.focus(&self.focus_handle);
10302        }
10303
10304        self.remove_blocks(
10305            [rename.block_id].into_iter().collect(),
10306            Some(Autoscroll::fit()),
10307            cx,
10308        );
10309        self.clear_highlights::<Rename>(cx);
10310        self.show_local_selections = true;
10311
10312        if moving_cursor {
10313            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10314                editor.selections.newest::<usize>(cx).head()
10315            });
10316
10317            // Update the selection to match the position of the selection inside
10318            // the rename editor.
10319            let snapshot = self.buffer.read(cx).read(cx);
10320            let rename_range = rename.range.to_offset(&snapshot);
10321            let cursor_in_editor = snapshot
10322                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10323                .min(rename_range.end);
10324            drop(snapshot);
10325
10326            self.change_selections(None, cx, |s| {
10327                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10328            });
10329        } else {
10330            self.refresh_document_highlights(cx);
10331        }
10332
10333        Some(rename)
10334    }
10335
10336    pub fn pending_rename(&self) -> Option<&RenameState> {
10337        self.pending_rename.as_ref()
10338    }
10339
10340    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10341        let project = match &self.project {
10342            Some(project) => project.clone(),
10343            None => return None,
10344        };
10345
10346        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffers, cx))
10347    }
10348
10349    fn format_selections(
10350        &mut self,
10351        _: &FormatSelections,
10352        cx: &mut ViewContext<Self>,
10353    ) -> Option<Task<Result<()>>> {
10354        let project = match &self.project {
10355            Some(project) => project.clone(),
10356            None => return None,
10357        };
10358
10359        let ranges = self
10360            .selections
10361            .all_adjusted(cx)
10362            .into_iter()
10363            .map(|selection| selection.range())
10364            .collect_vec();
10365
10366        Some(self.perform_format(
10367            project,
10368            FormatTrigger::Manual,
10369            FormatTarget::Ranges(ranges),
10370            cx,
10371        ))
10372    }
10373
10374    fn perform_format(
10375        &mut self,
10376        project: Model<Project>,
10377        trigger: FormatTrigger,
10378        target: FormatTarget,
10379        cx: &mut ViewContext<Self>,
10380    ) -> Task<Result<()>> {
10381        let buffer = self.buffer.clone();
10382        let (buffers, target) = match target {
10383            FormatTarget::Buffers => {
10384                let mut buffers = buffer.read(cx).all_buffers();
10385                if trigger == FormatTrigger::Save {
10386                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
10387                }
10388                (buffers, LspFormatTarget::Buffers)
10389            }
10390            FormatTarget::Ranges(selection_ranges) => {
10391                let multi_buffer = buffer.read(cx);
10392                let snapshot = multi_buffer.read(cx);
10393                let mut buffers = HashSet::default();
10394                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10395                    BTreeMap::new();
10396                for selection_range in selection_ranges {
10397                    for (buffer, buffer_range, _) in
10398                        snapshot.range_to_buffer_ranges(selection_range)
10399                    {
10400                        let buffer_id = buffer.remote_id();
10401                        let start = buffer.anchor_before(buffer_range.start);
10402                        let end = buffer.anchor_after(buffer_range.end);
10403                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10404                        buffer_id_to_ranges
10405                            .entry(buffer_id)
10406                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10407                            .or_insert_with(|| vec![start..end]);
10408                    }
10409                }
10410                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10411            }
10412        };
10413
10414        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10415        let format = project.update(cx, |project, cx| {
10416            project.format(buffers, target, true, trigger, cx)
10417        });
10418
10419        cx.spawn(|_, mut cx| async move {
10420            let transaction = futures::select_biased! {
10421                () = timeout => {
10422                    log::warn!("timed out waiting for formatting");
10423                    None
10424                }
10425                transaction = format.log_err().fuse() => transaction,
10426            };
10427
10428            buffer
10429                .update(&mut cx, |buffer, cx| {
10430                    if let Some(transaction) = transaction {
10431                        if !buffer.is_singleton() {
10432                            buffer.push_transaction(&transaction.0, cx);
10433                        }
10434                    }
10435
10436                    cx.notify();
10437                })
10438                .ok();
10439
10440            Ok(())
10441        })
10442    }
10443
10444    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10445        if let Some(project) = self.project.clone() {
10446            self.buffer.update(cx, |multi_buffer, cx| {
10447                project.update(cx, |project, cx| {
10448                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10449                });
10450            })
10451        }
10452    }
10453
10454    fn cancel_language_server_work(
10455        &mut self,
10456        _: &actions::CancelLanguageServerWork,
10457        cx: &mut ViewContext<Self>,
10458    ) {
10459        if let Some(project) = self.project.clone() {
10460            self.buffer.update(cx, |multi_buffer, cx| {
10461                project.update(cx, |project, cx| {
10462                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10463                });
10464            })
10465        }
10466    }
10467
10468    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10469        cx.show_character_palette();
10470    }
10471
10472    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10473        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10474            let buffer = self.buffer.read(cx).snapshot(cx);
10475            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10476            let is_valid = buffer
10477                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
10478                .any(|entry| {
10479                    entry.diagnostic.is_primary
10480                        && !entry.range.is_empty()
10481                        && entry.range.start == primary_range_start
10482                        && entry.diagnostic.message == active_diagnostics.primary_message
10483                });
10484
10485            if is_valid != active_diagnostics.is_valid {
10486                active_diagnostics.is_valid = is_valid;
10487                let mut new_styles = HashMap::default();
10488                for (block_id, diagnostic) in &active_diagnostics.blocks {
10489                    new_styles.insert(
10490                        *block_id,
10491                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10492                    );
10493                }
10494                self.display_map.update(cx, |display_map, _cx| {
10495                    display_map.replace_blocks(new_styles)
10496                });
10497            }
10498        }
10499    }
10500
10501    fn activate_diagnostics(
10502        &mut self,
10503        buffer_id: BufferId,
10504        group_id: usize,
10505        cx: &mut ViewContext<Self>,
10506    ) {
10507        self.dismiss_diagnostics(cx);
10508        let snapshot = self.snapshot(cx);
10509        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10510            let buffer = self.buffer.read(cx).snapshot(cx);
10511
10512            let mut primary_range = None;
10513            let mut primary_message = None;
10514            let diagnostic_group = buffer
10515                .diagnostic_group(buffer_id, group_id)
10516                .filter_map(|entry| {
10517                    let start = entry.range.start;
10518                    let end = entry.range.end;
10519                    if snapshot.is_line_folded(MultiBufferRow(start.row))
10520                        && (start.row == end.row
10521                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
10522                    {
10523                        return None;
10524                    }
10525                    if entry.diagnostic.is_primary {
10526                        primary_range = Some(entry.range.clone());
10527                        primary_message = Some(entry.diagnostic.message.clone());
10528                    }
10529                    Some(entry)
10530                })
10531                .collect::<Vec<_>>();
10532            let primary_range = primary_range?;
10533            let primary_message = primary_message?;
10534
10535            let blocks = display_map
10536                .insert_blocks(
10537                    diagnostic_group.iter().map(|entry| {
10538                        let diagnostic = entry.diagnostic.clone();
10539                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10540                        BlockProperties {
10541                            style: BlockStyle::Fixed,
10542                            placement: BlockPlacement::Below(
10543                                buffer.anchor_after(entry.range.start),
10544                            ),
10545                            height: message_height,
10546                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10547                            priority: 0,
10548                        }
10549                    }),
10550                    cx,
10551                )
10552                .into_iter()
10553                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10554                .collect();
10555
10556            Some(ActiveDiagnosticGroup {
10557                primary_range: buffer.anchor_before(primary_range.start)
10558                    ..buffer.anchor_after(primary_range.end),
10559                primary_message,
10560                group_id,
10561                blocks,
10562                is_valid: true,
10563            })
10564        });
10565    }
10566
10567    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10568        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10569            self.display_map.update(cx, |display_map, cx| {
10570                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10571            });
10572            cx.notify();
10573        }
10574    }
10575
10576    pub fn set_selections_from_remote(
10577        &mut self,
10578        selections: Vec<Selection<Anchor>>,
10579        pending_selection: Option<Selection<Anchor>>,
10580        cx: &mut ViewContext<Self>,
10581    ) {
10582        let old_cursor_position = self.selections.newest_anchor().head();
10583        self.selections.change_with(cx, |s| {
10584            s.select_anchors(selections);
10585            if let Some(pending_selection) = pending_selection {
10586                s.set_pending(pending_selection, SelectMode::Character);
10587            } else {
10588                s.clear_pending();
10589            }
10590        });
10591        self.selections_did_change(false, &old_cursor_position, true, cx);
10592    }
10593
10594    fn push_to_selection_history(&mut self) {
10595        self.selection_history.push(SelectionHistoryEntry {
10596            selections: self.selections.disjoint_anchors(),
10597            select_next_state: self.select_next_state.clone(),
10598            select_prev_state: self.select_prev_state.clone(),
10599            add_selections_state: self.add_selections_state.clone(),
10600        });
10601    }
10602
10603    pub fn transact(
10604        &mut self,
10605        cx: &mut ViewContext<Self>,
10606        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10607    ) -> Option<TransactionId> {
10608        self.start_transaction_at(Instant::now(), cx);
10609        update(self, cx);
10610        self.end_transaction_at(Instant::now(), cx)
10611    }
10612
10613    pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10614        self.end_selection(cx);
10615        if let Some(tx_id) = self
10616            .buffer
10617            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10618        {
10619            self.selection_history
10620                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10621            cx.emit(EditorEvent::TransactionBegun {
10622                transaction_id: tx_id,
10623            })
10624        }
10625    }
10626
10627    pub fn end_transaction_at(
10628        &mut self,
10629        now: Instant,
10630        cx: &mut ViewContext<Self>,
10631    ) -> Option<TransactionId> {
10632        if let Some(transaction_id) = self
10633            .buffer
10634            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10635        {
10636            if let Some((_, end_selections)) =
10637                self.selection_history.transaction_mut(transaction_id)
10638            {
10639                *end_selections = Some(self.selections.disjoint_anchors());
10640            } else {
10641                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10642            }
10643
10644            cx.emit(EditorEvent::Edited { transaction_id });
10645            Some(transaction_id)
10646        } else {
10647            None
10648        }
10649    }
10650
10651    pub fn set_mark(&mut self, _: &actions::SetMark, cx: &mut ViewContext<Self>) {
10652        if self.selection_mark_mode {
10653            self.change_selections(None, cx, |s| {
10654                s.move_with(|_, sel| {
10655                    sel.collapse_to(sel.head(), SelectionGoal::None);
10656                });
10657            })
10658        }
10659        self.selection_mark_mode = true;
10660        cx.notify();
10661    }
10662
10663    pub fn swap_selection_ends(
10664        &mut self,
10665        _: &actions::SwapSelectionEnds,
10666        cx: &mut ViewContext<Self>,
10667    ) {
10668        self.change_selections(None, cx, |s| {
10669            s.move_with(|_, sel| {
10670                if sel.start != sel.end {
10671                    sel.reversed = !sel.reversed
10672                }
10673            });
10674        });
10675        self.request_autoscroll(Autoscroll::newest(), cx);
10676        cx.notify();
10677    }
10678
10679    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10680        if self.is_singleton(cx) {
10681            let selection = self.selections.newest::<Point>(cx);
10682
10683            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10684            let range = if selection.is_empty() {
10685                let point = selection.head().to_display_point(&display_map);
10686                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10687                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10688                    .to_point(&display_map);
10689                start..end
10690            } else {
10691                selection.range()
10692            };
10693            if display_map.folds_in_range(range).next().is_some() {
10694                self.unfold_lines(&Default::default(), cx)
10695            } else {
10696                self.fold(&Default::default(), cx)
10697            }
10698        } else {
10699            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10700            let buffer_ids: HashSet<_> = multi_buffer_snapshot
10701                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
10702                .map(|(snapshot, _, _)| snapshot.remote_id())
10703                .collect();
10704
10705            for buffer_id in buffer_ids {
10706                if self.is_buffer_folded(buffer_id, cx) {
10707                    self.unfold_buffer(buffer_id, cx);
10708                } else {
10709                    self.fold_buffer(buffer_id, cx);
10710                }
10711            }
10712        }
10713    }
10714
10715    pub fn toggle_fold_recursive(
10716        &mut self,
10717        _: &actions::ToggleFoldRecursive,
10718        cx: &mut ViewContext<Self>,
10719    ) {
10720        let selection = self.selections.newest::<Point>(cx);
10721
10722        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10723        let range = if selection.is_empty() {
10724            let point = selection.head().to_display_point(&display_map);
10725            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10726            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10727                .to_point(&display_map);
10728            start..end
10729        } else {
10730            selection.range()
10731        };
10732        if display_map.folds_in_range(range).next().is_some() {
10733            self.unfold_recursive(&Default::default(), cx)
10734        } else {
10735            self.fold_recursive(&Default::default(), cx)
10736        }
10737    }
10738
10739    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10740        if self.is_singleton(cx) {
10741            let mut to_fold = Vec::new();
10742            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10743            let selections = self.selections.all_adjusted(cx);
10744
10745            for selection in selections {
10746                let range = selection.range().sorted();
10747                let buffer_start_row = range.start.row;
10748
10749                if range.start.row != range.end.row {
10750                    let mut found = false;
10751                    let mut row = range.start.row;
10752                    while row <= range.end.row {
10753                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10754                        {
10755                            found = true;
10756                            row = crease.range().end.row + 1;
10757                            to_fold.push(crease);
10758                        } else {
10759                            row += 1
10760                        }
10761                    }
10762                    if found {
10763                        continue;
10764                    }
10765                }
10766
10767                for row in (0..=range.start.row).rev() {
10768                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10769                        if crease.range().end.row >= buffer_start_row {
10770                            to_fold.push(crease);
10771                            if row <= range.start.row {
10772                                break;
10773                            }
10774                        }
10775                    }
10776                }
10777            }
10778
10779            self.fold_creases(to_fold, true, cx);
10780        } else {
10781            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10782
10783            let buffer_ids: HashSet<_> = multi_buffer_snapshot
10784                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
10785                .map(|(snapshot, _, _)| snapshot.remote_id())
10786                .collect();
10787            for buffer_id in buffer_ids {
10788                self.fold_buffer(buffer_id, cx);
10789            }
10790        }
10791    }
10792
10793    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10794        if !self.buffer.read(cx).is_singleton() {
10795            return;
10796        }
10797
10798        let fold_at_level = fold_at.level;
10799        let snapshot = self.buffer.read(cx).snapshot(cx);
10800        let mut to_fold = Vec::new();
10801        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10802
10803        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10804            while start_row < end_row {
10805                match self
10806                    .snapshot(cx)
10807                    .crease_for_buffer_row(MultiBufferRow(start_row))
10808                {
10809                    Some(crease) => {
10810                        let nested_start_row = crease.range().start.row + 1;
10811                        let nested_end_row = crease.range().end.row;
10812
10813                        if current_level < fold_at_level {
10814                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10815                        } else if current_level == fold_at_level {
10816                            to_fold.push(crease);
10817                        }
10818
10819                        start_row = nested_end_row + 1;
10820                    }
10821                    None => start_row += 1,
10822                }
10823            }
10824        }
10825
10826        self.fold_creases(to_fold, true, cx);
10827    }
10828
10829    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10830        if self.buffer.read(cx).is_singleton() {
10831            let mut fold_ranges = Vec::new();
10832            let snapshot = self.buffer.read(cx).snapshot(cx);
10833
10834            for row in 0..snapshot.max_row().0 {
10835                if let Some(foldable_range) =
10836                    self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10837                {
10838                    fold_ranges.push(foldable_range);
10839                }
10840            }
10841
10842            self.fold_creases(fold_ranges, true, cx);
10843        } else {
10844            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10845                editor
10846                    .update(&mut cx, |editor, cx| {
10847                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10848                            editor.fold_buffer(buffer_id, cx);
10849                        }
10850                    })
10851                    .ok();
10852            });
10853        }
10854    }
10855
10856    pub fn fold_function_bodies(
10857        &mut self,
10858        _: &actions::FoldFunctionBodies,
10859        cx: &mut ViewContext<Self>,
10860    ) {
10861        let snapshot = self.buffer.read(cx).snapshot(cx);
10862
10863        let ranges = snapshot
10864            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
10865            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
10866            .collect::<Vec<_>>();
10867
10868        let creases = ranges
10869            .into_iter()
10870            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10871            .collect();
10872
10873        self.fold_creases(creases, true, cx);
10874    }
10875
10876    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10877        let mut to_fold = Vec::new();
10878        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10879        let selections = self.selections.all_adjusted(cx);
10880
10881        for selection in selections {
10882            let range = selection.range().sorted();
10883            let buffer_start_row = range.start.row;
10884
10885            if range.start.row != range.end.row {
10886                let mut found = false;
10887                for row in range.start.row..=range.end.row {
10888                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10889                        found = true;
10890                        to_fold.push(crease);
10891                    }
10892                }
10893                if found {
10894                    continue;
10895                }
10896            }
10897
10898            for row in (0..=range.start.row).rev() {
10899                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10900                    if crease.range().end.row >= buffer_start_row {
10901                        to_fold.push(crease);
10902                    } else {
10903                        break;
10904                    }
10905                }
10906            }
10907        }
10908
10909        self.fold_creases(to_fold, true, cx);
10910    }
10911
10912    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10913        let buffer_row = fold_at.buffer_row;
10914        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10915
10916        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10917            let autoscroll = self
10918                .selections
10919                .all::<Point>(cx)
10920                .iter()
10921                .any(|selection| crease.range().overlaps(&selection.range()));
10922
10923            self.fold_creases(vec![crease], autoscroll, cx);
10924        }
10925    }
10926
10927    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10928        if self.is_singleton(cx) {
10929            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10930            let buffer = &display_map.buffer_snapshot;
10931            let selections = self.selections.all::<Point>(cx);
10932            let ranges = selections
10933                .iter()
10934                .map(|s| {
10935                    let range = s.display_range(&display_map).sorted();
10936                    let mut start = range.start.to_point(&display_map);
10937                    let mut end = range.end.to_point(&display_map);
10938                    start.column = 0;
10939                    end.column = buffer.line_len(MultiBufferRow(end.row));
10940                    start..end
10941                })
10942                .collect::<Vec<_>>();
10943
10944            self.unfold_ranges(&ranges, true, true, cx);
10945        } else {
10946            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10947            let buffer_ids: HashSet<_> = multi_buffer_snapshot
10948                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
10949                .map(|(snapshot, _, _)| snapshot.remote_id())
10950                .collect();
10951            for buffer_id in buffer_ids {
10952                self.unfold_buffer(buffer_id, cx);
10953            }
10954        }
10955    }
10956
10957    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10958        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10959        let selections = self.selections.all::<Point>(cx);
10960        let ranges = selections
10961            .iter()
10962            .map(|s| {
10963                let mut range = s.display_range(&display_map).sorted();
10964                *range.start.column_mut() = 0;
10965                *range.end.column_mut() = display_map.line_len(range.end.row());
10966                let start = range.start.to_point(&display_map);
10967                let end = range.end.to_point(&display_map);
10968                start..end
10969            })
10970            .collect::<Vec<_>>();
10971
10972        self.unfold_ranges(&ranges, true, true, cx);
10973    }
10974
10975    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10976        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10977
10978        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10979            ..Point::new(
10980                unfold_at.buffer_row.0,
10981                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10982            );
10983
10984        let autoscroll = self
10985            .selections
10986            .all::<Point>(cx)
10987            .iter()
10988            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10989
10990        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10991    }
10992
10993    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10994        if self.buffer.read(cx).is_singleton() {
10995            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10996            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10997        } else {
10998            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10999                editor
11000                    .update(&mut cx, |editor, cx| {
11001                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11002                            editor.unfold_buffer(buffer_id, cx);
11003                        }
11004                    })
11005                    .ok();
11006            });
11007        }
11008    }
11009
11010    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11011        let selections = self.selections.all::<Point>(cx);
11012        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11013        let line_mode = self.selections.line_mode;
11014        let ranges = selections
11015            .into_iter()
11016            .map(|s| {
11017                if line_mode {
11018                    let start = Point::new(s.start.row, 0);
11019                    let end = Point::new(
11020                        s.end.row,
11021                        display_map
11022                            .buffer_snapshot
11023                            .line_len(MultiBufferRow(s.end.row)),
11024                    );
11025                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11026                } else {
11027                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11028                }
11029            })
11030            .collect::<Vec<_>>();
11031        self.fold_creases(ranges, true, cx);
11032    }
11033
11034    pub fn fold_ranges<T: ToOffset + Clone>(
11035        &mut self,
11036        ranges: Vec<Range<T>>,
11037        auto_scroll: bool,
11038        cx: &mut ViewContext<Self>,
11039    ) {
11040        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11041        let ranges = ranges
11042            .into_iter()
11043            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
11044            .collect::<Vec<_>>();
11045        self.fold_creases(ranges, auto_scroll, cx);
11046    }
11047
11048    pub fn fold_creases<T: ToOffset + Clone>(
11049        &mut self,
11050        creases: Vec<Crease<T>>,
11051        auto_scroll: bool,
11052        cx: &mut ViewContext<Self>,
11053    ) {
11054        if creases.is_empty() {
11055            return;
11056        }
11057
11058        let mut buffers_affected = HashSet::default();
11059        let multi_buffer = self.buffer().read(cx);
11060        for crease in &creases {
11061            if let Some((_, buffer, _)) =
11062                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11063            {
11064                buffers_affected.insert(buffer.read(cx).remote_id());
11065            };
11066        }
11067
11068        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11069
11070        if auto_scroll {
11071            self.request_autoscroll(Autoscroll::fit(), cx);
11072        }
11073
11074        cx.notify();
11075
11076        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11077            // Clear diagnostics block when folding a range that contains it.
11078            let snapshot = self.snapshot(cx);
11079            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11080                drop(snapshot);
11081                self.active_diagnostics = Some(active_diagnostics);
11082                self.dismiss_diagnostics(cx);
11083            } else {
11084                self.active_diagnostics = Some(active_diagnostics);
11085            }
11086        }
11087
11088        self.scrollbar_marker_state.dirty = true;
11089    }
11090
11091    /// Removes any folds whose ranges intersect any of the given ranges.
11092    pub fn unfold_ranges<T: ToOffset + Clone>(
11093        &mut self,
11094        ranges: &[Range<T>],
11095        inclusive: bool,
11096        auto_scroll: bool,
11097        cx: &mut ViewContext<Self>,
11098    ) {
11099        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11100            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11101        });
11102    }
11103
11104    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11105        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
11106            return;
11107        }
11108        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11109            return;
11110        };
11111        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11112        self.display_map
11113            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11114        cx.emit(EditorEvent::BufferFoldToggled {
11115            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11116            folded: true,
11117        });
11118        cx.notify();
11119    }
11120
11121    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11122        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
11123            return;
11124        }
11125        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11126            return;
11127        };
11128        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11129        self.display_map.update(cx, |display_map, cx| {
11130            display_map.unfold_buffer(buffer_id, cx);
11131        });
11132        cx.emit(EditorEvent::BufferFoldToggled {
11133            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11134            folded: false,
11135        });
11136        cx.notify();
11137    }
11138
11139    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
11140        self.display_map.read(cx).is_buffer_folded(buffer)
11141    }
11142
11143    pub fn folded_buffers<'a>(&self, cx: &'a AppContext) -> &'a HashSet<BufferId> {
11144        self.display_map.read(cx).folded_buffers()
11145    }
11146
11147    /// Removes any folds with the given ranges.
11148    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11149        &mut self,
11150        ranges: &[Range<T>],
11151        type_id: TypeId,
11152        auto_scroll: bool,
11153        cx: &mut ViewContext<Self>,
11154    ) {
11155        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11156            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11157        });
11158    }
11159
11160    fn remove_folds_with<T: ToOffset + Clone>(
11161        &mut self,
11162        ranges: &[Range<T>],
11163        auto_scroll: bool,
11164        cx: &mut ViewContext<Self>,
11165        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11166    ) {
11167        if ranges.is_empty() {
11168            return;
11169        }
11170
11171        let mut buffers_affected = HashSet::default();
11172        let multi_buffer = self.buffer().read(cx);
11173        for range in ranges {
11174            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11175                buffers_affected.insert(buffer.read(cx).remote_id());
11176            };
11177        }
11178
11179        self.display_map.update(cx, update);
11180
11181        if auto_scroll {
11182            self.request_autoscroll(Autoscroll::fit(), cx);
11183        }
11184
11185        cx.notify();
11186        self.scrollbar_marker_state.dirty = true;
11187        self.active_indent_guides_state.dirty = true;
11188    }
11189
11190    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11191        self.display_map.read(cx).fold_placeholder.clone()
11192    }
11193
11194    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut AppContext) {
11195        self.buffer.update(cx, |buffer, cx| {
11196            buffer.set_all_diff_hunks_expanded(cx);
11197        });
11198    }
11199
11200    pub fn expand_all_diff_hunks(&mut self, _: &ExpandAllHunkDiffs, cx: &mut ViewContext<Self>) {
11201        self.buffer.update(cx, |buffer, cx| {
11202            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
11203        });
11204    }
11205
11206    pub fn toggle_selected_diff_hunks(
11207        &mut self,
11208        _: &ToggleSelectedDiffHunks,
11209        cx: &mut ViewContext<Self>,
11210    ) {
11211        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
11212        self.toggle_diff_hunks_in_ranges(ranges, cx);
11213    }
11214
11215    pub fn expand_selected_diff_hunks(&mut self, cx: &mut ViewContext<Self>) {
11216        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
11217        self.buffer
11218            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
11219    }
11220
11221    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut ViewContext<Self>) -> bool {
11222        self.buffer.update(cx, |buffer, cx| {
11223            let ranges = vec![Anchor::min()..Anchor::max()];
11224            if !buffer.all_diff_hunks_expanded()
11225                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
11226            {
11227                buffer.collapse_diff_hunks(ranges, cx);
11228                true
11229            } else {
11230                false
11231            }
11232        })
11233    }
11234
11235    fn toggle_diff_hunks_in_ranges(
11236        &mut self,
11237        ranges: Vec<Range<Anchor>>,
11238        cx: &mut ViewContext<'_, Editor>,
11239    ) {
11240        self.buffer.update(cx, |buffer, cx| {
11241            if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
11242                buffer.collapse_diff_hunks(ranges, cx)
11243            } else {
11244                buffer.expand_diff_hunks(ranges, cx)
11245            }
11246        })
11247    }
11248
11249    pub(crate) fn apply_all_diff_hunks(
11250        &mut self,
11251        _: &ApplyAllDiffHunks,
11252        cx: &mut ViewContext<Self>,
11253    ) {
11254        let buffers = self.buffer.read(cx).all_buffers();
11255        for branch_buffer in buffers {
11256            branch_buffer.update(cx, |branch_buffer, cx| {
11257                branch_buffer.merge_into_base(Vec::new(), cx);
11258            });
11259        }
11260
11261        if let Some(project) = self.project.clone() {
11262            self.save(true, project, cx).detach_and_log_err(cx);
11263        }
11264    }
11265
11266    pub(crate) fn apply_selected_diff_hunks(
11267        &mut self,
11268        _: &ApplyDiffHunk,
11269        cx: &mut ViewContext<Self>,
11270    ) {
11271        let snapshot = self.snapshot(cx);
11272        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
11273        let mut ranges_by_buffer = HashMap::default();
11274        self.transact(cx, |editor, cx| {
11275            for hunk in hunks {
11276                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
11277                    ranges_by_buffer
11278                        .entry(buffer.clone())
11279                        .or_insert_with(Vec::new)
11280                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
11281                }
11282            }
11283
11284            for (buffer, ranges) in ranges_by_buffer {
11285                buffer.update(cx, |buffer, cx| {
11286                    buffer.merge_into_base(ranges, cx);
11287                });
11288            }
11289        });
11290
11291        if let Some(project) = self.project.clone() {
11292            self.save(true, project, cx).detach_and_log_err(cx);
11293        }
11294    }
11295
11296    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11297        if hovered != self.gutter_hovered {
11298            self.gutter_hovered = hovered;
11299            cx.notify();
11300        }
11301    }
11302
11303    pub fn insert_blocks(
11304        &mut self,
11305        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11306        autoscroll: Option<Autoscroll>,
11307        cx: &mut ViewContext<Self>,
11308    ) -> Vec<CustomBlockId> {
11309        let blocks = self
11310            .display_map
11311            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11312        if let Some(autoscroll) = autoscroll {
11313            self.request_autoscroll(autoscroll, cx);
11314        }
11315        cx.notify();
11316        blocks
11317    }
11318
11319    pub fn resize_blocks(
11320        &mut self,
11321        heights: HashMap<CustomBlockId, u32>,
11322        autoscroll: Option<Autoscroll>,
11323        cx: &mut ViewContext<Self>,
11324    ) {
11325        self.display_map
11326            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11327        if let Some(autoscroll) = autoscroll {
11328            self.request_autoscroll(autoscroll, cx);
11329        }
11330        cx.notify();
11331    }
11332
11333    pub fn replace_blocks(
11334        &mut self,
11335        renderers: HashMap<CustomBlockId, RenderBlock>,
11336        autoscroll: Option<Autoscroll>,
11337        cx: &mut ViewContext<Self>,
11338    ) {
11339        self.display_map
11340            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11341        if let Some(autoscroll) = autoscroll {
11342            self.request_autoscroll(autoscroll, cx);
11343        }
11344        cx.notify();
11345    }
11346
11347    pub fn remove_blocks(
11348        &mut self,
11349        block_ids: HashSet<CustomBlockId>,
11350        autoscroll: Option<Autoscroll>,
11351        cx: &mut ViewContext<Self>,
11352    ) {
11353        self.display_map.update(cx, |display_map, cx| {
11354            display_map.remove_blocks(block_ids, cx)
11355        });
11356        if let Some(autoscroll) = autoscroll {
11357            self.request_autoscroll(autoscroll, cx);
11358        }
11359        cx.notify();
11360    }
11361
11362    pub fn row_for_block(
11363        &self,
11364        block_id: CustomBlockId,
11365        cx: &mut ViewContext<Self>,
11366    ) -> Option<DisplayRow> {
11367        self.display_map
11368            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11369    }
11370
11371    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11372        self.focused_block = Some(focused_block);
11373    }
11374
11375    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11376        self.focused_block.take()
11377    }
11378
11379    pub fn insert_creases(
11380        &mut self,
11381        creases: impl IntoIterator<Item = Crease<Anchor>>,
11382        cx: &mut ViewContext<Self>,
11383    ) -> Vec<CreaseId> {
11384        self.display_map
11385            .update(cx, |map, cx| map.insert_creases(creases, cx))
11386    }
11387
11388    pub fn remove_creases(
11389        &mut self,
11390        ids: impl IntoIterator<Item = CreaseId>,
11391        cx: &mut ViewContext<Self>,
11392    ) {
11393        self.display_map
11394            .update(cx, |map, cx| map.remove_creases(ids, cx));
11395    }
11396
11397    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11398        self.display_map
11399            .update(cx, |map, cx| map.snapshot(cx))
11400            .longest_row()
11401    }
11402
11403    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11404        self.display_map
11405            .update(cx, |map, cx| map.snapshot(cx))
11406            .max_point()
11407    }
11408
11409    pub fn text(&self, cx: &AppContext) -> String {
11410        self.buffer.read(cx).read(cx).text()
11411    }
11412
11413    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11414        let text = self.text(cx);
11415        let text = text.trim();
11416
11417        if text.is_empty() {
11418            return None;
11419        }
11420
11421        Some(text.to_string())
11422    }
11423
11424    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11425        self.transact(cx, |this, cx| {
11426            this.buffer
11427                .read(cx)
11428                .as_singleton()
11429                .expect("you can only call set_text on editors for singleton buffers")
11430                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11431        });
11432    }
11433
11434    pub fn display_text(&self, cx: &mut AppContext) -> String {
11435        self.display_map
11436            .update(cx, |map, cx| map.snapshot(cx))
11437            .text()
11438    }
11439
11440    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11441        let mut wrap_guides = smallvec::smallvec![];
11442
11443        if self.show_wrap_guides == Some(false) {
11444            return wrap_guides;
11445        }
11446
11447        let settings = self.buffer.read(cx).settings_at(0, cx);
11448        if settings.show_wrap_guides {
11449            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11450                wrap_guides.push((soft_wrap as usize, true));
11451            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11452                wrap_guides.push((soft_wrap as usize, true));
11453            }
11454            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11455        }
11456
11457        wrap_guides
11458    }
11459
11460    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11461        let settings = self.buffer.read(cx).settings_at(0, cx);
11462        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11463        match mode {
11464            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11465                SoftWrap::None
11466            }
11467            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11468            language_settings::SoftWrap::PreferredLineLength => {
11469                SoftWrap::Column(settings.preferred_line_length)
11470            }
11471            language_settings::SoftWrap::Bounded => {
11472                SoftWrap::Bounded(settings.preferred_line_length)
11473            }
11474        }
11475    }
11476
11477    pub fn set_soft_wrap_mode(
11478        &mut self,
11479        mode: language_settings::SoftWrap,
11480        cx: &mut ViewContext<Self>,
11481    ) {
11482        self.soft_wrap_mode_override = Some(mode);
11483        cx.notify();
11484    }
11485
11486    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11487        self.text_style_refinement = Some(style);
11488    }
11489
11490    /// called by the Element so we know what style we were most recently rendered with.
11491    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11492        let rem_size = cx.rem_size();
11493        self.display_map.update(cx, |map, cx| {
11494            map.set_font(
11495                style.text.font(),
11496                style.text.font_size.to_pixels(rem_size),
11497                cx,
11498            )
11499        });
11500        self.style = Some(style);
11501    }
11502
11503    pub fn style(&self) -> Option<&EditorStyle> {
11504        self.style.as_ref()
11505    }
11506
11507    // Called by the element. This method is not designed to be called outside of the editor
11508    // element's layout code because it does not notify when rewrapping is computed synchronously.
11509    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11510        self.display_map
11511            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11512    }
11513
11514    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11515        if self.soft_wrap_mode_override.is_some() {
11516            self.soft_wrap_mode_override.take();
11517        } else {
11518            let soft_wrap = match self.soft_wrap_mode(cx) {
11519                SoftWrap::GitDiff => return,
11520                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11521                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11522                    language_settings::SoftWrap::None
11523                }
11524            };
11525            self.soft_wrap_mode_override = Some(soft_wrap);
11526        }
11527        cx.notify();
11528    }
11529
11530    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11531        let Some(workspace) = self.workspace() else {
11532            return;
11533        };
11534        let fs = workspace.read(cx).app_state().fs.clone();
11535        let current_show = TabBarSettings::get_global(cx).show;
11536        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11537            setting.show = Some(!current_show);
11538        });
11539    }
11540
11541    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11542        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11543            self.buffer
11544                .read(cx)
11545                .settings_at(0, cx)
11546                .indent_guides
11547                .enabled
11548        });
11549        self.show_indent_guides = Some(!currently_enabled);
11550        cx.notify();
11551    }
11552
11553    fn should_show_indent_guides(&self) -> Option<bool> {
11554        self.show_indent_guides
11555    }
11556
11557    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11558        let mut editor_settings = EditorSettings::get_global(cx).clone();
11559        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11560        EditorSettings::override_global(editor_settings, cx);
11561    }
11562
11563    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11564        self.use_relative_line_numbers
11565            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11566    }
11567
11568    pub fn toggle_relative_line_numbers(
11569        &mut self,
11570        _: &ToggleRelativeLineNumbers,
11571        cx: &mut ViewContext<Self>,
11572    ) {
11573        let is_relative = self.should_use_relative_line_numbers(cx);
11574        self.set_relative_line_number(Some(!is_relative), cx)
11575    }
11576
11577    pub fn set_relative_line_number(
11578        &mut self,
11579        is_relative: Option<bool>,
11580        cx: &mut ViewContext<Self>,
11581    ) {
11582        self.use_relative_line_numbers = is_relative;
11583        cx.notify();
11584    }
11585
11586    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11587        self.show_gutter = show_gutter;
11588        cx.notify();
11589    }
11590
11591    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11592        self.show_scrollbars = show_scrollbars;
11593        cx.notify();
11594    }
11595
11596    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11597        self.show_line_numbers = Some(show_line_numbers);
11598        cx.notify();
11599    }
11600
11601    pub fn set_show_git_diff_gutter(
11602        &mut self,
11603        show_git_diff_gutter: bool,
11604        cx: &mut ViewContext<Self>,
11605    ) {
11606        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11607        cx.notify();
11608    }
11609
11610    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11611        self.show_code_actions = Some(show_code_actions);
11612        cx.notify();
11613    }
11614
11615    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11616        self.show_runnables = Some(show_runnables);
11617        cx.notify();
11618    }
11619
11620    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11621        if self.display_map.read(cx).masked != masked {
11622            self.display_map.update(cx, |map, _| map.masked = masked);
11623        }
11624        cx.notify()
11625    }
11626
11627    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11628        self.show_wrap_guides = Some(show_wrap_guides);
11629        cx.notify();
11630    }
11631
11632    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11633        self.show_indent_guides = Some(show_indent_guides);
11634        cx.notify();
11635    }
11636
11637    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11638        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11639            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11640                if let Some(dir) = file.abs_path(cx).parent() {
11641                    return Some(dir.to_owned());
11642                }
11643            }
11644
11645            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11646                return Some(project_path.path.to_path_buf());
11647            }
11648        }
11649
11650        None
11651    }
11652
11653    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11654        self.active_excerpt(cx)?
11655            .1
11656            .read(cx)
11657            .file()
11658            .and_then(|f| f.as_local())
11659    }
11660
11661    fn target_file_abs_path(&self, cx: &mut ViewContext<Self>) -> Option<PathBuf> {
11662        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
11663            let project_path = buffer.read(cx).project_path(cx)?;
11664            let project = self.project.as_ref()?.read(cx);
11665            project.absolute_path(&project_path, cx)
11666        })
11667    }
11668
11669    fn target_file_path(&self, cx: &mut ViewContext<Self>) -> Option<PathBuf> {
11670        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
11671            let project_path = buffer.read(cx).project_path(cx)?;
11672            let project = self.project.as_ref()?.read(cx);
11673            let entry = project.entry_for_path(&project_path, cx)?;
11674            let path = entry.path.to_path_buf();
11675            Some(path)
11676        })
11677    }
11678
11679    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11680        if let Some(target) = self.target_file(cx) {
11681            cx.reveal_path(&target.abs_path(cx));
11682        }
11683    }
11684
11685    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11686        if let Some(path) = self.target_file_abs_path(cx) {
11687            if let Some(path) = path.to_str() {
11688                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11689            }
11690        }
11691    }
11692
11693    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11694        if let Some(path) = self.target_file_path(cx) {
11695            if let Some(path) = path.to_str() {
11696                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11697            }
11698        }
11699    }
11700
11701    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11702        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11703
11704        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11705            self.start_git_blame(true, cx);
11706        }
11707
11708        cx.notify();
11709    }
11710
11711    pub fn toggle_git_blame_inline(
11712        &mut self,
11713        _: &ToggleGitBlameInline,
11714        cx: &mut ViewContext<Self>,
11715    ) {
11716        self.toggle_git_blame_inline_internal(true, cx);
11717        cx.notify();
11718    }
11719
11720    pub fn git_blame_inline_enabled(&self) -> bool {
11721        self.git_blame_inline_enabled
11722    }
11723
11724    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11725        self.show_selection_menu = self
11726            .show_selection_menu
11727            .map(|show_selections_menu| !show_selections_menu)
11728            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11729
11730        cx.notify();
11731    }
11732
11733    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11734        self.show_selection_menu
11735            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11736    }
11737
11738    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11739        if let Some(project) = self.project.as_ref() {
11740            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11741                return;
11742            };
11743
11744            if buffer.read(cx).file().is_none() {
11745                return;
11746            }
11747
11748            let focused = self.focus_handle(cx).contains_focused(cx);
11749
11750            let project = project.clone();
11751            let blame =
11752                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11753            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11754            self.blame = Some(blame);
11755        }
11756    }
11757
11758    fn toggle_git_blame_inline_internal(
11759        &mut self,
11760        user_triggered: bool,
11761        cx: &mut ViewContext<Self>,
11762    ) {
11763        if self.git_blame_inline_enabled {
11764            self.git_blame_inline_enabled = false;
11765            self.show_git_blame_inline = false;
11766            self.show_git_blame_inline_delay_task.take();
11767        } else {
11768            self.git_blame_inline_enabled = true;
11769            self.start_git_blame_inline(user_triggered, cx);
11770        }
11771
11772        cx.notify();
11773    }
11774
11775    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11776        self.start_git_blame(user_triggered, cx);
11777
11778        if ProjectSettings::get_global(cx)
11779            .git
11780            .inline_blame_delay()
11781            .is_some()
11782        {
11783            self.start_inline_blame_timer(cx);
11784        } else {
11785            self.show_git_blame_inline = true
11786        }
11787    }
11788
11789    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11790        self.blame.as_ref()
11791    }
11792
11793    pub fn show_git_blame_gutter(&self) -> bool {
11794        self.show_git_blame_gutter
11795    }
11796
11797    pub fn render_git_blame_gutter(&self, cx: &WindowContext) -> bool {
11798        self.show_git_blame_gutter && self.has_blame_entries(cx)
11799    }
11800
11801    pub fn render_git_blame_inline(&self, cx: &WindowContext) -> bool {
11802        self.show_git_blame_inline
11803            && self.focus_handle.is_focused(cx)
11804            && !self.newest_selection_head_on_empty_line(cx)
11805            && self.has_blame_entries(cx)
11806    }
11807
11808    fn has_blame_entries(&self, cx: &WindowContext) -> bool {
11809        self.blame()
11810            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11811    }
11812
11813    fn newest_selection_head_on_empty_line(&self, cx: &WindowContext) -> bool {
11814        let cursor_anchor = self.selections.newest_anchor().head();
11815
11816        let snapshot = self.buffer.read(cx).snapshot(cx);
11817        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11818
11819        snapshot.line_len(buffer_row) == 0
11820    }
11821
11822    fn get_permalink_to_line(&self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11823        let buffer_and_selection = maybe!({
11824            let selection = self.selections.newest::<Point>(cx);
11825            let selection_range = selection.range();
11826
11827            let multi_buffer = self.buffer().read(cx);
11828            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11829            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11830
11831            let (buffer, range, _) = if selection.reversed {
11832                buffer_ranges.first()
11833            } else {
11834                buffer_ranges.last()
11835            }?;
11836
11837            let selection = text::ToPoint::to_point(&range.start, &buffer).row
11838                ..text::ToPoint::to_point(&range.end, &buffer).row;
11839            Some((
11840                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
11841                selection,
11842            ))
11843        });
11844
11845        let Some((buffer, selection)) = buffer_and_selection else {
11846            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11847        };
11848
11849        let Some(project) = self.project.as_ref() else {
11850            return Task::ready(Err(anyhow!("editor does not have project")));
11851        };
11852
11853        project.update(cx, |project, cx| {
11854            project.get_permalink_to_line(&buffer, selection, cx)
11855        })
11856    }
11857
11858    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11859        let permalink_task = self.get_permalink_to_line(cx);
11860        let workspace = self.workspace();
11861
11862        cx.spawn(|_, mut cx| async move {
11863            match permalink_task.await {
11864                Ok(permalink) => {
11865                    cx.update(|cx| {
11866                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11867                    })
11868                    .ok();
11869                }
11870                Err(err) => {
11871                    let message = format!("Failed to copy permalink: {err}");
11872
11873                    Err::<(), anyhow::Error>(err).log_err();
11874
11875                    if let Some(workspace) = workspace {
11876                        workspace
11877                            .update(&mut cx, |workspace, cx| {
11878                                struct CopyPermalinkToLine;
11879
11880                                workspace.show_toast(
11881                                    Toast::new(
11882                                        NotificationId::unique::<CopyPermalinkToLine>(),
11883                                        message,
11884                                    ),
11885                                    cx,
11886                                )
11887                            })
11888                            .ok();
11889                    }
11890                }
11891            }
11892        })
11893        .detach();
11894    }
11895
11896    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11897        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11898        if let Some(file) = self.target_file(cx) {
11899            if let Some(path) = file.path().to_str() {
11900                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11901            }
11902        }
11903    }
11904
11905    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11906        let permalink_task = self.get_permalink_to_line(cx);
11907        let workspace = self.workspace();
11908
11909        cx.spawn(|_, mut cx| async move {
11910            match permalink_task.await {
11911                Ok(permalink) => {
11912                    cx.update(|cx| {
11913                        cx.open_url(permalink.as_ref());
11914                    })
11915                    .ok();
11916                }
11917                Err(err) => {
11918                    let message = format!("Failed to open permalink: {err}");
11919
11920                    Err::<(), anyhow::Error>(err).log_err();
11921
11922                    if let Some(workspace) = workspace {
11923                        workspace
11924                            .update(&mut cx, |workspace, cx| {
11925                                struct OpenPermalinkToLine;
11926
11927                                workspace.show_toast(
11928                                    Toast::new(
11929                                        NotificationId::unique::<OpenPermalinkToLine>(),
11930                                        message,
11931                                    ),
11932                                    cx,
11933                                )
11934                            })
11935                            .ok();
11936                    }
11937                }
11938            }
11939        })
11940        .detach();
11941    }
11942
11943    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11944        self.insert_uuid(UuidVersion::V4, cx);
11945    }
11946
11947    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11948        self.insert_uuid(UuidVersion::V7, cx);
11949    }
11950
11951    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11952        self.transact(cx, |this, cx| {
11953            let edits = this
11954                .selections
11955                .all::<Point>(cx)
11956                .into_iter()
11957                .map(|selection| {
11958                    let uuid = match version {
11959                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11960                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11961                    };
11962
11963                    (selection.range(), uuid.to_string())
11964                });
11965            this.edit(edits, cx);
11966            this.refresh_inline_completion(true, false, cx);
11967        });
11968    }
11969
11970    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11971    /// last highlight added will be used.
11972    ///
11973    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11974    pub fn highlight_rows<T: 'static>(
11975        &mut self,
11976        range: Range<Anchor>,
11977        color: Hsla,
11978        should_autoscroll: bool,
11979        cx: &mut ViewContext<Self>,
11980    ) {
11981        let snapshot = self.buffer().read(cx).snapshot(cx);
11982        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11983        let ix = row_highlights.binary_search_by(|highlight| {
11984            Ordering::Equal
11985                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11986                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11987        });
11988
11989        if let Err(mut ix) = ix {
11990            let index = post_inc(&mut self.highlight_order);
11991
11992            // If this range intersects with the preceding highlight, then merge it with
11993            // the preceding highlight. Otherwise insert a new highlight.
11994            let mut merged = false;
11995            if ix > 0 {
11996                let prev_highlight = &mut row_highlights[ix - 1];
11997                if prev_highlight
11998                    .range
11999                    .end
12000                    .cmp(&range.start, &snapshot)
12001                    .is_ge()
12002                {
12003                    ix -= 1;
12004                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12005                        prev_highlight.range.end = range.end;
12006                    }
12007                    merged = true;
12008                    prev_highlight.index = index;
12009                    prev_highlight.color = color;
12010                    prev_highlight.should_autoscroll = should_autoscroll;
12011                }
12012            }
12013
12014            if !merged {
12015                row_highlights.insert(
12016                    ix,
12017                    RowHighlight {
12018                        range: range.clone(),
12019                        index,
12020                        color,
12021                        should_autoscroll,
12022                    },
12023                );
12024            }
12025
12026            // If any of the following highlights intersect with this one, merge them.
12027            while let Some(next_highlight) = row_highlights.get(ix + 1) {
12028                let highlight = &row_highlights[ix];
12029                if next_highlight
12030                    .range
12031                    .start
12032                    .cmp(&highlight.range.end, &snapshot)
12033                    .is_le()
12034                {
12035                    if next_highlight
12036                        .range
12037                        .end
12038                        .cmp(&highlight.range.end, &snapshot)
12039                        .is_gt()
12040                    {
12041                        row_highlights[ix].range.end = next_highlight.range.end;
12042                    }
12043                    row_highlights.remove(ix + 1);
12044                } else {
12045                    break;
12046                }
12047            }
12048        }
12049    }
12050
12051    /// Remove any highlighted row ranges of the given type that intersect the
12052    /// given ranges.
12053    pub fn remove_highlighted_rows<T: 'static>(
12054        &mut self,
12055        ranges_to_remove: Vec<Range<Anchor>>,
12056        cx: &mut ViewContext<Self>,
12057    ) {
12058        let snapshot = self.buffer().read(cx).snapshot(cx);
12059        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12060        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12061        row_highlights.retain(|highlight| {
12062            while let Some(range_to_remove) = ranges_to_remove.peek() {
12063                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12064                    Ordering::Less | Ordering::Equal => {
12065                        ranges_to_remove.next();
12066                    }
12067                    Ordering::Greater => {
12068                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12069                            Ordering::Less | Ordering::Equal => {
12070                                return false;
12071                            }
12072                            Ordering::Greater => break,
12073                        }
12074                    }
12075                }
12076            }
12077
12078            true
12079        })
12080    }
12081
12082    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12083    pub fn clear_row_highlights<T: 'static>(&mut self) {
12084        self.highlighted_rows.remove(&TypeId::of::<T>());
12085    }
12086
12087    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12088    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12089        self.highlighted_rows
12090            .get(&TypeId::of::<T>())
12091            .map_or(&[] as &[_], |vec| vec.as_slice())
12092            .iter()
12093            .map(|highlight| (highlight.range.clone(), highlight.color))
12094    }
12095
12096    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12097    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
12098    /// Allows to ignore certain kinds of highlights.
12099    pub fn highlighted_display_rows(&self, cx: &mut WindowContext) -> BTreeMap<DisplayRow, Hsla> {
12100        let snapshot = self.snapshot(cx);
12101        let mut used_highlight_orders = HashMap::default();
12102        self.highlighted_rows
12103            .iter()
12104            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12105            .fold(
12106                BTreeMap::<DisplayRow, Hsla>::new(),
12107                |mut unique_rows, highlight| {
12108                    let start = highlight.range.start.to_display_point(&snapshot);
12109                    let end = highlight.range.end.to_display_point(&snapshot);
12110                    let start_row = start.row().0;
12111                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12112                        && end.column() == 0
12113                    {
12114                        end.row().0.saturating_sub(1)
12115                    } else {
12116                        end.row().0
12117                    };
12118                    for row in start_row..=end_row {
12119                        let used_index =
12120                            used_highlight_orders.entry(row).or_insert(highlight.index);
12121                        if highlight.index >= *used_index {
12122                            *used_index = highlight.index;
12123                            unique_rows.insert(DisplayRow(row), highlight.color);
12124                        }
12125                    }
12126                    unique_rows
12127                },
12128            )
12129    }
12130
12131    pub fn highlighted_display_row_for_autoscroll(
12132        &self,
12133        snapshot: &DisplaySnapshot,
12134    ) -> Option<DisplayRow> {
12135        self.highlighted_rows
12136            .values()
12137            .flat_map(|highlighted_rows| highlighted_rows.iter())
12138            .filter_map(|highlight| {
12139                if highlight.should_autoscroll {
12140                    Some(highlight.range.start.to_display_point(snapshot).row())
12141                } else {
12142                    None
12143                }
12144            })
12145            .min()
12146    }
12147
12148    pub fn set_search_within_ranges(
12149        &mut self,
12150        ranges: &[Range<Anchor>],
12151        cx: &mut ViewContext<Self>,
12152    ) {
12153        self.highlight_background::<SearchWithinRange>(
12154            ranges,
12155            |colors| colors.editor_document_highlight_read_background,
12156            cx,
12157        )
12158    }
12159
12160    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12161        self.breadcrumb_header = Some(new_header);
12162    }
12163
12164    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12165        self.clear_background_highlights::<SearchWithinRange>(cx);
12166    }
12167
12168    pub fn highlight_background<T: 'static>(
12169        &mut self,
12170        ranges: &[Range<Anchor>],
12171        color_fetcher: fn(&ThemeColors) -> Hsla,
12172        cx: &mut ViewContext<Self>,
12173    ) {
12174        self.background_highlights
12175            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12176        self.scrollbar_marker_state.dirty = true;
12177        cx.notify();
12178    }
12179
12180    pub fn clear_background_highlights<T: 'static>(
12181        &mut self,
12182        cx: &mut ViewContext<Self>,
12183    ) -> Option<BackgroundHighlight> {
12184        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12185        if !text_highlights.1.is_empty() {
12186            self.scrollbar_marker_state.dirty = true;
12187            cx.notify();
12188        }
12189        Some(text_highlights)
12190    }
12191
12192    pub fn highlight_gutter<T: 'static>(
12193        &mut self,
12194        ranges: &[Range<Anchor>],
12195        color_fetcher: fn(&AppContext) -> Hsla,
12196        cx: &mut ViewContext<Self>,
12197    ) {
12198        self.gutter_highlights
12199            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12200        cx.notify();
12201    }
12202
12203    pub fn clear_gutter_highlights<T: 'static>(
12204        &mut self,
12205        cx: &mut ViewContext<Self>,
12206    ) -> Option<GutterHighlight> {
12207        cx.notify();
12208        self.gutter_highlights.remove(&TypeId::of::<T>())
12209    }
12210
12211    #[cfg(feature = "test-support")]
12212    pub fn all_text_background_highlights(
12213        &self,
12214        cx: &mut ViewContext<Self>,
12215    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12216        let snapshot = self.snapshot(cx);
12217        let buffer = &snapshot.buffer_snapshot;
12218        let start = buffer.anchor_before(0);
12219        let end = buffer.anchor_after(buffer.len());
12220        let theme = cx.theme().colors();
12221        self.background_highlights_in_range(start..end, &snapshot, theme)
12222    }
12223
12224    #[cfg(feature = "test-support")]
12225    pub fn search_background_highlights(
12226        &mut self,
12227        cx: &mut ViewContext<Self>,
12228    ) -> Vec<Range<Point>> {
12229        let snapshot = self.buffer().read(cx).snapshot(cx);
12230
12231        let highlights = self
12232            .background_highlights
12233            .get(&TypeId::of::<items::BufferSearchHighlights>());
12234
12235        if let Some((_color, ranges)) = highlights {
12236            ranges
12237                .iter()
12238                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12239                .collect_vec()
12240        } else {
12241            vec![]
12242        }
12243    }
12244
12245    fn document_highlights_for_position<'a>(
12246        &'a self,
12247        position: Anchor,
12248        buffer: &'a MultiBufferSnapshot,
12249    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12250        let read_highlights = self
12251            .background_highlights
12252            .get(&TypeId::of::<DocumentHighlightRead>())
12253            .map(|h| &h.1);
12254        let write_highlights = self
12255            .background_highlights
12256            .get(&TypeId::of::<DocumentHighlightWrite>())
12257            .map(|h| &h.1);
12258        let left_position = position.bias_left(buffer);
12259        let right_position = position.bias_right(buffer);
12260        read_highlights
12261            .into_iter()
12262            .chain(write_highlights)
12263            .flat_map(move |ranges| {
12264                let start_ix = match ranges.binary_search_by(|probe| {
12265                    let cmp = probe.end.cmp(&left_position, buffer);
12266                    if cmp.is_ge() {
12267                        Ordering::Greater
12268                    } else {
12269                        Ordering::Less
12270                    }
12271                }) {
12272                    Ok(i) | Err(i) => i,
12273                };
12274
12275                ranges[start_ix..]
12276                    .iter()
12277                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12278            })
12279    }
12280
12281    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12282        self.background_highlights
12283            .get(&TypeId::of::<T>())
12284            .map_or(false, |(_, highlights)| !highlights.is_empty())
12285    }
12286
12287    pub fn background_highlights_in_range(
12288        &self,
12289        search_range: Range<Anchor>,
12290        display_snapshot: &DisplaySnapshot,
12291        theme: &ThemeColors,
12292    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12293        let mut results = Vec::new();
12294        for (color_fetcher, ranges) in self.background_highlights.values() {
12295            let color = color_fetcher(theme);
12296            let start_ix = match ranges.binary_search_by(|probe| {
12297                let cmp = probe
12298                    .end
12299                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12300                if cmp.is_gt() {
12301                    Ordering::Greater
12302                } else {
12303                    Ordering::Less
12304                }
12305            }) {
12306                Ok(i) | Err(i) => i,
12307            };
12308            for range in &ranges[start_ix..] {
12309                if range
12310                    .start
12311                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12312                    .is_ge()
12313                {
12314                    break;
12315                }
12316
12317                let start = range.start.to_display_point(display_snapshot);
12318                let end = range.end.to_display_point(display_snapshot);
12319                results.push((start..end, color))
12320            }
12321        }
12322        results
12323    }
12324
12325    pub fn background_highlight_row_ranges<T: 'static>(
12326        &self,
12327        search_range: Range<Anchor>,
12328        display_snapshot: &DisplaySnapshot,
12329        count: usize,
12330    ) -> Vec<RangeInclusive<DisplayPoint>> {
12331        let mut results = Vec::new();
12332        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12333            return vec![];
12334        };
12335
12336        let start_ix = match ranges.binary_search_by(|probe| {
12337            let cmp = probe
12338                .end
12339                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12340            if cmp.is_gt() {
12341                Ordering::Greater
12342            } else {
12343                Ordering::Less
12344            }
12345        }) {
12346            Ok(i) | Err(i) => i,
12347        };
12348        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12349            if let (Some(start_display), Some(end_display)) = (start, end) {
12350                results.push(
12351                    start_display.to_display_point(display_snapshot)
12352                        ..=end_display.to_display_point(display_snapshot),
12353                );
12354            }
12355        };
12356        let mut start_row: Option<Point> = None;
12357        let mut end_row: Option<Point> = None;
12358        if ranges.len() > count {
12359            return Vec::new();
12360        }
12361        for range in &ranges[start_ix..] {
12362            if range
12363                .start
12364                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12365                .is_ge()
12366            {
12367                break;
12368            }
12369            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12370            if let Some(current_row) = &end_row {
12371                if end.row == current_row.row {
12372                    continue;
12373                }
12374            }
12375            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12376            if start_row.is_none() {
12377                assert_eq!(end_row, None);
12378                start_row = Some(start);
12379                end_row = Some(end);
12380                continue;
12381            }
12382            if let Some(current_end) = end_row.as_mut() {
12383                if start.row > current_end.row + 1 {
12384                    push_region(start_row, end_row);
12385                    start_row = Some(start);
12386                    end_row = Some(end);
12387                } else {
12388                    // Merge two hunks.
12389                    *current_end = end;
12390                }
12391            } else {
12392                unreachable!();
12393            }
12394        }
12395        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12396        push_region(start_row, end_row);
12397        results
12398    }
12399
12400    pub fn gutter_highlights_in_range(
12401        &self,
12402        search_range: Range<Anchor>,
12403        display_snapshot: &DisplaySnapshot,
12404        cx: &AppContext,
12405    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12406        let mut results = Vec::new();
12407        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12408            let color = color_fetcher(cx);
12409            let start_ix = match ranges.binary_search_by(|probe| {
12410                let cmp = probe
12411                    .end
12412                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12413                if cmp.is_gt() {
12414                    Ordering::Greater
12415                } else {
12416                    Ordering::Less
12417                }
12418            }) {
12419                Ok(i) | Err(i) => i,
12420            };
12421            for range in &ranges[start_ix..] {
12422                if range
12423                    .start
12424                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12425                    .is_ge()
12426                {
12427                    break;
12428                }
12429
12430                let start = range.start.to_display_point(display_snapshot);
12431                let end = range.end.to_display_point(display_snapshot);
12432                results.push((start..end, color))
12433            }
12434        }
12435        results
12436    }
12437
12438    /// Get the text ranges corresponding to the redaction query
12439    pub fn redacted_ranges(
12440        &self,
12441        search_range: Range<Anchor>,
12442        display_snapshot: &DisplaySnapshot,
12443        cx: &WindowContext,
12444    ) -> Vec<Range<DisplayPoint>> {
12445        display_snapshot
12446            .buffer_snapshot
12447            .redacted_ranges(search_range, |file| {
12448                if let Some(file) = file {
12449                    file.is_private()
12450                        && EditorSettings::get(
12451                            Some(SettingsLocation {
12452                                worktree_id: file.worktree_id(cx),
12453                                path: file.path().as_ref(),
12454                            }),
12455                            cx,
12456                        )
12457                        .redact_private_values
12458                } else {
12459                    false
12460                }
12461            })
12462            .map(|range| {
12463                range.start.to_display_point(display_snapshot)
12464                    ..range.end.to_display_point(display_snapshot)
12465            })
12466            .collect()
12467    }
12468
12469    pub fn highlight_text<T: 'static>(
12470        &mut self,
12471        ranges: Vec<Range<Anchor>>,
12472        style: HighlightStyle,
12473        cx: &mut ViewContext<Self>,
12474    ) {
12475        self.display_map.update(cx, |map, _| {
12476            map.highlight_text(TypeId::of::<T>(), ranges, style)
12477        });
12478        cx.notify();
12479    }
12480
12481    pub(crate) fn highlight_inlays<T: 'static>(
12482        &mut self,
12483        highlights: Vec<InlayHighlight>,
12484        style: HighlightStyle,
12485        cx: &mut ViewContext<Self>,
12486    ) {
12487        self.display_map.update(cx, |map, _| {
12488            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12489        });
12490        cx.notify();
12491    }
12492
12493    pub fn text_highlights<'a, T: 'static>(
12494        &'a self,
12495        cx: &'a AppContext,
12496    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12497        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12498    }
12499
12500    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12501        let cleared = self
12502            .display_map
12503            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12504        if cleared {
12505            cx.notify();
12506        }
12507    }
12508
12509    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12510        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12511            && self.focus_handle.is_focused(cx)
12512    }
12513
12514    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12515        self.show_cursor_when_unfocused = is_enabled;
12516        cx.notify();
12517    }
12518
12519    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12520        self.project
12521            .as_ref()
12522            .map(|project| project.read(cx).lsp_store())
12523    }
12524
12525    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12526        cx.notify();
12527    }
12528
12529    fn on_buffer_event(
12530        &mut self,
12531        multibuffer: Model<MultiBuffer>,
12532        event: &multi_buffer::Event,
12533        cx: &mut ViewContext<Self>,
12534    ) {
12535        match event {
12536            multi_buffer::Event::Edited {
12537                singleton_buffer_edited,
12538                edited_buffer: buffer_edited,
12539            } => {
12540                self.scrollbar_marker_state.dirty = true;
12541                self.active_indent_guides_state.dirty = true;
12542                self.refresh_active_diagnostics(cx);
12543                self.refresh_code_actions(cx);
12544                if self.has_active_inline_completion() {
12545                    self.update_visible_inline_completion(cx);
12546                }
12547                if let Some(buffer) = buffer_edited {
12548                    let buffer_id = buffer.read(cx).remote_id();
12549                    if !self.registered_buffers.contains_key(&buffer_id) {
12550                        if let Some(lsp_store) = self.lsp_store(cx) {
12551                            lsp_store.update(cx, |lsp_store, cx| {
12552                                self.registered_buffers.insert(
12553                                    buffer_id,
12554                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
12555                                );
12556                            })
12557                        }
12558                    }
12559                }
12560                cx.emit(EditorEvent::BufferEdited);
12561                cx.emit(SearchEvent::MatchesInvalidated);
12562                if *singleton_buffer_edited {
12563                    if let Some(project) = &self.project {
12564                        let project = project.read(cx);
12565                        #[allow(clippy::mutable_key_type)]
12566                        let languages_affected = multibuffer
12567                            .read(cx)
12568                            .all_buffers()
12569                            .into_iter()
12570                            .filter_map(|buffer| {
12571                                let buffer = buffer.read(cx);
12572                                let language = buffer.language()?;
12573                                if project.is_local()
12574                                    && project
12575                                        .language_servers_for_local_buffer(buffer, cx)
12576                                        .count()
12577                                        == 0
12578                                {
12579                                    None
12580                                } else {
12581                                    Some(language)
12582                                }
12583                            })
12584                            .cloned()
12585                            .collect::<HashSet<_>>();
12586                        if !languages_affected.is_empty() {
12587                            self.refresh_inlay_hints(
12588                                InlayHintRefreshReason::BufferEdited(languages_affected),
12589                                cx,
12590                            );
12591                        }
12592                    }
12593                }
12594
12595                let Some(project) = &self.project else { return };
12596                let (telemetry, is_via_ssh) = {
12597                    let project = project.read(cx);
12598                    let telemetry = project.client().telemetry().clone();
12599                    let is_via_ssh = project.is_via_ssh();
12600                    (telemetry, is_via_ssh)
12601                };
12602                refresh_linked_ranges(self, cx);
12603                telemetry.log_edit_event("editor", is_via_ssh);
12604            }
12605            multi_buffer::Event::ExcerptsAdded {
12606                buffer,
12607                predecessor,
12608                excerpts,
12609            } => {
12610                self.tasks_update_task = Some(self.refresh_runnables(cx));
12611                let buffer_id = buffer.read(cx).remote_id();
12612                if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
12613                    if let Some(project) = &self.project {
12614                        get_unstaged_changes_for_buffers(
12615                            project,
12616                            [buffer.clone()],
12617                            self.buffer.clone(),
12618                            cx,
12619                        );
12620                    }
12621                }
12622                cx.emit(EditorEvent::ExcerptsAdded {
12623                    buffer: buffer.clone(),
12624                    predecessor: *predecessor,
12625                    excerpts: excerpts.clone(),
12626                });
12627                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12628            }
12629            multi_buffer::Event::ExcerptsRemoved { ids } => {
12630                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12631                let buffer = self.buffer.read(cx);
12632                self.registered_buffers
12633                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12634                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12635            }
12636            multi_buffer::Event::ExcerptsEdited { ids } => {
12637                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12638            }
12639            multi_buffer::Event::ExcerptsExpanded { ids } => {
12640                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12641                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12642            }
12643            multi_buffer::Event::Reparsed(buffer_id) => {
12644                self.tasks_update_task = Some(self.refresh_runnables(cx));
12645
12646                cx.emit(EditorEvent::Reparsed(*buffer_id));
12647            }
12648            multi_buffer::Event::LanguageChanged(buffer_id) => {
12649                linked_editing_ranges::refresh_linked_ranges(self, cx);
12650                cx.emit(EditorEvent::Reparsed(*buffer_id));
12651                cx.notify();
12652            }
12653            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12654            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12655            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12656                cx.emit(EditorEvent::TitleChanged)
12657            }
12658            // multi_buffer::Event::DiffBaseChanged => {
12659            //     self.scrollbar_marker_state.dirty = true;
12660            //     cx.emit(EditorEvent::DiffBaseChanged);
12661            //     cx.notify();
12662            // }
12663            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12664            multi_buffer::Event::DiagnosticsUpdated => {
12665                self.refresh_active_diagnostics(cx);
12666                self.scrollbar_marker_state.dirty = true;
12667                cx.notify();
12668            }
12669            _ => {}
12670        };
12671    }
12672
12673    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12674        cx.notify();
12675    }
12676
12677    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12678        self.tasks_update_task = Some(self.refresh_runnables(cx));
12679        self.refresh_inline_completion(true, false, cx);
12680        self.refresh_inlay_hints(
12681            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12682                self.selections.newest_anchor().head(),
12683                &self.buffer.read(cx).snapshot(cx),
12684                cx,
12685            )),
12686            cx,
12687        );
12688
12689        let old_cursor_shape = self.cursor_shape;
12690
12691        {
12692            let editor_settings = EditorSettings::get_global(cx);
12693            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12694            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12695            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12696        }
12697
12698        if old_cursor_shape != self.cursor_shape {
12699            cx.emit(EditorEvent::CursorShapeChanged);
12700        }
12701
12702        let project_settings = ProjectSettings::get_global(cx);
12703        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12704
12705        if self.mode == EditorMode::Full {
12706            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12707            if self.git_blame_inline_enabled != inline_blame_enabled {
12708                self.toggle_git_blame_inline_internal(false, cx);
12709            }
12710        }
12711
12712        cx.notify();
12713    }
12714
12715    pub fn set_searchable(&mut self, searchable: bool) {
12716        self.searchable = searchable;
12717    }
12718
12719    pub fn searchable(&self) -> bool {
12720        self.searchable
12721    }
12722
12723    fn open_proposed_changes_editor(
12724        &mut self,
12725        _: &OpenProposedChangesEditor,
12726        cx: &mut ViewContext<Self>,
12727    ) {
12728        let Some(workspace) = self.workspace() else {
12729            cx.propagate();
12730            return;
12731        };
12732
12733        let selections = self.selections.all::<usize>(cx);
12734        let multi_buffer = self.buffer.read(cx);
12735        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12736        let mut new_selections_by_buffer = HashMap::default();
12737        for selection in selections {
12738            for (buffer, range, _) in
12739                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12740            {
12741                let mut range = range.to_point(buffer);
12742                range.start.column = 0;
12743                range.end.column = buffer.line_len(range.end.row);
12744                new_selections_by_buffer
12745                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
12746                    .or_insert(Vec::new())
12747                    .push(range)
12748            }
12749        }
12750
12751        let proposed_changes_buffers = new_selections_by_buffer
12752            .into_iter()
12753            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12754            .collect::<Vec<_>>();
12755        let proposed_changes_editor = cx.new_view(|cx| {
12756            ProposedChangesEditor::new(
12757                "Proposed changes",
12758                proposed_changes_buffers,
12759                self.project.clone(),
12760                cx,
12761            )
12762        });
12763
12764        cx.window_context().defer(move |cx| {
12765            workspace.update(cx, |workspace, cx| {
12766                workspace.active_pane().update(cx, |pane, cx| {
12767                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12768                });
12769            });
12770        });
12771    }
12772
12773    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12774        self.open_excerpts_common(None, true, cx)
12775    }
12776
12777    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12778        self.open_excerpts_common(None, false, cx)
12779    }
12780
12781    fn open_excerpts_common(
12782        &mut self,
12783        jump_data: Option<JumpData>,
12784        split: bool,
12785        cx: &mut ViewContext<Self>,
12786    ) {
12787        let Some(workspace) = self.workspace() else {
12788            cx.propagate();
12789            return;
12790        };
12791
12792        if self.buffer.read(cx).is_singleton() {
12793            cx.propagate();
12794            return;
12795        }
12796
12797        let mut new_selections_by_buffer = HashMap::default();
12798        match &jump_data {
12799            Some(JumpData::MultiBufferPoint {
12800                excerpt_id,
12801                position,
12802                anchor,
12803                line_offset_from_top,
12804            }) => {
12805                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12806                if let Some(buffer) = multi_buffer_snapshot
12807                    .buffer_id_for_excerpt(*excerpt_id)
12808                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12809                {
12810                    let buffer_snapshot = buffer.read(cx).snapshot();
12811                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12812                        language::ToPoint::to_point(anchor, &buffer_snapshot)
12813                    } else {
12814                        buffer_snapshot.clip_point(*position, Bias::Left)
12815                    };
12816                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12817                    new_selections_by_buffer.insert(
12818                        buffer,
12819                        (
12820                            vec![jump_to_offset..jump_to_offset],
12821                            Some(*line_offset_from_top),
12822                        ),
12823                    );
12824                }
12825            }
12826            Some(JumpData::MultiBufferRow {
12827                row,
12828                line_offset_from_top,
12829            }) => {
12830                let point = MultiBufferPoint::new(row.0, 0);
12831                if let Some((buffer, buffer_point, _)) =
12832                    self.buffer.read(cx).point_to_buffer_point(point, cx)
12833                {
12834                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12835                    new_selections_by_buffer
12836                        .entry(buffer)
12837                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
12838                        .0
12839                        .push(buffer_offset..buffer_offset)
12840                }
12841            }
12842            None => {
12843                let selections = self.selections.all::<usize>(cx);
12844                let multi_buffer = self.buffer.read(cx);
12845                for selection in selections {
12846                    for (buffer, mut range, _) in multi_buffer
12847                        .snapshot(cx)
12848                        .range_to_buffer_ranges(selection.range())
12849                    {
12850                        // When editing branch buffers, jump to the corresponding location
12851                        // in their base buffer.
12852                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
12853                        let buffer = buffer_handle.read(cx);
12854                        if let Some(base_buffer) = buffer.base_buffer() {
12855                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12856                            buffer_handle = base_buffer;
12857                        }
12858
12859                        if selection.reversed {
12860                            mem::swap(&mut range.start, &mut range.end);
12861                        }
12862                        new_selections_by_buffer
12863                            .entry(buffer_handle)
12864                            .or_insert((Vec::new(), None))
12865                            .0
12866                            .push(range)
12867                    }
12868                }
12869            }
12870        }
12871
12872        if new_selections_by_buffer.is_empty() {
12873            return;
12874        }
12875
12876        // We defer the pane interaction because we ourselves are a workspace item
12877        // and activating a new item causes the pane to call a method on us reentrantly,
12878        // which panics if we're on the stack.
12879        cx.window_context().defer(move |cx| {
12880            workspace.update(cx, |workspace, cx| {
12881                let pane = if split {
12882                    workspace.adjacent_pane(cx)
12883                } else {
12884                    workspace.active_pane().clone()
12885                };
12886
12887                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12888                    let editor = buffer
12889                        .read(cx)
12890                        .file()
12891                        .is_none()
12892                        .then(|| {
12893                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12894                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12895                            // Instead, we try to activate the existing editor in the pane first.
12896                            let (editor, pane_item_index) =
12897                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12898                                    let editor = item.downcast::<Editor>()?;
12899                                    let singleton_buffer =
12900                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12901                                    if singleton_buffer == buffer {
12902                                        Some((editor, i))
12903                                    } else {
12904                                        None
12905                                    }
12906                                })?;
12907                            pane.update(cx, |pane, cx| {
12908                                pane.activate_item(pane_item_index, true, true, cx)
12909                            });
12910                            Some(editor)
12911                        })
12912                        .flatten()
12913                        .unwrap_or_else(|| {
12914                            workspace.open_project_item::<Self>(
12915                                pane.clone(),
12916                                buffer,
12917                                true,
12918                                true,
12919                                cx,
12920                            )
12921                        });
12922
12923                    editor.update(cx, |editor, cx| {
12924                        let autoscroll = match scroll_offset {
12925                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12926                            None => Autoscroll::newest(),
12927                        };
12928                        let nav_history = editor.nav_history.take();
12929                        editor.change_selections(Some(autoscroll), cx, |s| {
12930                            s.select_ranges(ranges);
12931                        });
12932                        editor.nav_history = nav_history;
12933                    });
12934                }
12935            })
12936        });
12937    }
12938
12939    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12940        let snapshot = self.buffer.read(cx).read(cx);
12941        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12942        Some(
12943            ranges
12944                .iter()
12945                .map(move |range| {
12946                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12947                })
12948                .collect(),
12949        )
12950    }
12951
12952    fn selection_replacement_ranges(
12953        &self,
12954        range: Range<OffsetUtf16>,
12955        cx: &mut AppContext,
12956    ) -> Vec<Range<OffsetUtf16>> {
12957        let selections = self.selections.all::<OffsetUtf16>(cx);
12958        let newest_selection = selections
12959            .iter()
12960            .max_by_key(|selection| selection.id)
12961            .unwrap();
12962        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12963        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12964        let snapshot = self.buffer.read(cx).read(cx);
12965        selections
12966            .into_iter()
12967            .map(|mut selection| {
12968                selection.start.0 =
12969                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12970                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12971                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12972                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12973            })
12974            .collect()
12975    }
12976
12977    fn report_editor_event(
12978        &self,
12979        event_type: &'static str,
12980        file_extension: Option<String>,
12981        cx: &AppContext,
12982    ) {
12983        if cfg!(any(test, feature = "test-support")) {
12984            return;
12985        }
12986
12987        let Some(project) = &self.project else { return };
12988
12989        // If None, we are in a file without an extension
12990        let file = self
12991            .buffer
12992            .read(cx)
12993            .as_singleton()
12994            .and_then(|b| b.read(cx).file());
12995        let file_extension = file_extension.or(file
12996            .as_ref()
12997            .and_then(|file| Path::new(file.file_name(cx)).extension())
12998            .and_then(|e| e.to_str())
12999            .map(|a| a.to_string()));
13000
13001        let vim_mode = cx
13002            .global::<SettingsStore>()
13003            .raw_user_settings()
13004            .get("vim_mode")
13005            == Some(&serde_json::Value::Bool(true));
13006
13007        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
13008            == language::language_settings::InlineCompletionProvider::Copilot;
13009        let copilot_enabled_for_language = self
13010            .buffer
13011            .read(cx)
13012            .settings_at(0, cx)
13013            .show_inline_completions;
13014
13015        let project = project.read(cx);
13016        telemetry::event!(
13017            event_type,
13018            file_extension,
13019            vim_mode,
13020            copilot_enabled,
13021            copilot_enabled_for_language,
13022            is_via_ssh = project.is_via_ssh(),
13023        );
13024    }
13025
13026    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
13027    /// with each line being an array of {text, highlight} objects.
13028    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
13029        #[derive(Serialize)]
13030        struct Chunk<'a> {
13031            text: String,
13032            highlight: Option<&'a str>,
13033        }
13034
13035        let snapshot = self.buffer.read(cx).snapshot(cx);
13036        let range = self
13037            .selected_text_range(false, cx)
13038            .and_then(|selection| {
13039                if selection.range.is_empty() {
13040                    None
13041                } else {
13042                    Some(selection.range)
13043                }
13044            })
13045            .unwrap_or_else(|| 0..snapshot.len());
13046
13047        let chunks = snapshot.chunks(range, true);
13048        let mut lines = Vec::new();
13049        let mut line: VecDeque<Chunk> = VecDeque::new();
13050
13051        let Some(style) = self.style.as_ref() else {
13052            return;
13053        };
13054
13055        for chunk in chunks {
13056            let highlight = chunk
13057                .syntax_highlight_id
13058                .and_then(|id| id.name(&style.syntax));
13059            let mut chunk_lines = chunk.text.split('\n').peekable();
13060            while let Some(text) = chunk_lines.next() {
13061                let mut merged_with_last_token = false;
13062                if let Some(last_token) = line.back_mut() {
13063                    if last_token.highlight == highlight {
13064                        last_token.text.push_str(text);
13065                        merged_with_last_token = true;
13066                    }
13067                }
13068
13069                if !merged_with_last_token {
13070                    line.push_back(Chunk {
13071                        text: text.into(),
13072                        highlight,
13073                    });
13074                }
13075
13076                if chunk_lines.peek().is_some() {
13077                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
13078                        line.pop_front();
13079                    }
13080                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
13081                        line.pop_back();
13082                    }
13083
13084                    lines.push(mem::take(&mut line));
13085                }
13086            }
13087        }
13088
13089        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13090            return;
13091        };
13092        cx.write_to_clipboard(ClipboardItem::new_string(lines));
13093    }
13094
13095    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
13096        self.request_autoscroll(Autoscroll::newest(), cx);
13097        let position = self.selections.newest_display(cx).start;
13098        mouse_context_menu::deploy_context_menu(self, None, position, cx);
13099    }
13100
13101    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13102        &self.inlay_hint_cache
13103    }
13104
13105    pub fn replay_insert_event(
13106        &mut self,
13107        text: &str,
13108        relative_utf16_range: Option<Range<isize>>,
13109        cx: &mut ViewContext<Self>,
13110    ) {
13111        if !self.input_enabled {
13112            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13113            return;
13114        }
13115        if let Some(relative_utf16_range) = relative_utf16_range {
13116            let selections = self.selections.all::<OffsetUtf16>(cx);
13117            self.change_selections(None, cx, |s| {
13118                let new_ranges = selections.into_iter().map(|range| {
13119                    let start = OffsetUtf16(
13120                        range
13121                            .head()
13122                            .0
13123                            .saturating_add_signed(relative_utf16_range.start),
13124                    );
13125                    let end = OffsetUtf16(
13126                        range
13127                            .head()
13128                            .0
13129                            .saturating_add_signed(relative_utf16_range.end),
13130                    );
13131                    start..end
13132                });
13133                s.select_ranges(new_ranges);
13134            });
13135        }
13136
13137        self.handle_input(text, cx);
13138    }
13139
13140    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13141        let Some(provider) = self.semantics_provider.as_ref() else {
13142            return false;
13143        };
13144
13145        let mut supports = false;
13146        self.buffer().read(cx).for_each_buffer(|buffer| {
13147            supports |= provider.supports_inlay_hints(buffer, cx);
13148        });
13149        supports
13150    }
13151
13152    pub fn focus(&self, cx: &mut WindowContext) {
13153        cx.focus(&self.focus_handle)
13154    }
13155
13156    pub fn is_focused(&self, cx: &WindowContext) -> bool {
13157        self.focus_handle.is_focused(cx)
13158    }
13159
13160    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13161        cx.emit(EditorEvent::Focused);
13162
13163        if let Some(descendant) = self
13164            .last_focused_descendant
13165            .take()
13166            .and_then(|descendant| descendant.upgrade())
13167        {
13168            cx.focus(&descendant);
13169        } else {
13170            if let Some(blame) = self.blame.as_ref() {
13171                blame.update(cx, GitBlame::focus)
13172            }
13173
13174            self.blink_manager.update(cx, BlinkManager::enable);
13175            self.show_cursor_names(cx);
13176            self.buffer.update(cx, |buffer, cx| {
13177                buffer.finalize_last_transaction(cx);
13178                if self.leader_peer_id.is_none() {
13179                    buffer.set_active_selections(
13180                        &self.selections.disjoint_anchors(),
13181                        self.selections.line_mode,
13182                        self.cursor_shape,
13183                        cx,
13184                    );
13185                }
13186            });
13187        }
13188    }
13189
13190    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13191        cx.emit(EditorEvent::FocusedIn)
13192    }
13193
13194    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13195        if event.blurred != self.focus_handle {
13196            self.last_focused_descendant = Some(event.blurred);
13197        }
13198    }
13199
13200    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13201        self.blink_manager.update(cx, BlinkManager::disable);
13202        self.buffer
13203            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13204
13205        if let Some(blame) = self.blame.as_ref() {
13206            blame.update(cx, GitBlame::blur)
13207        }
13208        if !self.hover_state.focused(cx) {
13209            hide_hover(self, cx);
13210        }
13211
13212        self.hide_context_menu(cx);
13213        cx.emit(EditorEvent::Blurred);
13214        cx.notify();
13215    }
13216
13217    pub fn register_action<A: Action>(
13218        &mut self,
13219        listener: impl Fn(&A, &mut WindowContext) + 'static,
13220    ) -> Subscription {
13221        let id = self.next_editor_action_id.post_inc();
13222        let listener = Arc::new(listener);
13223        self.editor_actions.borrow_mut().insert(
13224            id,
13225            Box::new(move |cx| {
13226                let cx = cx.window_context();
13227                let listener = listener.clone();
13228                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13229                    let action = action.downcast_ref().unwrap();
13230                    if phase == DispatchPhase::Bubble {
13231                        listener(action, cx)
13232                    }
13233                })
13234            }),
13235        );
13236
13237        let editor_actions = self.editor_actions.clone();
13238        Subscription::new(move || {
13239            editor_actions.borrow_mut().remove(&id);
13240        })
13241    }
13242
13243    pub fn file_header_size(&self) -> u32 {
13244        FILE_HEADER_HEIGHT
13245    }
13246
13247    pub fn revert(
13248        &mut self,
13249        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13250        cx: &mut ViewContext<Self>,
13251    ) {
13252        self.buffer().update(cx, |multi_buffer, cx| {
13253            for (buffer_id, changes) in revert_changes {
13254                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13255                    buffer.update(cx, |buffer, cx| {
13256                        buffer.edit(
13257                            changes.into_iter().map(|(range, text)| {
13258                                (range, text.to_string().map(Arc::<str>::from))
13259                            }),
13260                            None,
13261                            cx,
13262                        );
13263                    });
13264                }
13265            }
13266        });
13267        self.change_selections(None, cx, |selections| selections.refresh());
13268    }
13269
13270    pub fn to_pixel_point(
13271        &self,
13272        source: multi_buffer::Anchor,
13273        editor_snapshot: &EditorSnapshot,
13274        cx: &mut ViewContext<Self>,
13275    ) -> Option<gpui::Point<Pixels>> {
13276        let source_point = source.to_display_point(editor_snapshot);
13277        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13278    }
13279
13280    pub fn display_to_pixel_point(
13281        &self,
13282        source: DisplayPoint,
13283        editor_snapshot: &EditorSnapshot,
13284        cx: &WindowContext,
13285    ) -> Option<gpui::Point<Pixels>> {
13286        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13287        let text_layout_details = self.text_layout_details(cx);
13288        let scroll_top = text_layout_details
13289            .scroll_anchor
13290            .scroll_position(editor_snapshot)
13291            .y;
13292
13293        if source.row().as_f32() < scroll_top.floor() {
13294            return None;
13295        }
13296        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13297        let source_y = line_height * (source.row().as_f32() - scroll_top);
13298        Some(gpui::Point::new(source_x, source_y))
13299    }
13300
13301    pub fn has_active_completions_menu(&self) -> bool {
13302        self.context_menu.borrow().as_ref().map_or(false, |menu| {
13303            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13304        })
13305    }
13306
13307    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13308        self.addons
13309            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13310    }
13311
13312    pub fn unregister_addon<T: Addon>(&mut self) {
13313        self.addons.remove(&std::any::TypeId::of::<T>());
13314    }
13315
13316    pub fn addon<T: Addon>(&self) -> Option<&T> {
13317        let type_id = std::any::TypeId::of::<T>();
13318        self.addons
13319            .get(&type_id)
13320            .and_then(|item| item.to_any().downcast_ref::<T>())
13321    }
13322
13323    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13324        let text_layout_details = self.text_layout_details(cx);
13325        let style = &text_layout_details.editor_style;
13326        let font_id = cx.text_system().resolve_font(&style.text.font());
13327        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13328        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13329
13330        let em_width = cx
13331            .text_system()
13332            .typographic_bounds(font_id, font_size, 'm')
13333            .unwrap()
13334            .size
13335            .width;
13336
13337        gpui::Point::new(em_width, line_height)
13338    }
13339}
13340
13341fn get_unstaged_changes_for_buffers(
13342    project: &Model<Project>,
13343    buffers: impl IntoIterator<Item = Model<Buffer>>,
13344    buffer: Model<MultiBuffer>,
13345    cx: &mut AppContext,
13346) {
13347    let mut tasks = Vec::new();
13348    project.update(cx, |project, cx| {
13349        for buffer in buffers {
13350            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13351        }
13352    });
13353    cx.spawn(|mut cx| async move {
13354        let change_sets = futures::future::join_all(tasks).await;
13355        buffer
13356            .update(&mut cx, |buffer, cx| {
13357                for change_set in change_sets {
13358                    if let Some(change_set) = change_set.log_err() {
13359                        buffer.add_change_set(change_set, cx);
13360                    }
13361                }
13362            })
13363            .ok();
13364    })
13365    .detach();
13366}
13367
13368fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13369    let tab_size = tab_size.get() as usize;
13370    let mut width = offset;
13371
13372    for ch in text.chars() {
13373        width += if ch == '\t' {
13374            tab_size - (width % tab_size)
13375        } else {
13376            1
13377        };
13378    }
13379
13380    width - offset
13381}
13382
13383#[cfg(test)]
13384mod tests {
13385    use super::*;
13386
13387    #[test]
13388    fn test_string_size_with_expanded_tabs() {
13389        let nz = |val| NonZeroU32::new(val).unwrap();
13390        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13391        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13392        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13393        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13394        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13395        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13396        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13397        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13398    }
13399}
13400
13401/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13402struct WordBreakingTokenizer<'a> {
13403    input: &'a str,
13404}
13405
13406impl<'a> WordBreakingTokenizer<'a> {
13407    fn new(input: &'a str) -> Self {
13408        Self { input }
13409    }
13410}
13411
13412fn is_char_ideographic(ch: char) -> bool {
13413    use unicode_script::Script::*;
13414    use unicode_script::UnicodeScript;
13415    matches!(ch.script(), Han | Tangut | Yi)
13416}
13417
13418fn is_grapheme_ideographic(text: &str) -> bool {
13419    text.chars().any(is_char_ideographic)
13420}
13421
13422fn is_grapheme_whitespace(text: &str) -> bool {
13423    text.chars().any(|x| x.is_whitespace())
13424}
13425
13426fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13427    text.chars().next().map_or(false, |ch| {
13428        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13429    })
13430}
13431
13432#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13433struct WordBreakToken<'a> {
13434    token: &'a str,
13435    grapheme_len: usize,
13436    is_whitespace: bool,
13437}
13438
13439impl<'a> Iterator for WordBreakingTokenizer<'a> {
13440    /// Yields a span, the count of graphemes in the token, and whether it was
13441    /// whitespace. Note that it also breaks at word boundaries.
13442    type Item = WordBreakToken<'a>;
13443
13444    fn next(&mut self) -> Option<Self::Item> {
13445        use unicode_segmentation::UnicodeSegmentation;
13446        if self.input.is_empty() {
13447            return None;
13448        }
13449
13450        let mut iter = self.input.graphemes(true).peekable();
13451        let mut offset = 0;
13452        let mut graphemes = 0;
13453        if let Some(first_grapheme) = iter.next() {
13454            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13455            offset += first_grapheme.len();
13456            graphemes += 1;
13457            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13458                if let Some(grapheme) = iter.peek().copied() {
13459                    if should_stay_with_preceding_ideograph(grapheme) {
13460                        offset += grapheme.len();
13461                        graphemes += 1;
13462                    }
13463                }
13464            } else {
13465                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13466                let mut next_word_bound = words.peek().copied();
13467                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13468                    next_word_bound = words.next();
13469                }
13470                while let Some(grapheme) = iter.peek().copied() {
13471                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13472                        break;
13473                    };
13474                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13475                        break;
13476                    };
13477                    offset += grapheme.len();
13478                    graphemes += 1;
13479                    iter.next();
13480                }
13481            }
13482            let token = &self.input[..offset];
13483            self.input = &self.input[offset..];
13484            if is_whitespace {
13485                Some(WordBreakToken {
13486                    token: " ",
13487                    grapheme_len: 1,
13488                    is_whitespace: true,
13489                })
13490            } else {
13491                Some(WordBreakToken {
13492                    token,
13493                    grapheme_len: graphemes,
13494                    is_whitespace: false,
13495                })
13496            }
13497        } else {
13498            None
13499        }
13500    }
13501}
13502
13503#[test]
13504fn test_word_breaking_tokenizer() {
13505    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13506        ("", &[]),
13507        ("  ", &[(" ", 1, true)]),
13508        ("Ʒ", &[("Ʒ", 1, false)]),
13509        ("Ǽ", &[("Ǽ", 1, false)]),
13510        ("", &[("", 1, false)]),
13511        ("⋑⋑", &[("⋑⋑", 2, false)]),
13512        (
13513            "原理,进而",
13514            &[
13515                ("", 1, false),
13516                ("理,", 2, false),
13517                ("", 1, false),
13518                ("", 1, false),
13519            ],
13520        ),
13521        (
13522            "hello world",
13523            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13524        ),
13525        (
13526            "hello, world",
13527            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13528        ),
13529        (
13530            "  hello world",
13531            &[
13532                (" ", 1, true),
13533                ("hello", 5, false),
13534                (" ", 1, true),
13535                ("world", 5, false),
13536            ],
13537        ),
13538        (
13539            "这是什么 \n 钢笔",
13540            &[
13541                ("", 1, false),
13542                ("", 1, false),
13543                ("", 1, false),
13544                ("", 1, false),
13545                (" ", 1, true),
13546                ("", 1, false),
13547                ("", 1, false),
13548            ],
13549        ),
13550        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13551    ];
13552
13553    for (input, result) in tests {
13554        assert_eq!(
13555            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13556            result
13557                .iter()
13558                .copied()
13559                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13560                    token,
13561                    grapheme_len,
13562                    is_whitespace,
13563                })
13564                .collect::<Vec<_>>()
13565        );
13566    }
13567}
13568
13569fn wrap_with_prefix(
13570    line_prefix: String,
13571    unwrapped_text: String,
13572    wrap_column: usize,
13573    tab_size: NonZeroU32,
13574) -> String {
13575    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13576    let mut wrapped_text = String::new();
13577    let mut current_line = line_prefix.clone();
13578
13579    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13580    let mut current_line_len = line_prefix_len;
13581    for WordBreakToken {
13582        token,
13583        grapheme_len,
13584        is_whitespace,
13585    } in tokenizer
13586    {
13587        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13588            wrapped_text.push_str(current_line.trim_end());
13589            wrapped_text.push('\n');
13590            current_line.truncate(line_prefix.len());
13591            current_line_len = line_prefix_len;
13592            if !is_whitespace {
13593                current_line.push_str(token);
13594                current_line_len += grapheme_len;
13595            }
13596        } else if !is_whitespace {
13597            current_line.push_str(token);
13598            current_line_len += grapheme_len;
13599        } else if current_line_len != line_prefix_len {
13600            current_line.push(' ');
13601            current_line_len += 1;
13602        }
13603    }
13604
13605    if !current_line.is_empty() {
13606        wrapped_text.push_str(&current_line);
13607    }
13608    wrapped_text
13609}
13610
13611#[test]
13612fn test_wrap_with_prefix() {
13613    assert_eq!(
13614        wrap_with_prefix(
13615            "# ".to_string(),
13616            "abcdefg".to_string(),
13617            4,
13618            NonZeroU32::new(4).unwrap()
13619        ),
13620        "# abcdefg"
13621    );
13622    assert_eq!(
13623        wrap_with_prefix(
13624            "".to_string(),
13625            "\thello world".to_string(),
13626            8,
13627            NonZeroU32::new(4).unwrap()
13628        ),
13629        "hello\nworld"
13630    );
13631    assert_eq!(
13632        wrap_with_prefix(
13633            "// ".to_string(),
13634            "xx \nyy zz aa bb cc".to_string(),
13635            12,
13636            NonZeroU32::new(4).unwrap()
13637        ),
13638        "// xx yy zz\n// aa bb cc"
13639    );
13640    assert_eq!(
13641        wrap_with_prefix(
13642            String::new(),
13643            "这是什么 \n 钢笔".to_string(),
13644            3,
13645            NonZeroU32::new(4).unwrap()
13646        ),
13647        "这是什\n么 钢\n"
13648    );
13649}
13650
13651pub trait CollaborationHub {
13652    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13653    fn user_participant_indices<'a>(
13654        &self,
13655        cx: &'a AppContext,
13656    ) -> &'a HashMap<u64, ParticipantIndex>;
13657    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13658}
13659
13660impl CollaborationHub for Model<Project> {
13661    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13662        self.read(cx).collaborators()
13663    }
13664
13665    fn user_participant_indices<'a>(
13666        &self,
13667        cx: &'a AppContext,
13668    ) -> &'a HashMap<u64, ParticipantIndex> {
13669        self.read(cx).user_store().read(cx).participant_indices()
13670    }
13671
13672    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13673        let this = self.read(cx);
13674        let user_ids = this.collaborators().values().map(|c| c.user_id);
13675        this.user_store().read_with(cx, |user_store, cx| {
13676            user_store.participant_names(user_ids, cx)
13677        })
13678    }
13679}
13680
13681pub trait SemanticsProvider {
13682    fn hover(
13683        &self,
13684        buffer: &Model<Buffer>,
13685        position: text::Anchor,
13686        cx: &mut AppContext,
13687    ) -> Option<Task<Vec<project::Hover>>>;
13688
13689    fn inlay_hints(
13690        &self,
13691        buffer_handle: Model<Buffer>,
13692        range: Range<text::Anchor>,
13693        cx: &mut AppContext,
13694    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13695
13696    fn resolve_inlay_hint(
13697        &self,
13698        hint: InlayHint,
13699        buffer_handle: Model<Buffer>,
13700        server_id: LanguageServerId,
13701        cx: &mut AppContext,
13702    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13703
13704    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13705
13706    fn document_highlights(
13707        &self,
13708        buffer: &Model<Buffer>,
13709        position: text::Anchor,
13710        cx: &mut AppContext,
13711    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13712
13713    fn definitions(
13714        &self,
13715        buffer: &Model<Buffer>,
13716        position: text::Anchor,
13717        kind: GotoDefinitionKind,
13718        cx: &mut AppContext,
13719    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13720
13721    fn range_for_rename(
13722        &self,
13723        buffer: &Model<Buffer>,
13724        position: text::Anchor,
13725        cx: &mut AppContext,
13726    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13727
13728    fn perform_rename(
13729        &self,
13730        buffer: &Model<Buffer>,
13731        position: text::Anchor,
13732        new_name: String,
13733        cx: &mut AppContext,
13734    ) -> Option<Task<Result<ProjectTransaction>>>;
13735}
13736
13737pub trait CompletionProvider {
13738    fn completions(
13739        &self,
13740        buffer: &Model<Buffer>,
13741        buffer_position: text::Anchor,
13742        trigger: CompletionContext,
13743        cx: &mut ViewContext<Editor>,
13744    ) -> Task<Result<Vec<Completion>>>;
13745
13746    fn resolve_completions(
13747        &self,
13748        buffer: Model<Buffer>,
13749        completion_indices: Vec<usize>,
13750        completions: Rc<RefCell<Box<[Completion]>>>,
13751        cx: &mut ViewContext<Editor>,
13752    ) -> Task<Result<bool>>;
13753
13754    fn apply_additional_edits_for_completion(
13755        &self,
13756        _buffer: Model<Buffer>,
13757        _completions: Rc<RefCell<Box<[Completion]>>>,
13758        _completion_index: usize,
13759        _push_to_history: bool,
13760        _cx: &mut ViewContext<Editor>,
13761    ) -> Task<Result<Option<language::Transaction>>> {
13762        Task::ready(Ok(None))
13763    }
13764
13765    fn is_completion_trigger(
13766        &self,
13767        buffer: &Model<Buffer>,
13768        position: language::Anchor,
13769        text: &str,
13770        trigger_in_words: bool,
13771        cx: &mut ViewContext<Editor>,
13772    ) -> bool;
13773
13774    fn sort_completions(&self) -> bool {
13775        true
13776    }
13777}
13778
13779pub trait CodeActionProvider {
13780    fn id(&self) -> Arc<str>;
13781
13782    fn code_actions(
13783        &self,
13784        buffer: &Model<Buffer>,
13785        range: Range<text::Anchor>,
13786        cx: &mut WindowContext,
13787    ) -> Task<Result<Vec<CodeAction>>>;
13788
13789    fn apply_code_action(
13790        &self,
13791        buffer_handle: Model<Buffer>,
13792        action: CodeAction,
13793        excerpt_id: ExcerptId,
13794        push_to_history: bool,
13795        cx: &mut WindowContext,
13796    ) -> Task<Result<ProjectTransaction>>;
13797}
13798
13799impl CodeActionProvider for Model<Project> {
13800    fn id(&self) -> Arc<str> {
13801        "project".into()
13802    }
13803
13804    fn code_actions(
13805        &self,
13806        buffer: &Model<Buffer>,
13807        range: Range<text::Anchor>,
13808        cx: &mut WindowContext,
13809    ) -> Task<Result<Vec<CodeAction>>> {
13810        self.update(cx, |project, cx| {
13811            project.code_actions(buffer, range, None, cx)
13812        })
13813    }
13814
13815    fn apply_code_action(
13816        &self,
13817        buffer_handle: Model<Buffer>,
13818        action: CodeAction,
13819        _excerpt_id: ExcerptId,
13820        push_to_history: bool,
13821        cx: &mut WindowContext,
13822    ) -> Task<Result<ProjectTransaction>> {
13823        self.update(cx, |project, cx| {
13824            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13825        })
13826    }
13827}
13828
13829fn snippet_completions(
13830    project: &Project,
13831    buffer: &Model<Buffer>,
13832    buffer_position: text::Anchor,
13833    cx: &mut AppContext,
13834) -> Task<Result<Vec<Completion>>> {
13835    let language = buffer.read(cx).language_at(buffer_position);
13836    let language_name = language.as_ref().map(|language| language.lsp_id());
13837    let snippet_store = project.snippets().read(cx);
13838    let snippets = snippet_store.snippets_for(language_name, cx);
13839
13840    if snippets.is_empty() {
13841        return Task::ready(Ok(vec![]));
13842    }
13843    let snapshot = buffer.read(cx).text_snapshot();
13844    let chars: String = snapshot
13845        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13846        .collect();
13847
13848    let scope = language.map(|language| language.default_scope());
13849    let executor = cx.background_executor().clone();
13850
13851    cx.background_executor().spawn(async move {
13852        let classifier = CharClassifier::new(scope).for_completion(true);
13853        let mut last_word = chars
13854            .chars()
13855            .take_while(|c| classifier.is_word(*c))
13856            .collect::<String>();
13857        last_word = last_word.chars().rev().collect();
13858
13859        if last_word.is_empty() {
13860            return Ok(vec![]);
13861        }
13862
13863        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13864        let to_lsp = |point: &text::Anchor| {
13865            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13866            point_to_lsp(end)
13867        };
13868        let lsp_end = to_lsp(&buffer_position);
13869
13870        let candidates = snippets
13871            .iter()
13872            .enumerate()
13873            .flat_map(|(ix, snippet)| {
13874                snippet
13875                    .prefix
13876                    .iter()
13877                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13878            })
13879            .collect::<Vec<StringMatchCandidate>>();
13880
13881        let mut matches = fuzzy::match_strings(
13882            &candidates,
13883            &last_word,
13884            last_word.chars().any(|c| c.is_uppercase()),
13885            100,
13886            &Default::default(),
13887            executor,
13888        )
13889        .await;
13890
13891        // Remove all candidates where the query's start does not match the start of any word in the candidate
13892        if let Some(query_start) = last_word.chars().next() {
13893            matches.retain(|string_match| {
13894                split_words(&string_match.string).any(|word| {
13895                    // Check that the first codepoint of the word as lowercase matches the first
13896                    // codepoint of the query as lowercase
13897                    word.chars()
13898                        .flat_map(|codepoint| codepoint.to_lowercase())
13899                        .zip(query_start.to_lowercase())
13900                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13901                })
13902            });
13903        }
13904
13905        let matched_strings = matches
13906            .into_iter()
13907            .map(|m| m.string)
13908            .collect::<HashSet<_>>();
13909
13910        let result: Vec<Completion> = snippets
13911            .into_iter()
13912            .filter_map(|snippet| {
13913                let matching_prefix = snippet
13914                    .prefix
13915                    .iter()
13916                    .find(|prefix| matched_strings.contains(*prefix))?;
13917                let start = as_offset - last_word.len();
13918                let start = snapshot.anchor_before(start);
13919                let range = start..buffer_position;
13920                let lsp_start = to_lsp(&start);
13921                let lsp_range = lsp::Range {
13922                    start: lsp_start,
13923                    end: lsp_end,
13924                };
13925                Some(Completion {
13926                    old_range: range,
13927                    new_text: snippet.body.clone(),
13928                    resolved: false,
13929                    label: CodeLabel {
13930                        text: matching_prefix.clone(),
13931                        runs: vec![],
13932                        filter_range: 0..matching_prefix.len(),
13933                    },
13934                    server_id: LanguageServerId(usize::MAX),
13935                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13936                    lsp_completion: lsp::CompletionItem {
13937                        label: snippet.prefix.first().unwrap().clone(),
13938                        kind: Some(CompletionItemKind::SNIPPET),
13939                        label_details: snippet.description.as_ref().map(|description| {
13940                            lsp::CompletionItemLabelDetails {
13941                                detail: Some(description.clone()),
13942                                description: None,
13943                            }
13944                        }),
13945                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13946                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13947                            lsp::InsertReplaceEdit {
13948                                new_text: snippet.body.clone(),
13949                                insert: lsp_range,
13950                                replace: lsp_range,
13951                            },
13952                        )),
13953                        filter_text: Some(snippet.body.clone()),
13954                        sort_text: Some(char::MAX.to_string()),
13955                        ..Default::default()
13956                    },
13957                    confirm: None,
13958                })
13959            })
13960            .collect();
13961
13962        Ok(result)
13963    })
13964}
13965
13966impl CompletionProvider for Model<Project> {
13967    fn completions(
13968        &self,
13969        buffer: &Model<Buffer>,
13970        buffer_position: text::Anchor,
13971        options: CompletionContext,
13972        cx: &mut ViewContext<Editor>,
13973    ) -> Task<Result<Vec<Completion>>> {
13974        self.update(cx, |project, cx| {
13975            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13976            let project_completions = project.completions(buffer, buffer_position, options, cx);
13977            cx.background_executor().spawn(async move {
13978                let mut completions = project_completions.await?;
13979                let snippets_completions = snippets.await?;
13980                completions.extend(snippets_completions);
13981                Ok(completions)
13982            })
13983        })
13984    }
13985
13986    fn resolve_completions(
13987        &self,
13988        buffer: Model<Buffer>,
13989        completion_indices: Vec<usize>,
13990        completions: Rc<RefCell<Box<[Completion]>>>,
13991        cx: &mut ViewContext<Editor>,
13992    ) -> Task<Result<bool>> {
13993        self.update(cx, |project, cx| {
13994            project.lsp_store().update(cx, |lsp_store, cx| {
13995                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13996            })
13997        })
13998    }
13999
14000    fn apply_additional_edits_for_completion(
14001        &self,
14002        buffer: Model<Buffer>,
14003        completions: Rc<RefCell<Box<[Completion]>>>,
14004        completion_index: usize,
14005        push_to_history: bool,
14006        cx: &mut ViewContext<Editor>,
14007    ) -> Task<Result<Option<language::Transaction>>> {
14008        self.update(cx, |project, cx| {
14009            project.lsp_store().update(cx, |lsp_store, cx| {
14010                lsp_store.apply_additional_edits_for_completion(
14011                    buffer,
14012                    completions,
14013                    completion_index,
14014                    push_to_history,
14015                    cx,
14016                )
14017            })
14018        })
14019    }
14020
14021    fn is_completion_trigger(
14022        &self,
14023        buffer: &Model<Buffer>,
14024        position: language::Anchor,
14025        text: &str,
14026        trigger_in_words: bool,
14027        cx: &mut ViewContext<Editor>,
14028    ) -> bool {
14029        let mut chars = text.chars();
14030        let char = if let Some(char) = chars.next() {
14031            char
14032        } else {
14033            return false;
14034        };
14035        if chars.next().is_some() {
14036            return false;
14037        }
14038
14039        let buffer = buffer.read(cx);
14040        let snapshot = buffer.snapshot();
14041        if !snapshot.settings_at(position, cx).show_completions_on_input {
14042            return false;
14043        }
14044        let classifier = snapshot.char_classifier_at(position).for_completion(true);
14045        if trigger_in_words && classifier.is_word(char) {
14046            return true;
14047        }
14048
14049        buffer.completion_triggers().contains(text)
14050    }
14051}
14052
14053impl SemanticsProvider for Model<Project> {
14054    fn hover(
14055        &self,
14056        buffer: &Model<Buffer>,
14057        position: text::Anchor,
14058        cx: &mut AppContext,
14059    ) -> Option<Task<Vec<project::Hover>>> {
14060        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
14061    }
14062
14063    fn document_highlights(
14064        &self,
14065        buffer: &Model<Buffer>,
14066        position: text::Anchor,
14067        cx: &mut AppContext,
14068    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14069        Some(self.update(cx, |project, cx| {
14070            project.document_highlights(buffer, position, cx)
14071        }))
14072    }
14073
14074    fn definitions(
14075        &self,
14076        buffer: &Model<Buffer>,
14077        position: text::Anchor,
14078        kind: GotoDefinitionKind,
14079        cx: &mut AppContext,
14080    ) -> Option<Task<Result<Vec<LocationLink>>>> {
14081        Some(self.update(cx, |project, cx| match kind {
14082            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14083            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14084            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14085            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14086        }))
14087    }
14088
14089    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
14090        // TODO: make this work for remote projects
14091        self.read(cx)
14092            .language_servers_for_local_buffer(buffer.read(cx), cx)
14093            .any(
14094                |(_, server)| match server.capabilities().inlay_hint_provider {
14095                    Some(lsp::OneOf::Left(enabled)) => enabled,
14096                    Some(lsp::OneOf::Right(_)) => true,
14097                    None => false,
14098                },
14099            )
14100    }
14101
14102    fn inlay_hints(
14103        &self,
14104        buffer_handle: Model<Buffer>,
14105        range: Range<text::Anchor>,
14106        cx: &mut AppContext,
14107    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14108        Some(self.update(cx, |project, cx| {
14109            project.inlay_hints(buffer_handle, range, cx)
14110        }))
14111    }
14112
14113    fn resolve_inlay_hint(
14114        &self,
14115        hint: InlayHint,
14116        buffer_handle: Model<Buffer>,
14117        server_id: LanguageServerId,
14118        cx: &mut AppContext,
14119    ) -> Option<Task<anyhow::Result<InlayHint>>> {
14120        Some(self.update(cx, |project, cx| {
14121            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14122        }))
14123    }
14124
14125    fn range_for_rename(
14126        &self,
14127        buffer: &Model<Buffer>,
14128        position: text::Anchor,
14129        cx: &mut AppContext,
14130    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14131        Some(self.update(cx, |project, cx| {
14132            let buffer = buffer.clone();
14133            let task = project.prepare_rename(buffer.clone(), position, cx);
14134            cx.spawn(|_, mut cx| async move {
14135                Ok(match task.await? {
14136                    PrepareRenameResponse::Success(range) => Some(range),
14137                    PrepareRenameResponse::InvalidPosition => None,
14138                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
14139                        // Fallback on using TreeSitter info to determine identifier range
14140                        buffer.update(&mut cx, |buffer, _| {
14141                            let snapshot = buffer.snapshot();
14142                            let (range, kind) = snapshot.surrounding_word(position);
14143                            if kind != Some(CharKind::Word) {
14144                                return None;
14145                            }
14146                            Some(
14147                                snapshot.anchor_before(range.start)
14148                                    ..snapshot.anchor_after(range.end),
14149                            )
14150                        })?
14151                    }
14152                })
14153            })
14154        }))
14155    }
14156
14157    fn perform_rename(
14158        &self,
14159        buffer: &Model<Buffer>,
14160        position: text::Anchor,
14161        new_name: String,
14162        cx: &mut AppContext,
14163    ) -> Option<Task<Result<ProjectTransaction>>> {
14164        Some(self.update(cx, |project, cx| {
14165            project.perform_rename(buffer.clone(), position, new_name, cx)
14166        }))
14167    }
14168}
14169
14170fn inlay_hint_settings(
14171    location: Anchor,
14172    snapshot: &MultiBufferSnapshot,
14173    cx: &mut ViewContext<Editor>,
14174) -> InlayHintSettings {
14175    let file = snapshot.file_at(location);
14176    let language = snapshot.language_at(location).map(|l| l.name());
14177    language_settings(language, file, cx).inlay_hints
14178}
14179
14180fn consume_contiguous_rows(
14181    contiguous_row_selections: &mut Vec<Selection<Point>>,
14182    selection: &Selection<Point>,
14183    display_map: &DisplaySnapshot,
14184    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14185) -> (MultiBufferRow, MultiBufferRow) {
14186    contiguous_row_selections.push(selection.clone());
14187    let start_row = MultiBufferRow(selection.start.row);
14188    let mut end_row = ending_row(selection, display_map);
14189
14190    while let Some(next_selection) = selections.peek() {
14191        if next_selection.start.row <= end_row.0 {
14192            end_row = ending_row(next_selection, display_map);
14193            contiguous_row_selections.push(selections.next().unwrap().clone());
14194        } else {
14195            break;
14196        }
14197    }
14198    (start_row, end_row)
14199}
14200
14201fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14202    if next_selection.end.column > 0 || next_selection.is_empty() {
14203        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14204    } else {
14205        MultiBufferRow(next_selection.end.row)
14206    }
14207}
14208
14209impl EditorSnapshot {
14210    pub fn remote_selections_in_range<'a>(
14211        &'a self,
14212        range: &'a Range<Anchor>,
14213        collaboration_hub: &dyn CollaborationHub,
14214        cx: &'a AppContext,
14215    ) -> impl 'a + Iterator<Item = RemoteSelection> {
14216        let participant_names = collaboration_hub.user_names(cx);
14217        let participant_indices = collaboration_hub.user_participant_indices(cx);
14218        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14219        let collaborators_by_replica_id = collaborators_by_peer_id
14220            .iter()
14221            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14222            .collect::<HashMap<_, _>>();
14223        self.buffer_snapshot
14224            .selections_in_range(range, false)
14225            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14226                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14227                let participant_index = participant_indices.get(&collaborator.user_id).copied();
14228                let user_name = participant_names.get(&collaborator.user_id).cloned();
14229                Some(RemoteSelection {
14230                    replica_id,
14231                    selection,
14232                    cursor_shape,
14233                    line_mode,
14234                    participant_index,
14235                    peer_id: collaborator.peer_id,
14236                    user_name,
14237                })
14238            })
14239    }
14240
14241    pub fn hunks_for_ranges(
14242        &self,
14243        ranges: impl Iterator<Item = Range<Point>>,
14244    ) -> Vec<MultiBufferDiffHunk> {
14245        let mut hunks = Vec::new();
14246        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
14247            HashMap::default();
14248        for query_range in ranges {
14249            let query_rows =
14250                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
14251            for hunk in self.buffer_snapshot.diff_hunks_in_range(
14252                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
14253            ) {
14254                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
14255                // when the caret is just above or just below the deleted hunk.
14256                let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
14257                let related_to_selection = if allow_adjacent {
14258                    hunk.row_range.overlaps(&query_rows)
14259                        || hunk.row_range.start == query_rows.end
14260                        || hunk.row_range.end == query_rows.start
14261                } else {
14262                    hunk.row_range.overlaps(&query_rows)
14263                };
14264                if related_to_selection {
14265                    if !processed_buffer_rows
14266                        .entry(hunk.buffer_id)
14267                        .or_default()
14268                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
14269                    {
14270                        continue;
14271                    }
14272                    hunks.push(hunk);
14273                }
14274            }
14275        }
14276
14277        hunks
14278    }
14279
14280    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14281        self.display_snapshot.buffer_snapshot.language_at(position)
14282    }
14283
14284    pub fn is_focused(&self) -> bool {
14285        self.is_focused
14286    }
14287
14288    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14289        self.placeholder_text.as_ref()
14290    }
14291
14292    pub fn scroll_position(&self) -> gpui::Point<f32> {
14293        self.scroll_anchor.scroll_position(&self.display_snapshot)
14294    }
14295
14296    fn gutter_dimensions(
14297        &self,
14298        font_id: FontId,
14299        font_size: Pixels,
14300        em_width: Pixels,
14301        em_advance: Pixels,
14302        max_line_number_width: Pixels,
14303        cx: &AppContext,
14304    ) -> GutterDimensions {
14305        if !self.show_gutter {
14306            return GutterDimensions::default();
14307        }
14308        let descent = cx.text_system().descent(font_id, font_size);
14309
14310        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14311            matches!(
14312                ProjectSettings::get_global(cx).git.git_gutter,
14313                Some(GitGutterSetting::TrackedFiles)
14314            )
14315        });
14316        let gutter_settings = EditorSettings::get_global(cx).gutter;
14317        let show_line_numbers = self
14318            .show_line_numbers
14319            .unwrap_or(gutter_settings.line_numbers);
14320        let line_gutter_width = if show_line_numbers {
14321            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14322            let min_width_for_number_on_gutter = em_advance * 4.0;
14323            max_line_number_width.max(min_width_for_number_on_gutter)
14324        } else {
14325            0.0.into()
14326        };
14327
14328        let show_code_actions = self
14329            .show_code_actions
14330            .unwrap_or(gutter_settings.code_actions);
14331
14332        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14333
14334        let git_blame_entries_width =
14335            self.git_blame_gutter_max_author_length
14336                .map(|max_author_length| {
14337                    // Length of the author name, but also space for the commit hash,
14338                    // the spacing and the timestamp.
14339                    let max_char_count = max_author_length
14340                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14341                        + 7 // length of commit sha
14342                        + 14 // length of max relative timestamp ("60 minutes ago")
14343                        + 4; // gaps and margins
14344
14345                    em_advance * max_char_count
14346                });
14347
14348        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14349        left_padding += if show_code_actions || show_runnables {
14350            em_width * 3.0
14351        } else if show_git_gutter && show_line_numbers {
14352            em_width * 2.0
14353        } else if show_git_gutter || show_line_numbers {
14354            em_width
14355        } else {
14356            px(0.)
14357        };
14358
14359        let right_padding = if gutter_settings.folds && show_line_numbers {
14360            em_width * 4.0
14361        } else if gutter_settings.folds {
14362            em_width * 3.0
14363        } else if show_line_numbers {
14364            em_width
14365        } else {
14366            px(0.)
14367        };
14368
14369        GutterDimensions {
14370            left_padding,
14371            right_padding,
14372            width: line_gutter_width + left_padding + right_padding,
14373            margin: -descent,
14374            git_blame_entries_width,
14375        }
14376    }
14377
14378    pub fn render_crease_toggle(
14379        &self,
14380        buffer_row: MultiBufferRow,
14381        row_contains_cursor: bool,
14382        editor: View<Editor>,
14383        cx: &mut WindowContext,
14384    ) -> Option<AnyElement> {
14385        let folded = self.is_line_folded(buffer_row);
14386        let mut is_foldable = false;
14387
14388        if let Some(crease) = self
14389            .crease_snapshot
14390            .query_row(buffer_row, &self.buffer_snapshot)
14391        {
14392            is_foldable = true;
14393            match crease {
14394                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14395                    if let Some(render_toggle) = render_toggle {
14396                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14397                            if folded {
14398                                editor.update(cx, |editor, cx| {
14399                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14400                                });
14401                            } else {
14402                                editor.update(cx, |editor, cx| {
14403                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14404                                });
14405                            }
14406                        });
14407                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14408                    }
14409                }
14410            }
14411        }
14412
14413        is_foldable |= self.starts_indent(buffer_row);
14414
14415        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14416            Some(
14417                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14418                    .toggle_state(folded)
14419                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14420                        if folded {
14421                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14422                        } else {
14423                            this.fold_at(&FoldAt { buffer_row }, cx);
14424                        }
14425                    }))
14426                    .into_any_element(),
14427            )
14428        } else {
14429            None
14430        }
14431    }
14432
14433    pub fn render_crease_trailer(
14434        &self,
14435        buffer_row: MultiBufferRow,
14436        cx: &mut WindowContext,
14437    ) -> Option<AnyElement> {
14438        let folded = self.is_line_folded(buffer_row);
14439        if let Crease::Inline { render_trailer, .. } = self
14440            .crease_snapshot
14441            .query_row(buffer_row, &self.buffer_snapshot)?
14442        {
14443            let render_trailer = render_trailer.as_ref()?;
14444            Some(render_trailer(buffer_row, folded, cx))
14445        } else {
14446            None
14447        }
14448    }
14449}
14450
14451impl Deref for EditorSnapshot {
14452    type Target = DisplaySnapshot;
14453
14454    fn deref(&self) -> &Self::Target {
14455        &self.display_snapshot
14456    }
14457}
14458
14459#[derive(Clone, Debug, PartialEq, Eq)]
14460pub enum EditorEvent {
14461    InputIgnored {
14462        text: Arc<str>,
14463    },
14464    InputHandled {
14465        utf16_range_to_replace: Option<Range<isize>>,
14466        text: Arc<str>,
14467    },
14468    ExcerptsAdded {
14469        buffer: Model<Buffer>,
14470        predecessor: ExcerptId,
14471        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14472    },
14473    ExcerptsRemoved {
14474        ids: Vec<ExcerptId>,
14475    },
14476    BufferFoldToggled {
14477        ids: Vec<ExcerptId>,
14478        folded: bool,
14479    },
14480    ExcerptsEdited {
14481        ids: Vec<ExcerptId>,
14482    },
14483    ExcerptsExpanded {
14484        ids: Vec<ExcerptId>,
14485    },
14486    BufferEdited,
14487    Edited {
14488        transaction_id: clock::Lamport,
14489    },
14490    Reparsed(BufferId),
14491    Focused,
14492    FocusedIn,
14493    Blurred,
14494    DirtyChanged,
14495    Saved,
14496    TitleChanged,
14497    DiffBaseChanged,
14498    SelectionsChanged {
14499        local: bool,
14500    },
14501    ScrollPositionChanged {
14502        local: bool,
14503        autoscroll: bool,
14504    },
14505    Closed,
14506    TransactionUndone {
14507        transaction_id: clock::Lamport,
14508    },
14509    TransactionBegun {
14510        transaction_id: clock::Lamport,
14511    },
14512    Reloaded,
14513    CursorShapeChanged,
14514}
14515
14516impl EventEmitter<EditorEvent> for Editor {}
14517
14518impl FocusableView for Editor {
14519    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14520        self.focus_handle.clone()
14521    }
14522}
14523
14524impl Render for Editor {
14525    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14526        let settings = ThemeSettings::get_global(cx);
14527
14528        let mut text_style = match self.mode {
14529            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14530                color: cx.theme().colors().editor_foreground,
14531                font_family: settings.ui_font.family.clone(),
14532                font_features: settings.ui_font.features.clone(),
14533                font_fallbacks: settings.ui_font.fallbacks.clone(),
14534                font_size: rems(0.875).into(),
14535                font_weight: settings.ui_font.weight,
14536                line_height: relative(settings.buffer_line_height.value()),
14537                ..Default::default()
14538            },
14539            EditorMode::Full => TextStyle {
14540                color: cx.theme().colors().editor_foreground,
14541                font_family: settings.buffer_font.family.clone(),
14542                font_features: settings.buffer_font.features.clone(),
14543                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14544                font_size: settings.buffer_font_size().into(),
14545                font_weight: settings.buffer_font.weight,
14546                line_height: relative(settings.buffer_line_height.value()),
14547                ..Default::default()
14548            },
14549        };
14550        if let Some(text_style_refinement) = &self.text_style_refinement {
14551            text_style.refine(text_style_refinement)
14552        }
14553
14554        let background = match self.mode {
14555            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14556            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14557            EditorMode::Full => cx.theme().colors().editor_background,
14558        };
14559
14560        EditorElement::new(
14561            cx.view(),
14562            EditorStyle {
14563                background,
14564                local_player: cx.theme().players().local(),
14565                text: text_style,
14566                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14567                syntax: cx.theme().syntax().clone(),
14568                status: cx.theme().status().clone(),
14569                inlay_hints_style: make_inlay_hints_style(cx),
14570                inline_completion_styles: make_suggestion_styles(cx),
14571                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14572            },
14573        )
14574    }
14575}
14576
14577impl ViewInputHandler for Editor {
14578    fn text_for_range(
14579        &mut self,
14580        range_utf16: Range<usize>,
14581        adjusted_range: &mut Option<Range<usize>>,
14582        cx: &mut ViewContext<Self>,
14583    ) -> Option<String> {
14584        let snapshot = self.buffer.read(cx).read(cx);
14585        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14586        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14587        if (start.0..end.0) != range_utf16 {
14588            adjusted_range.replace(start.0..end.0);
14589        }
14590        Some(snapshot.text_for_range(start..end).collect())
14591    }
14592
14593    fn selected_text_range(
14594        &mut self,
14595        ignore_disabled_input: bool,
14596        cx: &mut ViewContext<Self>,
14597    ) -> Option<UTF16Selection> {
14598        // Prevent the IME menu from appearing when holding down an alphabetic key
14599        // while input is disabled.
14600        if !ignore_disabled_input && !self.input_enabled {
14601            return None;
14602        }
14603
14604        let selection = self.selections.newest::<OffsetUtf16>(cx);
14605        let range = selection.range();
14606
14607        Some(UTF16Selection {
14608            range: range.start.0..range.end.0,
14609            reversed: selection.reversed,
14610        })
14611    }
14612
14613    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14614        let snapshot = self.buffer.read(cx).read(cx);
14615        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14616        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14617    }
14618
14619    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14620        self.clear_highlights::<InputComposition>(cx);
14621        self.ime_transaction.take();
14622    }
14623
14624    fn replace_text_in_range(
14625        &mut self,
14626        range_utf16: Option<Range<usize>>,
14627        text: &str,
14628        cx: &mut ViewContext<Self>,
14629    ) {
14630        if !self.input_enabled {
14631            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14632            return;
14633        }
14634
14635        self.transact(cx, |this, cx| {
14636            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14637                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14638                Some(this.selection_replacement_ranges(range_utf16, cx))
14639            } else {
14640                this.marked_text_ranges(cx)
14641            };
14642
14643            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14644                let newest_selection_id = this.selections.newest_anchor().id;
14645                this.selections
14646                    .all::<OffsetUtf16>(cx)
14647                    .iter()
14648                    .zip(ranges_to_replace.iter())
14649                    .find_map(|(selection, range)| {
14650                        if selection.id == newest_selection_id {
14651                            Some(
14652                                (range.start.0 as isize - selection.head().0 as isize)
14653                                    ..(range.end.0 as isize - selection.head().0 as isize),
14654                            )
14655                        } else {
14656                            None
14657                        }
14658                    })
14659            });
14660
14661            cx.emit(EditorEvent::InputHandled {
14662                utf16_range_to_replace: range_to_replace,
14663                text: text.into(),
14664            });
14665
14666            if let Some(new_selected_ranges) = new_selected_ranges {
14667                this.change_selections(None, cx, |selections| {
14668                    selections.select_ranges(new_selected_ranges)
14669                });
14670                this.backspace(&Default::default(), cx);
14671            }
14672
14673            this.handle_input(text, cx);
14674        });
14675
14676        if let Some(transaction) = self.ime_transaction {
14677            self.buffer.update(cx, |buffer, cx| {
14678                buffer.group_until_transaction(transaction, cx);
14679            });
14680        }
14681
14682        self.unmark_text(cx);
14683    }
14684
14685    fn replace_and_mark_text_in_range(
14686        &mut self,
14687        range_utf16: Option<Range<usize>>,
14688        text: &str,
14689        new_selected_range_utf16: Option<Range<usize>>,
14690        cx: &mut ViewContext<Self>,
14691    ) {
14692        if !self.input_enabled {
14693            return;
14694        }
14695
14696        let transaction = self.transact(cx, |this, cx| {
14697            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14698                let snapshot = this.buffer.read(cx).read(cx);
14699                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14700                    for marked_range in &mut marked_ranges {
14701                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14702                        marked_range.start.0 += relative_range_utf16.start;
14703                        marked_range.start =
14704                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14705                        marked_range.end =
14706                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14707                    }
14708                }
14709                Some(marked_ranges)
14710            } else if let Some(range_utf16) = range_utf16 {
14711                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14712                Some(this.selection_replacement_ranges(range_utf16, cx))
14713            } else {
14714                None
14715            };
14716
14717            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14718                let newest_selection_id = this.selections.newest_anchor().id;
14719                this.selections
14720                    .all::<OffsetUtf16>(cx)
14721                    .iter()
14722                    .zip(ranges_to_replace.iter())
14723                    .find_map(|(selection, range)| {
14724                        if selection.id == newest_selection_id {
14725                            Some(
14726                                (range.start.0 as isize - selection.head().0 as isize)
14727                                    ..(range.end.0 as isize - selection.head().0 as isize),
14728                            )
14729                        } else {
14730                            None
14731                        }
14732                    })
14733            });
14734
14735            cx.emit(EditorEvent::InputHandled {
14736                utf16_range_to_replace: range_to_replace,
14737                text: text.into(),
14738            });
14739
14740            if let Some(ranges) = ranges_to_replace {
14741                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14742            }
14743
14744            let marked_ranges = {
14745                let snapshot = this.buffer.read(cx).read(cx);
14746                this.selections
14747                    .disjoint_anchors()
14748                    .iter()
14749                    .map(|selection| {
14750                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14751                    })
14752                    .collect::<Vec<_>>()
14753            };
14754
14755            if text.is_empty() {
14756                this.unmark_text(cx);
14757            } else {
14758                this.highlight_text::<InputComposition>(
14759                    marked_ranges.clone(),
14760                    HighlightStyle {
14761                        underline: Some(UnderlineStyle {
14762                            thickness: px(1.),
14763                            color: None,
14764                            wavy: false,
14765                        }),
14766                        ..Default::default()
14767                    },
14768                    cx,
14769                );
14770            }
14771
14772            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14773            let use_autoclose = this.use_autoclose;
14774            let use_auto_surround = this.use_auto_surround;
14775            this.set_use_autoclose(false);
14776            this.set_use_auto_surround(false);
14777            this.handle_input(text, cx);
14778            this.set_use_autoclose(use_autoclose);
14779            this.set_use_auto_surround(use_auto_surround);
14780
14781            if let Some(new_selected_range) = new_selected_range_utf16 {
14782                let snapshot = this.buffer.read(cx).read(cx);
14783                let new_selected_ranges = marked_ranges
14784                    .into_iter()
14785                    .map(|marked_range| {
14786                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14787                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14788                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14789                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14790                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14791                    })
14792                    .collect::<Vec<_>>();
14793
14794                drop(snapshot);
14795                this.change_selections(None, cx, |selections| {
14796                    selections.select_ranges(new_selected_ranges)
14797                });
14798            }
14799        });
14800
14801        self.ime_transaction = self.ime_transaction.or(transaction);
14802        if let Some(transaction) = self.ime_transaction {
14803            self.buffer.update(cx, |buffer, cx| {
14804                buffer.group_until_transaction(transaction, cx);
14805            });
14806        }
14807
14808        if self.text_highlights::<InputComposition>(cx).is_none() {
14809            self.ime_transaction.take();
14810        }
14811    }
14812
14813    fn bounds_for_range(
14814        &mut self,
14815        range_utf16: Range<usize>,
14816        element_bounds: gpui::Bounds<Pixels>,
14817        cx: &mut ViewContext<Self>,
14818    ) -> Option<gpui::Bounds<Pixels>> {
14819        let text_layout_details = self.text_layout_details(cx);
14820        let gpui::Point {
14821            x: em_width,
14822            y: line_height,
14823        } = self.character_size(cx);
14824
14825        let snapshot = self.snapshot(cx);
14826        let scroll_position = snapshot.scroll_position();
14827        let scroll_left = scroll_position.x * em_width;
14828
14829        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14830        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14831            + self.gutter_dimensions.width
14832            + self.gutter_dimensions.margin;
14833        let y = line_height * (start.row().as_f32() - scroll_position.y);
14834
14835        Some(Bounds {
14836            origin: element_bounds.origin + point(x, y),
14837            size: size(em_width, line_height),
14838        })
14839    }
14840}
14841
14842trait SelectionExt {
14843    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14844    fn spanned_rows(
14845        &self,
14846        include_end_if_at_line_start: bool,
14847        map: &DisplaySnapshot,
14848    ) -> Range<MultiBufferRow>;
14849}
14850
14851impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14852    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14853        let start = self
14854            .start
14855            .to_point(&map.buffer_snapshot)
14856            .to_display_point(map);
14857        let end = self
14858            .end
14859            .to_point(&map.buffer_snapshot)
14860            .to_display_point(map);
14861        if self.reversed {
14862            end..start
14863        } else {
14864            start..end
14865        }
14866    }
14867
14868    fn spanned_rows(
14869        &self,
14870        include_end_if_at_line_start: bool,
14871        map: &DisplaySnapshot,
14872    ) -> Range<MultiBufferRow> {
14873        let start = self.start.to_point(&map.buffer_snapshot);
14874        let mut end = self.end.to_point(&map.buffer_snapshot);
14875        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14876            end.row -= 1;
14877        }
14878
14879        let buffer_start = map.prev_line_boundary(start).0;
14880        let buffer_end = map.next_line_boundary(end).0;
14881        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14882    }
14883}
14884
14885impl<T: InvalidationRegion> InvalidationStack<T> {
14886    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14887    where
14888        S: Clone + ToOffset,
14889    {
14890        while let Some(region) = self.last() {
14891            let all_selections_inside_invalidation_ranges =
14892                if selections.len() == region.ranges().len() {
14893                    selections
14894                        .iter()
14895                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14896                        .all(|(selection, invalidation_range)| {
14897                            let head = selection.head().to_offset(buffer);
14898                            invalidation_range.start <= head && invalidation_range.end >= head
14899                        })
14900                } else {
14901                    false
14902                };
14903
14904            if all_selections_inside_invalidation_ranges {
14905                break;
14906            } else {
14907                self.pop();
14908            }
14909        }
14910    }
14911}
14912
14913impl<T> Default for InvalidationStack<T> {
14914    fn default() -> Self {
14915        Self(Default::default())
14916    }
14917}
14918
14919impl<T> Deref for InvalidationStack<T> {
14920    type Target = Vec<T>;
14921
14922    fn deref(&self) -> &Self::Target {
14923        &self.0
14924    }
14925}
14926
14927impl<T> DerefMut for InvalidationStack<T> {
14928    fn deref_mut(&mut self) -> &mut Self::Target {
14929        &mut self.0
14930    }
14931}
14932
14933impl InvalidationRegion for SnippetState {
14934    fn ranges(&self) -> &[Range<Anchor>] {
14935        &self.ranges[self.active_index]
14936    }
14937}
14938
14939pub fn diagnostic_block_renderer(
14940    diagnostic: Diagnostic,
14941    max_message_rows: Option<u8>,
14942    allow_closing: bool,
14943    _is_valid: bool,
14944) -> RenderBlock {
14945    let (text_without_backticks, code_ranges) =
14946        highlight_diagnostic_message(&diagnostic, max_message_rows);
14947
14948    Arc::new(move |cx: &mut BlockContext| {
14949        let group_id: SharedString = cx.block_id.to_string().into();
14950
14951        let mut text_style = cx.text_style().clone();
14952        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14953        let theme_settings = ThemeSettings::get_global(cx);
14954        text_style.font_family = theme_settings.buffer_font.family.clone();
14955        text_style.font_style = theme_settings.buffer_font.style;
14956        text_style.font_features = theme_settings.buffer_font.features.clone();
14957        text_style.font_weight = theme_settings.buffer_font.weight;
14958
14959        let multi_line_diagnostic = diagnostic.message.contains('\n');
14960
14961        let buttons = |diagnostic: &Diagnostic| {
14962            if multi_line_diagnostic {
14963                v_flex()
14964            } else {
14965                h_flex()
14966            }
14967            .when(allow_closing, |div| {
14968                div.children(diagnostic.is_primary.then(|| {
14969                    IconButton::new("close-block", IconName::XCircle)
14970                        .icon_color(Color::Muted)
14971                        .size(ButtonSize::Compact)
14972                        .style(ButtonStyle::Transparent)
14973                        .visible_on_hover(group_id.clone())
14974                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14975                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14976                }))
14977            })
14978            .child(
14979                IconButton::new("copy-block", IconName::Copy)
14980                    .icon_color(Color::Muted)
14981                    .size(ButtonSize::Compact)
14982                    .style(ButtonStyle::Transparent)
14983                    .visible_on_hover(group_id.clone())
14984                    .on_click({
14985                        let message = diagnostic.message.clone();
14986                        move |_click, cx| {
14987                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14988                        }
14989                    })
14990                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14991            )
14992        };
14993
14994        let icon_size = buttons(&diagnostic)
14995            .into_any_element()
14996            .layout_as_root(AvailableSpace::min_size(), cx);
14997
14998        h_flex()
14999            .id(cx.block_id)
15000            .group(group_id.clone())
15001            .relative()
15002            .size_full()
15003            .block_mouse_down()
15004            .pl(cx.gutter_dimensions.width)
15005            .w(cx.max_width - cx.gutter_dimensions.full_width())
15006            .child(
15007                div()
15008                    .flex()
15009                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
15010                    .flex_shrink(),
15011            )
15012            .child(buttons(&diagnostic))
15013            .child(div().flex().flex_shrink_0().child(
15014                StyledText::new(text_without_backticks.clone()).with_highlights(
15015                    &text_style,
15016                    code_ranges.iter().map(|range| {
15017                        (
15018                            range.clone(),
15019                            HighlightStyle {
15020                                font_weight: Some(FontWeight::BOLD),
15021                                ..Default::default()
15022                            },
15023                        )
15024                    }),
15025                ),
15026            ))
15027            .into_any_element()
15028    })
15029}
15030
15031fn inline_completion_edit_text(
15032    current_snapshot: &BufferSnapshot,
15033    edits: &[(Range<Anchor>, String)],
15034    edit_preview: &EditPreview,
15035    include_deletions: bool,
15036    cx: &WindowContext,
15037) -> Option<HighlightedEdits> {
15038    let edits = edits
15039        .iter()
15040        .map(|(anchor, text)| {
15041            (
15042                anchor.start.text_anchor..anchor.end.text_anchor,
15043                text.clone(),
15044            )
15045        })
15046        .collect::<Vec<_>>();
15047
15048    Some(edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx))
15049}
15050
15051pub fn highlight_diagnostic_message(
15052    diagnostic: &Diagnostic,
15053    mut max_message_rows: Option<u8>,
15054) -> (SharedString, Vec<Range<usize>>) {
15055    let mut text_without_backticks = String::new();
15056    let mut code_ranges = Vec::new();
15057
15058    if let Some(source) = &diagnostic.source {
15059        text_without_backticks.push_str(source);
15060        code_ranges.push(0..source.len());
15061        text_without_backticks.push_str(": ");
15062    }
15063
15064    let mut prev_offset = 0;
15065    let mut in_code_block = false;
15066    let has_row_limit = max_message_rows.is_some();
15067    let mut newline_indices = diagnostic
15068        .message
15069        .match_indices('\n')
15070        .filter(|_| has_row_limit)
15071        .map(|(ix, _)| ix)
15072        .fuse()
15073        .peekable();
15074
15075    for (quote_ix, _) in diagnostic
15076        .message
15077        .match_indices('`')
15078        .chain([(diagnostic.message.len(), "")])
15079    {
15080        let mut first_newline_ix = None;
15081        let mut last_newline_ix = None;
15082        while let Some(newline_ix) = newline_indices.peek() {
15083            if *newline_ix < quote_ix {
15084                if first_newline_ix.is_none() {
15085                    first_newline_ix = Some(*newline_ix);
15086                }
15087                last_newline_ix = Some(*newline_ix);
15088
15089                if let Some(rows_left) = &mut max_message_rows {
15090                    if *rows_left == 0 {
15091                        break;
15092                    } else {
15093                        *rows_left -= 1;
15094                    }
15095                }
15096                let _ = newline_indices.next();
15097            } else {
15098                break;
15099            }
15100        }
15101        let prev_len = text_without_backticks.len();
15102        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
15103        text_without_backticks.push_str(new_text);
15104        if in_code_block {
15105            code_ranges.push(prev_len..text_without_backticks.len());
15106        }
15107        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15108        in_code_block = !in_code_block;
15109        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15110            text_without_backticks.push_str("...");
15111            break;
15112        }
15113    }
15114
15115    (text_without_backticks.into(), code_ranges)
15116}
15117
15118fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15119    match severity {
15120        DiagnosticSeverity::ERROR => colors.error,
15121        DiagnosticSeverity::WARNING => colors.warning,
15122        DiagnosticSeverity::INFORMATION => colors.info,
15123        DiagnosticSeverity::HINT => colors.info,
15124        _ => colors.ignored,
15125    }
15126}
15127
15128pub fn styled_runs_for_code_label<'a>(
15129    label: &'a CodeLabel,
15130    syntax_theme: &'a theme::SyntaxTheme,
15131) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15132    let fade_out = HighlightStyle {
15133        fade_out: Some(0.35),
15134        ..Default::default()
15135    };
15136
15137    let mut prev_end = label.filter_range.end;
15138    label
15139        .runs
15140        .iter()
15141        .enumerate()
15142        .flat_map(move |(ix, (range, highlight_id))| {
15143            let style = if let Some(style) = highlight_id.style(syntax_theme) {
15144                style
15145            } else {
15146                return Default::default();
15147            };
15148            let mut muted_style = style;
15149            muted_style.highlight(fade_out);
15150
15151            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15152            if range.start >= label.filter_range.end {
15153                if range.start > prev_end {
15154                    runs.push((prev_end..range.start, fade_out));
15155                }
15156                runs.push((range.clone(), muted_style));
15157            } else if range.end <= label.filter_range.end {
15158                runs.push((range.clone(), style));
15159            } else {
15160                runs.push((range.start..label.filter_range.end, style));
15161                runs.push((label.filter_range.end..range.end, muted_style));
15162            }
15163            prev_end = cmp::max(prev_end, range.end);
15164
15165            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15166                runs.push((prev_end..label.text.len(), fade_out));
15167            }
15168
15169            runs
15170        })
15171}
15172
15173pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15174    let mut prev_index = 0;
15175    let mut prev_codepoint: Option<char> = None;
15176    text.char_indices()
15177        .chain([(text.len(), '\0')])
15178        .filter_map(move |(index, codepoint)| {
15179            let prev_codepoint = prev_codepoint.replace(codepoint)?;
15180            let is_boundary = index == text.len()
15181                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15182                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15183            if is_boundary {
15184                let chunk = &text[prev_index..index];
15185                prev_index = index;
15186                Some(chunk)
15187            } else {
15188                None
15189            }
15190        })
15191}
15192
15193pub trait RangeToAnchorExt: Sized {
15194    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15195
15196    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15197        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15198        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15199    }
15200}
15201
15202impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15203    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15204        let start_offset = self.start.to_offset(snapshot);
15205        let end_offset = self.end.to_offset(snapshot);
15206        if start_offset == end_offset {
15207            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15208        } else {
15209            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15210        }
15211    }
15212}
15213
15214pub trait RowExt {
15215    fn as_f32(&self) -> f32;
15216
15217    fn next_row(&self) -> Self;
15218
15219    fn previous_row(&self) -> Self;
15220
15221    fn minus(&self, other: Self) -> u32;
15222}
15223
15224impl RowExt for DisplayRow {
15225    fn as_f32(&self) -> f32 {
15226        self.0 as f32
15227    }
15228
15229    fn next_row(&self) -> Self {
15230        Self(self.0 + 1)
15231    }
15232
15233    fn previous_row(&self) -> Self {
15234        Self(self.0.saturating_sub(1))
15235    }
15236
15237    fn minus(&self, other: Self) -> u32 {
15238        self.0 - other.0
15239    }
15240}
15241
15242impl RowExt for MultiBufferRow {
15243    fn as_f32(&self) -> f32 {
15244        self.0 as f32
15245    }
15246
15247    fn next_row(&self) -> Self {
15248        Self(self.0 + 1)
15249    }
15250
15251    fn previous_row(&self) -> Self {
15252        Self(self.0.saturating_sub(1))
15253    }
15254
15255    fn minus(&self, other: Self) -> u32 {
15256        self.0 - other.0
15257    }
15258}
15259
15260trait RowRangeExt {
15261    type Row;
15262
15263    fn len(&self) -> usize;
15264
15265    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15266}
15267
15268impl RowRangeExt for Range<MultiBufferRow> {
15269    type Row = MultiBufferRow;
15270
15271    fn len(&self) -> usize {
15272        (self.end.0 - self.start.0) as usize
15273    }
15274
15275    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15276        (self.start.0..self.end.0).map(MultiBufferRow)
15277    }
15278}
15279
15280impl RowRangeExt for Range<DisplayRow> {
15281    type Row = DisplayRow;
15282
15283    fn len(&self) -> usize {
15284        (self.end.0 - self.start.0) as usize
15285    }
15286
15287    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15288        (self.start.0..self.end.0).map(DisplayRow)
15289    }
15290}
15291
15292/// If select range has more than one line, we
15293/// just point the cursor to range.start.
15294fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
15295    if range.start.row == range.end.row {
15296        range
15297    } else {
15298        range.start..range.start
15299    }
15300}
15301pub struct KillRing(ClipboardItem);
15302impl Global for KillRing {}
15303
15304const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
15305
15306fn all_edits_insertions_or_deletions(
15307    edits: &Vec<(Range<Anchor>, String)>,
15308    snapshot: &MultiBufferSnapshot,
15309) -> bool {
15310    let mut all_insertions = true;
15311    let mut all_deletions = true;
15312
15313    for (range, new_text) in edits.iter() {
15314        let range_is_empty = range.to_offset(&snapshot).is_empty();
15315        let text_is_empty = new_text.is_empty();
15316
15317        if range_is_empty != text_is_empty {
15318            if range_is_empty {
15319                all_deletions = false;
15320            } else {
15321                all_insertions = false;
15322            }
15323        } else {
15324            return false;
15325        }
15326
15327        if !all_insertions && !all_deletions {
15328            return false;
15329        }
15330    }
15331    all_insertions || all_deletions
15332}