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;
   19pub mod display_map;
   20mod editor_settings;
   21mod editor_settings_controls;
   22mod element;
   23mod git;
   24mod highlight_matching_bracket;
   25mod hover_links;
   26mod hover_popover;
   27mod hunk_diff;
   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, Bound, 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::{StringMatch, StringMatchCandidate};
   72use git::blame::GitBlame;
   73use gpui::{
   74    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   75    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
   76    ClipboardItem, Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent,
   77    FocusableView, FontId, FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext,
   78    ListSizingBehavior, Model, ModelContext, MouseButton, PaintQuad, ParentElement, Pixels, Render,
   79    ScrollStrategy, SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task,
   80    TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, View,
   81    ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle, WeakView, WindowContext,
   82};
   83use highlight_matching_bracket::refresh_matching_bracket_highlights;
   84use hover_popover::{hide_hover, HoverState};
   85pub(crate) use hunk_diff::HoveredHunk;
   86use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
   87use indent_guides::ActiveIndentGuidesState;
   88use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   89pub use inline_completion::Direction;
   90use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
   91pub use items::MAX_TAB_TITLE_LEN;
   92use itertools::Itertools;
   93use language::{
   94    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
   95    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   96    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   97    Point, Selection, SelectionGoal, TransactionId,
   98};
   99use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  100use linked_editing_ranges::refresh_linked_ranges;
  101pub use proposed_changes_editor::{
  102    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  103};
  104use similar::{ChangeTag, TextDiff};
  105use std::iter::Peekable;
  106use task::{ResolvedTask, TaskTemplate, TaskVariables};
  107
  108use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  109pub use lsp::CompletionContext;
  110use lsp::{
  111    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  112    LanguageServerId, LanguageServerName,
  113};
  114use mouse_context_menu::MouseContextMenu;
  115use movement::TextLayoutDetails;
  116pub use multi_buffer::{
  117    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  118    ToPoint,
  119};
  120use multi_buffer::{
  121    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  122};
  123use ordered_float::OrderedFloat;
  124use parking_lot::RwLock;
  125use project::{
  126    lsp_store::{FormatTarget, FormatTrigger},
  127    project_settings::{GitGutterSetting, ProjectSettings},
  128    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  129    Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  130};
  131use rand::prelude::*;
  132use rpc::{proto::*, ErrorExt};
  133use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  134use selections_collection::{
  135    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  136};
  137use serde::{Deserialize, Serialize};
  138use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  139use smallvec::SmallVec;
  140use snippet::Snippet;
  141use std::{
  142    any::TypeId,
  143    borrow::Cow,
  144    cell::{Cell, RefCell},
  145    cmp::{self, Ordering, Reverse},
  146    mem,
  147    num::NonZeroU32,
  148    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  149    path::{Path, PathBuf},
  150    rc::Rc,
  151    sync::Arc,
  152    time::{Duration, Instant},
  153};
  154pub use sum_tree::Bias;
  155use sum_tree::TreeMap;
  156use text::{BufferId, OffsetUtf16, Rope};
  157use theme::{
  158    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  159    ThemeColors, ThemeSettings,
  160};
  161use ui::{
  162    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  163    ListItem, Popover, PopoverMenuHandle, Tooltip,
  164};
  165use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  166use workspace::item::{ItemHandle, PreviewTabsSettings};
  167use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  168use workspace::{
  169    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  170};
  171use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  172
  173use crate::hover_links::find_url;
  174use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  175
  176pub const FILE_HEADER_HEIGHT: u32 = 2;
  177pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  178pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  179pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  180const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  181const MAX_LINE_LEN: usize = 1024;
  182const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  183const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  184pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  185#[doc(hidden)]
  186pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  187#[doc(hidden)]
  188pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  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(crate) enum InlayId {
  258    Suggestion(usize),
  259    Hint(usize),
  260}
  261
  262impl InlayId {
  263    fn id(&self) -> usize {
  264        match self {
  265            Self::Suggestion(id) => *id,
  266            Self::Hint(id) => *id,
  267        }
  268    }
  269}
  270
  271enum DiffRowHighlight {}
  272enum DocumentHighlightRead {}
  273enum DocumentHighlightWrite {}
  274enum InputComposition {}
  275
  276#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  277pub enum Navigated {
  278    Yes,
  279    No,
  280}
  281
  282impl Navigated {
  283    pub fn from_bool(yes: bool) -> Navigated {
  284        if yes {
  285            Navigated::Yes
  286        } else {
  287            Navigated::No
  288        }
  289    }
  290}
  291
  292pub fn init_settings(cx: &mut AppContext) {
  293    EditorSettings::register(cx);
  294}
  295
  296pub fn init(cx: &mut AppContext) {
  297    init_settings(cx);
  298
  299    workspace::register_project_item::<Editor>(cx);
  300    workspace::FollowableViewRegistry::register::<Editor>(cx);
  301    workspace::register_serializable_item::<Editor>(cx);
  302
  303    cx.observe_new_views(
  304        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  305            workspace.register_action(Editor::new_file);
  306            workspace.register_action(Editor::new_file_vertical);
  307            workspace.register_action(Editor::new_file_horizontal);
  308        },
  309    )
  310    .detach();
  311
  312    cx.on_action(move |_: &workspace::NewFile, cx| {
  313        let app_state = workspace::AppState::global(cx);
  314        if let Some(app_state) = app_state.upgrade() {
  315            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  316                Editor::new_file(workspace, &Default::default(), cx)
  317            })
  318            .detach();
  319        }
  320    });
  321    cx.on_action(move |_: &workspace::NewWindow, cx| {
  322        let app_state = workspace::AppState::global(cx);
  323        if let Some(app_state) = app_state.upgrade() {
  324            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  325                Editor::new_file(workspace, &Default::default(), cx)
  326            })
  327            .detach();
  328        }
  329    });
  330    git::project_diff::init(cx);
  331}
  332
  333pub struct SearchWithinRange;
  334
  335trait InvalidationRegion {
  336    fn ranges(&self) -> &[Range<Anchor>];
  337}
  338
  339#[derive(Clone, Debug, PartialEq)]
  340pub enum SelectPhase {
  341    Begin {
  342        position: DisplayPoint,
  343        add: bool,
  344        click_count: usize,
  345    },
  346    BeginColumnar {
  347        position: DisplayPoint,
  348        reset: bool,
  349        goal_column: u32,
  350    },
  351    Extend {
  352        position: DisplayPoint,
  353        click_count: usize,
  354    },
  355    Update {
  356        position: DisplayPoint,
  357        goal_column: u32,
  358        scroll_delta: gpui::Point<f32>,
  359    },
  360    End,
  361}
  362
  363#[derive(Clone, Debug)]
  364pub enum SelectMode {
  365    Character,
  366    Word(Range<Anchor>),
  367    Line(Range<Anchor>),
  368    All,
  369}
  370
  371#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  372pub enum EditorMode {
  373    SingleLine { auto_width: bool },
  374    AutoHeight { max_lines: usize },
  375    Full,
  376}
  377
  378#[derive(Copy, Clone, Debug)]
  379pub enum SoftWrap {
  380    /// Prefer not to wrap at all.
  381    ///
  382    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  383    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  384    GitDiff,
  385    /// Prefer a single line generally, unless an overly long line is encountered.
  386    None,
  387    /// Soft wrap lines that exceed the editor width.
  388    EditorWidth,
  389    /// Soft wrap lines at the preferred line length.
  390    Column(u32),
  391    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  392    Bounded(u32),
  393}
  394
  395#[derive(Clone)]
  396pub struct EditorStyle {
  397    pub background: Hsla,
  398    pub local_player: PlayerColor,
  399    pub text: TextStyle,
  400    pub scrollbar_width: Pixels,
  401    pub syntax: Arc<SyntaxTheme>,
  402    pub status: StatusColors,
  403    pub inlay_hints_style: HighlightStyle,
  404    pub suggestions_style: HighlightStyle,
  405    pub unnecessary_code_fade: f32,
  406}
  407
  408impl Default for EditorStyle {
  409    fn default() -> Self {
  410        Self {
  411            background: Hsla::default(),
  412            local_player: PlayerColor::default(),
  413            text: TextStyle::default(),
  414            scrollbar_width: Pixels::default(),
  415            syntax: Default::default(),
  416            // HACK: Status colors don't have a real default.
  417            // We should look into removing the status colors from the editor
  418            // style and retrieve them directly from the theme.
  419            status: StatusColors::dark(),
  420            inlay_hints_style: HighlightStyle::default(),
  421            suggestions_style: HighlightStyle::default(),
  422            unnecessary_code_fade: Default::default(),
  423        }
  424    }
  425}
  426
  427pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  428    let show_background = language_settings::language_settings(None, None, cx)
  429        .inlay_hints
  430        .show_background;
  431
  432    HighlightStyle {
  433        color: Some(cx.theme().status().hint),
  434        background_color: show_background.then(|| cx.theme().status().hint_background),
  435        ..HighlightStyle::default()
  436    }
  437}
  438
  439type CompletionId = usize;
  440
  441enum InlineCompletion {
  442    Edit(Vec<(Range<Anchor>, String)>),
  443    Move(Anchor),
  444}
  445
  446struct InlineCompletionState {
  447    inlay_ids: Vec<InlayId>,
  448    completion: InlineCompletion,
  449    invalidation_range: Range<Anchor>,
  450}
  451
  452enum InlineCompletionHighlight {}
  453
  454#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  455struct EditorActionId(usize);
  456
  457impl EditorActionId {
  458    pub fn post_inc(&mut self) -> Self {
  459        let answer = self.0;
  460
  461        *self = Self(answer + 1);
  462
  463        Self(answer)
  464    }
  465}
  466
  467// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  468// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  469
  470type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  471type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  472
  473#[derive(Default)]
  474struct ScrollbarMarkerState {
  475    scrollbar_size: Size<Pixels>,
  476    dirty: bool,
  477    markers: Arc<[PaintQuad]>,
  478    pending_refresh: Option<Task<Result<()>>>,
  479}
  480
  481impl ScrollbarMarkerState {
  482    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  483        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  484    }
  485}
  486
  487#[derive(Clone, Debug)]
  488struct RunnableTasks {
  489    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  490    offset: MultiBufferOffset,
  491    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  492    column: u32,
  493    // Values of all named captures, including those starting with '_'
  494    extra_variables: HashMap<String, String>,
  495    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  496    context_range: Range<BufferOffset>,
  497}
  498
  499impl RunnableTasks {
  500    fn resolve<'a>(
  501        &'a self,
  502        cx: &'a task::TaskContext,
  503    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  504        self.templates.iter().filter_map(|(kind, template)| {
  505            template
  506                .resolve_task(&kind.to_id_base(), cx)
  507                .map(|task| (kind.clone(), task))
  508        })
  509    }
  510}
  511
  512#[derive(Clone)]
  513struct ResolvedTasks {
  514    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  515    position: Anchor,
  516}
  517#[derive(Copy, Clone, Debug)]
  518struct MultiBufferOffset(usize);
  519#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  520struct BufferOffset(usize);
  521
  522// Addons allow storing per-editor state in other crates (e.g. Vim)
  523pub trait Addon: 'static {
  524    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  525
  526    fn to_any(&self) -> &dyn std::any::Any;
  527}
  528
  529#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  530pub enum IsVimMode {
  531    Yes,
  532    No,
  533}
  534
  535/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  536///
  537/// See the [module level documentation](self) for more information.
  538pub struct Editor {
  539    focus_handle: FocusHandle,
  540    last_focused_descendant: Option<WeakFocusHandle>,
  541    /// The text buffer being edited
  542    buffer: Model<MultiBuffer>,
  543    /// Map of how text in the buffer should be displayed.
  544    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  545    pub display_map: Model<DisplayMap>,
  546    pub selections: SelectionsCollection,
  547    pub scroll_manager: ScrollManager,
  548    /// When inline assist editors are linked, they all render cursors because
  549    /// typing enters text into each of them, even the ones that aren't focused.
  550    pub(crate) show_cursor_when_unfocused: bool,
  551    columnar_selection_tail: Option<Anchor>,
  552    add_selections_state: Option<AddSelectionsState>,
  553    select_next_state: Option<SelectNextState>,
  554    select_prev_state: Option<SelectNextState>,
  555    selection_history: SelectionHistory,
  556    autoclose_regions: Vec<AutocloseRegion>,
  557    snippet_stack: InvalidationStack<SnippetState>,
  558    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  559    ime_transaction: Option<TransactionId>,
  560    active_diagnostics: Option<ActiveDiagnosticGroup>,
  561    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  562
  563    project: Option<Model<Project>>,
  564    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  565    completion_provider: Option<Box<dyn CompletionProvider>>,
  566    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  567    blink_manager: Model<BlinkManager>,
  568    show_cursor_names: bool,
  569    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  570    pub show_local_selections: bool,
  571    mode: EditorMode,
  572    show_breadcrumbs: bool,
  573    show_gutter: bool,
  574    show_line_numbers: Option<bool>,
  575    use_relative_line_numbers: Option<bool>,
  576    show_git_diff_gutter: Option<bool>,
  577    show_code_actions: Option<bool>,
  578    show_runnables: Option<bool>,
  579    show_wrap_guides: Option<bool>,
  580    show_indent_guides: Option<bool>,
  581    placeholder_text: Option<Arc<str>>,
  582    highlight_order: usize,
  583    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  584    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  585    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  586    scrollbar_marker_state: ScrollbarMarkerState,
  587    active_indent_guides_state: ActiveIndentGuidesState,
  588    nav_history: Option<ItemNavHistory>,
  589    context_menu: RwLock<Option<ContextMenu>>,
  590    mouse_context_menu: Option<MouseContextMenu>,
  591    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  592    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  593    signature_help_state: SignatureHelpState,
  594    auto_signature_help: Option<bool>,
  595    find_all_references_task_sources: Vec<Anchor>,
  596    next_completion_id: CompletionId,
  597    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  598    code_actions_task: Option<Task<Result<()>>>,
  599    document_highlights_task: Option<Task<()>>,
  600    linked_editing_range_task: Option<Task<Option<()>>>,
  601    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  602    pending_rename: Option<RenameState>,
  603    searchable: bool,
  604    cursor_shape: CursorShape,
  605    current_line_highlight: Option<CurrentLineHighlight>,
  606    collapse_matches: bool,
  607    autoindent_mode: Option<AutoindentMode>,
  608    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  609    input_enabled: bool,
  610    use_modal_editing: bool,
  611    read_only: bool,
  612    leader_peer_id: Option<PeerId>,
  613    remote_id: Option<ViewId>,
  614    hover_state: HoverState,
  615    gutter_hovered: bool,
  616    hovered_link_state: Option<HoveredLinkState>,
  617    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  618    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  619    active_inline_completion: Option<InlineCompletionState>,
  620    // enable_inline_completions is a switch that Vim can use to disable
  621    // inline completions based on its mode.
  622    enable_inline_completions: bool,
  623    show_inline_completions_override: Option<bool>,
  624    inlay_hint_cache: InlayHintCache,
  625    diff_map: DiffMap,
  626    next_inlay_id: usize,
  627    _subscriptions: Vec<Subscription>,
  628    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  629    gutter_dimensions: GutterDimensions,
  630    style: Option<EditorStyle>,
  631    text_style_refinement: Option<TextStyleRefinement>,
  632    next_editor_action_id: EditorActionId,
  633    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  634    use_autoclose: bool,
  635    use_auto_surround: bool,
  636    auto_replace_emoji_shortcode: bool,
  637    show_git_blame_gutter: bool,
  638    show_git_blame_inline: bool,
  639    show_git_blame_inline_delay_task: Option<Task<()>>,
  640    git_blame_inline_enabled: bool,
  641    serialize_dirty_buffers: bool,
  642    show_selection_menu: Option<bool>,
  643    blame: Option<Model<GitBlame>>,
  644    blame_subscription: Option<Subscription>,
  645    custom_context_menu: Option<
  646        Box<
  647            dyn 'static
  648                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  649        >,
  650    >,
  651    last_bounds: Option<Bounds<Pixels>>,
  652    expect_bounds_change: Option<Bounds<Pixels>>,
  653    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  654    tasks_update_task: Option<Task<()>>,
  655    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  656    breadcrumb_header: Option<String>,
  657    focused_block: Option<FocusedBlock>,
  658    next_scroll_position: NextScrollCursorCenterTopBottom,
  659    addons: HashMap<TypeId, Box<dyn Addon>>,
  660    _scroll_cursor_center_top_bottom_task: Task<()>,
  661}
  662
  663#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  664enum NextScrollCursorCenterTopBottom {
  665    #[default]
  666    Center,
  667    Top,
  668    Bottom,
  669}
  670
  671impl NextScrollCursorCenterTopBottom {
  672    fn next(&self) -> Self {
  673        match self {
  674            Self::Center => Self::Top,
  675            Self::Top => Self::Bottom,
  676            Self::Bottom => Self::Center,
  677        }
  678    }
  679}
  680
  681#[derive(Clone)]
  682pub struct EditorSnapshot {
  683    pub mode: EditorMode,
  684    show_gutter: bool,
  685    show_line_numbers: Option<bool>,
  686    show_git_diff_gutter: Option<bool>,
  687    show_code_actions: Option<bool>,
  688    show_runnables: Option<bool>,
  689    git_blame_gutter_max_author_length: Option<usize>,
  690    pub display_snapshot: DisplaySnapshot,
  691    pub placeholder_text: Option<Arc<str>>,
  692    diff_map: DiffMapSnapshot,
  693    is_focused: bool,
  694    scroll_anchor: ScrollAnchor,
  695    ongoing_scroll: OngoingScroll,
  696    current_line_highlight: CurrentLineHighlight,
  697    gutter_hovered: bool,
  698}
  699
  700const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  701
  702#[derive(Default, Debug, Clone, Copy)]
  703pub struct GutterDimensions {
  704    pub left_padding: Pixels,
  705    pub right_padding: Pixels,
  706    pub width: Pixels,
  707    pub margin: Pixels,
  708    pub git_blame_entries_width: Option<Pixels>,
  709}
  710
  711impl GutterDimensions {
  712    /// The full width of the space taken up by the gutter.
  713    pub fn full_width(&self) -> Pixels {
  714        self.margin + self.width
  715    }
  716
  717    /// The width of the space reserved for the fold indicators,
  718    /// use alongside 'justify_end' and `gutter_width` to
  719    /// right align content with the line numbers
  720    pub fn fold_area_width(&self) -> Pixels {
  721        self.margin + self.right_padding
  722    }
  723}
  724
  725#[derive(Debug)]
  726pub struct RemoteSelection {
  727    pub replica_id: ReplicaId,
  728    pub selection: Selection<Anchor>,
  729    pub cursor_shape: CursorShape,
  730    pub peer_id: PeerId,
  731    pub line_mode: bool,
  732    pub participant_index: Option<ParticipantIndex>,
  733    pub user_name: Option<SharedString>,
  734}
  735
  736#[derive(Clone, Debug)]
  737struct SelectionHistoryEntry {
  738    selections: Arc<[Selection<Anchor>]>,
  739    select_next_state: Option<SelectNextState>,
  740    select_prev_state: Option<SelectNextState>,
  741    add_selections_state: Option<AddSelectionsState>,
  742}
  743
  744enum SelectionHistoryMode {
  745    Normal,
  746    Undoing,
  747    Redoing,
  748}
  749
  750#[derive(Clone, PartialEq, Eq, Hash)]
  751struct HoveredCursor {
  752    replica_id: u16,
  753    selection_id: usize,
  754}
  755
  756impl Default for SelectionHistoryMode {
  757    fn default() -> Self {
  758        Self::Normal
  759    }
  760}
  761
  762#[derive(Default)]
  763struct SelectionHistory {
  764    #[allow(clippy::type_complexity)]
  765    selections_by_transaction:
  766        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  767    mode: SelectionHistoryMode,
  768    undo_stack: VecDeque<SelectionHistoryEntry>,
  769    redo_stack: VecDeque<SelectionHistoryEntry>,
  770}
  771
  772impl SelectionHistory {
  773    fn insert_transaction(
  774        &mut self,
  775        transaction_id: TransactionId,
  776        selections: Arc<[Selection<Anchor>]>,
  777    ) {
  778        self.selections_by_transaction
  779            .insert(transaction_id, (selections, None));
  780    }
  781
  782    #[allow(clippy::type_complexity)]
  783    fn transaction(
  784        &self,
  785        transaction_id: TransactionId,
  786    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  787        self.selections_by_transaction.get(&transaction_id)
  788    }
  789
  790    #[allow(clippy::type_complexity)]
  791    fn transaction_mut(
  792        &mut self,
  793        transaction_id: TransactionId,
  794    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  795        self.selections_by_transaction.get_mut(&transaction_id)
  796    }
  797
  798    fn push(&mut self, entry: SelectionHistoryEntry) {
  799        if !entry.selections.is_empty() {
  800            match self.mode {
  801                SelectionHistoryMode::Normal => {
  802                    self.push_undo(entry);
  803                    self.redo_stack.clear();
  804                }
  805                SelectionHistoryMode::Undoing => self.push_redo(entry),
  806                SelectionHistoryMode::Redoing => self.push_undo(entry),
  807            }
  808        }
  809    }
  810
  811    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  812        if self
  813            .undo_stack
  814            .back()
  815            .map_or(true, |e| e.selections != entry.selections)
  816        {
  817            self.undo_stack.push_back(entry);
  818            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  819                self.undo_stack.pop_front();
  820            }
  821        }
  822    }
  823
  824    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  825        if self
  826            .redo_stack
  827            .back()
  828            .map_or(true, |e| e.selections != entry.selections)
  829        {
  830            self.redo_stack.push_back(entry);
  831            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  832                self.redo_stack.pop_front();
  833            }
  834        }
  835    }
  836}
  837
  838struct RowHighlight {
  839    index: usize,
  840    range: Range<Anchor>,
  841    color: Hsla,
  842    should_autoscroll: bool,
  843}
  844
  845#[derive(Clone, Debug)]
  846struct AddSelectionsState {
  847    above: bool,
  848    stack: Vec<usize>,
  849}
  850
  851#[derive(Clone)]
  852struct SelectNextState {
  853    query: AhoCorasick,
  854    wordwise: bool,
  855    done: bool,
  856}
  857
  858impl std::fmt::Debug for SelectNextState {
  859    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  860        f.debug_struct(std::any::type_name::<Self>())
  861            .field("wordwise", &self.wordwise)
  862            .field("done", &self.done)
  863            .finish()
  864    }
  865}
  866
  867#[derive(Debug)]
  868struct AutocloseRegion {
  869    selection_id: usize,
  870    range: Range<Anchor>,
  871    pair: BracketPair,
  872}
  873
  874#[derive(Debug)]
  875struct SnippetState {
  876    ranges: Vec<Vec<Range<Anchor>>>,
  877    active_index: usize,
  878    choices: Vec<Option<Vec<String>>>,
  879}
  880
  881#[doc(hidden)]
  882pub struct RenameState {
  883    pub range: Range<Anchor>,
  884    pub old_name: Arc<str>,
  885    pub editor: View<Editor>,
  886    block_id: CustomBlockId,
  887}
  888
  889struct InvalidationStack<T>(Vec<T>);
  890
  891struct RegisteredInlineCompletionProvider {
  892    provider: Arc<dyn InlineCompletionProviderHandle>,
  893    _subscription: Subscription,
  894}
  895
  896enum ContextMenu {
  897    Completions(CompletionsMenu),
  898    CodeActions(CodeActionsMenu),
  899}
  900
  901impl ContextMenu {
  902    fn select_first(
  903        &mut self,
  904        provider: Option<&dyn CompletionProvider>,
  905        cx: &mut ViewContext<Editor>,
  906    ) -> bool {
  907        if self.visible() {
  908            match self {
  909                ContextMenu::Completions(menu) => menu.select_first(provider, cx),
  910                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  911            }
  912            true
  913        } else {
  914            false
  915        }
  916    }
  917
  918    fn select_prev(
  919        &mut self,
  920        provider: Option<&dyn CompletionProvider>,
  921        cx: &mut ViewContext<Editor>,
  922    ) -> bool {
  923        if self.visible() {
  924            match self {
  925                ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
  926                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  927            }
  928            true
  929        } else {
  930            false
  931        }
  932    }
  933
  934    fn select_next(
  935        &mut self,
  936        provider: Option<&dyn CompletionProvider>,
  937        cx: &mut ViewContext<Editor>,
  938    ) -> bool {
  939        if self.visible() {
  940            match self {
  941                ContextMenu::Completions(menu) => menu.select_next(provider, cx),
  942                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  943            }
  944            true
  945        } else {
  946            false
  947        }
  948    }
  949
  950    fn select_last(
  951        &mut self,
  952        provider: Option<&dyn CompletionProvider>,
  953        cx: &mut ViewContext<Editor>,
  954    ) -> bool {
  955        if self.visible() {
  956            match self {
  957                ContextMenu::Completions(menu) => menu.select_last(provider, cx),
  958                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  959            }
  960            true
  961        } else {
  962            false
  963        }
  964    }
  965
  966    fn visible(&self) -> bool {
  967        match self {
  968            ContextMenu::Completions(menu) => menu.visible(),
  969            ContextMenu::CodeActions(menu) => menu.visible(),
  970        }
  971    }
  972
  973    fn render(
  974        &self,
  975        cursor_position: DisplayPoint,
  976        style: &EditorStyle,
  977        max_height: Pixels,
  978        workspace: Option<WeakView<Workspace>>,
  979        cx: &mut ViewContext<Editor>,
  980    ) -> (ContextMenuOrigin, AnyElement) {
  981        match self {
  982            ContextMenu::Completions(menu) => (
  983                ContextMenuOrigin::EditorPoint(cursor_position),
  984                menu.render(style, max_height, workspace, cx),
  985            ),
  986            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  987        }
  988    }
  989}
  990
  991enum ContextMenuOrigin {
  992    EditorPoint(DisplayPoint),
  993    GutterIndicator(DisplayRow),
  994}
  995
  996#[derive(Clone, Debug)]
  997struct CompletionsMenu {
  998    id: CompletionId,
  999    sort_completions: bool,
 1000    initial_position: Anchor,
 1001    buffer: Model<Buffer>,
 1002    completions: Arc<RwLock<Box<[Completion]>>>,
 1003    match_candidates: Arc<[StringMatchCandidate]>,
 1004    matches: Arc<[StringMatch]>,
 1005    selected_item: usize,
 1006    scroll_handle: UniformListScrollHandle,
 1007    resolve_completions: bool,
 1008    aside_was_displayed: Cell<bool>,
 1009}
 1010
 1011impl CompletionsMenu {
 1012    fn new(
 1013        id: CompletionId,
 1014        sort_completions: bool,
 1015        initial_position: Anchor,
 1016        buffer: Model<Buffer>,
 1017        completions: Box<[Completion]>,
 1018        aside_was_displayed: bool,
 1019    ) -> Self {
 1020        let match_candidates = completions
 1021            .iter()
 1022            .enumerate()
 1023            .map(|(id, completion)| {
 1024                StringMatchCandidate::new(
 1025                    id,
 1026                    completion.label.text[completion.label.filter_range.clone()].into(),
 1027                )
 1028            })
 1029            .collect();
 1030
 1031        Self {
 1032            id,
 1033            sort_completions,
 1034            initial_position,
 1035            buffer,
 1036            completions: Arc::new(RwLock::new(completions)),
 1037            match_candidates,
 1038            matches: Vec::new().into(),
 1039            selected_item: 0,
 1040            scroll_handle: UniformListScrollHandle::new(),
 1041            resolve_completions: true,
 1042            aside_was_displayed: Cell::new(aside_was_displayed),
 1043        }
 1044    }
 1045
 1046    fn new_snippet_choices(
 1047        id: CompletionId,
 1048        sort_completions: bool,
 1049        choices: &Vec<String>,
 1050        selection: Range<Anchor>,
 1051        buffer: Model<Buffer>,
 1052    ) -> Self {
 1053        let completions = choices
 1054            .iter()
 1055            .map(|choice| Completion {
 1056                old_range: selection.start.text_anchor..selection.end.text_anchor,
 1057                new_text: choice.to_string(),
 1058                label: CodeLabel {
 1059                    text: choice.to_string(),
 1060                    runs: Default::default(),
 1061                    filter_range: Default::default(),
 1062                },
 1063                server_id: LanguageServerId(usize::MAX),
 1064                documentation: None,
 1065                lsp_completion: Default::default(),
 1066                confirm: None,
 1067            })
 1068            .collect();
 1069
 1070        let match_candidates = choices
 1071            .iter()
 1072            .enumerate()
 1073            .map(|(id, completion)| StringMatchCandidate::new(id, completion.to_string()))
 1074            .collect();
 1075        let matches = choices
 1076            .iter()
 1077            .enumerate()
 1078            .map(|(id, completion)| StringMatch {
 1079                candidate_id: id,
 1080                score: 1.,
 1081                positions: vec![],
 1082                string: completion.clone(),
 1083            })
 1084            .collect();
 1085        Self {
 1086            id,
 1087            sort_completions,
 1088            initial_position: selection.start,
 1089            buffer,
 1090            completions: Arc::new(RwLock::new(completions)),
 1091            match_candidates,
 1092            matches,
 1093            selected_item: 0,
 1094            scroll_handle: UniformListScrollHandle::new(),
 1095            resolve_completions: false,
 1096            aside_was_displayed: Cell::new(false),
 1097        }
 1098    }
 1099
 1100    fn select_first(
 1101        &mut self,
 1102        provider: Option<&dyn CompletionProvider>,
 1103        cx: &mut ViewContext<Editor>,
 1104    ) {
 1105        self.selected_item = 0;
 1106        self.scroll_handle
 1107            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1108        self.resolve_selected_completion(provider, cx);
 1109        cx.notify();
 1110    }
 1111
 1112    fn select_prev(
 1113        &mut self,
 1114        provider: Option<&dyn CompletionProvider>,
 1115        cx: &mut ViewContext<Editor>,
 1116    ) {
 1117        if self.selected_item > 0 {
 1118            self.selected_item -= 1;
 1119        } else {
 1120            self.selected_item = self.matches.len() - 1;
 1121        }
 1122        self.scroll_handle
 1123            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1124        self.resolve_selected_completion(provider, cx);
 1125        cx.notify();
 1126    }
 1127
 1128    fn select_next(
 1129        &mut self,
 1130        provider: Option<&dyn CompletionProvider>,
 1131        cx: &mut ViewContext<Editor>,
 1132    ) {
 1133        if self.selected_item + 1 < self.matches.len() {
 1134            self.selected_item += 1;
 1135        } else {
 1136            self.selected_item = 0;
 1137        }
 1138        self.scroll_handle
 1139            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1140        self.resolve_selected_completion(provider, cx);
 1141        cx.notify();
 1142    }
 1143
 1144    fn select_last(
 1145        &mut self,
 1146        provider: Option<&dyn CompletionProvider>,
 1147        cx: &mut ViewContext<Editor>,
 1148    ) {
 1149        self.selected_item = self.matches.len() - 1;
 1150        self.scroll_handle
 1151            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1152        self.resolve_selected_completion(provider, cx);
 1153        cx.notify();
 1154    }
 1155
 1156    fn resolve_selected_completion(
 1157        &mut self,
 1158        provider: Option<&dyn CompletionProvider>,
 1159        cx: &mut ViewContext<Editor>,
 1160    ) {
 1161        if !self.resolve_completions {
 1162            return;
 1163        }
 1164        let Some(provider) = provider else {
 1165            return;
 1166        };
 1167
 1168        let completion_index = self.matches[self.selected_item].candidate_id;
 1169        let resolve_task = provider.resolve_completions(
 1170            self.buffer.clone(),
 1171            vec![completion_index],
 1172            self.completions.clone(),
 1173            cx,
 1174        );
 1175
 1176        cx.spawn(move |editor, mut cx| async move {
 1177            if let Some(true) = resolve_task.await.log_err() {
 1178                editor.update(&mut cx, |_, cx| cx.notify()).ok();
 1179            }
 1180        })
 1181        .detach();
 1182    }
 1183
 1184    fn visible(&self) -> bool {
 1185        !self.matches.is_empty()
 1186    }
 1187
 1188    fn render(
 1189        &self,
 1190        style: &EditorStyle,
 1191        max_height: Pixels,
 1192        workspace: Option<WeakView<Workspace>>,
 1193        cx: &mut ViewContext<Editor>,
 1194    ) -> AnyElement {
 1195        let settings = EditorSettings::get_global(cx);
 1196        let show_completion_documentation = settings.show_completion_documentation;
 1197
 1198        let widest_completion_ix = self
 1199            .matches
 1200            .iter()
 1201            .enumerate()
 1202            .max_by_key(|(_, mat)| {
 1203                let completions = self.completions.read();
 1204                let completion = &completions[mat.candidate_id];
 1205                let documentation = &completion.documentation;
 1206
 1207                let mut len = completion.label.text.chars().count();
 1208                if let Some(Documentation::SingleLine(text)) = documentation {
 1209                    if show_completion_documentation {
 1210                        len += text.chars().count();
 1211                    }
 1212                }
 1213
 1214                len
 1215            })
 1216            .map(|(ix, _)| ix);
 1217
 1218        let completions = self.completions.clone();
 1219        let matches = self.matches.clone();
 1220        let selected_item = self.selected_item;
 1221        let style = style.clone();
 1222
 1223        let multiline_docs = if show_completion_documentation {
 1224            let mat = &self.matches[selected_item];
 1225            match &self.completions.read()[mat.candidate_id].documentation {
 1226                Some(Documentation::MultiLinePlainText(text)) => {
 1227                    Some(div().child(SharedString::from(text.clone())))
 1228                }
 1229                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1230                    Some(div().child(render_parsed_markdown(
 1231                        "completions_markdown",
 1232                        parsed,
 1233                        &style,
 1234                        workspace,
 1235                        cx,
 1236                    )))
 1237                }
 1238                Some(Documentation::Undocumented) if self.aside_was_displayed.get() => {
 1239                    Some(div().child("No documentation"))
 1240                }
 1241                _ => None,
 1242            }
 1243        } else {
 1244            None
 1245        };
 1246
 1247        let aside_contents = if let Some(multiline_docs) = multiline_docs {
 1248            Some(multiline_docs)
 1249        } else if self.aside_was_displayed.get() {
 1250            Some(div().child("Fetching documentation..."))
 1251        } else {
 1252            None
 1253        };
 1254        self.aside_was_displayed.set(aside_contents.is_some());
 1255
 1256        let aside_contents = aside_contents.map(|div| {
 1257            div.id("multiline_docs")
 1258                .max_h(max_height)
 1259                .flex_1()
 1260                .px_1p5()
 1261                .py_1()
 1262                .min_w(px(260.))
 1263                .max_w(px(640.))
 1264                .w(px(500.))
 1265                .overflow_y_scroll()
 1266                .occlude()
 1267        });
 1268
 1269        let list = uniform_list(
 1270            cx.view().clone(),
 1271            "completions",
 1272            matches.len(),
 1273            move |_editor, range, cx| {
 1274                let start_ix = range.start;
 1275                let completions_guard = completions.read();
 1276
 1277                matches[range]
 1278                    .iter()
 1279                    .enumerate()
 1280                    .map(|(ix, mat)| {
 1281                        let item_ix = start_ix + ix;
 1282                        let candidate_id = mat.candidate_id;
 1283                        let completion = &completions_guard[candidate_id];
 1284
 1285                        let documentation = if show_completion_documentation {
 1286                            &completion.documentation
 1287                        } else {
 1288                            &None
 1289                        };
 1290
 1291                        let highlights = gpui::combine_highlights(
 1292                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1293                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1294                                |(range, mut highlight)| {
 1295                                    // Ignore font weight for syntax highlighting, as we'll use it
 1296                                    // for fuzzy matches.
 1297                                    highlight.font_weight = None;
 1298
 1299                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1300                                        highlight.strikethrough = Some(StrikethroughStyle {
 1301                                            thickness: 1.0.into(),
 1302                                            ..Default::default()
 1303                                        });
 1304                                        highlight.color = Some(cx.theme().colors().text_muted);
 1305                                    }
 1306
 1307                                    (range, highlight)
 1308                                },
 1309                            ),
 1310                        );
 1311                        let completion_label = StyledText::new(completion.label.text.clone())
 1312                            .with_highlights(&style.text, highlights);
 1313                        let documentation_label =
 1314                            if let Some(Documentation::SingleLine(text)) = documentation {
 1315                                if text.trim().is_empty() {
 1316                                    None
 1317                                } else {
 1318                                    Some(
 1319                                        Label::new(text.clone())
 1320                                            .ml_4()
 1321                                            .size(LabelSize::Small)
 1322                                            .color(Color::Muted),
 1323                                    )
 1324                                }
 1325                            } else {
 1326                                None
 1327                            };
 1328
 1329                        let color_swatch = completion
 1330                            .color()
 1331                            .map(|color| div().size_4().bg(color).rounded_sm());
 1332
 1333                        div().min_w(px(220.)).max_w(px(540.)).child(
 1334                            ListItem::new(mat.candidate_id)
 1335                                .inset(true)
 1336                                .selected(item_ix == selected_item)
 1337                                .on_click(cx.listener(move |editor, _event, cx| {
 1338                                    cx.stop_propagation();
 1339                                    if let Some(task) = editor.confirm_completion(
 1340                                        &ConfirmCompletion {
 1341                                            item_ix: Some(item_ix),
 1342                                        },
 1343                                        cx,
 1344                                    ) {
 1345                                        task.detach_and_log_err(cx)
 1346                                    }
 1347                                }))
 1348                                .start_slot::<Div>(color_swatch)
 1349                                .child(h_flex().overflow_hidden().child(completion_label))
 1350                                .end_slot::<Label>(documentation_label),
 1351                        )
 1352                    })
 1353                    .collect()
 1354            },
 1355        )
 1356        .occlude()
 1357        .max_h(max_height)
 1358        .track_scroll(self.scroll_handle.clone())
 1359        .with_width_from_item(widest_completion_ix)
 1360        .with_sizing_behavior(ListSizingBehavior::Infer);
 1361
 1362        Popover::new()
 1363            .child(list)
 1364            .when_some(aside_contents, |popover, aside_contents| {
 1365                popover.aside(aside_contents)
 1366            })
 1367            .into_any_element()
 1368    }
 1369
 1370    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1371        let mut matches = if let Some(query) = query {
 1372            fuzzy::match_strings(
 1373                &self.match_candidates,
 1374                query,
 1375                query.chars().any(|c| c.is_uppercase()),
 1376                100,
 1377                &Default::default(),
 1378                executor,
 1379            )
 1380            .await
 1381        } else {
 1382            self.match_candidates
 1383                .iter()
 1384                .enumerate()
 1385                .map(|(candidate_id, candidate)| StringMatch {
 1386                    candidate_id,
 1387                    score: Default::default(),
 1388                    positions: Default::default(),
 1389                    string: candidate.string.clone(),
 1390                })
 1391                .collect()
 1392        };
 1393
 1394        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1395        if let Some(query) = query {
 1396            if let Some(query_start) = query.chars().next() {
 1397                matches.retain(|string_match| {
 1398                    split_words(&string_match.string).any(|word| {
 1399                        // Check that the first codepoint of the word as lowercase matches the first
 1400                        // codepoint of the query as lowercase
 1401                        word.chars()
 1402                            .flat_map(|codepoint| codepoint.to_lowercase())
 1403                            .zip(query_start.to_lowercase())
 1404                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1405                    })
 1406                });
 1407            }
 1408        }
 1409
 1410        let completions = self.completions.read();
 1411        if self.sort_completions {
 1412            matches.sort_unstable_by_key(|mat| {
 1413                // We do want to strike a balance here between what the language server tells us
 1414                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1415                // `Creat` and there is a local variable called `CreateComponent`).
 1416                // So what we do is: we bucket all matches into two buckets
 1417                // - Strong matches
 1418                // - Weak matches
 1419                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1420                // and the Weak matches are the rest.
 1421                //
 1422                // For the strong matches, we sort by our fuzzy-finder score first and for the weak
 1423                // matches, we prefer language-server sort_text first.
 1424                //
 1425                // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
 1426                // Rest of the matches(weak) can be sorted as language-server expects.
 1427
 1428                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1429                enum MatchScore<'a> {
 1430                    Strong {
 1431                        score: Reverse<OrderedFloat<f64>>,
 1432                        sort_text: Option<&'a str>,
 1433                        sort_key: (usize, &'a str),
 1434                    },
 1435                    Weak {
 1436                        sort_text: Option<&'a str>,
 1437                        score: Reverse<OrderedFloat<f64>>,
 1438                        sort_key: (usize, &'a str),
 1439                    },
 1440                }
 1441
 1442                let completion = &completions[mat.candidate_id];
 1443                let sort_key = completion.sort_key();
 1444                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1445                let score = Reverse(OrderedFloat(mat.score));
 1446
 1447                if mat.score >= 0.2 {
 1448                    MatchScore::Strong {
 1449                        score,
 1450                        sort_text,
 1451                        sort_key,
 1452                    }
 1453                } else {
 1454                    MatchScore::Weak {
 1455                        sort_text,
 1456                        score,
 1457                        sort_key,
 1458                    }
 1459                }
 1460            });
 1461        }
 1462
 1463        for mat in &mut matches {
 1464            let completion = &completions[mat.candidate_id];
 1465            mat.string.clone_from(&completion.label.text);
 1466            for position in &mut mat.positions {
 1467                *position += completion.label.filter_range.start;
 1468            }
 1469        }
 1470        drop(completions);
 1471
 1472        self.matches = matches.into();
 1473        self.selected_item = 0;
 1474    }
 1475}
 1476
 1477#[derive(Clone)]
 1478struct AvailableCodeAction {
 1479    excerpt_id: ExcerptId,
 1480    action: CodeAction,
 1481    provider: Arc<dyn CodeActionProvider>,
 1482}
 1483
 1484#[derive(Clone)]
 1485struct CodeActionContents {
 1486    tasks: Option<Arc<ResolvedTasks>>,
 1487    actions: Option<Arc<[AvailableCodeAction]>>,
 1488}
 1489
 1490impl CodeActionContents {
 1491    fn len(&self) -> usize {
 1492        match (&self.tasks, &self.actions) {
 1493            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1494            (Some(tasks), None) => tasks.templates.len(),
 1495            (None, Some(actions)) => actions.len(),
 1496            (None, None) => 0,
 1497        }
 1498    }
 1499
 1500    fn is_empty(&self) -> bool {
 1501        match (&self.tasks, &self.actions) {
 1502            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1503            (Some(tasks), None) => tasks.templates.is_empty(),
 1504            (None, Some(actions)) => actions.is_empty(),
 1505            (None, None) => true,
 1506        }
 1507    }
 1508
 1509    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1510        self.tasks
 1511            .iter()
 1512            .flat_map(|tasks| {
 1513                tasks
 1514                    .templates
 1515                    .iter()
 1516                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1517            })
 1518            .chain(self.actions.iter().flat_map(|actions| {
 1519                actions.iter().map(|available| CodeActionsItem::CodeAction {
 1520                    excerpt_id: available.excerpt_id,
 1521                    action: available.action.clone(),
 1522                    provider: available.provider.clone(),
 1523                })
 1524            }))
 1525    }
 1526    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1527        match (&self.tasks, &self.actions) {
 1528            (Some(tasks), Some(actions)) => {
 1529                if index < tasks.templates.len() {
 1530                    tasks
 1531                        .templates
 1532                        .get(index)
 1533                        .cloned()
 1534                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1535                } else {
 1536                    actions.get(index - tasks.templates.len()).map(|available| {
 1537                        CodeActionsItem::CodeAction {
 1538                            excerpt_id: available.excerpt_id,
 1539                            action: available.action.clone(),
 1540                            provider: available.provider.clone(),
 1541                        }
 1542                    })
 1543                }
 1544            }
 1545            (Some(tasks), None) => tasks
 1546                .templates
 1547                .get(index)
 1548                .cloned()
 1549                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1550            (None, Some(actions)) => {
 1551                actions
 1552                    .get(index)
 1553                    .map(|available| CodeActionsItem::CodeAction {
 1554                        excerpt_id: available.excerpt_id,
 1555                        action: available.action.clone(),
 1556                        provider: available.provider.clone(),
 1557                    })
 1558            }
 1559            (None, None) => None,
 1560        }
 1561    }
 1562}
 1563
 1564#[allow(clippy::large_enum_variant)]
 1565#[derive(Clone)]
 1566enum CodeActionsItem {
 1567    Task(TaskSourceKind, ResolvedTask),
 1568    CodeAction {
 1569        excerpt_id: ExcerptId,
 1570        action: CodeAction,
 1571        provider: Arc<dyn CodeActionProvider>,
 1572    },
 1573}
 1574
 1575impl CodeActionsItem {
 1576    fn as_task(&self) -> Option<&ResolvedTask> {
 1577        let Self::Task(_, task) = self else {
 1578            return None;
 1579        };
 1580        Some(task)
 1581    }
 1582    fn as_code_action(&self) -> Option<&CodeAction> {
 1583        let Self::CodeAction { action, .. } = self else {
 1584            return None;
 1585        };
 1586        Some(action)
 1587    }
 1588    fn label(&self) -> String {
 1589        match self {
 1590            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 1591            Self::Task(_, task) => task.resolved_label.clone(),
 1592        }
 1593    }
 1594}
 1595
 1596struct CodeActionsMenu {
 1597    actions: CodeActionContents,
 1598    buffer: Model<Buffer>,
 1599    selected_item: usize,
 1600    scroll_handle: UniformListScrollHandle,
 1601    deployed_from_indicator: Option<DisplayRow>,
 1602}
 1603
 1604impl CodeActionsMenu {
 1605    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1606        self.selected_item = 0;
 1607        self.scroll_handle
 1608            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1609        cx.notify()
 1610    }
 1611
 1612    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1613        if self.selected_item > 0 {
 1614            self.selected_item -= 1;
 1615        } else {
 1616            self.selected_item = self.actions.len() - 1;
 1617        }
 1618        self.scroll_handle
 1619            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1620        cx.notify();
 1621    }
 1622
 1623    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1624        if self.selected_item + 1 < self.actions.len() {
 1625            self.selected_item += 1;
 1626        } else {
 1627            self.selected_item = 0;
 1628        }
 1629        self.scroll_handle
 1630            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1631        cx.notify();
 1632    }
 1633
 1634    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1635        self.selected_item = self.actions.len() - 1;
 1636        self.scroll_handle
 1637            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 1638        cx.notify()
 1639    }
 1640
 1641    fn visible(&self) -> bool {
 1642        !self.actions.is_empty()
 1643    }
 1644
 1645    fn render(
 1646        &self,
 1647        cursor_position: DisplayPoint,
 1648        _style: &EditorStyle,
 1649        max_height: Pixels,
 1650        cx: &mut ViewContext<Editor>,
 1651    ) -> (ContextMenuOrigin, AnyElement) {
 1652        let actions = self.actions.clone();
 1653        let selected_item = self.selected_item;
 1654        let element = uniform_list(
 1655            cx.view().clone(),
 1656            "code_actions_menu",
 1657            self.actions.len(),
 1658            move |_this, range, cx| {
 1659                actions
 1660                    .iter()
 1661                    .skip(range.start)
 1662                    .take(range.end - range.start)
 1663                    .enumerate()
 1664                    .map(|(ix, action)| {
 1665                        let item_ix = range.start + ix;
 1666                        let selected = selected_item == item_ix;
 1667                        let colors = cx.theme().colors();
 1668                        div()
 1669                            .px_1()
 1670                            .rounded_md()
 1671                            .text_color(colors.text)
 1672                            .when(selected, |style| {
 1673                                style
 1674                                    .bg(colors.element_active)
 1675                                    .text_color(colors.text_accent)
 1676                            })
 1677                            .hover(|style| {
 1678                                style
 1679                                    .bg(colors.element_hover)
 1680                                    .text_color(colors.text_accent)
 1681                            })
 1682                            .whitespace_nowrap()
 1683                            .when_some(action.as_code_action(), |this, action| {
 1684                                this.on_mouse_down(
 1685                                    MouseButton::Left,
 1686                                    cx.listener(move |editor, _, cx| {
 1687                                        cx.stop_propagation();
 1688                                        if let Some(task) = editor.confirm_code_action(
 1689                                            &ConfirmCodeAction {
 1690                                                item_ix: Some(item_ix),
 1691                                            },
 1692                                            cx,
 1693                                        ) {
 1694                                            task.detach_and_log_err(cx)
 1695                                        }
 1696                                    }),
 1697                                )
 1698                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1699                                .child(SharedString::from(
 1700                                    action.lsp_action.title.replace("\n", ""),
 1701                                ))
 1702                            })
 1703                            .when_some(action.as_task(), |this, task| {
 1704                                this.on_mouse_down(
 1705                                    MouseButton::Left,
 1706                                    cx.listener(move |editor, _, cx| {
 1707                                        cx.stop_propagation();
 1708                                        if let Some(task) = editor.confirm_code_action(
 1709                                            &ConfirmCodeAction {
 1710                                                item_ix: Some(item_ix),
 1711                                            },
 1712                                            cx,
 1713                                        ) {
 1714                                            task.detach_and_log_err(cx)
 1715                                        }
 1716                                    }),
 1717                                )
 1718                                .child(SharedString::from(task.resolved_label.replace("\n", "")))
 1719                            })
 1720                    })
 1721                    .collect()
 1722            },
 1723        )
 1724        .elevation_1(cx)
 1725        .p_1()
 1726        .max_h(max_height)
 1727        .occlude()
 1728        .track_scroll(self.scroll_handle.clone())
 1729        .with_width_from_item(
 1730            self.actions
 1731                .iter()
 1732                .enumerate()
 1733                .max_by_key(|(_, action)| match action {
 1734                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1735                    CodeActionsItem::CodeAction { action, .. } => {
 1736                        action.lsp_action.title.chars().count()
 1737                    }
 1738                })
 1739                .map(|(ix, _)| ix),
 1740        )
 1741        .with_sizing_behavior(ListSizingBehavior::Infer)
 1742        .into_any_element();
 1743
 1744        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1745            ContextMenuOrigin::GutterIndicator(row)
 1746        } else {
 1747            ContextMenuOrigin::EditorPoint(cursor_position)
 1748        };
 1749
 1750        (cursor_position, element)
 1751    }
 1752}
 1753
 1754#[derive(Debug)]
 1755struct ActiveDiagnosticGroup {
 1756    primary_range: Range<Anchor>,
 1757    primary_message: String,
 1758    group_id: usize,
 1759    blocks: HashMap<CustomBlockId, Diagnostic>,
 1760    is_valid: bool,
 1761}
 1762
 1763#[derive(Serialize, Deserialize, Clone, Debug)]
 1764pub struct ClipboardSelection {
 1765    pub len: usize,
 1766    pub is_entire_line: bool,
 1767    pub first_line_indent: u32,
 1768}
 1769
 1770#[derive(Debug)]
 1771pub(crate) struct NavigationData {
 1772    cursor_anchor: Anchor,
 1773    cursor_position: Point,
 1774    scroll_anchor: ScrollAnchor,
 1775    scroll_top_row: u32,
 1776}
 1777
 1778#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1779pub enum GotoDefinitionKind {
 1780    Symbol,
 1781    Declaration,
 1782    Type,
 1783    Implementation,
 1784}
 1785
 1786#[derive(Debug, Clone)]
 1787enum InlayHintRefreshReason {
 1788    Toggle(bool),
 1789    SettingsChange(InlayHintSettings),
 1790    NewLinesShown,
 1791    BufferEdited(HashSet<Arc<Language>>),
 1792    RefreshRequested,
 1793    ExcerptsRemoved(Vec<ExcerptId>),
 1794}
 1795
 1796impl InlayHintRefreshReason {
 1797    fn description(&self) -> &'static str {
 1798        match self {
 1799            Self::Toggle(_) => "toggle",
 1800            Self::SettingsChange(_) => "settings change",
 1801            Self::NewLinesShown => "new lines shown",
 1802            Self::BufferEdited(_) => "buffer edited",
 1803            Self::RefreshRequested => "refresh requested",
 1804            Self::ExcerptsRemoved(_) => "excerpts removed",
 1805        }
 1806    }
 1807}
 1808
 1809pub(crate) struct FocusedBlock {
 1810    id: BlockId,
 1811    focus_handle: WeakFocusHandle,
 1812}
 1813
 1814#[derive(Clone)]
 1815struct JumpData {
 1816    excerpt_id: ExcerptId,
 1817    position: Point,
 1818    anchor: text::Anchor,
 1819    path: Option<project::ProjectPath>,
 1820    line_offset_from_top: u32,
 1821}
 1822
 1823impl Editor {
 1824    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1825        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1826        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1827        Self::new(
 1828            EditorMode::SingleLine { auto_width: false },
 1829            buffer,
 1830            None,
 1831            false,
 1832            cx,
 1833        )
 1834    }
 1835
 1836    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1837        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1838        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1839        Self::new(EditorMode::Full, buffer, None, false, cx)
 1840    }
 1841
 1842    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1843        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1844        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1845        Self::new(
 1846            EditorMode::SingleLine { auto_width: true },
 1847            buffer,
 1848            None,
 1849            false,
 1850            cx,
 1851        )
 1852    }
 1853
 1854    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1855        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1856        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1857        Self::new(
 1858            EditorMode::AutoHeight { max_lines },
 1859            buffer,
 1860            None,
 1861            false,
 1862            cx,
 1863        )
 1864    }
 1865
 1866    pub fn for_buffer(
 1867        buffer: Model<Buffer>,
 1868        project: Option<Model<Project>>,
 1869        cx: &mut ViewContext<Self>,
 1870    ) -> Self {
 1871        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1872        Self::new(EditorMode::Full, buffer, project, false, cx)
 1873    }
 1874
 1875    pub fn for_multibuffer(
 1876        buffer: Model<MultiBuffer>,
 1877        project: Option<Model<Project>>,
 1878        show_excerpt_controls: bool,
 1879        cx: &mut ViewContext<Self>,
 1880    ) -> Self {
 1881        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1882    }
 1883
 1884    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1885        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1886        let mut clone = Self::new(
 1887            self.mode,
 1888            self.buffer.clone(),
 1889            self.project.clone(),
 1890            show_excerpt_controls,
 1891            cx,
 1892        );
 1893        self.display_map.update(cx, |display_map, cx| {
 1894            let snapshot = display_map.snapshot(cx);
 1895            clone.display_map.update(cx, |display_map, cx| {
 1896                display_map.set_state(&snapshot, cx);
 1897            });
 1898        });
 1899        clone.selections.clone_state(&self.selections);
 1900        clone.scroll_manager.clone_state(&self.scroll_manager);
 1901        clone.searchable = self.searchable;
 1902        clone
 1903    }
 1904
 1905    pub fn new(
 1906        mode: EditorMode,
 1907        buffer: Model<MultiBuffer>,
 1908        project: Option<Model<Project>>,
 1909        show_excerpt_controls: bool,
 1910        cx: &mut ViewContext<Self>,
 1911    ) -> Self {
 1912        let style = cx.text_style();
 1913        let font_size = style.font_size.to_pixels(cx.rem_size());
 1914        let editor = cx.view().downgrade();
 1915        let fold_placeholder = FoldPlaceholder {
 1916            constrain_width: true,
 1917            render: Arc::new(move |fold_id, fold_range, cx| {
 1918                let editor = editor.clone();
 1919                div()
 1920                    .id(fold_id)
 1921                    .bg(cx.theme().colors().ghost_element_background)
 1922                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1923                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1924                    .rounded_sm()
 1925                    .size_full()
 1926                    .cursor_pointer()
 1927                    .child("")
 1928                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1929                    .on_click(move |_, cx| {
 1930                        editor
 1931                            .update(cx, |editor, cx| {
 1932                                editor.unfold_ranges(
 1933                                    &[fold_range.start..fold_range.end],
 1934                                    true,
 1935                                    false,
 1936                                    cx,
 1937                                );
 1938                                cx.stop_propagation();
 1939                            })
 1940                            .ok();
 1941                    })
 1942                    .into_any()
 1943            }),
 1944            merge_adjacent: true,
 1945            ..Default::default()
 1946        };
 1947        let display_map = cx.new_model(|cx| {
 1948            DisplayMap::new(
 1949                buffer.clone(),
 1950                style.font(),
 1951                font_size,
 1952                None,
 1953                show_excerpt_controls,
 1954                FILE_HEADER_HEIGHT,
 1955                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1956                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1957                fold_placeholder,
 1958                cx,
 1959            )
 1960        });
 1961
 1962        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1963
 1964        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1965
 1966        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1967            .then(|| language_settings::SoftWrap::None);
 1968
 1969        let mut project_subscriptions = Vec::new();
 1970        if mode == EditorMode::Full {
 1971            if let Some(project) = project.as_ref() {
 1972                if buffer.read(cx).is_singleton() {
 1973                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1974                        cx.emit(EditorEvent::TitleChanged);
 1975                    }));
 1976                }
 1977                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1978                    if let project::Event::RefreshInlayHints = event {
 1979                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1980                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1981                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1982                            let focus_handle = editor.focus_handle(cx);
 1983                            if focus_handle.is_focused(cx) {
 1984                                let snapshot = buffer.read(cx).snapshot();
 1985                                for (range, snippet) in snippet_edits {
 1986                                    let editor_range =
 1987                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1988                                    editor
 1989                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1990                                        .ok();
 1991                                }
 1992                            }
 1993                        }
 1994                    }
 1995                }));
 1996                if let Some(task_inventory) = project
 1997                    .read(cx)
 1998                    .task_store()
 1999                    .read(cx)
 2000                    .task_inventory()
 2001                    .cloned()
 2002                {
 2003                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 2004                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 2005                    }));
 2006                }
 2007            }
 2008        }
 2009
 2010        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 2011
 2012        let inlay_hint_settings =
 2013            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 2014        let focus_handle = cx.focus_handle();
 2015        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 2016        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 2017            .detach();
 2018        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 2019            .detach();
 2020        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 2021
 2022        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 2023            Some(false)
 2024        } else {
 2025            None
 2026        };
 2027
 2028        let mut code_action_providers = Vec::new();
 2029        if let Some(project) = project.clone() {
 2030            get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
 2031            code_action_providers.push(Arc::new(project) as Arc<_>);
 2032        }
 2033
 2034        let mut this = Self {
 2035            focus_handle,
 2036            show_cursor_when_unfocused: false,
 2037            last_focused_descendant: None,
 2038            buffer: buffer.clone(),
 2039            display_map: display_map.clone(),
 2040            selections,
 2041            scroll_manager: ScrollManager::new(cx),
 2042            columnar_selection_tail: None,
 2043            add_selections_state: None,
 2044            select_next_state: None,
 2045            select_prev_state: None,
 2046            selection_history: Default::default(),
 2047            autoclose_regions: Default::default(),
 2048            snippet_stack: Default::default(),
 2049            select_larger_syntax_node_stack: Vec::new(),
 2050            ime_transaction: Default::default(),
 2051            active_diagnostics: None,
 2052            soft_wrap_mode_override,
 2053            completion_provider: project.clone().map(|project| Box::new(project) as _),
 2054            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 2055            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 2056            project,
 2057            blink_manager: blink_manager.clone(),
 2058            show_local_selections: true,
 2059            mode,
 2060            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 2061            show_gutter: mode == EditorMode::Full,
 2062            show_line_numbers: None,
 2063            use_relative_line_numbers: None,
 2064            show_git_diff_gutter: None,
 2065            show_code_actions: None,
 2066            show_runnables: None,
 2067            show_wrap_guides: None,
 2068            show_indent_guides,
 2069            placeholder_text: None,
 2070            highlight_order: 0,
 2071            highlighted_rows: HashMap::default(),
 2072            background_highlights: Default::default(),
 2073            gutter_highlights: TreeMap::default(),
 2074            scrollbar_marker_state: ScrollbarMarkerState::default(),
 2075            active_indent_guides_state: ActiveIndentGuidesState::default(),
 2076            nav_history: None,
 2077            context_menu: RwLock::new(None),
 2078            mouse_context_menu: None,
 2079            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 2080            completion_tasks: Default::default(),
 2081            signature_help_state: SignatureHelpState::default(),
 2082            auto_signature_help: None,
 2083            find_all_references_task_sources: Vec::new(),
 2084            next_completion_id: 0,
 2085            next_inlay_id: 0,
 2086            code_action_providers,
 2087            available_code_actions: Default::default(),
 2088            code_actions_task: Default::default(),
 2089            document_highlights_task: Default::default(),
 2090            linked_editing_range_task: Default::default(),
 2091            pending_rename: Default::default(),
 2092            searchable: true,
 2093            cursor_shape: EditorSettings::get_global(cx)
 2094                .cursor_shape
 2095                .unwrap_or_default(),
 2096            current_line_highlight: None,
 2097            autoindent_mode: Some(AutoindentMode::EachLine),
 2098            collapse_matches: false,
 2099            workspace: None,
 2100            input_enabled: true,
 2101            use_modal_editing: mode == EditorMode::Full,
 2102            read_only: false,
 2103            use_autoclose: true,
 2104            use_auto_surround: true,
 2105            auto_replace_emoji_shortcode: false,
 2106            leader_peer_id: None,
 2107            remote_id: None,
 2108            hover_state: Default::default(),
 2109            hovered_link_state: Default::default(),
 2110            inline_completion_provider: None,
 2111            active_inline_completion: None,
 2112            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 2113            diff_map: DiffMap::default(),
 2114            gutter_hovered: false,
 2115            pixel_position_of_newest_cursor: None,
 2116            last_bounds: None,
 2117            expect_bounds_change: None,
 2118            gutter_dimensions: GutterDimensions::default(),
 2119            style: None,
 2120            show_cursor_names: false,
 2121            hovered_cursors: Default::default(),
 2122            next_editor_action_id: EditorActionId::default(),
 2123            editor_actions: Rc::default(),
 2124            show_inline_completions_override: None,
 2125            enable_inline_completions: true,
 2126            custom_context_menu: None,
 2127            show_git_blame_gutter: false,
 2128            show_git_blame_inline: false,
 2129            show_selection_menu: None,
 2130            show_git_blame_inline_delay_task: None,
 2131            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 2132            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 2133                .session
 2134                .restore_unsaved_buffers,
 2135            blame: None,
 2136            blame_subscription: None,
 2137            tasks: Default::default(),
 2138            _subscriptions: vec![
 2139                cx.observe(&buffer, Self::on_buffer_changed),
 2140                cx.subscribe(&buffer, Self::on_buffer_event),
 2141                cx.observe(&display_map, Self::on_display_map_changed),
 2142                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 2143                cx.observe_global::<SettingsStore>(Self::settings_changed),
 2144                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 2145                cx.observe_window_activation(|editor, cx| {
 2146                    let active = cx.is_window_active();
 2147                    editor.blink_manager.update(cx, |blink_manager, cx| {
 2148                        if active {
 2149                            blink_manager.enable(cx);
 2150                        } else {
 2151                            blink_manager.disable(cx);
 2152                        }
 2153                    });
 2154                }),
 2155            ],
 2156            tasks_update_task: None,
 2157            linked_edit_ranges: Default::default(),
 2158            previous_search_ranges: None,
 2159            breadcrumb_header: None,
 2160            focused_block: None,
 2161            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 2162            addons: HashMap::default(),
 2163            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 2164            text_style_refinement: None,
 2165        };
 2166        this.tasks_update_task = Some(this.refresh_runnables(cx));
 2167        this._subscriptions.extend(project_subscriptions);
 2168
 2169        this.end_selection(cx);
 2170        this.scroll_manager.show_scrollbar(cx);
 2171
 2172        if mode == EditorMode::Full {
 2173            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2174            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2175
 2176            if this.git_blame_inline_enabled {
 2177                this.git_blame_inline_enabled = true;
 2178                this.start_git_blame_inline(false, cx);
 2179            }
 2180        }
 2181
 2182        this.report_editor_event("open", None, cx);
 2183        this
 2184    }
 2185
 2186    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2187        self.mouse_context_menu
 2188            .as_ref()
 2189            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2190    }
 2191
 2192    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2193        let mut key_context = KeyContext::new_with_defaults();
 2194        key_context.add("Editor");
 2195        let mode = match self.mode {
 2196            EditorMode::SingleLine { .. } => "single_line",
 2197            EditorMode::AutoHeight { .. } => "auto_height",
 2198            EditorMode::Full => "full",
 2199        };
 2200
 2201        if EditorSettings::jupyter_enabled(cx) {
 2202            key_context.add("jupyter");
 2203        }
 2204
 2205        key_context.set("mode", mode);
 2206        if self.pending_rename.is_some() {
 2207            key_context.add("renaming");
 2208        }
 2209        if self.context_menu_visible() {
 2210            match self.context_menu.read().as_ref() {
 2211                Some(ContextMenu::Completions(_)) => {
 2212                    key_context.add("menu");
 2213                    key_context.add("showing_completions")
 2214                }
 2215                Some(ContextMenu::CodeActions(_)) => {
 2216                    key_context.add("menu");
 2217                    key_context.add("showing_code_actions")
 2218                }
 2219                None => {}
 2220            }
 2221        }
 2222
 2223        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2224        if !self.focus_handle(cx).contains_focused(cx)
 2225            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2226        {
 2227            for addon in self.addons.values() {
 2228                addon.extend_key_context(&mut key_context, cx)
 2229            }
 2230        }
 2231
 2232        if let Some(extension) = self
 2233            .buffer
 2234            .read(cx)
 2235            .as_singleton()
 2236            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2237        {
 2238            key_context.set("extension", extension.to_string());
 2239        }
 2240
 2241        if self.has_active_inline_completion() {
 2242            key_context.add("copilot_suggestion");
 2243            key_context.add("inline_completion");
 2244        }
 2245
 2246        key_context
 2247    }
 2248
 2249    pub fn new_file(
 2250        workspace: &mut Workspace,
 2251        _: &workspace::NewFile,
 2252        cx: &mut ViewContext<Workspace>,
 2253    ) {
 2254        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2255            "Failed to create buffer",
 2256            cx,
 2257            |e, _| match e.error_code() {
 2258                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2259                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2260                e.error_tag("required").unwrap_or("the latest version")
 2261            )),
 2262                _ => None,
 2263            },
 2264        );
 2265    }
 2266
 2267    pub fn new_in_workspace(
 2268        workspace: &mut Workspace,
 2269        cx: &mut ViewContext<Workspace>,
 2270    ) -> Task<Result<View<Editor>>> {
 2271        let project = workspace.project().clone();
 2272        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2273
 2274        cx.spawn(|workspace, mut cx| async move {
 2275            let buffer = create.await?;
 2276            workspace.update(&mut cx, |workspace, cx| {
 2277                let editor =
 2278                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2279                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2280                editor
 2281            })
 2282        })
 2283    }
 2284
 2285    fn new_file_vertical(
 2286        workspace: &mut Workspace,
 2287        _: &workspace::NewFileSplitVertical,
 2288        cx: &mut ViewContext<Workspace>,
 2289    ) {
 2290        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2291    }
 2292
 2293    fn new_file_horizontal(
 2294        workspace: &mut Workspace,
 2295        _: &workspace::NewFileSplitHorizontal,
 2296        cx: &mut ViewContext<Workspace>,
 2297    ) {
 2298        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2299    }
 2300
 2301    fn new_file_in_direction(
 2302        workspace: &mut Workspace,
 2303        direction: SplitDirection,
 2304        cx: &mut ViewContext<Workspace>,
 2305    ) {
 2306        let project = workspace.project().clone();
 2307        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2308
 2309        cx.spawn(|workspace, mut cx| async move {
 2310            let buffer = create.await?;
 2311            workspace.update(&mut cx, move |workspace, cx| {
 2312                workspace.split_item(
 2313                    direction,
 2314                    Box::new(
 2315                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2316                    ),
 2317                    cx,
 2318                )
 2319            })?;
 2320            anyhow::Ok(())
 2321        })
 2322        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2323            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2324                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2325                e.error_tag("required").unwrap_or("the latest version")
 2326            )),
 2327            _ => None,
 2328        });
 2329    }
 2330
 2331    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2332        self.leader_peer_id
 2333    }
 2334
 2335    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2336        &self.buffer
 2337    }
 2338
 2339    pub fn workspace(&self) -> Option<View<Workspace>> {
 2340        self.workspace.as_ref()?.0.upgrade()
 2341    }
 2342
 2343    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2344        self.buffer().read(cx).title(cx)
 2345    }
 2346
 2347    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2348        let git_blame_gutter_max_author_length = self
 2349            .render_git_blame_gutter(cx)
 2350            .then(|| {
 2351                if let Some(blame) = self.blame.as_ref() {
 2352                    let max_author_length =
 2353                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2354                    Some(max_author_length)
 2355                } else {
 2356                    None
 2357                }
 2358            })
 2359            .flatten();
 2360
 2361        EditorSnapshot {
 2362            mode: self.mode,
 2363            show_gutter: self.show_gutter,
 2364            show_line_numbers: self.show_line_numbers,
 2365            show_git_diff_gutter: self.show_git_diff_gutter,
 2366            show_code_actions: self.show_code_actions,
 2367            show_runnables: self.show_runnables,
 2368            git_blame_gutter_max_author_length,
 2369            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2370            scroll_anchor: self.scroll_manager.anchor(),
 2371            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2372            placeholder_text: self.placeholder_text.clone(),
 2373            diff_map: self.diff_map.snapshot(),
 2374            is_focused: self.focus_handle.is_focused(cx),
 2375            current_line_highlight: self
 2376                .current_line_highlight
 2377                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2378            gutter_hovered: self.gutter_hovered,
 2379        }
 2380    }
 2381
 2382    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2383        self.buffer.read(cx).language_at(point, cx)
 2384    }
 2385
 2386    pub fn file_at<T: ToOffset>(
 2387        &self,
 2388        point: T,
 2389        cx: &AppContext,
 2390    ) -> Option<Arc<dyn language::File>> {
 2391        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2392    }
 2393
 2394    pub fn active_excerpt(
 2395        &self,
 2396        cx: &AppContext,
 2397    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2398        self.buffer
 2399            .read(cx)
 2400            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2401    }
 2402
 2403    pub fn mode(&self) -> EditorMode {
 2404        self.mode
 2405    }
 2406
 2407    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2408        self.collaboration_hub.as_deref()
 2409    }
 2410
 2411    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2412        self.collaboration_hub = Some(hub);
 2413    }
 2414
 2415    pub fn set_custom_context_menu(
 2416        &mut self,
 2417        f: impl 'static
 2418            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2419    ) {
 2420        self.custom_context_menu = Some(Box::new(f))
 2421    }
 2422
 2423    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2424        self.completion_provider = provider;
 2425    }
 2426
 2427    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2428        self.semantics_provider.clone()
 2429    }
 2430
 2431    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2432        self.semantics_provider = provider;
 2433    }
 2434
 2435    pub fn set_inline_completion_provider<T>(
 2436        &mut self,
 2437        provider: Option<Model<T>>,
 2438        cx: &mut ViewContext<Self>,
 2439    ) where
 2440        T: InlineCompletionProvider,
 2441    {
 2442        self.inline_completion_provider =
 2443            provider.map(|provider| RegisteredInlineCompletionProvider {
 2444                _subscription: cx.observe(&provider, |this, _, cx| {
 2445                    if this.focus_handle.is_focused(cx) {
 2446                        this.update_visible_inline_completion(cx);
 2447                    }
 2448                }),
 2449                provider: Arc::new(provider),
 2450            });
 2451        self.refresh_inline_completion(false, false, cx);
 2452    }
 2453
 2454    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2455        self.placeholder_text.as_deref()
 2456    }
 2457
 2458    pub fn set_placeholder_text(
 2459        &mut self,
 2460        placeholder_text: impl Into<Arc<str>>,
 2461        cx: &mut ViewContext<Self>,
 2462    ) {
 2463        let placeholder_text = Some(placeholder_text.into());
 2464        if self.placeholder_text != placeholder_text {
 2465            self.placeholder_text = placeholder_text;
 2466            cx.notify();
 2467        }
 2468    }
 2469
 2470    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2471        self.cursor_shape = cursor_shape;
 2472
 2473        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2474        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2475
 2476        cx.notify();
 2477    }
 2478
 2479    pub fn set_current_line_highlight(
 2480        &mut self,
 2481        current_line_highlight: Option<CurrentLineHighlight>,
 2482    ) {
 2483        self.current_line_highlight = current_line_highlight;
 2484    }
 2485
 2486    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2487        self.collapse_matches = collapse_matches;
 2488    }
 2489
 2490    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2491        if self.collapse_matches {
 2492            return range.start..range.start;
 2493        }
 2494        range.clone()
 2495    }
 2496
 2497    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2498        if self.display_map.read(cx).clip_at_line_ends != clip {
 2499            self.display_map
 2500                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2501        }
 2502    }
 2503
 2504    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2505        self.input_enabled = input_enabled;
 2506    }
 2507
 2508    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2509        self.enable_inline_completions = enabled;
 2510    }
 2511
 2512    pub fn set_autoindent(&mut self, autoindent: bool) {
 2513        if autoindent {
 2514            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2515        } else {
 2516            self.autoindent_mode = None;
 2517        }
 2518    }
 2519
 2520    pub fn read_only(&self, cx: &AppContext) -> bool {
 2521        self.read_only || self.buffer.read(cx).read_only()
 2522    }
 2523
 2524    pub fn set_read_only(&mut self, read_only: bool) {
 2525        self.read_only = read_only;
 2526    }
 2527
 2528    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2529        self.use_autoclose = autoclose;
 2530    }
 2531
 2532    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2533        self.use_auto_surround = auto_surround;
 2534    }
 2535
 2536    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2537        self.auto_replace_emoji_shortcode = auto_replace;
 2538    }
 2539
 2540    pub fn toggle_inline_completions(
 2541        &mut self,
 2542        _: &ToggleInlineCompletions,
 2543        cx: &mut ViewContext<Self>,
 2544    ) {
 2545        if self.show_inline_completions_override.is_some() {
 2546            self.set_show_inline_completions(None, cx);
 2547        } else {
 2548            let cursor = self.selections.newest_anchor().head();
 2549            if let Some((buffer, cursor_buffer_position)) =
 2550                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2551            {
 2552                let show_inline_completions =
 2553                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2554                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2555            }
 2556        }
 2557    }
 2558
 2559    pub fn set_show_inline_completions(
 2560        &mut self,
 2561        show_inline_completions: Option<bool>,
 2562        cx: &mut ViewContext<Self>,
 2563    ) {
 2564        self.show_inline_completions_override = show_inline_completions;
 2565        self.refresh_inline_completion(false, true, cx);
 2566    }
 2567
 2568    fn should_show_inline_completions(
 2569        &self,
 2570        buffer: &Model<Buffer>,
 2571        buffer_position: language::Anchor,
 2572        cx: &AppContext,
 2573    ) -> bool {
 2574        if !self.snippet_stack.is_empty() {
 2575            return false;
 2576        }
 2577
 2578        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 2579            return false;
 2580        }
 2581
 2582        if let Some(provider) = self.inline_completion_provider() {
 2583            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2584                show_inline_completions
 2585            } else {
 2586                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2587            }
 2588        } else {
 2589            false
 2590        }
 2591    }
 2592
 2593    fn inline_completions_disabled_in_scope(
 2594        &self,
 2595        buffer: &Model<Buffer>,
 2596        buffer_position: language::Anchor,
 2597        cx: &AppContext,
 2598    ) -> bool {
 2599        let snapshot = buffer.read(cx).snapshot();
 2600        let settings = snapshot.settings_at(buffer_position, cx);
 2601
 2602        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2603            return false;
 2604        };
 2605
 2606        scope.override_name().map_or(false, |scope_name| {
 2607            settings
 2608                .inline_completions_disabled_in
 2609                .iter()
 2610                .any(|s| s == scope_name)
 2611        })
 2612    }
 2613
 2614    pub fn set_use_modal_editing(&mut self, to: bool) {
 2615        self.use_modal_editing = to;
 2616    }
 2617
 2618    pub fn use_modal_editing(&self) -> bool {
 2619        self.use_modal_editing
 2620    }
 2621
 2622    fn selections_did_change(
 2623        &mut self,
 2624        local: bool,
 2625        old_cursor_position: &Anchor,
 2626        show_completions: bool,
 2627        cx: &mut ViewContext<Self>,
 2628    ) {
 2629        cx.invalidate_character_coordinates();
 2630
 2631        // Copy selections to primary selection buffer
 2632        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2633        if local {
 2634            let selections = self.selections.all::<usize>(cx);
 2635            let buffer_handle = self.buffer.read(cx).read(cx);
 2636
 2637            let mut text = String::new();
 2638            for (index, selection) in selections.iter().enumerate() {
 2639                let text_for_selection = buffer_handle
 2640                    .text_for_range(selection.start..selection.end)
 2641                    .collect::<String>();
 2642
 2643                text.push_str(&text_for_selection);
 2644                if index != selections.len() - 1 {
 2645                    text.push('\n');
 2646                }
 2647            }
 2648
 2649            if !text.is_empty() {
 2650                cx.write_to_primary(ClipboardItem::new_string(text));
 2651            }
 2652        }
 2653
 2654        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2655            self.buffer.update(cx, |buffer, cx| {
 2656                buffer.set_active_selections(
 2657                    &self.selections.disjoint_anchors(),
 2658                    self.selections.line_mode,
 2659                    self.cursor_shape,
 2660                    cx,
 2661                )
 2662            });
 2663        }
 2664        let display_map = self
 2665            .display_map
 2666            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2667        let buffer = &display_map.buffer_snapshot;
 2668        self.add_selections_state = None;
 2669        self.select_next_state = None;
 2670        self.select_prev_state = None;
 2671        self.select_larger_syntax_node_stack.clear();
 2672        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2673        self.snippet_stack
 2674            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2675        self.take_rename(false, cx);
 2676
 2677        let new_cursor_position = self.selections.newest_anchor().head();
 2678
 2679        self.push_to_nav_history(
 2680            *old_cursor_position,
 2681            Some(new_cursor_position.to_point(buffer)),
 2682            cx,
 2683        );
 2684
 2685        if local {
 2686            let new_cursor_position = self.selections.newest_anchor().head();
 2687            let mut context_menu = self.context_menu.write();
 2688            let completion_menu = match context_menu.as_ref() {
 2689                Some(ContextMenu::Completions(menu)) => Some(menu),
 2690
 2691                _ => {
 2692                    *context_menu = None;
 2693                    None
 2694                }
 2695            };
 2696
 2697            if let Some(completion_menu) = completion_menu {
 2698                let cursor_position = new_cursor_position.to_offset(buffer);
 2699                let (word_range, kind) =
 2700                    buffer.surrounding_word(completion_menu.initial_position, true);
 2701                if kind == Some(CharKind::Word)
 2702                    && word_range.to_inclusive().contains(&cursor_position)
 2703                {
 2704                    let mut completion_menu = completion_menu.clone();
 2705                    drop(context_menu);
 2706
 2707                    let query = Self::completion_query(buffer, cursor_position);
 2708                    cx.spawn(move |this, mut cx| async move {
 2709                        completion_menu
 2710                            .filter(query.as_deref(), cx.background_executor().clone())
 2711                            .await;
 2712
 2713                        this.update(&mut cx, |this, cx| {
 2714                            let mut context_menu = this.context_menu.write();
 2715                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2716                                return;
 2717                            };
 2718
 2719                            if menu.id > completion_menu.id {
 2720                                return;
 2721                            }
 2722
 2723                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2724                            drop(context_menu);
 2725                            cx.notify();
 2726                        })
 2727                    })
 2728                    .detach();
 2729
 2730                    if show_completions {
 2731                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2732                    }
 2733                } else {
 2734                    drop(context_menu);
 2735                    self.hide_context_menu(cx);
 2736                }
 2737            } else {
 2738                drop(context_menu);
 2739            }
 2740
 2741            hide_hover(self, cx);
 2742
 2743            if old_cursor_position.to_display_point(&display_map).row()
 2744                != new_cursor_position.to_display_point(&display_map).row()
 2745            {
 2746                self.available_code_actions.take();
 2747            }
 2748            self.refresh_code_actions(cx);
 2749            self.refresh_document_highlights(cx);
 2750            refresh_matching_bracket_highlights(self, cx);
 2751            self.update_visible_inline_completion(cx);
 2752            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2753            if self.git_blame_inline_enabled {
 2754                self.start_inline_blame_timer(cx);
 2755            }
 2756        }
 2757
 2758        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2759        cx.emit(EditorEvent::SelectionsChanged { local });
 2760
 2761        if self.selections.disjoint_anchors().len() == 1 {
 2762            cx.emit(SearchEvent::ActiveMatchChanged)
 2763        }
 2764        cx.notify();
 2765    }
 2766
 2767    pub fn change_selections<R>(
 2768        &mut self,
 2769        autoscroll: Option<Autoscroll>,
 2770        cx: &mut ViewContext<Self>,
 2771        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2772    ) -> R {
 2773        self.change_selections_inner(autoscroll, true, cx, change)
 2774    }
 2775
 2776    pub fn change_selections_inner<R>(
 2777        &mut self,
 2778        autoscroll: Option<Autoscroll>,
 2779        request_completions: bool,
 2780        cx: &mut ViewContext<Self>,
 2781        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2782    ) -> R {
 2783        let old_cursor_position = self.selections.newest_anchor().head();
 2784        self.push_to_selection_history();
 2785
 2786        let (changed, result) = self.selections.change_with(cx, change);
 2787
 2788        if changed {
 2789            if let Some(autoscroll) = autoscroll {
 2790                self.request_autoscroll(autoscroll, cx);
 2791            }
 2792            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2793
 2794            if self.should_open_signature_help_automatically(
 2795                &old_cursor_position,
 2796                self.signature_help_state.backspace_pressed(),
 2797                cx,
 2798            ) {
 2799                self.show_signature_help(&ShowSignatureHelp, cx);
 2800            }
 2801            self.signature_help_state.set_backspace_pressed(false);
 2802        }
 2803
 2804        result
 2805    }
 2806
 2807    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2808    where
 2809        I: IntoIterator<Item = (Range<S>, T)>,
 2810        S: ToOffset,
 2811        T: Into<Arc<str>>,
 2812    {
 2813        if self.read_only(cx) {
 2814            return;
 2815        }
 2816
 2817        self.buffer
 2818            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2819    }
 2820
 2821    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2822    where
 2823        I: IntoIterator<Item = (Range<S>, T)>,
 2824        S: ToOffset,
 2825        T: Into<Arc<str>>,
 2826    {
 2827        if self.read_only(cx) {
 2828            return;
 2829        }
 2830
 2831        self.buffer.update(cx, |buffer, cx| {
 2832            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2833        });
 2834    }
 2835
 2836    pub fn edit_with_block_indent<I, S, T>(
 2837        &mut self,
 2838        edits: I,
 2839        original_indent_columns: Vec<u32>,
 2840        cx: &mut ViewContext<Self>,
 2841    ) where
 2842        I: IntoIterator<Item = (Range<S>, T)>,
 2843        S: ToOffset,
 2844        T: Into<Arc<str>>,
 2845    {
 2846        if self.read_only(cx) {
 2847            return;
 2848        }
 2849
 2850        self.buffer.update(cx, |buffer, cx| {
 2851            buffer.edit(
 2852                edits,
 2853                Some(AutoindentMode::Block {
 2854                    original_indent_columns,
 2855                }),
 2856                cx,
 2857            )
 2858        });
 2859    }
 2860
 2861    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2862        self.hide_context_menu(cx);
 2863
 2864        match phase {
 2865            SelectPhase::Begin {
 2866                position,
 2867                add,
 2868                click_count,
 2869            } => self.begin_selection(position, add, click_count, cx),
 2870            SelectPhase::BeginColumnar {
 2871                position,
 2872                goal_column,
 2873                reset,
 2874            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2875            SelectPhase::Extend {
 2876                position,
 2877                click_count,
 2878            } => self.extend_selection(position, click_count, cx),
 2879            SelectPhase::Update {
 2880                position,
 2881                goal_column,
 2882                scroll_delta,
 2883            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2884            SelectPhase::End => self.end_selection(cx),
 2885        }
 2886    }
 2887
 2888    fn extend_selection(
 2889        &mut self,
 2890        position: DisplayPoint,
 2891        click_count: usize,
 2892        cx: &mut ViewContext<Self>,
 2893    ) {
 2894        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2895        let tail = self.selections.newest::<usize>(cx).tail();
 2896        self.begin_selection(position, false, click_count, cx);
 2897
 2898        let position = position.to_offset(&display_map, Bias::Left);
 2899        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2900
 2901        let mut pending_selection = self
 2902            .selections
 2903            .pending_anchor()
 2904            .expect("extend_selection not called with pending selection");
 2905        if position >= tail {
 2906            pending_selection.start = tail_anchor;
 2907        } else {
 2908            pending_selection.end = tail_anchor;
 2909            pending_selection.reversed = true;
 2910        }
 2911
 2912        let mut pending_mode = self.selections.pending_mode().unwrap();
 2913        match &mut pending_mode {
 2914            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2915            _ => {}
 2916        }
 2917
 2918        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2919            s.set_pending(pending_selection, pending_mode)
 2920        });
 2921    }
 2922
 2923    fn begin_selection(
 2924        &mut self,
 2925        position: DisplayPoint,
 2926        add: bool,
 2927        click_count: usize,
 2928        cx: &mut ViewContext<Self>,
 2929    ) {
 2930        if !self.focus_handle.is_focused(cx) {
 2931            self.last_focused_descendant = None;
 2932            cx.focus(&self.focus_handle);
 2933        }
 2934
 2935        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2936        let buffer = &display_map.buffer_snapshot;
 2937        let newest_selection = self.selections.newest_anchor().clone();
 2938        let position = display_map.clip_point(position, Bias::Left);
 2939
 2940        let start;
 2941        let end;
 2942        let mode;
 2943        let mut auto_scroll;
 2944        match click_count {
 2945            1 => {
 2946                start = buffer.anchor_before(position.to_point(&display_map));
 2947                end = start;
 2948                mode = SelectMode::Character;
 2949                auto_scroll = true;
 2950            }
 2951            2 => {
 2952                let range = movement::surrounding_word(&display_map, position);
 2953                start = buffer.anchor_before(range.start.to_point(&display_map));
 2954                end = buffer.anchor_before(range.end.to_point(&display_map));
 2955                mode = SelectMode::Word(start..end);
 2956                auto_scroll = true;
 2957            }
 2958            3 => {
 2959                let position = display_map
 2960                    .clip_point(position, Bias::Left)
 2961                    .to_point(&display_map);
 2962                let line_start = display_map.prev_line_boundary(position).0;
 2963                let next_line_start = buffer.clip_point(
 2964                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2965                    Bias::Left,
 2966                );
 2967                start = buffer.anchor_before(line_start);
 2968                end = buffer.anchor_before(next_line_start);
 2969                mode = SelectMode::Line(start..end);
 2970                auto_scroll = true;
 2971            }
 2972            _ => {
 2973                start = buffer.anchor_before(0);
 2974                end = buffer.anchor_before(buffer.len());
 2975                mode = SelectMode::All;
 2976                auto_scroll = false;
 2977            }
 2978        }
 2979        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2980
 2981        let point_to_delete: Option<usize> = {
 2982            let selected_points: Vec<Selection<Point>> =
 2983                self.selections.disjoint_in_range(start..end, cx);
 2984
 2985            if !add || click_count > 1 {
 2986                None
 2987            } else if !selected_points.is_empty() {
 2988                Some(selected_points[0].id)
 2989            } else {
 2990                let clicked_point_already_selected =
 2991                    self.selections.disjoint.iter().find(|selection| {
 2992                        selection.start.to_point(buffer) == start.to_point(buffer)
 2993                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2994                    });
 2995
 2996                clicked_point_already_selected.map(|selection| selection.id)
 2997            }
 2998        };
 2999
 3000        let selections_count = self.selections.count();
 3001
 3002        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 3003            if let Some(point_to_delete) = point_to_delete {
 3004                s.delete(point_to_delete);
 3005
 3006                if selections_count == 1 {
 3007                    s.set_pending_anchor_range(start..end, mode);
 3008                }
 3009            } else {
 3010                if !add {
 3011                    s.clear_disjoint();
 3012                } else if click_count > 1 {
 3013                    s.delete(newest_selection.id)
 3014                }
 3015
 3016                s.set_pending_anchor_range(start..end, mode);
 3017            }
 3018        });
 3019    }
 3020
 3021    fn begin_columnar_selection(
 3022        &mut self,
 3023        position: DisplayPoint,
 3024        goal_column: u32,
 3025        reset: bool,
 3026        cx: &mut ViewContext<Self>,
 3027    ) {
 3028        if !self.focus_handle.is_focused(cx) {
 3029            self.last_focused_descendant = None;
 3030            cx.focus(&self.focus_handle);
 3031        }
 3032
 3033        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3034
 3035        if reset {
 3036            let pointer_position = display_map
 3037                .buffer_snapshot
 3038                .anchor_before(position.to_point(&display_map));
 3039
 3040            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 3041                s.clear_disjoint();
 3042                s.set_pending_anchor_range(
 3043                    pointer_position..pointer_position,
 3044                    SelectMode::Character,
 3045                );
 3046            });
 3047        }
 3048
 3049        let tail = self.selections.newest::<Point>(cx).tail();
 3050        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 3051
 3052        if !reset {
 3053            self.select_columns(
 3054                tail.to_display_point(&display_map),
 3055                position,
 3056                goal_column,
 3057                &display_map,
 3058                cx,
 3059            );
 3060        }
 3061    }
 3062
 3063    fn update_selection(
 3064        &mut self,
 3065        position: DisplayPoint,
 3066        goal_column: u32,
 3067        scroll_delta: gpui::Point<f32>,
 3068        cx: &mut ViewContext<Self>,
 3069    ) {
 3070        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3071
 3072        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 3073            let tail = tail.to_display_point(&display_map);
 3074            self.select_columns(tail, position, goal_column, &display_map, cx);
 3075        } else if let Some(mut pending) = self.selections.pending_anchor() {
 3076            let buffer = self.buffer.read(cx).snapshot(cx);
 3077            let head;
 3078            let tail;
 3079            let mode = self.selections.pending_mode().unwrap();
 3080            match &mode {
 3081                SelectMode::Character => {
 3082                    head = position.to_point(&display_map);
 3083                    tail = pending.tail().to_point(&buffer);
 3084                }
 3085                SelectMode::Word(original_range) => {
 3086                    let original_display_range = original_range.start.to_display_point(&display_map)
 3087                        ..original_range.end.to_display_point(&display_map);
 3088                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 3089                        ..original_display_range.end.to_point(&display_map);
 3090                    if movement::is_inside_word(&display_map, position)
 3091                        || original_display_range.contains(&position)
 3092                    {
 3093                        let word_range = movement::surrounding_word(&display_map, position);
 3094                        if word_range.start < original_display_range.start {
 3095                            head = word_range.start.to_point(&display_map);
 3096                        } else {
 3097                            head = word_range.end.to_point(&display_map);
 3098                        }
 3099                    } else {
 3100                        head = position.to_point(&display_map);
 3101                    }
 3102
 3103                    if head <= original_buffer_range.start {
 3104                        tail = original_buffer_range.end;
 3105                    } else {
 3106                        tail = original_buffer_range.start;
 3107                    }
 3108                }
 3109                SelectMode::Line(original_range) => {
 3110                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3111
 3112                    let position = display_map
 3113                        .clip_point(position, Bias::Left)
 3114                        .to_point(&display_map);
 3115                    let line_start = display_map.prev_line_boundary(position).0;
 3116                    let next_line_start = buffer.clip_point(
 3117                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3118                        Bias::Left,
 3119                    );
 3120
 3121                    if line_start < original_range.start {
 3122                        head = line_start
 3123                    } else {
 3124                        head = next_line_start
 3125                    }
 3126
 3127                    if head <= original_range.start {
 3128                        tail = original_range.end;
 3129                    } else {
 3130                        tail = original_range.start;
 3131                    }
 3132                }
 3133                SelectMode::All => {
 3134                    return;
 3135                }
 3136            };
 3137
 3138            if head < tail {
 3139                pending.start = buffer.anchor_before(head);
 3140                pending.end = buffer.anchor_before(tail);
 3141                pending.reversed = true;
 3142            } else {
 3143                pending.start = buffer.anchor_before(tail);
 3144                pending.end = buffer.anchor_before(head);
 3145                pending.reversed = false;
 3146            }
 3147
 3148            self.change_selections(None, cx, |s| {
 3149                s.set_pending(pending, mode);
 3150            });
 3151        } else {
 3152            log::error!("update_selection dispatched with no pending selection");
 3153            return;
 3154        }
 3155
 3156        self.apply_scroll_delta(scroll_delta, cx);
 3157        cx.notify();
 3158    }
 3159
 3160    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 3161        self.columnar_selection_tail.take();
 3162        if self.selections.pending_anchor().is_some() {
 3163            let selections = self.selections.all::<usize>(cx);
 3164            self.change_selections(None, cx, |s| {
 3165                s.select(selections);
 3166                s.clear_pending();
 3167            });
 3168        }
 3169    }
 3170
 3171    fn select_columns(
 3172        &mut self,
 3173        tail: DisplayPoint,
 3174        head: DisplayPoint,
 3175        goal_column: u32,
 3176        display_map: &DisplaySnapshot,
 3177        cx: &mut ViewContext<Self>,
 3178    ) {
 3179        let start_row = cmp::min(tail.row(), head.row());
 3180        let end_row = cmp::max(tail.row(), head.row());
 3181        let start_column = cmp::min(tail.column(), goal_column);
 3182        let end_column = cmp::max(tail.column(), goal_column);
 3183        let reversed = start_column < tail.column();
 3184
 3185        let selection_ranges = (start_row.0..=end_row.0)
 3186            .map(DisplayRow)
 3187            .filter_map(|row| {
 3188                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3189                    let start = display_map
 3190                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3191                        .to_point(display_map);
 3192                    let end = display_map
 3193                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3194                        .to_point(display_map);
 3195                    if reversed {
 3196                        Some(end..start)
 3197                    } else {
 3198                        Some(start..end)
 3199                    }
 3200                } else {
 3201                    None
 3202                }
 3203            })
 3204            .collect::<Vec<_>>();
 3205
 3206        self.change_selections(None, cx, |s| {
 3207            s.select_ranges(selection_ranges);
 3208        });
 3209        cx.notify();
 3210    }
 3211
 3212    pub fn has_pending_nonempty_selection(&self) -> bool {
 3213        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3214            Some(Selection { start, end, .. }) => start != end,
 3215            None => false,
 3216        };
 3217
 3218        pending_nonempty_selection
 3219            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3220    }
 3221
 3222    pub fn has_pending_selection(&self) -> bool {
 3223        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3224    }
 3225
 3226    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3227        if self.clear_expanded_diff_hunks(cx) {
 3228            cx.notify();
 3229            return;
 3230        }
 3231        if self.dismiss_menus_and_popups(true, cx) {
 3232            return;
 3233        }
 3234
 3235        if self.mode == EditorMode::Full
 3236            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3237        {
 3238            return;
 3239        }
 3240
 3241        cx.propagate();
 3242    }
 3243
 3244    pub fn dismiss_menus_and_popups(
 3245        &mut self,
 3246        should_report_inline_completion_event: bool,
 3247        cx: &mut ViewContext<Self>,
 3248    ) -> bool {
 3249        if self.take_rename(false, cx).is_some() {
 3250            return true;
 3251        }
 3252
 3253        if hide_hover(self, cx) {
 3254            return true;
 3255        }
 3256
 3257        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3258            return true;
 3259        }
 3260
 3261        if self.hide_context_menu(cx).is_some() {
 3262            return true;
 3263        }
 3264
 3265        if self.mouse_context_menu.take().is_some() {
 3266            return true;
 3267        }
 3268
 3269        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3270            return true;
 3271        }
 3272
 3273        if self.snippet_stack.pop().is_some() {
 3274            return true;
 3275        }
 3276
 3277        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3278            self.dismiss_diagnostics(cx);
 3279            return true;
 3280        }
 3281
 3282        false
 3283    }
 3284
 3285    fn linked_editing_ranges_for(
 3286        &self,
 3287        selection: Range<text::Anchor>,
 3288        cx: &AppContext,
 3289    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3290        if self.linked_edit_ranges.is_empty() {
 3291            return None;
 3292        }
 3293        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3294            selection.end.buffer_id.and_then(|end_buffer_id| {
 3295                if selection.start.buffer_id != Some(end_buffer_id) {
 3296                    return None;
 3297                }
 3298                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3299                let snapshot = buffer.read(cx).snapshot();
 3300                self.linked_edit_ranges
 3301                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3302                    .map(|ranges| (ranges, snapshot, buffer))
 3303            })?;
 3304        use text::ToOffset as TO;
 3305        // find offset from the start of current range to current cursor position
 3306        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3307
 3308        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3309        let start_difference = start_offset - start_byte_offset;
 3310        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3311        let end_difference = end_offset - start_byte_offset;
 3312        // Current range has associated linked ranges.
 3313        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3314        for range in linked_ranges.iter() {
 3315            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3316            let end_offset = start_offset + end_difference;
 3317            let start_offset = start_offset + start_difference;
 3318            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3319                continue;
 3320            }
 3321            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3322                if s.start.buffer_id != selection.start.buffer_id
 3323                    || s.end.buffer_id != selection.end.buffer_id
 3324                {
 3325                    return false;
 3326                }
 3327                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3328                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3329            }) {
 3330                continue;
 3331            }
 3332            let start = buffer_snapshot.anchor_after(start_offset);
 3333            let end = buffer_snapshot.anchor_after(end_offset);
 3334            linked_edits
 3335                .entry(buffer.clone())
 3336                .or_default()
 3337                .push(start..end);
 3338        }
 3339        Some(linked_edits)
 3340    }
 3341
 3342    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3343        let text: Arc<str> = text.into();
 3344
 3345        if self.read_only(cx) {
 3346            return;
 3347        }
 3348
 3349        let selections = self.selections.all_adjusted(cx);
 3350        let mut bracket_inserted = false;
 3351        let mut edits = Vec::new();
 3352        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3353        let mut new_selections = Vec::with_capacity(selections.len());
 3354        let mut new_autoclose_regions = Vec::new();
 3355        let snapshot = self.buffer.read(cx).read(cx);
 3356
 3357        for (selection, autoclose_region) in
 3358            self.selections_with_autoclose_regions(selections, &snapshot)
 3359        {
 3360            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3361                // Determine if the inserted text matches the opening or closing
 3362                // bracket of any of this language's bracket pairs.
 3363                let mut bracket_pair = None;
 3364                let mut is_bracket_pair_start = false;
 3365                let mut is_bracket_pair_end = false;
 3366                if !text.is_empty() {
 3367                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3368                    //  and they are removing the character that triggered IME popup.
 3369                    for (pair, enabled) in scope.brackets() {
 3370                        if !pair.close && !pair.surround {
 3371                            continue;
 3372                        }
 3373
 3374                        if enabled && pair.start.ends_with(text.as_ref()) {
 3375                            let prefix_len = pair.start.len() - text.len();
 3376                            let preceding_text_matches_prefix = prefix_len == 0
 3377                                || (selection.start.column >= (prefix_len as u32)
 3378                                    && snapshot.contains_str_at(
 3379                                        Point::new(
 3380                                            selection.start.row,
 3381                                            selection.start.column - (prefix_len as u32),
 3382                                        ),
 3383                                        &pair.start[..prefix_len],
 3384                                    ));
 3385                            if preceding_text_matches_prefix {
 3386                                bracket_pair = Some(pair.clone());
 3387                                is_bracket_pair_start = true;
 3388                                break;
 3389                            }
 3390                        }
 3391                        if pair.end.as_str() == text.as_ref() {
 3392                            bracket_pair = Some(pair.clone());
 3393                            is_bracket_pair_end = true;
 3394                            break;
 3395                        }
 3396                    }
 3397                }
 3398
 3399                if let Some(bracket_pair) = bracket_pair {
 3400                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3401                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3402                    let auto_surround =
 3403                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3404                    if selection.is_empty() {
 3405                        if is_bracket_pair_start {
 3406                            // If the inserted text is a suffix of an opening bracket and the
 3407                            // selection is preceded by the rest of the opening bracket, then
 3408                            // insert the closing bracket.
 3409                            let following_text_allows_autoclose = snapshot
 3410                                .chars_at(selection.start)
 3411                                .next()
 3412                                .map_or(true, |c| scope.should_autoclose_before(c));
 3413
 3414                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3415                                && bracket_pair.start.len() == 1
 3416                            {
 3417                                let target = bracket_pair.start.chars().next().unwrap();
 3418                                let current_line_count = snapshot
 3419                                    .reversed_chars_at(selection.start)
 3420                                    .take_while(|&c| c != '\n')
 3421                                    .filter(|&c| c == target)
 3422                                    .count();
 3423                                current_line_count % 2 == 1
 3424                            } else {
 3425                                false
 3426                            };
 3427
 3428                            if autoclose
 3429                                && bracket_pair.close
 3430                                && following_text_allows_autoclose
 3431                                && !is_closing_quote
 3432                            {
 3433                                let anchor = snapshot.anchor_before(selection.end);
 3434                                new_selections.push((selection.map(|_| anchor), text.len()));
 3435                                new_autoclose_regions.push((
 3436                                    anchor,
 3437                                    text.len(),
 3438                                    selection.id,
 3439                                    bracket_pair.clone(),
 3440                                ));
 3441                                edits.push((
 3442                                    selection.range(),
 3443                                    format!("{}{}", text, bracket_pair.end).into(),
 3444                                ));
 3445                                bracket_inserted = true;
 3446                                continue;
 3447                            }
 3448                        }
 3449
 3450                        if let Some(region) = autoclose_region {
 3451                            // If the selection is followed by an auto-inserted closing bracket,
 3452                            // then don't insert that closing bracket again; just move the selection
 3453                            // past the closing bracket.
 3454                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3455                                && text.as_ref() == region.pair.end.as_str();
 3456                            if should_skip {
 3457                                let anchor = snapshot.anchor_after(selection.end);
 3458                                new_selections
 3459                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3460                                continue;
 3461                            }
 3462                        }
 3463
 3464                        let always_treat_brackets_as_autoclosed = snapshot
 3465                            .settings_at(selection.start, cx)
 3466                            .always_treat_brackets_as_autoclosed;
 3467                        if always_treat_brackets_as_autoclosed
 3468                            && is_bracket_pair_end
 3469                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3470                        {
 3471                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3472                            // and the inserted text is a closing bracket and the selection is followed
 3473                            // by the closing bracket then move the selection past the closing bracket.
 3474                            let anchor = snapshot.anchor_after(selection.end);
 3475                            new_selections.push((selection.map(|_| anchor), text.len()));
 3476                            continue;
 3477                        }
 3478                    }
 3479                    // If an opening bracket is 1 character long and is typed while
 3480                    // text is selected, then surround that text with the bracket pair.
 3481                    else if auto_surround
 3482                        && bracket_pair.surround
 3483                        && is_bracket_pair_start
 3484                        && bracket_pair.start.chars().count() == 1
 3485                    {
 3486                        edits.push((selection.start..selection.start, text.clone()));
 3487                        edits.push((
 3488                            selection.end..selection.end,
 3489                            bracket_pair.end.as_str().into(),
 3490                        ));
 3491                        bracket_inserted = true;
 3492                        new_selections.push((
 3493                            Selection {
 3494                                id: selection.id,
 3495                                start: snapshot.anchor_after(selection.start),
 3496                                end: snapshot.anchor_before(selection.end),
 3497                                reversed: selection.reversed,
 3498                                goal: selection.goal,
 3499                            },
 3500                            0,
 3501                        ));
 3502                        continue;
 3503                    }
 3504                }
 3505            }
 3506
 3507            if self.auto_replace_emoji_shortcode
 3508                && selection.is_empty()
 3509                && text.as_ref().ends_with(':')
 3510            {
 3511                if let Some(possible_emoji_short_code) =
 3512                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3513                {
 3514                    if !possible_emoji_short_code.is_empty() {
 3515                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3516                            let emoji_shortcode_start = Point::new(
 3517                                selection.start.row,
 3518                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3519                            );
 3520
 3521                            // Remove shortcode from buffer
 3522                            edits.push((
 3523                                emoji_shortcode_start..selection.start,
 3524                                "".to_string().into(),
 3525                            ));
 3526                            new_selections.push((
 3527                                Selection {
 3528                                    id: selection.id,
 3529                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3530                                    end: snapshot.anchor_before(selection.start),
 3531                                    reversed: selection.reversed,
 3532                                    goal: selection.goal,
 3533                                },
 3534                                0,
 3535                            ));
 3536
 3537                            // Insert emoji
 3538                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3539                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3540                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3541
 3542                            continue;
 3543                        }
 3544                    }
 3545                }
 3546            }
 3547
 3548            // If not handling any auto-close operation, then just replace the selected
 3549            // text with the given input and move the selection to the end of the
 3550            // newly inserted text.
 3551            let anchor = snapshot.anchor_after(selection.end);
 3552            if !self.linked_edit_ranges.is_empty() {
 3553                let start_anchor = snapshot.anchor_before(selection.start);
 3554
 3555                let is_word_char = text.chars().next().map_or(true, |char| {
 3556                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3557                    classifier.is_word(char)
 3558                });
 3559
 3560                if is_word_char {
 3561                    if let Some(ranges) = self
 3562                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3563                    {
 3564                        for (buffer, edits) in ranges {
 3565                            linked_edits
 3566                                .entry(buffer.clone())
 3567                                .or_default()
 3568                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3569                        }
 3570                    }
 3571                }
 3572            }
 3573
 3574            new_selections.push((selection.map(|_| anchor), 0));
 3575            edits.push((selection.start..selection.end, text.clone()));
 3576        }
 3577
 3578        drop(snapshot);
 3579
 3580        self.transact(cx, |this, cx| {
 3581            this.buffer.update(cx, |buffer, cx| {
 3582                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3583            });
 3584            for (buffer, edits) in linked_edits {
 3585                buffer.update(cx, |buffer, cx| {
 3586                    let snapshot = buffer.snapshot();
 3587                    let edits = edits
 3588                        .into_iter()
 3589                        .map(|(range, text)| {
 3590                            use text::ToPoint as TP;
 3591                            let end_point = TP::to_point(&range.end, &snapshot);
 3592                            let start_point = TP::to_point(&range.start, &snapshot);
 3593                            (start_point..end_point, text)
 3594                        })
 3595                        .sorted_by_key(|(range, _)| range.start)
 3596                        .collect::<Vec<_>>();
 3597                    buffer.edit(edits, None, cx);
 3598                })
 3599            }
 3600            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3601            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3602            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3603            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3604                .zip(new_selection_deltas)
 3605                .map(|(selection, delta)| Selection {
 3606                    id: selection.id,
 3607                    start: selection.start + delta,
 3608                    end: selection.end + delta,
 3609                    reversed: selection.reversed,
 3610                    goal: SelectionGoal::None,
 3611                })
 3612                .collect::<Vec<_>>();
 3613
 3614            let mut i = 0;
 3615            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3616                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3617                let start = map.buffer_snapshot.anchor_before(position);
 3618                let end = map.buffer_snapshot.anchor_after(position);
 3619                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3620                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3621                        Ordering::Less => i += 1,
 3622                        Ordering::Greater => break,
 3623                        Ordering::Equal => {
 3624                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3625                                Ordering::Less => i += 1,
 3626                                Ordering::Equal => break,
 3627                                Ordering::Greater => break,
 3628                            }
 3629                        }
 3630                    }
 3631                }
 3632                this.autoclose_regions.insert(
 3633                    i,
 3634                    AutocloseRegion {
 3635                        selection_id,
 3636                        range: start..end,
 3637                        pair,
 3638                    },
 3639                );
 3640            }
 3641
 3642            let had_active_inline_completion = this.has_active_inline_completion();
 3643            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3644                s.select(new_selections)
 3645            });
 3646
 3647            if !bracket_inserted {
 3648                if let Some(on_type_format_task) =
 3649                    this.trigger_on_type_formatting(text.to_string(), cx)
 3650                {
 3651                    on_type_format_task.detach_and_log_err(cx);
 3652                }
 3653            }
 3654
 3655            let editor_settings = EditorSettings::get_global(cx);
 3656            if bracket_inserted
 3657                && (editor_settings.auto_signature_help
 3658                    || editor_settings.show_signature_help_after_edits)
 3659            {
 3660                this.show_signature_help(&ShowSignatureHelp, cx);
 3661            }
 3662
 3663            let trigger_in_words = !had_active_inline_completion;
 3664            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3665            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3666            this.refresh_inline_completion(true, false, cx);
 3667        });
 3668    }
 3669
 3670    fn find_possible_emoji_shortcode_at_position(
 3671        snapshot: &MultiBufferSnapshot,
 3672        position: Point,
 3673    ) -> Option<String> {
 3674        let mut chars = Vec::new();
 3675        let mut found_colon = false;
 3676        for char in snapshot.reversed_chars_at(position).take(100) {
 3677            // Found a possible emoji shortcode in the middle of the buffer
 3678            if found_colon {
 3679                if char.is_whitespace() {
 3680                    chars.reverse();
 3681                    return Some(chars.iter().collect());
 3682                }
 3683                // If the previous character is not a whitespace, we are in the middle of a word
 3684                // and we only want to complete the shortcode if the word is made up of other emojis
 3685                let mut containing_word = String::new();
 3686                for ch in snapshot
 3687                    .reversed_chars_at(position)
 3688                    .skip(chars.len() + 1)
 3689                    .take(100)
 3690                {
 3691                    if ch.is_whitespace() {
 3692                        break;
 3693                    }
 3694                    containing_word.push(ch);
 3695                }
 3696                let containing_word = containing_word.chars().rev().collect::<String>();
 3697                if util::word_consists_of_emojis(containing_word.as_str()) {
 3698                    chars.reverse();
 3699                    return Some(chars.iter().collect());
 3700                }
 3701            }
 3702
 3703            if char.is_whitespace() || !char.is_ascii() {
 3704                return None;
 3705            }
 3706            if char == ':' {
 3707                found_colon = true;
 3708            } else {
 3709                chars.push(char);
 3710            }
 3711        }
 3712        // Found a possible emoji shortcode at the beginning of the buffer
 3713        chars.reverse();
 3714        Some(chars.iter().collect())
 3715    }
 3716
 3717    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3718        self.transact(cx, |this, cx| {
 3719            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3720                let selections = this.selections.all::<usize>(cx);
 3721                let multi_buffer = this.buffer.read(cx);
 3722                let buffer = multi_buffer.snapshot(cx);
 3723                selections
 3724                    .iter()
 3725                    .map(|selection| {
 3726                        let start_point = selection.start.to_point(&buffer);
 3727                        let mut indent =
 3728                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3729                        indent.len = cmp::min(indent.len, start_point.column);
 3730                        let start = selection.start;
 3731                        let end = selection.end;
 3732                        let selection_is_empty = start == end;
 3733                        let language_scope = buffer.language_scope_at(start);
 3734                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3735                            &language_scope
 3736                        {
 3737                            let leading_whitespace_len = buffer
 3738                                .reversed_chars_at(start)
 3739                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3740                                .map(|c| c.len_utf8())
 3741                                .sum::<usize>();
 3742
 3743                            let trailing_whitespace_len = buffer
 3744                                .chars_at(end)
 3745                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3746                                .map(|c| c.len_utf8())
 3747                                .sum::<usize>();
 3748
 3749                            let insert_extra_newline =
 3750                                language.brackets().any(|(pair, enabled)| {
 3751                                    let pair_start = pair.start.trim_end();
 3752                                    let pair_end = pair.end.trim_start();
 3753
 3754                                    enabled
 3755                                        && pair.newline
 3756                                        && buffer.contains_str_at(
 3757                                            end + trailing_whitespace_len,
 3758                                            pair_end,
 3759                                        )
 3760                                        && buffer.contains_str_at(
 3761                                            (start - leading_whitespace_len)
 3762                                                .saturating_sub(pair_start.len()),
 3763                                            pair_start,
 3764                                        )
 3765                                });
 3766
 3767                            // Comment extension on newline is allowed only for cursor selections
 3768                            let comment_delimiter = maybe!({
 3769                                if !selection_is_empty {
 3770                                    return None;
 3771                                }
 3772
 3773                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3774                                    return None;
 3775                                }
 3776
 3777                                let delimiters = language.line_comment_prefixes();
 3778                                let max_len_of_delimiter =
 3779                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3780                                let (snapshot, range) =
 3781                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3782
 3783                                let mut index_of_first_non_whitespace = 0;
 3784                                let comment_candidate = snapshot
 3785                                    .chars_for_range(range)
 3786                                    .skip_while(|c| {
 3787                                        let should_skip = c.is_whitespace();
 3788                                        if should_skip {
 3789                                            index_of_first_non_whitespace += 1;
 3790                                        }
 3791                                        should_skip
 3792                                    })
 3793                                    .take(max_len_of_delimiter)
 3794                                    .collect::<String>();
 3795                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3796                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3797                                })?;
 3798                                let cursor_is_placed_after_comment_marker =
 3799                                    index_of_first_non_whitespace + comment_prefix.len()
 3800                                        <= start_point.column as usize;
 3801                                if cursor_is_placed_after_comment_marker {
 3802                                    Some(comment_prefix.clone())
 3803                                } else {
 3804                                    None
 3805                                }
 3806                            });
 3807                            (comment_delimiter, insert_extra_newline)
 3808                        } else {
 3809                            (None, false)
 3810                        };
 3811
 3812                        let capacity_for_delimiter = comment_delimiter
 3813                            .as_deref()
 3814                            .map(str::len)
 3815                            .unwrap_or_default();
 3816                        let mut new_text =
 3817                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3818                        new_text.push('\n');
 3819                        new_text.extend(indent.chars());
 3820                        if let Some(delimiter) = &comment_delimiter {
 3821                            new_text.push_str(delimiter);
 3822                        }
 3823                        if insert_extra_newline {
 3824                            new_text = new_text.repeat(2);
 3825                        }
 3826
 3827                        let anchor = buffer.anchor_after(end);
 3828                        let new_selection = selection.map(|_| anchor);
 3829                        (
 3830                            (start..end, new_text),
 3831                            (insert_extra_newline, new_selection),
 3832                        )
 3833                    })
 3834                    .unzip()
 3835            };
 3836
 3837            this.edit_with_autoindent(edits, cx);
 3838            let buffer = this.buffer.read(cx).snapshot(cx);
 3839            let new_selections = selection_fixup_info
 3840                .into_iter()
 3841                .map(|(extra_newline_inserted, new_selection)| {
 3842                    let mut cursor = new_selection.end.to_point(&buffer);
 3843                    if extra_newline_inserted {
 3844                        cursor.row -= 1;
 3845                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3846                    }
 3847                    new_selection.map(|_| cursor)
 3848                })
 3849                .collect();
 3850
 3851            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3852            this.refresh_inline_completion(true, false, cx);
 3853        });
 3854    }
 3855
 3856    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3857        let buffer = self.buffer.read(cx);
 3858        let snapshot = buffer.snapshot(cx);
 3859
 3860        let mut edits = Vec::new();
 3861        let mut rows = Vec::new();
 3862
 3863        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3864            let cursor = selection.head();
 3865            let row = cursor.row;
 3866
 3867            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3868
 3869            let newline = "\n".to_string();
 3870            edits.push((start_of_line..start_of_line, newline));
 3871
 3872            rows.push(row + rows_inserted as u32);
 3873        }
 3874
 3875        self.transact(cx, |editor, cx| {
 3876            editor.edit(edits, cx);
 3877
 3878            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3879                let mut index = 0;
 3880                s.move_cursors_with(|map, _, _| {
 3881                    let row = rows[index];
 3882                    index += 1;
 3883
 3884                    let point = Point::new(row, 0);
 3885                    let boundary = map.next_line_boundary(point).1;
 3886                    let clipped = map.clip_point(boundary, Bias::Left);
 3887
 3888                    (clipped, SelectionGoal::None)
 3889                });
 3890            });
 3891
 3892            let mut indent_edits = Vec::new();
 3893            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3894            for row in rows {
 3895                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3896                for (row, indent) in indents {
 3897                    if indent.len == 0 {
 3898                        continue;
 3899                    }
 3900
 3901                    let text = match indent.kind {
 3902                        IndentKind::Space => " ".repeat(indent.len as usize),
 3903                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3904                    };
 3905                    let point = Point::new(row.0, 0);
 3906                    indent_edits.push((point..point, text));
 3907                }
 3908            }
 3909            editor.edit(indent_edits, cx);
 3910        });
 3911    }
 3912
 3913    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3914        let buffer = self.buffer.read(cx);
 3915        let snapshot = buffer.snapshot(cx);
 3916
 3917        let mut edits = Vec::new();
 3918        let mut rows = Vec::new();
 3919        let mut rows_inserted = 0;
 3920
 3921        for selection in self.selections.all_adjusted(cx) {
 3922            let cursor = selection.head();
 3923            let row = cursor.row;
 3924
 3925            let point = Point::new(row + 1, 0);
 3926            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3927
 3928            let newline = "\n".to_string();
 3929            edits.push((start_of_line..start_of_line, newline));
 3930
 3931            rows_inserted += 1;
 3932            rows.push(row + rows_inserted);
 3933        }
 3934
 3935        self.transact(cx, |editor, cx| {
 3936            editor.edit(edits, cx);
 3937
 3938            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3939                let mut index = 0;
 3940                s.move_cursors_with(|map, _, _| {
 3941                    let row = rows[index];
 3942                    index += 1;
 3943
 3944                    let point = Point::new(row, 0);
 3945                    let boundary = map.next_line_boundary(point).1;
 3946                    let clipped = map.clip_point(boundary, Bias::Left);
 3947
 3948                    (clipped, SelectionGoal::None)
 3949                });
 3950            });
 3951
 3952            let mut indent_edits = Vec::new();
 3953            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3954            for row in rows {
 3955                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3956                for (row, indent) in indents {
 3957                    if indent.len == 0 {
 3958                        continue;
 3959                    }
 3960
 3961                    let text = match indent.kind {
 3962                        IndentKind::Space => " ".repeat(indent.len as usize),
 3963                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3964                    };
 3965                    let point = Point::new(row.0, 0);
 3966                    indent_edits.push((point..point, text));
 3967                }
 3968            }
 3969            editor.edit(indent_edits, cx);
 3970        });
 3971    }
 3972
 3973    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3974        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3975            original_indent_columns: Vec::new(),
 3976        });
 3977        self.insert_with_autoindent_mode(text, autoindent, cx);
 3978    }
 3979
 3980    fn insert_with_autoindent_mode(
 3981        &mut self,
 3982        text: &str,
 3983        autoindent_mode: Option<AutoindentMode>,
 3984        cx: &mut ViewContext<Self>,
 3985    ) {
 3986        if self.read_only(cx) {
 3987            return;
 3988        }
 3989
 3990        let text: Arc<str> = text.into();
 3991        self.transact(cx, |this, cx| {
 3992            let old_selections = this.selections.all_adjusted(cx);
 3993            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3994                let anchors = {
 3995                    let snapshot = buffer.read(cx);
 3996                    old_selections
 3997                        .iter()
 3998                        .map(|s| {
 3999                            let anchor = snapshot.anchor_after(s.head());
 4000                            s.map(|_| anchor)
 4001                        })
 4002                        .collect::<Vec<_>>()
 4003                };
 4004                buffer.edit(
 4005                    old_selections
 4006                        .iter()
 4007                        .map(|s| (s.start..s.end, text.clone())),
 4008                    autoindent_mode,
 4009                    cx,
 4010                );
 4011                anchors
 4012            });
 4013
 4014            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4015                s.select_anchors(selection_anchors);
 4016            })
 4017        });
 4018    }
 4019
 4020    fn trigger_completion_on_input(
 4021        &mut self,
 4022        text: &str,
 4023        trigger_in_words: bool,
 4024        cx: &mut ViewContext<Self>,
 4025    ) {
 4026        if self.is_completion_trigger(text, trigger_in_words, cx) {
 4027            self.show_completions(
 4028                &ShowCompletions {
 4029                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 4030                },
 4031                cx,
 4032            );
 4033        } else {
 4034            self.hide_context_menu(cx);
 4035        }
 4036    }
 4037
 4038    fn is_completion_trigger(
 4039        &self,
 4040        text: &str,
 4041        trigger_in_words: bool,
 4042        cx: &mut ViewContext<Self>,
 4043    ) -> bool {
 4044        let position = self.selections.newest_anchor().head();
 4045        let multibuffer = self.buffer.read(cx);
 4046        let Some(buffer) = position
 4047            .buffer_id
 4048            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4049        else {
 4050            return false;
 4051        };
 4052
 4053        if let Some(completion_provider) = &self.completion_provider {
 4054            completion_provider.is_completion_trigger(
 4055                &buffer,
 4056                position.text_anchor,
 4057                text,
 4058                trigger_in_words,
 4059                cx,
 4060            )
 4061        } else {
 4062            false
 4063        }
 4064    }
 4065
 4066    /// If any empty selections is touching the start of its innermost containing autoclose
 4067    /// region, expand it to select the brackets.
 4068    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 4069        let selections = self.selections.all::<usize>(cx);
 4070        let buffer = self.buffer.read(cx).read(cx);
 4071        let new_selections = self
 4072            .selections_with_autoclose_regions(selections, &buffer)
 4073            .map(|(mut selection, region)| {
 4074                if !selection.is_empty() {
 4075                    return selection;
 4076                }
 4077
 4078                if let Some(region) = region {
 4079                    let mut range = region.range.to_offset(&buffer);
 4080                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4081                        range.start -= region.pair.start.len();
 4082                        if buffer.contains_str_at(range.start, &region.pair.start)
 4083                            && buffer.contains_str_at(range.end, &region.pair.end)
 4084                        {
 4085                            range.end += region.pair.end.len();
 4086                            selection.start = range.start;
 4087                            selection.end = range.end;
 4088
 4089                            return selection;
 4090                        }
 4091                    }
 4092                }
 4093
 4094                let always_treat_brackets_as_autoclosed = buffer
 4095                    .settings_at(selection.start, cx)
 4096                    .always_treat_brackets_as_autoclosed;
 4097
 4098                if !always_treat_brackets_as_autoclosed {
 4099                    return selection;
 4100                }
 4101
 4102                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4103                    for (pair, enabled) in scope.brackets() {
 4104                        if !enabled || !pair.close {
 4105                            continue;
 4106                        }
 4107
 4108                        if buffer.contains_str_at(selection.start, &pair.end) {
 4109                            let pair_start_len = pair.start.len();
 4110                            if buffer.contains_str_at(
 4111                                selection.start.saturating_sub(pair_start_len),
 4112                                &pair.start,
 4113                            ) {
 4114                                selection.start -= pair_start_len;
 4115                                selection.end += pair.end.len();
 4116
 4117                                return selection;
 4118                            }
 4119                        }
 4120                    }
 4121                }
 4122
 4123                selection
 4124            })
 4125            .collect();
 4126
 4127        drop(buffer);
 4128        self.change_selections(None, cx, |selections| selections.select(new_selections));
 4129    }
 4130
 4131    /// Iterate the given selections, and for each one, find the smallest surrounding
 4132    /// autoclose region. This uses the ordering of the selections and the autoclose
 4133    /// regions to avoid repeated comparisons.
 4134    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4135        &'a self,
 4136        selections: impl IntoIterator<Item = Selection<D>>,
 4137        buffer: &'a MultiBufferSnapshot,
 4138    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4139        let mut i = 0;
 4140        let mut regions = self.autoclose_regions.as_slice();
 4141        selections.into_iter().map(move |selection| {
 4142            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4143
 4144            let mut enclosing = None;
 4145            while let Some(pair_state) = regions.get(i) {
 4146                if pair_state.range.end.to_offset(buffer) < range.start {
 4147                    regions = &regions[i + 1..];
 4148                    i = 0;
 4149                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4150                    break;
 4151                } else {
 4152                    if pair_state.selection_id == selection.id {
 4153                        enclosing = Some(pair_state);
 4154                    }
 4155                    i += 1;
 4156                }
 4157            }
 4158
 4159            (selection, enclosing)
 4160        })
 4161    }
 4162
 4163    /// Remove any autoclose regions that no longer contain their selection.
 4164    fn invalidate_autoclose_regions(
 4165        &mut self,
 4166        mut selections: &[Selection<Anchor>],
 4167        buffer: &MultiBufferSnapshot,
 4168    ) {
 4169        self.autoclose_regions.retain(|state| {
 4170            let mut i = 0;
 4171            while let Some(selection) = selections.get(i) {
 4172                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4173                    selections = &selections[1..];
 4174                    continue;
 4175                }
 4176                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4177                    break;
 4178                }
 4179                if selection.id == state.selection_id {
 4180                    return true;
 4181                } else {
 4182                    i += 1;
 4183                }
 4184            }
 4185            false
 4186        });
 4187    }
 4188
 4189    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4190        let offset = position.to_offset(buffer);
 4191        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4192        if offset > word_range.start && kind == Some(CharKind::Word) {
 4193            Some(
 4194                buffer
 4195                    .text_for_range(word_range.start..offset)
 4196                    .collect::<String>(),
 4197            )
 4198        } else {
 4199            None
 4200        }
 4201    }
 4202
 4203    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 4204        self.refresh_inlay_hints(
 4205            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 4206            cx,
 4207        );
 4208    }
 4209
 4210    pub fn inlay_hints_enabled(&self) -> bool {
 4211        self.inlay_hint_cache.enabled
 4212    }
 4213
 4214    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 4215        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4216            return;
 4217        }
 4218
 4219        let reason_description = reason.description();
 4220        let ignore_debounce = matches!(
 4221            reason,
 4222            InlayHintRefreshReason::SettingsChange(_)
 4223                | InlayHintRefreshReason::Toggle(_)
 4224                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4225        );
 4226        let (invalidate_cache, required_languages) = match reason {
 4227            InlayHintRefreshReason::Toggle(enabled) => {
 4228                self.inlay_hint_cache.enabled = enabled;
 4229                if enabled {
 4230                    (InvalidationStrategy::RefreshRequested, None)
 4231                } else {
 4232                    self.inlay_hint_cache.clear();
 4233                    self.splice_inlays(
 4234                        self.visible_inlay_hints(cx)
 4235                            .iter()
 4236                            .map(|inlay| inlay.id)
 4237                            .collect(),
 4238                        Vec::new(),
 4239                        cx,
 4240                    );
 4241                    return;
 4242                }
 4243            }
 4244            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4245                match self.inlay_hint_cache.update_settings(
 4246                    &self.buffer,
 4247                    new_settings,
 4248                    self.visible_inlay_hints(cx),
 4249                    cx,
 4250                ) {
 4251                    ControlFlow::Break(Some(InlaySplice {
 4252                        to_remove,
 4253                        to_insert,
 4254                    })) => {
 4255                        self.splice_inlays(to_remove, to_insert, cx);
 4256                        return;
 4257                    }
 4258                    ControlFlow::Break(None) => return,
 4259                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4260                }
 4261            }
 4262            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4263                if let Some(InlaySplice {
 4264                    to_remove,
 4265                    to_insert,
 4266                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4267                {
 4268                    self.splice_inlays(to_remove, to_insert, cx);
 4269                }
 4270                return;
 4271            }
 4272            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4273            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4274                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4275            }
 4276            InlayHintRefreshReason::RefreshRequested => {
 4277                (InvalidationStrategy::RefreshRequested, None)
 4278            }
 4279        };
 4280
 4281        if let Some(InlaySplice {
 4282            to_remove,
 4283            to_insert,
 4284        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4285            reason_description,
 4286            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4287            invalidate_cache,
 4288            ignore_debounce,
 4289            cx,
 4290        ) {
 4291            self.splice_inlays(to_remove, to_insert, cx);
 4292        }
 4293    }
 4294
 4295    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4296        self.display_map
 4297            .read(cx)
 4298            .current_inlays()
 4299            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4300            .cloned()
 4301            .collect()
 4302    }
 4303
 4304    pub fn excerpts_for_inlay_hints_query(
 4305        &self,
 4306        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4307        cx: &mut ViewContext<Editor>,
 4308    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4309        let Some(project) = self.project.as_ref() else {
 4310            return HashMap::default();
 4311        };
 4312        let project = project.read(cx);
 4313        let multi_buffer = self.buffer().read(cx);
 4314        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4315        let multi_buffer_visible_start = self
 4316            .scroll_manager
 4317            .anchor()
 4318            .anchor
 4319            .to_point(&multi_buffer_snapshot);
 4320        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4321            multi_buffer_visible_start
 4322                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4323            Bias::Left,
 4324        );
 4325        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4326        multi_buffer
 4327            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4328            .into_iter()
 4329            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4330            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4331                let buffer = buffer_handle.read(cx);
 4332                let buffer_file = project::File::from_dyn(buffer.file())?;
 4333                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4334                let worktree_entry = buffer_worktree
 4335                    .read(cx)
 4336                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4337                if worktree_entry.is_ignored {
 4338                    return None;
 4339                }
 4340
 4341                let language = buffer.language()?;
 4342                if let Some(restrict_to_languages) = restrict_to_languages {
 4343                    if !restrict_to_languages.contains(language) {
 4344                        return None;
 4345                    }
 4346                }
 4347                Some((
 4348                    excerpt_id,
 4349                    (
 4350                        buffer_handle,
 4351                        buffer.version().clone(),
 4352                        excerpt_visible_range,
 4353                    ),
 4354                ))
 4355            })
 4356            .collect()
 4357    }
 4358
 4359    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4360        TextLayoutDetails {
 4361            text_system: cx.text_system().clone(),
 4362            editor_style: self.style.clone().unwrap(),
 4363            rem_size: cx.rem_size(),
 4364            scroll_anchor: self.scroll_manager.anchor(),
 4365            visible_rows: self.visible_line_count(),
 4366            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4367        }
 4368    }
 4369
 4370    fn splice_inlays(
 4371        &self,
 4372        to_remove: Vec<InlayId>,
 4373        to_insert: Vec<Inlay>,
 4374        cx: &mut ViewContext<Self>,
 4375    ) {
 4376        self.display_map.update(cx, |display_map, cx| {
 4377            display_map.splice_inlays(to_remove, to_insert, cx)
 4378        });
 4379        cx.notify();
 4380    }
 4381
 4382    fn trigger_on_type_formatting(
 4383        &self,
 4384        input: String,
 4385        cx: &mut ViewContext<Self>,
 4386    ) -> Option<Task<Result<()>>> {
 4387        if input.len() != 1 {
 4388            return None;
 4389        }
 4390
 4391        let project = self.project.as_ref()?;
 4392        let position = self.selections.newest_anchor().head();
 4393        let (buffer, buffer_position) = self
 4394            .buffer
 4395            .read(cx)
 4396            .text_anchor_for_position(position, cx)?;
 4397
 4398        let settings = language_settings::language_settings(
 4399            buffer
 4400                .read(cx)
 4401                .language_at(buffer_position)
 4402                .map(|l| l.name()),
 4403            buffer.read(cx).file(),
 4404            cx,
 4405        );
 4406        if !settings.use_on_type_format {
 4407            return None;
 4408        }
 4409
 4410        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4411        // hence we do LSP request & edit on host side only — add formats to host's history.
 4412        let push_to_lsp_host_history = true;
 4413        // If this is not the host, append its history with new edits.
 4414        let push_to_client_history = project.read(cx).is_via_collab();
 4415
 4416        let on_type_formatting = project.update(cx, |project, cx| {
 4417            project.on_type_format(
 4418                buffer.clone(),
 4419                buffer_position,
 4420                input,
 4421                push_to_lsp_host_history,
 4422                cx,
 4423            )
 4424        });
 4425        Some(cx.spawn(|editor, mut cx| async move {
 4426            if let Some(transaction) = on_type_formatting.await? {
 4427                if push_to_client_history {
 4428                    buffer
 4429                        .update(&mut cx, |buffer, _| {
 4430                            buffer.push_transaction(transaction, Instant::now());
 4431                        })
 4432                        .ok();
 4433                }
 4434                editor.update(&mut cx, |editor, cx| {
 4435                    editor.refresh_document_highlights(cx);
 4436                })?;
 4437            }
 4438            Ok(())
 4439        }))
 4440    }
 4441
 4442    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4443        if self.pending_rename.is_some() {
 4444            return;
 4445        }
 4446
 4447        let Some(provider) = self.completion_provider.as_ref() else {
 4448            return;
 4449        };
 4450
 4451        if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
 4452            return;
 4453        }
 4454
 4455        let position = self.selections.newest_anchor().head();
 4456        let (buffer, buffer_position) =
 4457            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4458                output
 4459            } else {
 4460                return;
 4461            };
 4462
 4463        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4464        let (is_followup_invoke, aside_was_displayed) = match self.context_menu.read().deref() {
 4465            Some(ContextMenu::Completions(menu)) => (true, menu.aside_was_displayed.get()),
 4466            _ => (false, false),
 4467        };
 4468        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4469            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4470            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4471                CompletionTriggerKind::TRIGGER_CHARACTER
 4472            }
 4473
 4474            _ => CompletionTriggerKind::INVOKED,
 4475        };
 4476        let completion_context = CompletionContext {
 4477            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4478                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4479                    Some(String::from(trigger))
 4480                } else {
 4481                    None
 4482                }
 4483            }),
 4484            trigger_kind,
 4485        };
 4486        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4487        let sort_completions = provider.sort_completions();
 4488
 4489        let id = post_inc(&mut self.next_completion_id);
 4490        let task = cx.spawn(|editor, mut cx| {
 4491            async move {
 4492                editor.update(&mut cx, |this, _| {
 4493                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4494                })?;
 4495                let completions = completions.await.log_err();
 4496                let menu = if let Some(completions) = completions {
 4497                    let mut menu = CompletionsMenu::new(
 4498                        id,
 4499                        sort_completions,
 4500                        position,
 4501                        buffer.clone(),
 4502                        completions.into(),
 4503                        aside_was_displayed,
 4504                    );
 4505                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4506                        .await;
 4507
 4508                    if menu.matches.is_empty() {
 4509                        None
 4510                    } else {
 4511                        Some(menu)
 4512                    }
 4513                } else {
 4514                    None
 4515                };
 4516
 4517                editor.update(&mut cx, |editor, cx| {
 4518                    let mut context_menu = editor.context_menu.write();
 4519                    match context_menu.as_ref() {
 4520                        None => {}
 4521
 4522                        Some(ContextMenu::Completions(prev_menu)) => {
 4523                            if prev_menu.id > id {
 4524                                return;
 4525                            }
 4526                        }
 4527
 4528                        _ => return,
 4529                    }
 4530
 4531                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 4532                        let mut menu = menu.unwrap();
 4533                        menu.resolve_selected_completion(editor.completion_provider.as_deref(), cx);
 4534                        *context_menu = Some(ContextMenu::Completions(menu));
 4535                        drop(context_menu);
 4536                        editor.discard_inline_completion(false, cx);
 4537                        cx.notify();
 4538                    } else if editor.completion_tasks.len() <= 1 {
 4539                        // If there are no more completion tasks and the last menu was
 4540                        // empty, we should hide it. If it was already hidden, we should
 4541                        // also show the copilot completion when available.
 4542                        drop(context_menu);
 4543                        if editor.hide_context_menu(cx).is_none() {
 4544                            editor.update_visible_inline_completion(cx);
 4545                        }
 4546                    }
 4547                })?;
 4548
 4549                Ok::<_, anyhow::Error>(())
 4550            }
 4551            .log_err()
 4552        });
 4553
 4554        self.completion_tasks.push((id, task));
 4555    }
 4556
 4557    pub fn confirm_completion(
 4558        &mut self,
 4559        action: &ConfirmCompletion,
 4560        cx: &mut ViewContext<Self>,
 4561    ) -> Option<Task<Result<()>>> {
 4562        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4563    }
 4564
 4565    pub fn compose_completion(
 4566        &mut self,
 4567        action: &ComposeCompletion,
 4568        cx: &mut ViewContext<Self>,
 4569    ) -> Option<Task<Result<()>>> {
 4570        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4571    }
 4572
 4573    fn do_completion(
 4574        &mut self,
 4575        item_ix: Option<usize>,
 4576        intent: CompletionIntent,
 4577        cx: &mut ViewContext<Editor>,
 4578    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4579        use language::ToOffset as _;
 4580
 4581        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4582            menu
 4583        } else {
 4584            return None;
 4585        };
 4586
 4587        let mat = completions_menu
 4588            .matches
 4589            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4590        let buffer_handle = completions_menu.buffer;
 4591        let completions = completions_menu.completions.read();
 4592        let completion = completions.get(mat.candidate_id)?;
 4593        cx.stop_propagation();
 4594
 4595        let snippet;
 4596        let text;
 4597
 4598        if completion.is_snippet() {
 4599            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4600            text = snippet.as_ref().unwrap().text.clone();
 4601        } else {
 4602            snippet = None;
 4603            text = completion.new_text.clone();
 4604        };
 4605        let selections = self.selections.all::<usize>(cx);
 4606        let buffer = buffer_handle.read(cx);
 4607        let old_range = completion.old_range.to_offset(buffer);
 4608        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4609
 4610        let newest_selection = self.selections.newest_anchor();
 4611        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4612            return None;
 4613        }
 4614
 4615        let lookbehind = newest_selection
 4616            .start
 4617            .text_anchor
 4618            .to_offset(buffer)
 4619            .saturating_sub(old_range.start);
 4620        let lookahead = old_range
 4621            .end
 4622            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4623        let mut common_prefix_len = old_text
 4624            .bytes()
 4625            .zip(text.bytes())
 4626            .take_while(|(a, b)| a == b)
 4627            .count();
 4628
 4629        let snapshot = self.buffer.read(cx).snapshot(cx);
 4630        let mut range_to_replace: Option<Range<isize>> = None;
 4631        let mut ranges = Vec::new();
 4632        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4633        for selection in &selections {
 4634            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4635                let start = selection.start.saturating_sub(lookbehind);
 4636                let end = selection.end + lookahead;
 4637                if selection.id == newest_selection.id {
 4638                    range_to_replace = Some(
 4639                        ((start + common_prefix_len) as isize - selection.start as isize)
 4640                            ..(end as isize - selection.start as isize),
 4641                    );
 4642                }
 4643                ranges.push(start + common_prefix_len..end);
 4644            } else {
 4645                common_prefix_len = 0;
 4646                ranges.clear();
 4647                ranges.extend(selections.iter().map(|s| {
 4648                    if s.id == newest_selection.id {
 4649                        range_to_replace = Some(
 4650                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4651                                - selection.start as isize
 4652                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4653                                    - selection.start as isize,
 4654                        );
 4655                        old_range.clone()
 4656                    } else {
 4657                        s.start..s.end
 4658                    }
 4659                }));
 4660                break;
 4661            }
 4662            if !self.linked_edit_ranges.is_empty() {
 4663                let start_anchor = snapshot.anchor_before(selection.head());
 4664                let end_anchor = snapshot.anchor_after(selection.tail());
 4665                if let Some(ranges) = self
 4666                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4667                {
 4668                    for (buffer, edits) in ranges {
 4669                        linked_edits.entry(buffer.clone()).or_default().extend(
 4670                            edits
 4671                                .into_iter()
 4672                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4673                        );
 4674                    }
 4675                }
 4676            }
 4677        }
 4678        let text = &text[common_prefix_len..];
 4679
 4680        cx.emit(EditorEvent::InputHandled {
 4681            utf16_range_to_replace: range_to_replace,
 4682            text: text.into(),
 4683        });
 4684
 4685        self.transact(cx, |this, cx| {
 4686            if let Some(mut snippet) = snippet {
 4687                snippet.text = text.to_string();
 4688                for tabstop in snippet
 4689                    .tabstops
 4690                    .iter_mut()
 4691                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4692                {
 4693                    tabstop.start -= common_prefix_len as isize;
 4694                    tabstop.end -= common_prefix_len as isize;
 4695                }
 4696
 4697                this.insert_snippet(&ranges, snippet, cx).log_err();
 4698            } else {
 4699                this.buffer.update(cx, |buffer, cx| {
 4700                    buffer.edit(
 4701                        ranges.iter().map(|range| (range.clone(), text)),
 4702                        this.autoindent_mode.clone(),
 4703                        cx,
 4704                    );
 4705                });
 4706            }
 4707            for (buffer, edits) in linked_edits {
 4708                buffer.update(cx, |buffer, cx| {
 4709                    let snapshot = buffer.snapshot();
 4710                    let edits = edits
 4711                        .into_iter()
 4712                        .map(|(range, text)| {
 4713                            use text::ToPoint as TP;
 4714                            let end_point = TP::to_point(&range.end, &snapshot);
 4715                            let start_point = TP::to_point(&range.start, &snapshot);
 4716                            (start_point..end_point, text)
 4717                        })
 4718                        .sorted_by_key(|(range, _)| range.start)
 4719                        .collect::<Vec<_>>();
 4720                    buffer.edit(edits, None, cx);
 4721                })
 4722            }
 4723
 4724            this.refresh_inline_completion(true, false, cx);
 4725        });
 4726
 4727        let show_new_completions_on_confirm = completion
 4728            .confirm
 4729            .as_ref()
 4730            .map_or(false, |confirm| confirm(intent, cx));
 4731        if show_new_completions_on_confirm {
 4732            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4733        }
 4734
 4735        let provider = self.completion_provider.as_ref()?;
 4736        let apply_edits = provider.apply_additional_edits_for_completion(
 4737            buffer_handle,
 4738            completion.clone(),
 4739            true,
 4740            cx,
 4741        );
 4742
 4743        let editor_settings = EditorSettings::get_global(cx);
 4744        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4745            // After the code completion is finished, users often want to know what signatures are needed.
 4746            // so we should automatically call signature_help
 4747            self.show_signature_help(&ShowSignatureHelp, cx);
 4748        }
 4749
 4750        Some(cx.foreground_executor().spawn(async move {
 4751            apply_edits.await?;
 4752            Ok(())
 4753        }))
 4754    }
 4755
 4756    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4757        let mut context_menu = self.context_menu.write();
 4758        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4759            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4760                // Toggle if we're selecting the same one
 4761                *context_menu = None;
 4762                cx.notify();
 4763                return;
 4764            } else {
 4765                // Otherwise, clear it and start a new one
 4766                *context_menu = None;
 4767                cx.notify();
 4768            }
 4769        }
 4770        drop(context_menu);
 4771        let snapshot = self.snapshot(cx);
 4772        let deployed_from_indicator = action.deployed_from_indicator;
 4773        let mut task = self.code_actions_task.take();
 4774        let action = action.clone();
 4775        cx.spawn(|editor, mut cx| async move {
 4776            while let Some(prev_task) = task {
 4777                prev_task.await.log_err();
 4778                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4779            }
 4780
 4781            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4782                if editor.focus_handle.is_focused(cx) {
 4783                    let multibuffer_point = action
 4784                        .deployed_from_indicator
 4785                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4786                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4787                    let (buffer, buffer_row) = snapshot
 4788                        .buffer_snapshot
 4789                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4790                        .and_then(|(buffer_snapshot, range)| {
 4791                            editor
 4792                                .buffer
 4793                                .read(cx)
 4794                                .buffer(buffer_snapshot.remote_id())
 4795                                .map(|buffer| (buffer, range.start.row))
 4796                        })?;
 4797                    let (_, code_actions) = editor
 4798                        .available_code_actions
 4799                        .clone()
 4800                        .and_then(|(location, code_actions)| {
 4801                            let snapshot = location.buffer.read(cx).snapshot();
 4802                            let point_range = location.range.to_point(&snapshot);
 4803                            let point_range = point_range.start.row..=point_range.end.row;
 4804                            if point_range.contains(&buffer_row) {
 4805                                Some((location, code_actions))
 4806                            } else {
 4807                                None
 4808                            }
 4809                        })
 4810                        .unzip();
 4811                    let buffer_id = buffer.read(cx).remote_id();
 4812                    let tasks = editor
 4813                        .tasks
 4814                        .get(&(buffer_id, buffer_row))
 4815                        .map(|t| Arc::new(t.to_owned()));
 4816                    if tasks.is_none() && code_actions.is_none() {
 4817                        return None;
 4818                    }
 4819
 4820                    editor.completion_tasks.clear();
 4821                    editor.discard_inline_completion(false, cx);
 4822                    let task_context =
 4823                        tasks
 4824                            .as_ref()
 4825                            .zip(editor.project.clone())
 4826                            .map(|(tasks, project)| {
 4827                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4828                            });
 4829
 4830                    Some(cx.spawn(|editor, mut cx| async move {
 4831                        let task_context = match task_context {
 4832                            Some(task_context) => task_context.await,
 4833                            None => None,
 4834                        };
 4835                        let resolved_tasks =
 4836                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4837                                Arc::new(ResolvedTasks {
 4838                                    templates: tasks.resolve(&task_context).collect(),
 4839                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4840                                        multibuffer_point.row,
 4841                                        tasks.column,
 4842                                    )),
 4843                                })
 4844                            });
 4845                        let spawn_straight_away = resolved_tasks
 4846                            .as_ref()
 4847                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4848                            && code_actions
 4849                                .as_ref()
 4850                                .map_or(true, |actions| actions.is_empty());
 4851                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4852                            *editor.context_menu.write() =
 4853                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4854                                    buffer,
 4855                                    actions: CodeActionContents {
 4856                                        tasks: resolved_tasks,
 4857                                        actions: code_actions,
 4858                                    },
 4859                                    selected_item: Default::default(),
 4860                                    scroll_handle: UniformListScrollHandle::default(),
 4861                                    deployed_from_indicator,
 4862                                }));
 4863                            if spawn_straight_away {
 4864                                if let Some(task) = editor.confirm_code_action(
 4865                                    &ConfirmCodeAction { item_ix: Some(0) },
 4866                                    cx,
 4867                                ) {
 4868                                    cx.notify();
 4869                                    return task;
 4870                                }
 4871                            }
 4872                            cx.notify();
 4873                            Task::ready(Ok(()))
 4874                        }) {
 4875                            task.await
 4876                        } else {
 4877                            Ok(())
 4878                        }
 4879                    }))
 4880                } else {
 4881                    Some(Task::ready(Ok(())))
 4882                }
 4883            })?;
 4884            if let Some(task) = spawned_test_task {
 4885                task.await?;
 4886            }
 4887
 4888            Ok::<_, anyhow::Error>(())
 4889        })
 4890        .detach_and_log_err(cx);
 4891    }
 4892
 4893    pub fn confirm_code_action(
 4894        &mut self,
 4895        action: &ConfirmCodeAction,
 4896        cx: &mut ViewContext<Self>,
 4897    ) -> Option<Task<Result<()>>> {
 4898        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4899            menu
 4900        } else {
 4901            return None;
 4902        };
 4903        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4904        let action = actions_menu.actions.get(action_ix)?;
 4905        let title = action.label();
 4906        let buffer = actions_menu.buffer;
 4907        let workspace = self.workspace()?;
 4908
 4909        match action {
 4910            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4911                workspace.update(cx, |workspace, cx| {
 4912                    workspace::tasks::schedule_resolved_task(
 4913                        workspace,
 4914                        task_source_kind,
 4915                        resolved_task,
 4916                        false,
 4917                        cx,
 4918                    );
 4919
 4920                    Some(Task::ready(Ok(())))
 4921                })
 4922            }
 4923            CodeActionsItem::CodeAction {
 4924                excerpt_id,
 4925                action,
 4926                provider,
 4927            } => {
 4928                let apply_code_action =
 4929                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4930                let workspace = workspace.downgrade();
 4931                Some(cx.spawn(|editor, cx| async move {
 4932                    let project_transaction = apply_code_action.await?;
 4933                    Self::open_project_transaction(
 4934                        &editor,
 4935                        workspace,
 4936                        project_transaction,
 4937                        title,
 4938                        cx,
 4939                    )
 4940                    .await
 4941                }))
 4942            }
 4943        }
 4944    }
 4945
 4946    pub async fn open_project_transaction(
 4947        this: &WeakView<Editor>,
 4948        workspace: WeakView<Workspace>,
 4949        transaction: ProjectTransaction,
 4950        title: String,
 4951        mut cx: AsyncWindowContext,
 4952    ) -> Result<()> {
 4953        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4954        cx.update(|cx| {
 4955            entries.sort_unstable_by_key(|(buffer, _)| {
 4956                buffer.read(cx).file().map(|f| f.path().clone())
 4957            });
 4958        })?;
 4959
 4960        // If the project transaction's edits are all contained within this editor, then
 4961        // avoid opening a new editor to display them.
 4962
 4963        if let Some((buffer, transaction)) = entries.first() {
 4964            if entries.len() == 1 {
 4965                let excerpt = this.update(&mut cx, |editor, cx| {
 4966                    editor
 4967                        .buffer()
 4968                        .read(cx)
 4969                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4970                })?;
 4971                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4972                    if excerpted_buffer == *buffer {
 4973                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4974                            let excerpt_range = excerpt_range.to_offset(buffer);
 4975                            buffer
 4976                                .edited_ranges_for_transaction::<usize>(transaction)
 4977                                .all(|range| {
 4978                                    excerpt_range.start <= range.start
 4979                                        && excerpt_range.end >= range.end
 4980                                })
 4981                        })?;
 4982
 4983                        if all_edits_within_excerpt {
 4984                            return Ok(());
 4985                        }
 4986                    }
 4987                }
 4988            }
 4989        } else {
 4990            return Ok(());
 4991        }
 4992
 4993        let mut ranges_to_highlight = Vec::new();
 4994        let excerpt_buffer = cx.new_model(|cx| {
 4995            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4996            for (buffer_handle, transaction) in &entries {
 4997                let buffer = buffer_handle.read(cx);
 4998                ranges_to_highlight.extend(
 4999                    multibuffer.push_excerpts_with_context_lines(
 5000                        buffer_handle.clone(),
 5001                        buffer
 5002                            .edited_ranges_for_transaction::<usize>(transaction)
 5003                            .collect(),
 5004                        DEFAULT_MULTIBUFFER_CONTEXT,
 5005                        cx,
 5006                    ),
 5007                );
 5008            }
 5009            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5010            multibuffer
 5011        })?;
 5012
 5013        workspace.update(&mut cx, |workspace, cx| {
 5014            let project = workspace.project().clone();
 5015            let editor =
 5016                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 5017            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 5018            editor.update(cx, |editor, cx| {
 5019                editor.highlight_background::<Self>(
 5020                    &ranges_to_highlight,
 5021                    |theme| theme.editor_highlighted_line_background,
 5022                    cx,
 5023                );
 5024            });
 5025        })?;
 5026
 5027        Ok(())
 5028    }
 5029
 5030    pub fn clear_code_action_providers(&mut self) {
 5031        self.code_action_providers.clear();
 5032        self.available_code_actions.take();
 5033    }
 5034
 5035    pub fn push_code_action_provider(
 5036        &mut self,
 5037        provider: Arc<dyn CodeActionProvider>,
 5038        cx: &mut ViewContext<Self>,
 5039    ) {
 5040        self.code_action_providers.push(provider);
 5041        self.refresh_code_actions(cx);
 5042    }
 5043
 5044    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5045        let buffer = self.buffer.read(cx);
 5046        let newest_selection = self.selections.newest_anchor().clone();
 5047        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 5048        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 5049        if start_buffer != end_buffer {
 5050            return None;
 5051        }
 5052
 5053        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 5054            cx.background_executor()
 5055                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5056                .await;
 5057
 5058            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 5059                let providers = this.code_action_providers.clone();
 5060                let tasks = this
 5061                    .code_action_providers
 5062                    .iter()
 5063                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 5064                    .collect::<Vec<_>>();
 5065                (providers, tasks)
 5066            })?;
 5067
 5068            let mut actions = Vec::new();
 5069            for (provider, provider_actions) in
 5070                providers.into_iter().zip(future::join_all(tasks).await)
 5071            {
 5072                if let Some(provider_actions) = provider_actions.log_err() {
 5073                    actions.extend(provider_actions.into_iter().map(|action| {
 5074                        AvailableCodeAction {
 5075                            excerpt_id: newest_selection.start.excerpt_id,
 5076                            action,
 5077                            provider: provider.clone(),
 5078                        }
 5079                    }));
 5080                }
 5081            }
 5082
 5083            this.update(&mut cx, |this, cx| {
 5084                this.available_code_actions = if actions.is_empty() {
 5085                    None
 5086                } else {
 5087                    Some((
 5088                        Location {
 5089                            buffer: start_buffer,
 5090                            range: start..end,
 5091                        },
 5092                        actions.into(),
 5093                    ))
 5094                };
 5095                cx.notify();
 5096            })
 5097        }));
 5098        None
 5099    }
 5100
 5101    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 5102        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5103            self.show_git_blame_inline = false;
 5104
 5105            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 5106                cx.background_executor().timer(delay).await;
 5107
 5108                this.update(&mut cx, |this, cx| {
 5109                    this.show_git_blame_inline = true;
 5110                    cx.notify();
 5111                })
 5112                .log_err();
 5113            }));
 5114        }
 5115    }
 5116
 5117    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5118        if self.pending_rename.is_some() {
 5119            return None;
 5120        }
 5121
 5122        let provider = self.semantics_provider.clone()?;
 5123        let buffer = self.buffer.read(cx);
 5124        let newest_selection = self.selections.newest_anchor().clone();
 5125        let cursor_position = newest_selection.head();
 5126        let (cursor_buffer, cursor_buffer_position) =
 5127            buffer.text_anchor_for_position(cursor_position, cx)?;
 5128        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5129        if cursor_buffer != tail_buffer {
 5130            return None;
 5131        }
 5132
 5133        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 5134            cx.background_executor()
 5135                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 5136                .await;
 5137
 5138            let highlights = if let Some(highlights) = cx
 5139                .update(|cx| {
 5140                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5141                })
 5142                .ok()
 5143                .flatten()
 5144            {
 5145                highlights.await.log_err()
 5146            } else {
 5147                None
 5148            };
 5149
 5150            if let Some(highlights) = highlights {
 5151                this.update(&mut cx, |this, cx| {
 5152                    if this.pending_rename.is_some() {
 5153                        return;
 5154                    }
 5155
 5156                    let buffer_id = cursor_position.buffer_id;
 5157                    let buffer = this.buffer.read(cx);
 5158                    if !buffer
 5159                        .text_anchor_for_position(cursor_position, cx)
 5160                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5161                    {
 5162                        return;
 5163                    }
 5164
 5165                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5166                    let mut write_ranges = Vec::new();
 5167                    let mut read_ranges = Vec::new();
 5168                    for highlight in highlights {
 5169                        for (excerpt_id, excerpt_range) in
 5170                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 5171                        {
 5172                            let start = highlight
 5173                                .range
 5174                                .start
 5175                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5176                            let end = highlight
 5177                                .range
 5178                                .end
 5179                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5180                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5181                                continue;
 5182                            }
 5183
 5184                            let range = Anchor {
 5185                                buffer_id,
 5186                                excerpt_id,
 5187                                text_anchor: start,
 5188                            }..Anchor {
 5189                                buffer_id,
 5190                                excerpt_id,
 5191                                text_anchor: end,
 5192                            };
 5193                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5194                                write_ranges.push(range);
 5195                            } else {
 5196                                read_ranges.push(range);
 5197                            }
 5198                        }
 5199                    }
 5200
 5201                    this.highlight_background::<DocumentHighlightRead>(
 5202                        &read_ranges,
 5203                        |theme| theme.editor_document_highlight_read_background,
 5204                        cx,
 5205                    );
 5206                    this.highlight_background::<DocumentHighlightWrite>(
 5207                        &write_ranges,
 5208                        |theme| theme.editor_document_highlight_write_background,
 5209                        cx,
 5210                    );
 5211                    cx.notify();
 5212                })
 5213                .log_err();
 5214            }
 5215        }));
 5216        None
 5217    }
 5218
 5219    pub fn refresh_inline_completion(
 5220        &mut self,
 5221        debounce: bool,
 5222        user_requested: bool,
 5223        cx: &mut ViewContext<Self>,
 5224    ) -> Option<()> {
 5225        let provider = self.inline_completion_provider()?;
 5226        let cursor = self.selections.newest_anchor().head();
 5227        let (buffer, cursor_buffer_position) =
 5228            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5229
 5230        if !user_requested
 5231            && (!self.enable_inline_completions
 5232                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5233                || !self.is_focused(cx))
 5234        {
 5235            self.discard_inline_completion(false, cx);
 5236            return None;
 5237        }
 5238
 5239        self.update_visible_inline_completion(cx);
 5240        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5241        Some(())
 5242    }
 5243
 5244    fn cycle_inline_completion(
 5245        &mut self,
 5246        direction: Direction,
 5247        cx: &mut ViewContext<Self>,
 5248    ) -> Option<()> {
 5249        let provider = self.inline_completion_provider()?;
 5250        let cursor = self.selections.newest_anchor().head();
 5251        let (buffer, cursor_buffer_position) =
 5252            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5253        if !self.enable_inline_completions
 5254            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5255        {
 5256            return None;
 5257        }
 5258
 5259        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5260        self.update_visible_inline_completion(cx);
 5261
 5262        Some(())
 5263    }
 5264
 5265    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5266        if !self.has_active_inline_completion() {
 5267            self.refresh_inline_completion(false, true, cx);
 5268            return;
 5269        }
 5270
 5271        self.update_visible_inline_completion(cx);
 5272    }
 5273
 5274    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5275        self.show_cursor_names(cx);
 5276    }
 5277
 5278    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5279        self.show_cursor_names = true;
 5280        cx.notify();
 5281        cx.spawn(|this, mut cx| async move {
 5282            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5283            this.update(&mut cx, |this, cx| {
 5284                this.show_cursor_names = false;
 5285                cx.notify()
 5286            })
 5287            .ok()
 5288        })
 5289        .detach();
 5290    }
 5291
 5292    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5293        if self.has_active_inline_completion() {
 5294            self.cycle_inline_completion(Direction::Next, cx);
 5295        } else {
 5296            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5297            if is_copilot_disabled {
 5298                cx.propagate();
 5299            }
 5300        }
 5301    }
 5302
 5303    pub fn previous_inline_completion(
 5304        &mut self,
 5305        _: &PreviousInlineCompletion,
 5306        cx: &mut ViewContext<Self>,
 5307    ) {
 5308        if self.has_active_inline_completion() {
 5309            self.cycle_inline_completion(Direction::Prev, cx);
 5310        } else {
 5311            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5312            if is_copilot_disabled {
 5313                cx.propagate();
 5314            }
 5315        }
 5316    }
 5317
 5318    pub fn accept_inline_completion(
 5319        &mut self,
 5320        _: &AcceptInlineCompletion,
 5321        cx: &mut ViewContext<Self>,
 5322    ) {
 5323        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5324            return;
 5325        };
 5326
 5327        self.report_inline_completion_event(true, cx);
 5328
 5329        match &active_inline_completion.completion {
 5330            InlineCompletion::Move(position) => {
 5331                let position = *position;
 5332                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 5333                    selections.select_anchor_ranges([position..position]);
 5334                });
 5335            }
 5336            InlineCompletion::Edit(edits) => {
 5337                if let Some(provider) = self.inline_completion_provider() {
 5338                    provider.accept(cx);
 5339                }
 5340
 5341                let snapshot = self.buffer.read(cx).snapshot(cx);
 5342                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5343
 5344                self.buffer.update(cx, |buffer, cx| {
 5345                    buffer.edit(edits.iter().cloned(), None, cx)
 5346                });
 5347
 5348                self.change_selections(None, cx, |s| {
 5349                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5350                });
 5351
 5352                self.update_visible_inline_completion(cx);
 5353                if self.active_inline_completion.is_none() {
 5354                    self.refresh_inline_completion(true, true, cx);
 5355                }
 5356
 5357                cx.notify();
 5358            }
 5359        }
 5360    }
 5361
 5362    pub fn accept_partial_inline_completion(
 5363        &mut self,
 5364        _: &AcceptPartialInlineCompletion,
 5365        cx: &mut ViewContext<Self>,
 5366    ) {
 5367        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5368            return;
 5369        };
 5370        if self.selections.count() != 1 {
 5371            return;
 5372        }
 5373
 5374        self.report_inline_completion_event(true, cx);
 5375
 5376        match &active_inline_completion.completion {
 5377            InlineCompletion::Move(position) => {
 5378                let position = *position;
 5379                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 5380                    selections.select_anchor_ranges([position..position]);
 5381                });
 5382            }
 5383            InlineCompletion::Edit(edits) => {
 5384                if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
 5385                    let text = edits[0].1.as_str();
 5386                    let mut partial_completion = text
 5387                        .chars()
 5388                        .by_ref()
 5389                        .take_while(|c| c.is_alphabetic())
 5390                        .collect::<String>();
 5391                    if partial_completion.is_empty() {
 5392                        partial_completion = text
 5393                            .chars()
 5394                            .by_ref()
 5395                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5396                            .collect::<String>();
 5397                    }
 5398
 5399                    cx.emit(EditorEvent::InputHandled {
 5400                        utf16_range_to_replace: None,
 5401                        text: partial_completion.clone().into(),
 5402                    });
 5403
 5404                    self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5405
 5406                    self.refresh_inline_completion(true, true, cx);
 5407                    cx.notify();
 5408                }
 5409            }
 5410        }
 5411    }
 5412
 5413    fn discard_inline_completion(
 5414        &mut self,
 5415        should_report_inline_completion_event: bool,
 5416        cx: &mut ViewContext<Self>,
 5417    ) -> bool {
 5418        if should_report_inline_completion_event {
 5419            self.report_inline_completion_event(false, cx);
 5420        }
 5421
 5422        if let Some(provider) = self.inline_completion_provider() {
 5423            provider.discard(cx);
 5424        }
 5425
 5426        self.take_active_inline_completion(cx).is_some()
 5427    }
 5428
 5429    fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
 5430        let Some(provider) = self.inline_completion_provider() else {
 5431            return;
 5432        };
 5433        let Some(project) = self.project.as_ref() else {
 5434            return;
 5435        };
 5436        let Some((_, buffer, _)) = self
 5437            .buffer
 5438            .read(cx)
 5439            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5440        else {
 5441            return;
 5442        };
 5443
 5444        let project = project.read(cx);
 5445        let extension = buffer
 5446            .read(cx)
 5447            .file()
 5448            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5449        project.client().telemetry().report_inline_completion_event(
 5450            provider.name().into(),
 5451            accepted,
 5452            extension,
 5453        );
 5454    }
 5455
 5456    pub fn has_active_inline_completion(&self) -> bool {
 5457        self.active_inline_completion.is_some()
 5458    }
 5459
 5460    fn take_active_inline_completion(
 5461        &mut self,
 5462        cx: &mut ViewContext<Self>,
 5463    ) -> Option<InlineCompletion> {
 5464        let active_inline_completion = self.active_inline_completion.take()?;
 5465        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 5466        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5467        Some(active_inline_completion.completion)
 5468    }
 5469
 5470    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 5471        let selection = self.selections.newest_anchor();
 5472        let cursor = selection.head();
 5473        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5474        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5475        let excerpt_id = cursor.excerpt_id;
 5476
 5477        if self.context_menu.read().is_some()
 5478            || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion())
 5479            || !offset_selection.is_empty()
 5480            || self
 5481                .active_inline_completion
 5482                .as_ref()
 5483                .map_or(false, |completion| {
 5484                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5485                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5486                    !invalidation_range.contains(&offset_selection.head())
 5487                })
 5488        {
 5489            self.discard_inline_completion(false, cx);
 5490            return None;
 5491        }
 5492
 5493        self.take_active_inline_completion(cx);
 5494        let provider = self.inline_completion_provider()?;
 5495
 5496        let (buffer, cursor_buffer_position) =
 5497            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5498
 5499        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5500        let edits = completion
 5501            .edits
 5502            .into_iter()
 5503            .map(|(range, new_text)| {
 5504                (
 5505                    multibuffer
 5506                        .anchor_in_excerpt(excerpt_id, range.start)
 5507                        .unwrap()
 5508                        ..multibuffer
 5509                            .anchor_in_excerpt(excerpt_id, range.end)
 5510                            .unwrap(),
 5511                    new_text,
 5512                )
 5513            })
 5514            .collect::<Vec<_>>();
 5515        if edits.is_empty() {
 5516            return None;
 5517        }
 5518
 5519        let first_edit_start = edits.first().unwrap().0.start;
 5520        let edit_start_row = first_edit_start
 5521            .to_point(&multibuffer)
 5522            .row
 5523            .saturating_sub(2);
 5524
 5525        let last_edit_end = edits.last().unwrap().0.end;
 5526        let edit_end_row = cmp::min(
 5527            multibuffer.max_point().row,
 5528            last_edit_end.to_point(&multibuffer).row + 2,
 5529        );
 5530
 5531        let cursor_row = cursor.to_point(&multibuffer).row;
 5532
 5533        let mut inlay_ids = Vec::new();
 5534        let invalidation_row_range;
 5535        let completion;
 5536        if cursor_row < edit_start_row {
 5537            invalidation_row_range = cursor_row..edit_end_row;
 5538            completion = InlineCompletion::Move(first_edit_start);
 5539        } else if cursor_row > edit_end_row {
 5540            invalidation_row_range = edit_start_row..cursor_row;
 5541            completion = InlineCompletion::Move(first_edit_start);
 5542        } else {
 5543            if edits
 5544                .iter()
 5545                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5546            {
 5547                let mut inlays = Vec::new();
 5548                for (range, new_text) in &edits {
 5549                    let inlay = Inlay::suggestion(
 5550                        post_inc(&mut self.next_inlay_id),
 5551                        range.start,
 5552                        new_text.as_str(),
 5553                    );
 5554                    inlay_ids.push(inlay.id);
 5555                    inlays.push(inlay);
 5556                }
 5557
 5558                self.splice_inlays(vec![], inlays, cx);
 5559            } else {
 5560                let background_color = cx.theme().status().deleted_background;
 5561                self.highlight_text::<InlineCompletionHighlight>(
 5562                    edits.iter().map(|(range, _)| range.clone()).collect(),
 5563                    HighlightStyle {
 5564                        background_color: Some(background_color),
 5565                        ..Default::default()
 5566                    },
 5567                    cx,
 5568                );
 5569            }
 5570
 5571            invalidation_row_range = edit_start_row..edit_end_row;
 5572            completion = InlineCompletion::Edit(edits);
 5573        };
 5574
 5575        let invalidation_range = multibuffer
 5576            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5577            ..multibuffer.anchor_after(Point::new(
 5578                invalidation_row_range.end,
 5579                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5580            ));
 5581
 5582        self.active_inline_completion = Some(InlineCompletionState {
 5583            inlay_ids,
 5584            completion,
 5585            invalidation_range,
 5586        });
 5587        cx.notify();
 5588
 5589        Some(())
 5590    }
 5591
 5592    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5593        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5594    }
 5595
 5596    fn render_code_actions_indicator(
 5597        &self,
 5598        _style: &EditorStyle,
 5599        row: DisplayRow,
 5600        is_active: bool,
 5601        cx: &mut ViewContext<Self>,
 5602    ) -> Option<IconButton> {
 5603        if self.available_code_actions.is_some() {
 5604            Some(
 5605                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5606                    .shape(ui::IconButtonShape::Square)
 5607                    .icon_size(IconSize::XSmall)
 5608                    .icon_color(Color::Muted)
 5609                    .selected(is_active)
 5610                    .tooltip({
 5611                        let focus_handle = self.focus_handle.clone();
 5612                        move |cx| {
 5613                            Tooltip::for_action_in(
 5614                                "Toggle Code Actions",
 5615                                &ToggleCodeActions {
 5616                                    deployed_from_indicator: None,
 5617                                },
 5618                                &focus_handle,
 5619                                cx,
 5620                            )
 5621                        }
 5622                    })
 5623                    .on_click(cx.listener(move |editor, _e, cx| {
 5624                        editor.focus(cx);
 5625                        editor.toggle_code_actions(
 5626                            &ToggleCodeActions {
 5627                                deployed_from_indicator: Some(row),
 5628                            },
 5629                            cx,
 5630                        );
 5631                    })),
 5632            )
 5633        } else {
 5634            None
 5635        }
 5636    }
 5637
 5638    fn clear_tasks(&mut self) {
 5639        self.tasks.clear()
 5640    }
 5641
 5642    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5643        if self.tasks.insert(key, value).is_some() {
 5644            // This case should hopefully be rare, but just in case...
 5645            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5646        }
 5647    }
 5648
 5649    fn build_tasks_context(
 5650        project: &Model<Project>,
 5651        buffer: &Model<Buffer>,
 5652        buffer_row: u32,
 5653        tasks: &Arc<RunnableTasks>,
 5654        cx: &mut ViewContext<Self>,
 5655    ) -> Task<Option<task::TaskContext>> {
 5656        let position = Point::new(buffer_row, tasks.column);
 5657        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5658        let location = Location {
 5659            buffer: buffer.clone(),
 5660            range: range_start..range_start,
 5661        };
 5662        // Fill in the environmental variables from the tree-sitter captures
 5663        let mut captured_task_variables = TaskVariables::default();
 5664        for (capture_name, value) in tasks.extra_variables.clone() {
 5665            captured_task_variables.insert(
 5666                task::VariableName::Custom(capture_name.into()),
 5667                value.clone(),
 5668            );
 5669        }
 5670        project.update(cx, |project, cx| {
 5671            project.task_store().update(cx, |task_store, cx| {
 5672                task_store.task_context_for_location(captured_task_variables, location, cx)
 5673            })
 5674        })
 5675    }
 5676
 5677    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5678        let Some((workspace, _)) = self.workspace.clone() else {
 5679            return;
 5680        };
 5681        let Some(project) = self.project.clone() else {
 5682            return;
 5683        };
 5684
 5685        // Try to find a closest, enclosing node using tree-sitter that has a
 5686        // task
 5687        let Some((buffer, buffer_row, tasks)) = self
 5688            .find_enclosing_node_task(cx)
 5689            // Or find the task that's closest in row-distance.
 5690            .or_else(|| self.find_closest_task(cx))
 5691        else {
 5692            return;
 5693        };
 5694
 5695        let reveal_strategy = action.reveal;
 5696        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5697        cx.spawn(|_, mut cx| async move {
 5698            let context = task_context.await?;
 5699            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5700
 5701            let resolved = resolved_task.resolved.as_mut()?;
 5702            resolved.reveal = reveal_strategy;
 5703
 5704            workspace
 5705                .update(&mut cx, |workspace, cx| {
 5706                    workspace::tasks::schedule_resolved_task(
 5707                        workspace,
 5708                        task_source_kind,
 5709                        resolved_task,
 5710                        false,
 5711                        cx,
 5712                    );
 5713                })
 5714                .ok()
 5715        })
 5716        .detach();
 5717    }
 5718
 5719    fn find_closest_task(
 5720        &mut self,
 5721        cx: &mut ViewContext<Self>,
 5722    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5723        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5724
 5725        let ((buffer_id, row), tasks) = self
 5726            .tasks
 5727            .iter()
 5728            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5729
 5730        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5731        let tasks = Arc::new(tasks.to_owned());
 5732        Some((buffer, *row, tasks))
 5733    }
 5734
 5735    fn find_enclosing_node_task(
 5736        &mut self,
 5737        cx: &mut ViewContext<Self>,
 5738    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5739        let snapshot = self.buffer.read(cx).snapshot(cx);
 5740        let offset = self.selections.newest::<usize>(cx).head();
 5741        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5742        let buffer_id = excerpt.buffer().remote_id();
 5743
 5744        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5745        let mut cursor = layer.node().walk();
 5746
 5747        while cursor.goto_first_child_for_byte(offset).is_some() {
 5748            if cursor.node().end_byte() == offset {
 5749                cursor.goto_next_sibling();
 5750            }
 5751        }
 5752
 5753        // Ascend to the smallest ancestor that contains the range and has a task.
 5754        loop {
 5755            let node = cursor.node();
 5756            let node_range = node.byte_range();
 5757            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5758
 5759            // Check if this node contains our offset
 5760            if node_range.start <= offset && node_range.end >= offset {
 5761                // If it contains offset, check for task
 5762                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5763                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5764                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5765                }
 5766            }
 5767
 5768            if !cursor.goto_parent() {
 5769                break;
 5770            }
 5771        }
 5772        None
 5773    }
 5774
 5775    fn render_run_indicator(
 5776        &self,
 5777        _style: &EditorStyle,
 5778        is_active: bool,
 5779        row: DisplayRow,
 5780        cx: &mut ViewContext<Self>,
 5781    ) -> IconButton {
 5782        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5783            .shape(ui::IconButtonShape::Square)
 5784            .icon_size(IconSize::XSmall)
 5785            .icon_color(Color::Muted)
 5786            .selected(is_active)
 5787            .on_click(cx.listener(move |editor, _e, cx| {
 5788                editor.focus(cx);
 5789                editor.toggle_code_actions(
 5790                    &ToggleCodeActions {
 5791                        deployed_from_indicator: Some(row),
 5792                    },
 5793                    cx,
 5794                );
 5795            }))
 5796    }
 5797
 5798    pub fn context_menu_visible(&self) -> bool {
 5799        self.context_menu
 5800            .read()
 5801            .as_ref()
 5802            .map_or(false, |menu| menu.visible())
 5803    }
 5804
 5805    fn render_context_menu(
 5806        &self,
 5807        cursor_position: DisplayPoint,
 5808        style: &EditorStyle,
 5809        max_height: Pixels,
 5810        cx: &mut ViewContext<Editor>,
 5811    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5812        self.context_menu.read().as_ref().map(|menu| {
 5813            menu.render(
 5814                cursor_position,
 5815                style,
 5816                max_height,
 5817                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5818                cx,
 5819            )
 5820        })
 5821    }
 5822
 5823    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5824        cx.notify();
 5825        self.completion_tasks.clear();
 5826        let context_menu = self.context_menu.write().take();
 5827        if context_menu.is_some() {
 5828            self.update_visible_inline_completion(cx);
 5829        }
 5830        context_menu
 5831    }
 5832
 5833    fn show_snippet_choices(
 5834        &mut self,
 5835        choices: &Vec<String>,
 5836        selection: Range<Anchor>,
 5837        cx: &mut ViewContext<Self>,
 5838    ) {
 5839        if selection.start.buffer_id.is_none() {
 5840            return;
 5841        }
 5842        let buffer_id = selection.start.buffer_id.unwrap();
 5843        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5844        let id = post_inc(&mut self.next_completion_id);
 5845
 5846        if let Some(buffer) = buffer {
 5847            *self.context_menu.write() = Some(ContextMenu::Completions(
 5848                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5849            ));
 5850        }
 5851    }
 5852
 5853    pub fn insert_snippet(
 5854        &mut self,
 5855        insertion_ranges: &[Range<usize>],
 5856        snippet: Snippet,
 5857        cx: &mut ViewContext<Self>,
 5858    ) -> Result<()> {
 5859        struct Tabstop<T> {
 5860            is_end_tabstop: bool,
 5861            ranges: Vec<Range<T>>,
 5862            choices: Option<Vec<String>>,
 5863        }
 5864
 5865        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5866            let snippet_text: Arc<str> = snippet.text.clone().into();
 5867            buffer.edit(
 5868                insertion_ranges
 5869                    .iter()
 5870                    .cloned()
 5871                    .map(|range| (range, snippet_text.clone())),
 5872                Some(AutoindentMode::EachLine),
 5873                cx,
 5874            );
 5875
 5876            let snapshot = &*buffer.read(cx);
 5877            let snippet = &snippet;
 5878            snippet
 5879                .tabstops
 5880                .iter()
 5881                .map(|tabstop| {
 5882                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5883                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5884                    });
 5885                    let mut tabstop_ranges = tabstop
 5886                        .ranges
 5887                        .iter()
 5888                        .flat_map(|tabstop_range| {
 5889                            let mut delta = 0_isize;
 5890                            insertion_ranges.iter().map(move |insertion_range| {
 5891                                let insertion_start = insertion_range.start as isize + delta;
 5892                                delta +=
 5893                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5894
 5895                                let start = ((insertion_start + tabstop_range.start) as usize)
 5896                                    .min(snapshot.len());
 5897                                let end = ((insertion_start + tabstop_range.end) as usize)
 5898                                    .min(snapshot.len());
 5899                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5900                            })
 5901                        })
 5902                        .collect::<Vec<_>>();
 5903                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5904
 5905                    Tabstop {
 5906                        is_end_tabstop,
 5907                        ranges: tabstop_ranges,
 5908                        choices: tabstop.choices.clone(),
 5909                    }
 5910                })
 5911                .collect::<Vec<_>>()
 5912        });
 5913        if let Some(tabstop) = tabstops.first() {
 5914            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5915                s.select_ranges(tabstop.ranges.iter().cloned());
 5916            });
 5917
 5918            if let Some(choices) = &tabstop.choices {
 5919                if let Some(selection) = tabstop.ranges.first() {
 5920                    self.show_snippet_choices(choices, selection.clone(), cx)
 5921                }
 5922            }
 5923
 5924            // If we're already at the last tabstop and it's at the end of the snippet,
 5925            // we're done, we don't need to keep the state around.
 5926            if !tabstop.is_end_tabstop {
 5927                let choices = tabstops
 5928                    .iter()
 5929                    .map(|tabstop| tabstop.choices.clone())
 5930                    .collect();
 5931
 5932                let ranges = tabstops
 5933                    .into_iter()
 5934                    .map(|tabstop| tabstop.ranges)
 5935                    .collect::<Vec<_>>();
 5936
 5937                self.snippet_stack.push(SnippetState {
 5938                    active_index: 0,
 5939                    ranges,
 5940                    choices,
 5941                });
 5942            }
 5943
 5944            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5945            if self.autoclose_regions.is_empty() {
 5946                let snapshot = self.buffer.read(cx).snapshot(cx);
 5947                for selection in &mut self.selections.all::<Point>(cx) {
 5948                    let selection_head = selection.head();
 5949                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5950                        continue;
 5951                    };
 5952
 5953                    let mut bracket_pair = None;
 5954                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5955                    let prev_chars = snapshot
 5956                        .reversed_chars_at(selection_head)
 5957                        .collect::<String>();
 5958                    for (pair, enabled) in scope.brackets() {
 5959                        if enabled
 5960                            && pair.close
 5961                            && prev_chars.starts_with(pair.start.as_str())
 5962                            && next_chars.starts_with(pair.end.as_str())
 5963                        {
 5964                            bracket_pair = Some(pair.clone());
 5965                            break;
 5966                        }
 5967                    }
 5968                    if let Some(pair) = bracket_pair {
 5969                        let start = snapshot.anchor_after(selection_head);
 5970                        let end = snapshot.anchor_after(selection_head);
 5971                        self.autoclose_regions.push(AutocloseRegion {
 5972                            selection_id: selection.id,
 5973                            range: start..end,
 5974                            pair,
 5975                        });
 5976                    }
 5977                }
 5978            }
 5979        }
 5980        Ok(())
 5981    }
 5982
 5983    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5984        self.move_to_snippet_tabstop(Bias::Right, cx)
 5985    }
 5986
 5987    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5988        self.move_to_snippet_tabstop(Bias::Left, cx)
 5989    }
 5990
 5991    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5992        if let Some(mut snippet) = self.snippet_stack.pop() {
 5993            match bias {
 5994                Bias::Left => {
 5995                    if snippet.active_index > 0 {
 5996                        snippet.active_index -= 1;
 5997                    } else {
 5998                        self.snippet_stack.push(snippet);
 5999                        return false;
 6000                    }
 6001                }
 6002                Bias::Right => {
 6003                    if snippet.active_index + 1 < snippet.ranges.len() {
 6004                        snippet.active_index += 1;
 6005                    } else {
 6006                        self.snippet_stack.push(snippet);
 6007                        return false;
 6008                    }
 6009                }
 6010            }
 6011            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6012                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6013                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6014                });
 6015
 6016                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6017                    if let Some(selection) = current_ranges.first() {
 6018                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6019                    }
 6020                }
 6021
 6022                // If snippet state is not at the last tabstop, push it back on the stack
 6023                if snippet.active_index + 1 < snippet.ranges.len() {
 6024                    self.snippet_stack.push(snippet);
 6025                }
 6026                return true;
 6027            }
 6028        }
 6029
 6030        false
 6031    }
 6032
 6033    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 6034        self.transact(cx, |this, cx| {
 6035            this.select_all(&SelectAll, cx);
 6036            this.insert("", cx);
 6037        });
 6038    }
 6039
 6040    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 6041        self.transact(cx, |this, cx| {
 6042            this.select_autoclose_pair(cx);
 6043            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6044            if !this.linked_edit_ranges.is_empty() {
 6045                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6046                let snapshot = this.buffer.read(cx).snapshot(cx);
 6047
 6048                for selection in selections.iter() {
 6049                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6050                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6051                    if selection_start.buffer_id != selection_end.buffer_id {
 6052                        continue;
 6053                    }
 6054                    if let Some(ranges) =
 6055                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6056                    {
 6057                        for (buffer, entries) in ranges {
 6058                            linked_ranges.entry(buffer).or_default().extend(entries);
 6059                        }
 6060                    }
 6061                }
 6062            }
 6063
 6064            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6065            if !this.selections.line_mode {
 6066                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6067                for selection in &mut selections {
 6068                    if selection.is_empty() {
 6069                        let old_head = selection.head();
 6070                        let mut new_head =
 6071                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6072                                .to_point(&display_map);
 6073                        if let Some((buffer, line_buffer_range)) = display_map
 6074                            .buffer_snapshot
 6075                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6076                        {
 6077                            let indent_size =
 6078                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6079                            let indent_len = match indent_size.kind {
 6080                                IndentKind::Space => {
 6081                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6082                                }
 6083                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6084                            };
 6085                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6086                                let indent_len = indent_len.get();
 6087                                new_head = cmp::min(
 6088                                    new_head,
 6089                                    MultiBufferPoint::new(
 6090                                        old_head.row,
 6091                                        ((old_head.column - 1) / indent_len) * indent_len,
 6092                                    ),
 6093                                );
 6094                            }
 6095                        }
 6096
 6097                        selection.set_head(new_head, SelectionGoal::None);
 6098                    }
 6099                }
 6100            }
 6101
 6102            this.signature_help_state.set_backspace_pressed(true);
 6103            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6104            this.insert("", cx);
 6105            let empty_str: Arc<str> = Arc::from("");
 6106            for (buffer, edits) in linked_ranges {
 6107                let snapshot = buffer.read(cx).snapshot();
 6108                use text::ToPoint as TP;
 6109
 6110                let edits = edits
 6111                    .into_iter()
 6112                    .map(|range| {
 6113                        let end_point = TP::to_point(&range.end, &snapshot);
 6114                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6115
 6116                        if end_point == start_point {
 6117                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6118                                .saturating_sub(1);
 6119                            start_point = TP::to_point(&offset, &snapshot);
 6120                        };
 6121
 6122                        (start_point..end_point, empty_str.clone())
 6123                    })
 6124                    .sorted_by_key(|(range, _)| range.start)
 6125                    .collect::<Vec<_>>();
 6126                buffer.update(cx, |this, cx| {
 6127                    this.edit(edits, None, cx);
 6128                })
 6129            }
 6130            this.refresh_inline_completion(true, false, cx);
 6131            linked_editing_ranges::refresh_linked_ranges(this, cx);
 6132        });
 6133    }
 6134
 6135    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 6136        self.transact(cx, |this, cx| {
 6137            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6138                let line_mode = s.line_mode;
 6139                s.move_with(|map, selection| {
 6140                    if selection.is_empty() && !line_mode {
 6141                        let cursor = movement::right(map, selection.head());
 6142                        selection.end = cursor;
 6143                        selection.reversed = true;
 6144                        selection.goal = SelectionGoal::None;
 6145                    }
 6146                })
 6147            });
 6148            this.insert("", cx);
 6149            this.refresh_inline_completion(true, false, cx);
 6150        });
 6151    }
 6152
 6153    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 6154        if self.move_to_prev_snippet_tabstop(cx) {
 6155            return;
 6156        }
 6157
 6158        self.outdent(&Outdent, cx);
 6159    }
 6160
 6161    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 6162        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 6163            return;
 6164        }
 6165
 6166        let mut selections = self.selections.all_adjusted(cx);
 6167        let buffer = self.buffer.read(cx);
 6168        let snapshot = buffer.snapshot(cx);
 6169        let rows_iter = selections.iter().map(|s| s.head().row);
 6170        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6171
 6172        let mut edits = Vec::new();
 6173        let mut prev_edited_row = 0;
 6174        let mut row_delta = 0;
 6175        for selection in &mut selections {
 6176            if selection.start.row != prev_edited_row {
 6177                row_delta = 0;
 6178            }
 6179            prev_edited_row = selection.end.row;
 6180
 6181            // If the selection is non-empty, then increase the indentation of the selected lines.
 6182            if !selection.is_empty() {
 6183                row_delta =
 6184                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6185                continue;
 6186            }
 6187
 6188            // If the selection is empty and the cursor is in the leading whitespace before the
 6189            // suggested indentation, then auto-indent the line.
 6190            let cursor = selection.head();
 6191            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6192            if let Some(suggested_indent) =
 6193                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6194            {
 6195                if cursor.column < suggested_indent.len
 6196                    && cursor.column <= current_indent.len
 6197                    && current_indent.len <= suggested_indent.len
 6198                {
 6199                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6200                    selection.end = selection.start;
 6201                    if row_delta == 0 {
 6202                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6203                            cursor.row,
 6204                            current_indent,
 6205                            suggested_indent,
 6206                        ));
 6207                        row_delta = suggested_indent.len - current_indent.len;
 6208                    }
 6209                    continue;
 6210                }
 6211            }
 6212
 6213            // Otherwise, insert a hard or soft tab.
 6214            let settings = buffer.settings_at(cursor, cx);
 6215            let tab_size = if settings.hard_tabs {
 6216                IndentSize::tab()
 6217            } else {
 6218                let tab_size = settings.tab_size.get();
 6219                let char_column = snapshot
 6220                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6221                    .flat_map(str::chars)
 6222                    .count()
 6223                    + row_delta as usize;
 6224                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6225                IndentSize::spaces(chars_to_next_tab_stop)
 6226            };
 6227            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6228            selection.end = selection.start;
 6229            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6230            row_delta += tab_size.len;
 6231        }
 6232
 6233        self.transact(cx, |this, cx| {
 6234            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6235            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6236            this.refresh_inline_completion(true, false, cx);
 6237        });
 6238    }
 6239
 6240    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 6241        if self.read_only(cx) {
 6242            return;
 6243        }
 6244        let mut selections = self.selections.all::<Point>(cx);
 6245        let mut prev_edited_row = 0;
 6246        let mut row_delta = 0;
 6247        let mut edits = Vec::new();
 6248        let buffer = self.buffer.read(cx);
 6249        let snapshot = buffer.snapshot(cx);
 6250        for selection in &mut selections {
 6251            if selection.start.row != prev_edited_row {
 6252                row_delta = 0;
 6253            }
 6254            prev_edited_row = selection.end.row;
 6255
 6256            row_delta =
 6257                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6258        }
 6259
 6260        self.transact(cx, |this, cx| {
 6261            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6262            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6263        });
 6264    }
 6265
 6266    fn indent_selection(
 6267        buffer: &MultiBuffer,
 6268        snapshot: &MultiBufferSnapshot,
 6269        selection: &mut Selection<Point>,
 6270        edits: &mut Vec<(Range<Point>, String)>,
 6271        delta_for_start_row: u32,
 6272        cx: &AppContext,
 6273    ) -> u32 {
 6274        let settings = buffer.settings_at(selection.start, cx);
 6275        let tab_size = settings.tab_size.get();
 6276        let indent_kind = if settings.hard_tabs {
 6277            IndentKind::Tab
 6278        } else {
 6279            IndentKind::Space
 6280        };
 6281        let mut start_row = selection.start.row;
 6282        let mut end_row = selection.end.row + 1;
 6283
 6284        // If a selection ends at the beginning of a line, don't indent
 6285        // that last line.
 6286        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6287            end_row -= 1;
 6288        }
 6289
 6290        // Avoid re-indenting a row that has already been indented by a
 6291        // previous selection, but still update this selection's column
 6292        // to reflect that indentation.
 6293        if delta_for_start_row > 0 {
 6294            start_row += 1;
 6295            selection.start.column += delta_for_start_row;
 6296            if selection.end.row == selection.start.row {
 6297                selection.end.column += delta_for_start_row;
 6298            }
 6299        }
 6300
 6301        let mut delta_for_end_row = 0;
 6302        let has_multiple_rows = start_row + 1 != end_row;
 6303        for row in start_row..end_row {
 6304            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6305            let indent_delta = match (current_indent.kind, indent_kind) {
 6306                (IndentKind::Space, IndentKind::Space) => {
 6307                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6308                    IndentSize::spaces(columns_to_next_tab_stop)
 6309                }
 6310                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6311                (_, IndentKind::Tab) => IndentSize::tab(),
 6312            };
 6313
 6314            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6315                0
 6316            } else {
 6317                selection.start.column
 6318            };
 6319            let row_start = Point::new(row, start);
 6320            edits.push((
 6321                row_start..row_start,
 6322                indent_delta.chars().collect::<String>(),
 6323            ));
 6324
 6325            // Update this selection's endpoints to reflect the indentation.
 6326            if row == selection.start.row {
 6327                selection.start.column += indent_delta.len;
 6328            }
 6329            if row == selection.end.row {
 6330                selection.end.column += indent_delta.len;
 6331                delta_for_end_row = indent_delta.len;
 6332            }
 6333        }
 6334
 6335        if selection.start.row == selection.end.row {
 6336            delta_for_start_row + delta_for_end_row
 6337        } else {
 6338            delta_for_end_row
 6339        }
 6340    }
 6341
 6342    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 6343        if self.read_only(cx) {
 6344            return;
 6345        }
 6346        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6347        let selections = self.selections.all::<Point>(cx);
 6348        let mut deletion_ranges = Vec::new();
 6349        let mut last_outdent = None;
 6350        {
 6351            let buffer = self.buffer.read(cx);
 6352            let snapshot = buffer.snapshot(cx);
 6353            for selection in &selections {
 6354                let settings = buffer.settings_at(selection.start, cx);
 6355                let tab_size = settings.tab_size.get();
 6356                let mut rows = selection.spanned_rows(false, &display_map);
 6357
 6358                // Avoid re-outdenting a row that has already been outdented by a
 6359                // previous selection.
 6360                if let Some(last_row) = last_outdent {
 6361                    if last_row == rows.start {
 6362                        rows.start = rows.start.next_row();
 6363                    }
 6364                }
 6365                let has_multiple_rows = rows.len() > 1;
 6366                for row in rows.iter_rows() {
 6367                    let indent_size = snapshot.indent_size_for_line(row);
 6368                    if indent_size.len > 0 {
 6369                        let deletion_len = match indent_size.kind {
 6370                            IndentKind::Space => {
 6371                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6372                                if columns_to_prev_tab_stop == 0 {
 6373                                    tab_size
 6374                                } else {
 6375                                    columns_to_prev_tab_stop
 6376                                }
 6377                            }
 6378                            IndentKind::Tab => 1,
 6379                        };
 6380                        let start = if has_multiple_rows
 6381                            || deletion_len > selection.start.column
 6382                            || indent_size.len < selection.start.column
 6383                        {
 6384                            0
 6385                        } else {
 6386                            selection.start.column - deletion_len
 6387                        };
 6388                        deletion_ranges.push(
 6389                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6390                        );
 6391                        last_outdent = Some(row);
 6392                    }
 6393                }
 6394            }
 6395        }
 6396
 6397        self.transact(cx, |this, cx| {
 6398            this.buffer.update(cx, |buffer, cx| {
 6399                let empty_str: Arc<str> = Arc::default();
 6400                buffer.edit(
 6401                    deletion_ranges
 6402                        .into_iter()
 6403                        .map(|range| (range, empty_str.clone())),
 6404                    None,
 6405                    cx,
 6406                );
 6407            });
 6408            let selections = this.selections.all::<usize>(cx);
 6409            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6410        });
 6411    }
 6412
 6413    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 6414        if self.read_only(cx) {
 6415            return;
 6416        }
 6417        let selections = self
 6418            .selections
 6419            .all::<usize>(cx)
 6420            .into_iter()
 6421            .map(|s| s.range());
 6422
 6423        self.transact(cx, |this, cx| {
 6424            this.buffer.update(cx, |buffer, cx| {
 6425                buffer.autoindent_ranges(selections, cx);
 6426            });
 6427            let selections = this.selections.all::<usize>(cx);
 6428            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6429        });
 6430    }
 6431
 6432    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 6433        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6434        let selections = self.selections.all::<Point>(cx);
 6435
 6436        let mut new_cursors = Vec::new();
 6437        let mut edit_ranges = Vec::new();
 6438        let mut selections = selections.iter().peekable();
 6439        while let Some(selection) = selections.next() {
 6440            let mut rows = selection.spanned_rows(false, &display_map);
 6441            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6442
 6443            // Accumulate contiguous regions of rows that we want to delete.
 6444            while let Some(next_selection) = selections.peek() {
 6445                let next_rows = next_selection.spanned_rows(false, &display_map);
 6446                if next_rows.start <= rows.end {
 6447                    rows.end = next_rows.end;
 6448                    selections.next().unwrap();
 6449                } else {
 6450                    break;
 6451                }
 6452            }
 6453
 6454            let buffer = &display_map.buffer_snapshot;
 6455            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6456            let edit_end;
 6457            let cursor_buffer_row;
 6458            if buffer.max_point().row >= rows.end.0 {
 6459                // If there's a line after the range, delete the \n from the end of the row range
 6460                // and position the cursor on the next line.
 6461                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6462                cursor_buffer_row = rows.end;
 6463            } else {
 6464                // If there isn't a line after the range, delete the \n from the line before the
 6465                // start of the row range and position the cursor there.
 6466                edit_start = edit_start.saturating_sub(1);
 6467                edit_end = buffer.len();
 6468                cursor_buffer_row = rows.start.previous_row();
 6469            }
 6470
 6471            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6472            *cursor.column_mut() =
 6473                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6474
 6475            new_cursors.push((
 6476                selection.id,
 6477                buffer.anchor_after(cursor.to_point(&display_map)),
 6478            ));
 6479            edit_ranges.push(edit_start..edit_end);
 6480        }
 6481
 6482        self.transact(cx, |this, cx| {
 6483            let buffer = this.buffer.update(cx, |buffer, cx| {
 6484                let empty_str: Arc<str> = Arc::default();
 6485                buffer.edit(
 6486                    edit_ranges
 6487                        .into_iter()
 6488                        .map(|range| (range, empty_str.clone())),
 6489                    None,
 6490                    cx,
 6491                );
 6492                buffer.snapshot(cx)
 6493            });
 6494            let new_selections = new_cursors
 6495                .into_iter()
 6496                .map(|(id, cursor)| {
 6497                    let cursor = cursor.to_point(&buffer);
 6498                    Selection {
 6499                        id,
 6500                        start: cursor,
 6501                        end: cursor,
 6502                        reversed: false,
 6503                        goal: SelectionGoal::None,
 6504                    }
 6505                })
 6506                .collect();
 6507
 6508            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6509                s.select(new_selections);
 6510            });
 6511        });
 6512    }
 6513
 6514    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6515        if self.read_only(cx) {
 6516            return;
 6517        }
 6518        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6519        for selection in self.selections.all::<Point>(cx) {
 6520            let start = MultiBufferRow(selection.start.row);
 6521            // Treat single line selections as if they include the next line. Otherwise this action
 6522            // would do nothing for single line selections individual cursors.
 6523            let end = if selection.start.row == selection.end.row {
 6524                MultiBufferRow(selection.start.row + 1)
 6525            } else {
 6526                MultiBufferRow(selection.end.row)
 6527            };
 6528
 6529            if let Some(last_row_range) = row_ranges.last_mut() {
 6530                if start <= last_row_range.end {
 6531                    last_row_range.end = end;
 6532                    continue;
 6533                }
 6534            }
 6535            row_ranges.push(start..end);
 6536        }
 6537
 6538        let snapshot = self.buffer.read(cx).snapshot(cx);
 6539        let mut cursor_positions = Vec::new();
 6540        for row_range in &row_ranges {
 6541            let anchor = snapshot.anchor_before(Point::new(
 6542                row_range.end.previous_row().0,
 6543                snapshot.line_len(row_range.end.previous_row()),
 6544            ));
 6545            cursor_positions.push(anchor..anchor);
 6546        }
 6547
 6548        self.transact(cx, |this, cx| {
 6549            for row_range in row_ranges.into_iter().rev() {
 6550                for row in row_range.iter_rows().rev() {
 6551                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6552                    let next_line_row = row.next_row();
 6553                    let indent = snapshot.indent_size_for_line(next_line_row);
 6554                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6555
 6556                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6557                        " "
 6558                    } else {
 6559                        ""
 6560                    };
 6561
 6562                    this.buffer.update(cx, |buffer, cx| {
 6563                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6564                    });
 6565                }
 6566            }
 6567
 6568            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6569                s.select_anchor_ranges(cursor_positions)
 6570            });
 6571        });
 6572    }
 6573
 6574    pub fn sort_lines_case_sensitive(
 6575        &mut self,
 6576        _: &SortLinesCaseSensitive,
 6577        cx: &mut ViewContext<Self>,
 6578    ) {
 6579        self.manipulate_lines(cx, |lines| lines.sort())
 6580    }
 6581
 6582    pub fn sort_lines_case_insensitive(
 6583        &mut self,
 6584        _: &SortLinesCaseInsensitive,
 6585        cx: &mut ViewContext<Self>,
 6586    ) {
 6587        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6588    }
 6589
 6590    pub fn unique_lines_case_insensitive(
 6591        &mut self,
 6592        _: &UniqueLinesCaseInsensitive,
 6593        cx: &mut ViewContext<Self>,
 6594    ) {
 6595        self.manipulate_lines(cx, |lines| {
 6596            let mut seen = HashSet::default();
 6597            lines.retain(|line| seen.insert(line.to_lowercase()));
 6598        })
 6599    }
 6600
 6601    pub fn unique_lines_case_sensitive(
 6602        &mut self,
 6603        _: &UniqueLinesCaseSensitive,
 6604        cx: &mut ViewContext<Self>,
 6605    ) {
 6606        self.manipulate_lines(cx, |lines| {
 6607            let mut seen = HashSet::default();
 6608            lines.retain(|line| seen.insert(*line));
 6609        })
 6610    }
 6611
 6612    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6613        let mut revert_changes = HashMap::default();
 6614        let snapshot = self.snapshot(cx);
 6615        for hunk in hunks_for_ranges(
 6616            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 6617            &snapshot,
 6618        ) {
 6619            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6620        }
 6621        if !revert_changes.is_empty() {
 6622            self.transact(cx, |editor, cx| {
 6623                editor.revert(revert_changes, cx);
 6624            });
 6625        }
 6626    }
 6627
 6628    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6629        let Some(project) = self.project.clone() else {
 6630            return;
 6631        };
 6632        self.reload(project, cx).detach_and_notify_err(cx);
 6633    }
 6634
 6635    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6636        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 6637        if !revert_changes.is_empty() {
 6638            self.transact(cx, |editor, cx| {
 6639                editor.revert(revert_changes, cx);
 6640            });
 6641        }
 6642    }
 6643
 6644    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 6645        let snapshot = self.buffer.read(cx).read(cx);
 6646        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 6647            drop(snapshot);
 6648            let mut revert_changes = HashMap::default();
 6649            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6650            if !revert_changes.is_empty() {
 6651                self.revert(revert_changes, cx)
 6652            }
 6653        }
 6654    }
 6655
 6656    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6657        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6658            let project_path = buffer.read(cx).project_path(cx)?;
 6659            let project = self.project.as_ref()?.read(cx);
 6660            let entry = project.entry_for_path(&project_path, cx)?;
 6661            let parent = match &entry.canonical_path {
 6662                Some(canonical_path) => canonical_path.to_path_buf(),
 6663                None => project.absolute_path(&project_path, cx)?,
 6664            }
 6665            .parent()?
 6666            .to_path_buf();
 6667            Some(parent)
 6668        }) {
 6669            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6670        }
 6671    }
 6672
 6673    fn gather_revert_changes(
 6674        &mut self,
 6675        selections: &[Selection<Point>],
 6676        cx: &mut ViewContext<'_, Editor>,
 6677    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6678        let mut revert_changes = HashMap::default();
 6679        let snapshot = self.snapshot(cx);
 6680        for hunk in hunks_for_selections(&snapshot, selections) {
 6681            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6682        }
 6683        revert_changes
 6684    }
 6685
 6686    pub fn prepare_revert_change(
 6687        &mut self,
 6688        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6689        hunk: &MultiBufferDiffHunk,
 6690        cx: &AppContext,
 6691    ) -> Option<()> {
 6692        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 6693        let buffer = buffer.read(cx);
 6694        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 6695        let original_text = change_set
 6696            .read(cx)
 6697            .base_text
 6698            .as_ref()?
 6699            .read(cx)
 6700            .as_rope()
 6701            .slice(hunk.diff_base_byte_range.clone());
 6702        let buffer_snapshot = buffer.snapshot();
 6703        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6704        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6705            probe
 6706                .0
 6707                .start
 6708                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6709                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6710        }) {
 6711            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6712            Some(())
 6713        } else {
 6714            None
 6715        }
 6716    }
 6717
 6718    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6719        self.manipulate_lines(cx, |lines| lines.reverse())
 6720    }
 6721
 6722    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6723        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6724    }
 6725
 6726    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6727    where
 6728        Fn: FnMut(&mut Vec<&str>),
 6729    {
 6730        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6731        let buffer = self.buffer.read(cx).snapshot(cx);
 6732
 6733        let mut edits = Vec::new();
 6734
 6735        let selections = self.selections.all::<Point>(cx);
 6736        let mut selections = selections.iter().peekable();
 6737        let mut contiguous_row_selections = Vec::new();
 6738        let mut new_selections = Vec::new();
 6739        let mut added_lines = 0;
 6740        let mut removed_lines = 0;
 6741
 6742        while let Some(selection) = selections.next() {
 6743            let (start_row, end_row) = consume_contiguous_rows(
 6744                &mut contiguous_row_selections,
 6745                selection,
 6746                &display_map,
 6747                &mut selections,
 6748            );
 6749
 6750            let start_point = Point::new(start_row.0, 0);
 6751            let end_point = Point::new(
 6752                end_row.previous_row().0,
 6753                buffer.line_len(end_row.previous_row()),
 6754            );
 6755            let text = buffer
 6756                .text_for_range(start_point..end_point)
 6757                .collect::<String>();
 6758
 6759            let mut lines = text.split('\n').collect_vec();
 6760
 6761            let lines_before = lines.len();
 6762            callback(&mut lines);
 6763            let lines_after = lines.len();
 6764
 6765            edits.push((start_point..end_point, lines.join("\n")));
 6766
 6767            // Selections must change based on added and removed line count
 6768            let start_row =
 6769                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6770            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6771            new_selections.push(Selection {
 6772                id: selection.id,
 6773                start: start_row,
 6774                end: end_row,
 6775                goal: SelectionGoal::None,
 6776                reversed: selection.reversed,
 6777            });
 6778
 6779            if lines_after > lines_before {
 6780                added_lines += lines_after - lines_before;
 6781            } else if lines_before > lines_after {
 6782                removed_lines += lines_before - lines_after;
 6783            }
 6784        }
 6785
 6786        self.transact(cx, |this, cx| {
 6787            let buffer = this.buffer.update(cx, |buffer, cx| {
 6788                buffer.edit(edits, None, cx);
 6789                buffer.snapshot(cx)
 6790            });
 6791
 6792            // Recalculate offsets on newly edited buffer
 6793            let new_selections = new_selections
 6794                .iter()
 6795                .map(|s| {
 6796                    let start_point = Point::new(s.start.0, 0);
 6797                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6798                    Selection {
 6799                        id: s.id,
 6800                        start: buffer.point_to_offset(start_point),
 6801                        end: buffer.point_to_offset(end_point),
 6802                        goal: s.goal,
 6803                        reversed: s.reversed,
 6804                    }
 6805                })
 6806                .collect();
 6807
 6808            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6809                s.select(new_selections);
 6810            });
 6811
 6812            this.request_autoscroll(Autoscroll::fit(), cx);
 6813        });
 6814    }
 6815
 6816    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6817        self.manipulate_text(cx, |text| text.to_uppercase())
 6818    }
 6819
 6820    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6821        self.manipulate_text(cx, |text| text.to_lowercase())
 6822    }
 6823
 6824    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6825        self.manipulate_text(cx, |text| {
 6826            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6827            // https://github.com/rutrum/convert-case/issues/16
 6828            text.split('\n')
 6829                .map(|line| line.to_case(Case::Title))
 6830                .join("\n")
 6831        })
 6832    }
 6833
 6834    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6835        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6836    }
 6837
 6838    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6839        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6840    }
 6841
 6842    pub fn convert_to_upper_camel_case(
 6843        &mut self,
 6844        _: &ConvertToUpperCamelCase,
 6845        cx: &mut ViewContext<Self>,
 6846    ) {
 6847        self.manipulate_text(cx, |text| {
 6848            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6849            // https://github.com/rutrum/convert-case/issues/16
 6850            text.split('\n')
 6851                .map(|line| line.to_case(Case::UpperCamel))
 6852                .join("\n")
 6853        })
 6854    }
 6855
 6856    pub fn convert_to_lower_camel_case(
 6857        &mut self,
 6858        _: &ConvertToLowerCamelCase,
 6859        cx: &mut ViewContext<Self>,
 6860    ) {
 6861        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6862    }
 6863
 6864    pub fn convert_to_opposite_case(
 6865        &mut self,
 6866        _: &ConvertToOppositeCase,
 6867        cx: &mut ViewContext<Self>,
 6868    ) {
 6869        self.manipulate_text(cx, |text| {
 6870            text.chars()
 6871                .fold(String::with_capacity(text.len()), |mut t, c| {
 6872                    if c.is_uppercase() {
 6873                        t.extend(c.to_lowercase());
 6874                    } else {
 6875                        t.extend(c.to_uppercase());
 6876                    }
 6877                    t
 6878                })
 6879        })
 6880    }
 6881
 6882    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6883    where
 6884        Fn: FnMut(&str) -> String,
 6885    {
 6886        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6887        let buffer = self.buffer.read(cx).snapshot(cx);
 6888
 6889        let mut new_selections = Vec::new();
 6890        let mut edits = Vec::new();
 6891        let mut selection_adjustment = 0i32;
 6892
 6893        for selection in self.selections.all::<usize>(cx) {
 6894            let selection_is_empty = selection.is_empty();
 6895
 6896            let (start, end) = if selection_is_empty {
 6897                let word_range = movement::surrounding_word(
 6898                    &display_map,
 6899                    selection.start.to_display_point(&display_map),
 6900                );
 6901                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6902                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6903                (start, end)
 6904            } else {
 6905                (selection.start, selection.end)
 6906            };
 6907
 6908            let text = buffer.text_for_range(start..end).collect::<String>();
 6909            let old_length = text.len() as i32;
 6910            let text = callback(&text);
 6911
 6912            new_selections.push(Selection {
 6913                start: (start as i32 - selection_adjustment) as usize,
 6914                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6915                goal: SelectionGoal::None,
 6916                ..selection
 6917            });
 6918
 6919            selection_adjustment += old_length - text.len() as i32;
 6920
 6921            edits.push((start..end, text));
 6922        }
 6923
 6924        self.transact(cx, |this, cx| {
 6925            this.buffer.update(cx, |buffer, cx| {
 6926                buffer.edit(edits, None, cx);
 6927            });
 6928
 6929            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6930                s.select(new_selections);
 6931            });
 6932
 6933            this.request_autoscroll(Autoscroll::fit(), cx);
 6934        });
 6935    }
 6936
 6937    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6938        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6939        let buffer = &display_map.buffer_snapshot;
 6940        let selections = self.selections.all::<Point>(cx);
 6941
 6942        let mut edits = Vec::new();
 6943        let mut selections_iter = selections.iter().peekable();
 6944        while let Some(selection) = selections_iter.next() {
 6945            // Avoid duplicating the same lines twice.
 6946            let mut rows = selection.spanned_rows(false, &display_map);
 6947
 6948            while let Some(next_selection) = selections_iter.peek() {
 6949                let next_rows = next_selection.spanned_rows(false, &display_map);
 6950                if next_rows.start < rows.end {
 6951                    rows.end = next_rows.end;
 6952                    selections_iter.next().unwrap();
 6953                } else {
 6954                    break;
 6955                }
 6956            }
 6957
 6958            // Copy the text from the selected row region and splice it either at the start
 6959            // or end of the region.
 6960            let start = Point::new(rows.start.0, 0);
 6961            let end = Point::new(
 6962                rows.end.previous_row().0,
 6963                buffer.line_len(rows.end.previous_row()),
 6964            );
 6965            let text = buffer
 6966                .text_for_range(start..end)
 6967                .chain(Some("\n"))
 6968                .collect::<String>();
 6969            let insert_location = if upwards {
 6970                Point::new(rows.end.0, 0)
 6971            } else {
 6972                start
 6973            };
 6974            edits.push((insert_location..insert_location, text));
 6975        }
 6976
 6977        self.transact(cx, |this, cx| {
 6978            this.buffer.update(cx, |buffer, cx| {
 6979                buffer.edit(edits, None, cx);
 6980            });
 6981
 6982            this.request_autoscroll(Autoscroll::fit(), cx);
 6983        });
 6984    }
 6985
 6986    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6987        self.duplicate_line(true, cx);
 6988    }
 6989
 6990    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6991        self.duplicate_line(false, cx);
 6992    }
 6993
 6994    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6995        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6996        let buffer = self.buffer.read(cx).snapshot(cx);
 6997
 6998        let mut edits = Vec::new();
 6999        let mut unfold_ranges = Vec::new();
 7000        let mut refold_creases = Vec::new();
 7001
 7002        let selections = self.selections.all::<Point>(cx);
 7003        let mut selections = selections.iter().peekable();
 7004        let mut contiguous_row_selections = Vec::new();
 7005        let mut new_selections = Vec::new();
 7006
 7007        while let Some(selection) = selections.next() {
 7008            // Find all the selections that span a contiguous row range
 7009            let (start_row, end_row) = consume_contiguous_rows(
 7010                &mut contiguous_row_selections,
 7011                selection,
 7012                &display_map,
 7013                &mut selections,
 7014            );
 7015
 7016            // Move the text spanned by the row range to be before the line preceding the row range
 7017            if start_row.0 > 0 {
 7018                let range_to_move = Point::new(
 7019                    start_row.previous_row().0,
 7020                    buffer.line_len(start_row.previous_row()),
 7021                )
 7022                    ..Point::new(
 7023                        end_row.previous_row().0,
 7024                        buffer.line_len(end_row.previous_row()),
 7025                    );
 7026                let insertion_point = display_map
 7027                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7028                    .0;
 7029
 7030                // Don't move lines across excerpts
 7031                if buffer
 7032                    .excerpt_boundaries_in_range((
 7033                        Bound::Excluded(insertion_point),
 7034                        Bound::Included(range_to_move.end),
 7035                    ))
 7036                    .next()
 7037                    .is_none()
 7038                {
 7039                    let text = buffer
 7040                        .text_for_range(range_to_move.clone())
 7041                        .flat_map(|s| s.chars())
 7042                        .skip(1)
 7043                        .chain(['\n'])
 7044                        .collect::<String>();
 7045
 7046                    edits.push((
 7047                        buffer.anchor_after(range_to_move.start)
 7048                            ..buffer.anchor_before(range_to_move.end),
 7049                        String::new(),
 7050                    ));
 7051                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7052                    edits.push((insertion_anchor..insertion_anchor, text));
 7053
 7054                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7055
 7056                    // Move selections up
 7057                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7058                        |mut selection| {
 7059                            selection.start.row -= row_delta;
 7060                            selection.end.row -= row_delta;
 7061                            selection
 7062                        },
 7063                    ));
 7064
 7065                    // Move folds up
 7066                    unfold_ranges.push(range_to_move.clone());
 7067                    for fold in display_map.folds_in_range(
 7068                        buffer.anchor_before(range_to_move.start)
 7069                            ..buffer.anchor_after(range_to_move.end),
 7070                    ) {
 7071                        let mut start = fold.range.start.to_point(&buffer);
 7072                        let mut end = fold.range.end.to_point(&buffer);
 7073                        start.row -= row_delta;
 7074                        end.row -= row_delta;
 7075                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7076                    }
 7077                }
 7078            }
 7079
 7080            // If we didn't move line(s), preserve the existing selections
 7081            new_selections.append(&mut contiguous_row_selections);
 7082        }
 7083
 7084        self.transact(cx, |this, cx| {
 7085            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7086            this.buffer.update(cx, |buffer, cx| {
 7087                for (range, text) in edits {
 7088                    buffer.edit([(range, text)], None, cx);
 7089                }
 7090            });
 7091            this.fold_creases(refold_creases, true, cx);
 7092            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7093                s.select(new_selections);
 7094            })
 7095        });
 7096    }
 7097
 7098    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 7099        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7100        let buffer = self.buffer.read(cx).snapshot(cx);
 7101
 7102        let mut edits = Vec::new();
 7103        let mut unfold_ranges = Vec::new();
 7104        let mut refold_creases = Vec::new();
 7105
 7106        let selections = self.selections.all::<Point>(cx);
 7107        let mut selections = selections.iter().peekable();
 7108        let mut contiguous_row_selections = Vec::new();
 7109        let mut new_selections = Vec::new();
 7110
 7111        while let Some(selection) = selections.next() {
 7112            // Find all the selections that span a contiguous row range
 7113            let (start_row, end_row) = consume_contiguous_rows(
 7114                &mut contiguous_row_selections,
 7115                selection,
 7116                &display_map,
 7117                &mut selections,
 7118            );
 7119
 7120            // Move the text spanned by the row range to be after the last line of the row range
 7121            if end_row.0 <= buffer.max_point().row {
 7122                let range_to_move =
 7123                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7124                let insertion_point = display_map
 7125                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7126                    .0;
 7127
 7128                // Don't move lines across excerpt boundaries
 7129                if buffer
 7130                    .excerpt_boundaries_in_range((
 7131                        Bound::Excluded(range_to_move.start),
 7132                        Bound::Included(insertion_point),
 7133                    ))
 7134                    .next()
 7135                    .is_none()
 7136                {
 7137                    let mut text = String::from("\n");
 7138                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7139                    text.pop(); // Drop trailing newline
 7140                    edits.push((
 7141                        buffer.anchor_after(range_to_move.start)
 7142                            ..buffer.anchor_before(range_to_move.end),
 7143                        String::new(),
 7144                    ));
 7145                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7146                    edits.push((insertion_anchor..insertion_anchor, text));
 7147
 7148                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7149
 7150                    // Move selections down
 7151                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7152                        |mut selection| {
 7153                            selection.start.row += row_delta;
 7154                            selection.end.row += row_delta;
 7155                            selection
 7156                        },
 7157                    ));
 7158
 7159                    // Move folds down
 7160                    unfold_ranges.push(range_to_move.clone());
 7161                    for fold in display_map.folds_in_range(
 7162                        buffer.anchor_before(range_to_move.start)
 7163                            ..buffer.anchor_after(range_to_move.end),
 7164                    ) {
 7165                        let mut start = fold.range.start.to_point(&buffer);
 7166                        let mut end = fold.range.end.to_point(&buffer);
 7167                        start.row += row_delta;
 7168                        end.row += row_delta;
 7169                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7170                    }
 7171                }
 7172            }
 7173
 7174            // If we didn't move line(s), preserve the existing selections
 7175            new_selections.append(&mut contiguous_row_selections);
 7176        }
 7177
 7178        self.transact(cx, |this, cx| {
 7179            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7180            this.buffer.update(cx, |buffer, cx| {
 7181                for (range, text) in edits {
 7182                    buffer.edit([(range, text)], None, cx);
 7183                }
 7184            });
 7185            this.fold_creases(refold_creases, true, cx);
 7186            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 7187        });
 7188    }
 7189
 7190    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 7191        let text_layout_details = &self.text_layout_details(cx);
 7192        self.transact(cx, |this, cx| {
 7193            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7194                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7195                let line_mode = s.line_mode;
 7196                s.move_with(|display_map, selection| {
 7197                    if !selection.is_empty() || line_mode {
 7198                        return;
 7199                    }
 7200
 7201                    let mut head = selection.head();
 7202                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7203                    if head.column() == display_map.line_len(head.row()) {
 7204                        transpose_offset = display_map
 7205                            .buffer_snapshot
 7206                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7207                    }
 7208
 7209                    if transpose_offset == 0 {
 7210                        return;
 7211                    }
 7212
 7213                    *head.column_mut() += 1;
 7214                    head = display_map.clip_point(head, Bias::Right);
 7215                    let goal = SelectionGoal::HorizontalPosition(
 7216                        display_map
 7217                            .x_for_display_point(head, text_layout_details)
 7218                            .into(),
 7219                    );
 7220                    selection.collapse_to(head, goal);
 7221
 7222                    let transpose_start = display_map
 7223                        .buffer_snapshot
 7224                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7225                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7226                        let transpose_end = display_map
 7227                            .buffer_snapshot
 7228                            .clip_offset(transpose_offset + 1, Bias::Right);
 7229                        if let Some(ch) =
 7230                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7231                        {
 7232                            edits.push((transpose_start..transpose_offset, String::new()));
 7233                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7234                        }
 7235                    }
 7236                });
 7237                edits
 7238            });
 7239            this.buffer
 7240                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7241            let selections = this.selections.all::<usize>(cx);
 7242            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7243                s.select(selections);
 7244            });
 7245        });
 7246    }
 7247
 7248    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 7249        self.rewrap_impl(IsVimMode::No, cx)
 7250    }
 7251
 7252    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 7253        let buffer = self.buffer.read(cx).snapshot(cx);
 7254        let selections = self.selections.all::<Point>(cx);
 7255        let mut selections = selections.iter().peekable();
 7256
 7257        let mut edits = Vec::new();
 7258        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7259
 7260        while let Some(selection) = selections.next() {
 7261            let mut start_row = selection.start.row;
 7262            let mut end_row = selection.end.row;
 7263
 7264            // Skip selections that overlap with a range that has already been rewrapped.
 7265            let selection_range = start_row..end_row;
 7266            if rewrapped_row_ranges
 7267                .iter()
 7268                .any(|range| range.overlaps(&selection_range))
 7269            {
 7270                continue;
 7271            }
 7272
 7273            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7274
 7275            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7276                match language_scope.language_name().0.as_ref() {
 7277                    "Markdown" | "Plain Text" => {
 7278                        should_rewrap = true;
 7279                    }
 7280                    _ => {}
 7281                }
 7282            }
 7283
 7284            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7285
 7286            // Since not all lines in the selection may be at the same indent
 7287            // level, choose the indent size that is the most common between all
 7288            // of the lines.
 7289            //
 7290            // If there is a tie, we use the deepest indent.
 7291            let (indent_size, indent_end) = {
 7292                let mut indent_size_occurrences = HashMap::default();
 7293                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7294
 7295                for row in start_row..=end_row {
 7296                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7297                    rows_by_indent_size.entry(indent).or_default().push(row);
 7298                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7299                }
 7300
 7301                let indent_size = indent_size_occurrences
 7302                    .into_iter()
 7303                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7304                    .map(|(indent, _)| indent)
 7305                    .unwrap_or_default();
 7306                let row = rows_by_indent_size[&indent_size][0];
 7307                let indent_end = Point::new(row, indent_size.len);
 7308
 7309                (indent_size, indent_end)
 7310            };
 7311
 7312            let mut line_prefix = indent_size.chars().collect::<String>();
 7313
 7314            if let Some(comment_prefix) =
 7315                buffer
 7316                    .language_scope_at(selection.head())
 7317                    .and_then(|language| {
 7318                        language
 7319                            .line_comment_prefixes()
 7320                            .iter()
 7321                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7322                            .cloned()
 7323                    })
 7324            {
 7325                line_prefix.push_str(&comment_prefix);
 7326                should_rewrap = true;
 7327            }
 7328
 7329            if !should_rewrap {
 7330                continue;
 7331            }
 7332
 7333            if selection.is_empty() {
 7334                'expand_upwards: while start_row > 0 {
 7335                    let prev_row = start_row - 1;
 7336                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7337                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7338                    {
 7339                        start_row = prev_row;
 7340                    } else {
 7341                        break 'expand_upwards;
 7342                    }
 7343                }
 7344
 7345                'expand_downwards: while end_row < buffer.max_point().row {
 7346                    let next_row = end_row + 1;
 7347                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7348                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7349                    {
 7350                        end_row = next_row;
 7351                    } else {
 7352                        break 'expand_downwards;
 7353                    }
 7354                }
 7355            }
 7356
 7357            let start = Point::new(start_row, 0);
 7358            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7359            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7360            let Some(lines_without_prefixes) = selection_text
 7361                .lines()
 7362                .map(|line| {
 7363                    line.strip_prefix(&line_prefix)
 7364                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7365                        .ok_or_else(|| {
 7366                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7367                        })
 7368                })
 7369                .collect::<Result<Vec<_>, _>>()
 7370                .log_err()
 7371            else {
 7372                continue;
 7373            };
 7374
 7375            let wrap_column = buffer
 7376                .settings_at(Point::new(start_row, 0), cx)
 7377                .preferred_line_length as usize;
 7378            let wrapped_text = wrap_with_prefix(
 7379                line_prefix,
 7380                lines_without_prefixes.join(" "),
 7381                wrap_column,
 7382                tab_size,
 7383            );
 7384
 7385            // TODO: should always use char-based diff while still supporting cursor behavior that
 7386            // matches vim.
 7387            let diff = match is_vim_mode {
 7388                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7389                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7390            };
 7391            let mut offset = start.to_offset(&buffer);
 7392            let mut moved_since_edit = true;
 7393
 7394            for change in diff.iter_all_changes() {
 7395                let value = change.value();
 7396                match change.tag() {
 7397                    ChangeTag::Equal => {
 7398                        offset += value.len();
 7399                        moved_since_edit = true;
 7400                    }
 7401                    ChangeTag::Delete => {
 7402                        let start = buffer.anchor_after(offset);
 7403                        let end = buffer.anchor_before(offset + value.len());
 7404
 7405                        if moved_since_edit {
 7406                            edits.push((start..end, String::new()));
 7407                        } else {
 7408                            edits.last_mut().unwrap().0.end = end;
 7409                        }
 7410
 7411                        offset += value.len();
 7412                        moved_since_edit = false;
 7413                    }
 7414                    ChangeTag::Insert => {
 7415                        if moved_since_edit {
 7416                            let anchor = buffer.anchor_after(offset);
 7417                            edits.push((anchor..anchor, value.to_string()));
 7418                        } else {
 7419                            edits.last_mut().unwrap().1.push_str(value);
 7420                        }
 7421
 7422                        moved_since_edit = false;
 7423                    }
 7424                }
 7425            }
 7426
 7427            rewrapped_row_ranges.push(start_row..=end_row);
 7428        }
 7429
 7430        self.buffer
 7431            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7432    }
 7433
 7434    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 7435        let mut text = String::new();
 7436        let buffer = self.buffer.read(cx).snapshot(cx);
 7437        let mut selections = self.selections.all::<Point>(cx);
 7438        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7439        {
 7440            let max_point = buffer.max_point();
 7441            let mut is_first = true;
 7442            for selection in &mut selections {
 7443                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7444                if is_entire_line {
 7445                    selection.start = Point::new(selection.start.row, 0);
 7446                    if !selection.is_empty() && selection.end.column == 0 {
 7447                        selection.end = cmp::min(max_point, selection.end);
 7448                    } else {
 7449                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7450                    }
 7451                    selection.goal = SelectionGoal::None;
 7452                }
 7453                if is_first {
 7454                    is_first = false;
 7455                } else {
 7456                    text += "\n";
 7457                }
 7458                let mut len = 0;
 7459                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7460                    text.push_str(chunk);
 7461                    len += chunk.len();
 7462                }
 7463                clipboard_selections.push(ClipboardSelection {
 7464                    len,
 7465                    is_entire_line,
 7466                    first_line_indent: buffer
 7467                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7468                        .len,
 7469                });
 7470            }
 7471        }
 7472
 7473        self.transact(cx, |this, cx| {
 7474            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7475                s.select(selections);
 7476            });
 7477            this.insert("", cx);
 7478        });
 7479        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7480    }
 7481
 7482    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 7483        let item = self.cut_common(cx);
 7484        cx.write_to_clipboard(item);
 7485    }
 7486
 7487    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 7488        self.change_selections(None, cx, |s| {
 7489            s.move_with(|snapshot, sel| {
 7490                if sel.is_empty() {
 7491                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7492                }
 7493            });
 7494        });
 7495        let item = self.cut_common(cx);
 7496        cx.set_global(KillRing(item))
 7497    }
 7498
 7499    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 7500        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7501            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7502                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7503            } else {
 7504                return;
 7505            }
 7506        } else {
 7507            return;
 7508        };
 7509        self.do_paste(&text, metadata, false, cx);
 7510    }
 7511
 7512    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 7513        let selections = self.selections.all::<Point>(cx);
 7514        let buffer = self.buffer.read(cx).read(cx);
 7515        let mut text = String::new();
 7516
 7517        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7518        {
 7519            let max_point = buffer.max_point();
 7520            let mut is_first = true;
 7521            for selection in selections.iter() {
 7522                let mut start = selection.start;
 7523                let mut end = selection.end;
 7524                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7525                if is_entire_line {
 7526                    start = Point::new(start.row, 0);
 7527                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7528                }
 7529                if is_first {
 7530                    is_first = false;
 7531                } else {
 7532                    text += "\n";
 7533                }
 7534                let mut len = 0;
 7535                for chunk in buffer.text_for_range(start..end) {
 7536                    text.push_str(chunk);
 7537                    len += chunk.len();
 7538                }
 7539                clipboard_selections.push(ClipboardSelection {
 7540                    len,
 7541                    is_entire_line,
 7542                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7543                });
 7544            }
 7545        }
 7546
 7547        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7548            text,
 7549            clipboard_selections,
 7550        ));
 7551    }
 7552
 7553    pub fn do_paste(
 7554        &mut self,
 7555        text: &String,
 7556        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7557        handle_entire_lines: bool,
 7558        cx: &mut ViewContext<Self>,
 7559    ) {
 7560        if self.read_only(cx) {
 7561            return;
 7562        }
 7563
 7564        let clipboard_text = Cow::Borrowed(text);
 7565
 7566        self.transact(cx, |this, cx| {
 7567            if let Some(mut clipboard_selections) = clipboard_selections {
 7568                let old_selections = this.selections.all::<usize>(cx);
 7569                let all_selections_were_entire_line =
 7570                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7571                let first_selection_indent_column =
 7572                    clipboard_selections.first().map(|s| s.first_line_indent);
 7573                if clipboard_selections.len() != old_selections.len() {
 7574                    clipboard_selections.drain(..);
 7575                }
 7576                let cursor_offset = this.selections.last::<usize>(cx).head();
 7577                let mut auto_indent_on_paste = true;
 7578
 7579                this.buffer.update(cx, |buffer, cx| {
 7580                    let snapshot = buffer.read(cx);
 7581                    auto_indent_on_paste =
 7582                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7583
 7584                    let mut start_offset = 0;
 7585                    let mut edits = Vec::new();
 7586                    let mut original_indent_columns = Vec::new();
 7587                    for (ix, selection) in old_selections.iter().enumerate() {
 7588                        let to_insert;
 7589                        let entire_line;
 7590                        let original_indent_column;
 7591                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7592                            let end_offset = start_offset + clipboard_selection.len;
 7593                            to_insert = &clipboard_text[start_offset..end_offset];
 7594                            entire_line = clipboard_selection.is_entire_line;
 7595                            start_offset = end_offset + 1;
 7596                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7597                        } else {
 7598                            to_insert = clipboard_text.as_str();
 7599                            entire_line = all_selections_were_entire_line;
 7600                            original_indent_column = first_selection_indent_column
 7601                        }
 7602
 7603                        // If the corresponding selection was empty when this slice of the
 7604                        // clipboard text was written, then the entire line containing the
 7605                        // selection was copied. If this selection is also currently empty,
 7606                        // then paste the line before the current line of the buffer.
 7607                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7608                            let column = selection.start.to_point(&snapshot).column as usize;
 7609                            let line_start = selection.start - column;
 7610                            line_start..line_start
 7611                        } else {
 7612                            selection.range()
 7613                        };
 7614
 7615                        edits.push((range, to_insert));
 7616                        original_indent_columns.extend(original_indent_column);
 7617                    }
 7618                    drop(snapshot);
 7619
 7620                    buffer.edit(
 7621                        edits,
 7622                        if auto_indent_on_paste {
 7623                            Some(AutoindentMode::Block {
 7624                                original_indent_columns,
 7625                            })
 7626                        } else {
 7627                            None
 7628                        },
 7629                        cx,
 7630                    );
 7631                });
 7632
 7633                let selections = this.selections.all::<usize>(cx);
 7634                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7635            } else {
 7636                this.insert(&clipboard_text, cx);
 7637            }
 7638        });
 7639    }
 7640
 7641    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7642        if let Some(item) = cx.read_from_clipboard() {
 7643            let entries = item.entries();
 7644
 7645            match entries.first() {
 7646                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7647                // of all the pasted entries.
 7648                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7649                    .do_paste(
 7650                        clipboard_string.text(),
 7651                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7652                        true,
 7653                        cx,
 7654                    ),
 7655                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7656            }
 7657        }
 7658    }
 7659
 7660    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7661        if self.read_only(cx) {
 7662            return;
 7663        }
 7664
 7665        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7666            if let Some((selections, _)) =
 7667                self.selection_history.transaction(transaction_id).cloned()
 7668            {
 7669                self.change_selections(None, cx, |s| {
 7670                    s.select_anchors(selections.to_vec());
 7671                });
 7672            }
 7673            self.request_autoscroll(Autoscroll::fit(), cx);
 7674            self.unmark_text(cx);
 7675            self.refresh_inline_completion(true, false, cx);
 7676            cx.emit(EditorEvent::Edited { transaction_id });
 7677            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7678        }
 7679    }
 7680
 7681    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7682        if self.read_only(cx) {
 7683            return;
 7684        }
 7685
 7686        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7687            if let Some((_, Some(selections))) =
 7688                self.selection_history.transaction(transaction_id).cloned()
 7689            {
 7690                self.change_selections(None, cx, |s| {
 7691                    s.select_anchors(selections.to_vec());
 7692                });
 7693            }
 7694            self.request_autoscroll(Autoscroll::fit(), cx);
 7695            self.unmark_text(cx);
 7696            self.refresh_inline_completion(true, false, cx);
 7697            cx.emit(EditorEvent::Edited { transaction_id });
 7698        }
 7699    }
 7700
 7701    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7702        self.buffer
 7703            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7704    }
 7705
 7706    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7707        self.buffer
 7708            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7709    }
 7710
 7711    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7712        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7713            let line_mode = s.line_mode;
 7714            s.move_with(|map, selection| {
 7715                let cursor = if selection.is_empty() && !line_mode {
 7716                    movement::left(map, selection.start)
 7717                } else {
 7718                    selection.start
 7719                };
 7720                selection.collapse_to(cursor, SelectionGoal::None);
 7721            });
 7722        })
 7723    }
 7724
 7725    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7726        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7727            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7728        })
 7729    }
 7730
 7731    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7732        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7733            let line_mode = s.line_mode;
 7734            s.move_with(|map, selection| {
 7735                let cursor = if selection.is_empty() && !line_mode {
 7736                    movement::right(map, selection.end)
 7737                } else {
 7738                    selection.end
 7739                };
 7740                selection.collapse_to(cursor, SelectionGoal::None)
 7741            });
 7742        })
 7743    }
 7744
 7745    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7746        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7747            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7748        })
 7749    }
 7750
 7751    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7752        if self.take_rename(true, cx).is_some() {
 7753            return;
 7754        }
 7755
 7756        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7757            cx.propagate();
 7758            return;
 7759        }
 7760
 7761        let text_layout_details = &self.text_layout_details(cx);
 7762        let selection_count = self.selections.count();
 7763        let first_selection = self.selections.first_anchor();
 7764
 7765        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7766            let line_mode = s.line_mode;
 7767            s.move_with(|map, selection| {
 7768                if !selection.is_empty() && !line_mode {
 7769                    selection.goal = SelectionGoal::None;
 7770                }
 7771                let (cursor, goal) = movement::up(
 7772                    map,
 7773                    selection.start,
 7774                    selection.goal,
 7775                    false,
 7776                    text_layout_details,
 7777                );
 7778                selection.collapse_to(cursor, goal);
 7779            });
 7780        });
 7781
 7782        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7783        {
 7784            cx.propagate();
 7785        }
 7786    }
 7787
 7788    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7789        if self.take_rename(true, cx).is_some() {
 7790            return;
 7791        }
 7792
 7793        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7794            cx.propagate();
 7795            return;
 7796        }
 7797
 7798        let text_layout_details = &self.text_layout_details(cx);
 7799
 7800        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7801            let line_mode = s.line_mode;
 7802            s.move_with(|map, selection| {
 7803                if !selection.is_empty() && !line_mode {
 7804                    selection.goal = SelectionGoal::None;
 7805                }
 7806                let (cursor, goal) = movement::up_by_rows(
 7807                    map,
 7808                    selection.start,
 7809                    action.lines,
 7810                    selection.goal,
 7811                    false,
 7812                    text_layout_details,
 7813                );
 7814                selection.collapse_to(cursor, goal);
 7815            });
 7816        })
 7817    }
 7818
 7819    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7820        if self.take_rename(true, cx).is_some() {
 7821            return;
 7822        }
 7823
 7824        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7825            cx.propagate();
 7826            return;
 7827        }
 7828
 7829        let text_layout_details = &self.text_layout_details(cx);
 7830
 7831        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7832            let line_mode = s.line_mode;
 7833            s.move_with(|map, selection| {
 7834                if !selection.is_empty() && !line_mode {
 7835                    selection.goal = SelectionGoal::None;
 7836                }
 7837                let (cursor, goal) = movement::down_by_rows(
 7838                    map,
 7839                    selection.start,
 7840                    action.lines,
 7841                    selection.goal,
 7842                    false,
 7843                    text_layout_details,
 7844                );
 7845                selection.collapse_to(cursor, goal);
 7846            });
 7847        })
 7848    }
 7849
 7850    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7851        let text_layout_details = &self.text_layout_details(cx);
 7852        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7853            s.move_heads_with(|map, head, goal| {
 7854                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7855            })
 7856        })
 7857    }
 7858
 7859    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7860        let text_layout_details = &self.text_layout_details(cx);
 7861        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7862            s.move_heads_with(|map, head, goal| {
 7863                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7864            })
 7865        })
 7866    }
 7867
 7868    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7869        let Some(row_count) = self.visible_row_count() else {
 7870            return;
 7871        };
 7872
 7873        let text_layout_details = &self.text_layout_details(cx);
 7874
 7875        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7876            s.move_heads_with(|map, head, goal| {
 7877                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7878            })
 7879        })
 7880    }
 7881
 7882    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7883        if self.take_rename(true, cx).is_some() {
 7884            return;
 7885        }
 7886
 7887        if self
 7888            .context_menu
 7889            .write()
 7890            .as_mut()
 7891            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7892            .unwrap_or(false)
 7893        {
 7894            return;
 7895        }
 7896
 7897        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7898            cx.propagate();
 7899            return;
 7900        }
 7901
 7902        let Some(row_count) = self.visible_row_count() else {
 7903            return;
 7904        };
 7905
 7906        let autoscroll = if action.center_cursor {
 7907            Autoscroll::center()
 7908        } else {
 7909            Autoscroll::fit()
 7910        };
 7911
 7912        let text_layout_details = &self.text_layout_details(cx);
 7913
 7914        self.change_selections(Some(autoscroll), cx, |s| {
 7915            let line_mode = s.line_mode;
 7916            s.move_with(|map, selection| {
 7917                if !selection.is_empty() && !line_mode {
 7918                    selection.goal = SelectionGoal::None;
 7919                }
 7920                let (cursor, goal) = movement::up_by_rows(
 7921                    map,
 7922                    selection.end,
 7923                    row_count,
 7924                    selection.goal,
 7925                    false,
 7926                    text_layout_details,
 7927                );
 7928                selection.collapse_to(cursor, goal);
 7929            });
 7930        });
 7931    }
 7932
 7933    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7934        let text_layout_details = &self.text_layout_details(cx);
 7935        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7936            s.move_heads_with(|map, head, goal| {
 7937                movement::up(map, head, goal, false, text_layout_details)
 7938            })
 7939        })
 7940    }
 7941
 7942    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7943        self.take_rename(true, cx);
 7944
 7945        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7946            cx.propagate();
 7947            return;
 7948        }
 7949
 7950        let text_layout_details = &self.text_layout_details(cx);
 7951        let selection_count = self.selections.count();
 7952        let first_selection = self.selections.first_anchor();
 7953
 7954        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7955            let line_mode = s.line_mode;
 7956            s.move_with(|map, selection| {
 7957                if !selection.is_empty() && !line_mode {
 7958                    selection.goal = SelectionGoal::None;
 7959                }
 7960                let (cursor, goal) = movement::down(
 7961                    map,
 7962                    selection.end,
 7963                    selection.goal,
 7964                    false,
 7965                    text_layout_details,
 7966                );
 7967                selection.collapse_to(cursor, goal);
 7968            });
 7969        });
 7970
 7971        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7972        {
 7973            cx.propagate();
 7974        }
 7975    }
 7976
 7977    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7978        let Some(row_count) = self.visible_row_count() else {
 7979            return;
 7980        };
 7981
 7982        let text_layout_details = &self.text_layout_details(cx);
 7983
 7984        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7985            s.move_heads_with(|map, head, goal| {
 7986                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7987            })
 7988        })
 7989    }
 7990
 7991    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7992        if self.take_rename(true, cx).is_some() {
 7993            return;
 7994        }
 7995
 7996        if self
 7997            .context_menu
 7998            .write()
 7999            .as_mut()
 8000            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8001            .unwrap_or(false)
 8002        {
 8003            return;
 8004        }
 8005
 8006        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8007            cx.propagate();
 8008            return;
 8009        }
 8010
 8011        let Some(row_count) = self.visible_row_count() else {
 8012            return;
 8013        };
 8014
 8015        let autoscroll = if action.center_cursor {
 8016            Autoscroll::center()
 8017        } else {
 8018            Autoscroll::fit()
 8019        };
 8020
 8021        let text_layout_details = &self.text_layout_details(cx);
 8022        self.change_selections(Some(autoscroll), cx, |s| {
 8023            let line_mode = s.line_mode;
 8024            s.move_with(|map, selection| {
 8025                if !selection.is_empty() && !line_mode {
 8026                    selection.goal = SelectionGoal::None;
 8027                }
 8028                let (cursor, goal) = movement::down_by_rows(
 8029                    map,
 8030                    selection.end,
 8031                    row_count,
 8032                    selection.goal,
 8033                    false,
 8034                    text_layout_details,
 8035                );
 8036                selection.collapse_to(cursor, goal);
 8037            });
 8038        });
 8039    }
 8040
 8041    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 8042        let text_layout_details = &self.text_layout_details(cx);
 8043        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8044            s.move_heads_with(|map, head, goal| {
 8045                movement::down(map, head, goal, false, text_layout_details)
 8046            })
 8047        });
 8048    }
 8049
 8050    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 8051        if let Some(context_menu) = self.context_menu.write().as_mut() {
 8052            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8053        }
 8054    }
 8055
 8056    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 8057        if let Some(context_menu) = self.context_menu.write().as_mut() {
 8058            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8059        }
 8060    }
 8061
 8062    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 8063        if let Some(context_menu) = self.context_menu.write().as_mut() {
 8064            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8065        }
 8066    }
 8067
 8068    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 8069        if let Some(context_menu) = self.context_menu.write().as_mut() {
 8070            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8071        }
 8072    }
 8073
 8074    pub fn move_to_previous_word_start(
 8075        &mut self,
 8076        _: &MoveToPreviousWordStart,
 8077        cx: &mut ViewContext<Self>,
 8078    ) {
 8079        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8080            s.move_cursors_with(|map, head, _| {
 8081                (
 8082                    movement::previous_word_start(map, head),
 8083                    SelectionGoal::None,
 8084                )
 8085            });
 8086        })
 8087    }
 8088
 8089    pub fn move_to_previous_subword_start(
 8090        &mut self,
 8091        _: &MoveToPreviousSubwordStart,
 8092        cx: &mut ViewContext<Self>,
 8093    ) {
 8094        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8095            s.move_cursors_with(|map, head, _| {
 8096                (
 8097                    movement::previous_subword_start(map, head),
 8098                    SelectionGoal::None,
 8099                )
 8100            });
 8101        })
 8102    }
 8103
 8104    pub fn select_to_previous_word_start(
 8105        &mut self,
 8106        _: &SelectToPreviousWordStart,
 8107        cx: &mut ViewContext<Self>,
 8108    ) {
 8109        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8110            s.move_heads_with(|map, head, _| {
 8111                (
 8112                    movement::previous_word_start(map, head),
 8113                    SelectionGoal::None,
 8114                )
 8115            });
 8116        })
 8117    }
 8118
 8119    pub fn select_to_previous_subword_start(
 8120        &mut self,
 8121        _: &SelectToPreviousSubwordStart,
 8122        cx: &mut ViewContext<Self>,
 8123    ) {
 8124        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8125            s.move_heads_with(|map, head, _| {
 8126                (
 8127                    movement::previous_subword_start(map, head),
 8128                    SelectionGoal::None,
 8129                )
 8130            });
 8131        })
 8132    }
 8133
 8134    pub fn delete_to_previous_word_start(
 8135        &mut self,
 8136        action: &DeleteToPreviousWordStart,
 8137        cx: &mut ViewContext<Self>,
 8138    ) {
 8139        self.transact(cx, |this, cx| {
 8140            this.select_autoclose_pair(cx);
 8141            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8142                let line_mode = s.line_mode;
 8143                s.move_with(|map, selection| {
 8144                    if selection.is_empty() && !line_mode {
 8145                        let cursor = if action.ignore_newlines {
 8146                            movement::previous_word_start(map, selection.head())
 8147                        } else {
 8148                            movement::previous_word_start_or_newline(map, selection.head())
 8149                        };
 8150                        selection.set_head(cursor, SelectionGoal::None);
 8151                    }
 8152                });
 8153            });
 8154            this.insert("", cx);
 8155        });
 8156    }
 8157
 8158    pub fn delete_to_previous_subword_start(
 8159        &mut self,
 8160        _: &DeleteToPreviousSubwordStart,
 8161        cx: &mut ViewContext<Self>,
 8162    ) {
 8163        self.transact(cx, |this, cx| {
 8164            this.select_autoclose_pair(cx);
 8165            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8166                let line_mode = s.line_mode;
 8167                s.move_with(|map, selection| {
 8168                    if selection.is_empty() && !line_mode {
 8169                        let cursor = movement::previous_subword_start(map, selection.head());
 8170                        selection.set_head(cursor, SelectionGoal::None);
 8171                    }
 8172                });
 8173            });
 8174            this.insert("", cx);
 8175        });
 8176    }
 8177
 8178    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 8179        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8180            s.move_cursors_with(|map, head, _| {
 8181                (movement::next_word_end(map, head), SelectionGoal::None)
 8182            });
 8183        })
 8184    }
 8185
 8186    pub fn move_to_next_subword_end(
 8187        &mut self,
 8188        _: &MoveToNextSubwordEnd,
 8189        cx: &mut ViewContext<Self>,
 8190    ) {
 8191        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8192            s.move_cursors_with(|map, head, _| {
 8193                (movement::next_subword_end(map, head), SelectionGoal::None)
 8194            });
 8195        })
 8196    }
 8197
 8198    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 8199        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8200            s.move_heads_with(|map, head, _| {
 8201                (movement::next_word_end(map, head), SelectionGoal::None)
 8202            });
 8203        })
 8204    }
 8205
 8206    pub fn select_to_next_subword_end(
 8207        &mut self,
 8208        _: &SelectToNextSubwordEnd,
 8209        cx: &mut ViewContext<Self>,
 8210    ) {
 8211        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8212            s.move_heads_with(|map, head, _| {
 8213                (movement::next_subword_end(map, head), SelectionGoal::None)
 8214            });
 8215        })
 8216    }
 8217
 8218    pub fn delete_to_next_word_end(
 8219        &mut self,
 8220        action: &DeleteToNextWordEnd,
 8221        cx: &mut ViewContext<Self>,
 8222    ) {
 8223        self.transact(cx, |this, cx| {
 8224            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8225                let line_mode = s.line_mode;
 8226                s.move_with(|map, selection| {
 8227                    if selection.is_empty() && !line_mode {
 8228                        let cursor = if action.ignore_newlines {
 8229                            movement::next_word_end(map, selection.head())
 8230                        } else {
 8231                            movement::next_word_end_or_newline(map, selection.head())
 8232                        };
 8233                        selection.set_head(cursor, SelectionGoal::None);
 8234                    }
 8235                });
 8236            });
 8237            this.insert("", cx);
 8238        });
 8239    }
 8240
 8241    pub fn delete_to_next_subword_end(
 8242        &mut self,
 8243        _: &DeleteToNextSubwordEnd,
 8244        cx: &mut ViewContext<Self>,
 8245    ) {
 8246        self.transact(cx, |this, cx| {
 8247            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8248                s.move_with(|map, selection| {
 8249                    if selection.is_empty() {
 8250                        let cursor = movement::next_subword_end(map, selection.head());
 8251                        selection.set_head(cursor, SelectionGoal::None);
 8252                    }
 8253                });
 8254            });
 8255            this.insert("", cx);
 8256        });
 8257    }
 8258
 8259    pub fn move_to_beginning_of_line(
 8260        &mut self,
 8261        action: &MoveToBeginningOfLine,
 8262        cx: &mut ViewContext<Self>,
 8263    ) {
 8264        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8265            s.move_cursors_with(|map, head, _| {
 8266                (
 8267                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8268                    SelectionGoal::None,
 8269                )
 8270            });
 8271        })
 8272    }
 8273
 8274    pub fn select_to_beginning_of_line(
 8275        &mut self,
 8276        action: &SelectToBeginningOfLine,
 8277        cx: &mut ViewContext<Self>,
 8278    ) {
 8279        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8280            s.move_heads_with(|map, head, _| {
 8281                (
 8282                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8283                    SelectionGoal::None,
 8284                )
 8285            });
 8286        });
 8287    }
 8288
 8289    pub fn delete_to_beginning_of_line(
 8290        &mut self,
 8291        _: &DeleteToBeginningOfLine,
 8292        cx: &mut ViewContext<Self>,
 8293    ) {
 8294        self.transact(cx, |this, cx| {
 8295            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8296                s.move_with(|_, selection| {
 8297                    selection.reversed = true;
 8298                });
 8299            });
 8300
 8301            this.select_to_beginning_of_line(
 8302                &SelectToBeginningOfLine {
 8303                    stop_at_soft_wraps: false,
 8304                },
 8305                cx,
 8306            );
 8307            this.backspace(&Backspace, cx);
 8308        });
 8309    }
 8310
 8311    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 8312        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8313            s.move_cursors_with(|map, head, _| {
 8314                (
 8315                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8316                    SelectionGoal::None,
 8317                )
 8318            });
 8319        })
 8320    }
 8321
 8322    pub fn select_to_end_of_line(
 8323        &mut self,
 8324        action: &SelectToEndOfLine,
 8325        cx: &mut ViewContext<Self>,
 8326    ) {
 8327        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8328            s.move_heads_with(|map, head, _| {
 8329                (
 8330                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8331                    SelectionGoal::None,
 8332                )
 8333            });
 8334        })
 8335    }
 8336
 8337    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 8338        self.transact(cx, |this, cx| {
 8339            this.select_to_end_of_line(
 8340                &SelectToEndOfLine {
 8341                    stop_at_soft_wraps: false,
 8342                },
 8343                cx,
 8344            );
 8345            this.delete(&Delete, cx);
 8346        });
 8347    }
 8348
 8349    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 8350        self.transact(cx, |this, cx| {
 8351            this.select_to_end_of_line(
 8352                &SelectToEndOfLine {
 8353                    stop_at_soft_wraps: false,
 8354                },
 8355                cx,
 8356            );
 8357            this.cut(&Cut, cx);
 8358        });
 8359    }
 8360
 8361    pub fn move_to_start_of_paragraph(
 8362        &mut self,
 8363        _: &MoveToStartOfParagraph,
 8364        cx: &mut ViewContext<Self>,
 8365    ) {
 8366        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8367            cx.propagate();
 8368            return;
 8369        }
 8370
 8371        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8372            s.move_with(|map, selection| {
 8373                selection.collapse_to(
 8374                    movement::start_of_paragraph(map, selection.head(), 1),
 8375                    SelectionGoal::None,
 8376                )
 8377            });
 8378        })
 8379    }
 8380
 8381    pub fn move_to_end_of_paragraph(
 8382        &mut self,
 8383        _: &MoveToEndOfParagraph,
 8384        cx: &mut ViewContext<Self>,
 8385    ) {
 8386        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8387            cx.propagate();
 8388            return;
 8389        }
 8390
 8391        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8392            s.move_with(|map, selection| {
 8393                selection.collapse_to(
 8394                    movement::end_of_paragraph(map, selection.head(), 1),
 8395                    SelectionGoal::None,
 8396                )
 8397            });
 8398        })
 8399    }
 8400
 8401    pub fn select_to_start_of_paragraph(
 8402        &mut self,
 8403        _: &SelectToStartOfParagraph,
 8404        cx: &mut ViewContext<Self>,
 8405    ) {
 8406        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8407            cx.propagate();
 8408            return;
 8409        }
 8410
 8411        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8412            s.move_heads_with(|map, head, _| {
 8413                (
 8414                    movement::start_of_paragraph(map, head, 1),
 8415                    SelectionGoal::None,
 8416                )
 8417            });
 8418        })
 8419    }
 8420
 8421    pub fn select_to_end_of_paragraph(
 8422        &mut self,
 8423        _: &SelectToEndOfParagraph,
 8424        cx: &mut ViewContext<Self>,
 8425    ) {
 8426        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8427            cx.propagate();
 8428            return;
 8429        }
 8430
 8431        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8432            s.move_heads_with(|map, head, _| {
 8433                (
 8434                    movement::end_of_paragraph(map, head, 1),
 8435                    SelectionGoal::None,
 8436                )
 8437            });
 8438        })
 8439    }
 8440
 8441    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 8442        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8443            cx.propagate();
 8444            return;
 8445        }
 8446
 8447        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8448            s.select_ranges(vec![0..0]);
 8449        });
 8450    }
 8451
 8452    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 8453        let mut selection = self.selections.last::<Point>(cx);
 8454        selection.set_head(Point::zero(), SelectionGoal::None);
 8455
 8456        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8457            s.select(vec![selection]);
 8458        });
 8459    }
 8460
 8461    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 8462        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8463            cx.propagate();
 8464            return;
 8465        }
 8466
 8467        let cursor = self.buffer.read(cx).read(cx).len();
 8468        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8469            s.select_ranges(vec![cursor..cursor])
 8470        });
 8471    }
 8472
 8473    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8474        self.nav_history = nav_history;
 8475    }
 8476
 8477    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8478        self.nav_history.as_ref()
 8479    }
 8480
 8481    fn push_to_nav_history(
 8482        &mut self,
 8483        cursor_anchor: Anchor,
 8484        new_position: Option<Point>,
 8485        cx: &mut ViewContext<Self>,
 8486    ) {
 8487        if let Some(nav_history) = self.nav_history.as_mut() {
 8488            let buffer = self.buffer.read(cx).read(cx);
 8489            let cursor_position = cursor_anchor.to_point(&buffer);
 8490            let scroll_state = self.scroll_manager.anchor();
 8491            let scroll_top_row = scroll_state.top_row(&buffer);
 8492            drop(buffer);
 8493
 8494            if let Some(new_position) = new_position {
 8495                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8496                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8497                    return;
 8498                }
 8499            }
 8500
 8501            nav_history.push(
 8502                Some(NavigationData {
 8503                    cursor_anchor,
 8504                    cursor_position,
 8505                    scroll_anchor: scroll_state,
 8506                    scroll_top_row,
 8507                }),
 8508                cx,
 8509            );
 8510        }
 8511    }
 8512
 8513    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 8514        let buffer = self.buffer.read(cx).snapshot(cx);
 8515        let mut selection = self.selections.first::<usize>(cx);
 8516        selection.set_head(buffer.len(), SelectionGoal::None);
 8517        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8518            s.select(vec![selection]);
 8519        });
 8520    }
 8521
 8522    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 8523        let end = self.buffer.read(cx).read(cx).len();
 8524        self.change_selections(None, cx, |s| {
 8525            s.select_ranges(vec![0..end]);
 8526        });
 8527    }
 8528
 8529    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 8530        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8531        let mut selections = self.selections.all::<Point>(cx);
 8532        let max_point = display_map.buffer_snapshot.max_point();
 8533        for selection in &mut selections {
 8534            let rows = selection.spanned_rows(true, &display_map);
 8535            selection.start = Point::new(rows.start.0, 0);
 8536            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8537            selection.reversed = false;
 8538        }
 8539        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8540            s.select(selections);
 8541        });
 8542    }
 8543
 8544    pub fn split_selection_into_lines(
 8545        &mut self,
 8546        _: &SplitSelectionIntoLines,
 8547        cx: &mut ViewContext<Self>,
 8548    ) {
 8549        let mut to_unfold = Vec::new();
 8550        let mut new_selection_ranges = Vec::new();
 8551        {
 8552            let selections = self.selections.all::<Point>(cx);
 8553            let buffer = self.buffer.read(cx).read(cx);
 8554            for selection in selections {
 8555                for row in selection.start.row..selection.end.row {
 8556                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8557                    new_selection_ranges.push(cursor..cursor);
 8558                }
 8559                new_selection_ranges.push(selection.end..selection.end);
 8560                to_unfold.push(selection.start..selection.end);
 8561            }
 8562        }
 8563        self.unfold_ranges(&to_unfold, true, true, cx);
 8564        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8565            s.select_ranges(new_selection_ranges);
 8566        });
 8567    }
 8568
 8569    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8570        self.add_selection(true, cx);
 8571    }
 8572
 8573    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8574        self.add_selection(false, cx);
 8575    }
 8576
 8577    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8578        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8579        let mut selections = self.selections.all::<Point>(cx);
 8580        let text_layout_details = self.text_layout_details(cx);
 8581        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8582            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8583            let range = oldest_selection.display_range(&display_map).sorted();
 8584
 8585            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8586            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8587            let positions = start_x.min(end_x)..start_x.max(end_x);
 8588
 8589            selections.clear();
 8590            let mut stack = Vec::new();
 8591            for row in range.start.row().0..=range.end.row().0 {
 8592                if let Some(selection) = self.selections.build_columnar_selection(
 8593                    &display_map,
 8594                    DisplayRow(row),
 8595                    &positions,
 8596                    oldest_selection.reversed,
 8597                    &text_layout_details,
 8598                ) {
 8599                    stack.push(selection.id);
 8600                    selections.push(selection);
 8601                }
 8602            }
 8603
 8604            if above {
 8605                stack.reverse();
 8606            }
 8607
 8608            AddSelectionsState { above, stack }
 8609        });
 8610
 8611        let last_added_selection = *state.stack.last().unwrap();
 8612        let mut new_selections = Vec::new();
 8613        if above == state.above {
 8614            let end_row = if above {
 8615                DisplayRow(0)
 8616            } else {
 8617                display_map.max_point().row()
 8618            };
 8619
 8620            'outer: for selection in selections {
 8621                if selection.id == last_added_selection {
 8622                    let range = selection.display_range(&display_map).sorted();
 8623                    debug_assert_eq!(range.start.row(), range.end.row());
 8624                    let mut row = range.start.row();
 8625                    let positions =
 8626                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8627                            px(start)..px(end)
 8628                        } else {
 8629                            let start_x =
 8630                                display_map.x_for_display_point(range.start, &text_layout_details);
 8631                            let end_x =
 8632                                display_map.x_for_display_point(range.end, &text_layout_details);
 8633                            start_x.min(end_x)..start_x.max(end_x)
 8634                        };
 8635
 8636                    while row != end_row {
 8637                        if above {
 8638                            row.0 -= 1;
 8639                        } else {
 8640                            row.0 += 1;
 8641                        }
 8642
 8643                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8644                            &display_map,
 8645                            row,
 8646                            &positions,
 8647                            selection.reversed,
 8648                            &text_layout_details,
 8649                        ) {
 8650                            state.stack.push(new_selection.id);
 8651                            if above {
 8652                                new_selections.push(new_selection);
 8653                                new_selections.push(selection);
 8654                            } else {
 8655                                new_selections.push(selection);
 8656                                new_selections.push(new_selection);
 8657                            }
 8658
 8659                            continue 'outer;
 8660                        }
 8661                    }
 8662                }
 8663
 8664                new_selections.push(selection);
 8665            }
 8666        } else {
 8667            new_selections = selections;
 8668            new_selections.retain(|s| s.id != last_added_selection);
 8669            state.stack.pop();
 8670        }
 8671
 8672        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8673            s.select(new_selections);
 8674        });
 8675        if state.stack.len() > 1 {
 8676            self.add_selections_state = Some(state);
 8677        }
 8678    }
 8679
 8680    pub fn select_next_match_internal(
 8681        &mut self,
 8682        display_map: &DisplaySnapshot,
 8683        replace_newest: bool,
 8684        autoscroll: Option<Autoscroll>,
 8685        cx: &mut ViewContext<Self>,
 8686    ) -> Result<()> {
 8687        fn select_next_match_ranges(
 8688            this: &mut Editor,
 8689            range: Range<usize>,
 8690            replace_newest: bool,
 8691            auto_scroll: Option<Autoscroll>,
 8692            cx: &mut ViewContext<Editor>,
 8693        ) {
 8694            this.unfold_ranges(&[range.clone()], false, true, cx);
 8695            this.change_selections(auto_scroll, cx, |s| {
 8696                if replace_newest {
 8697                    s.delete(s.newest_anchor().id);
 8698                }
 8699                s.insert_range(range.clone());
 8700            });
 8701        }
 8702
 8703        let buffer = &display_map.buffer_snapshot;
 8704        let mut selections = self.selections.all::<usize>(cx);
 8705        if let Some(mut select_next_state) = self.select_next_state.take() {
 8706            let query = &select_next_state.query;
 8707            if !select_next_state.done {
 8708                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8709                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8710                let mut next_selected_range = None;
 8711
 8712                let bytes_after_last_selection =
 8713                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8714                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8715                let query_matches = query
 8716                    .stream_find_iter(bytes_after_last_selection)
 8717                    .map(|result| (last_selection.end, result))
 8718                    .chain(
 8719                        query
 8720                            .stream_find_iter(bytes_before_first_selection)
 8721                            .map(|result| (0, result)),
 8722                    );
 8723
 8724                for (start_offset, query_match) in query_matches {
 8725                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8726                    let offset_range =
 8727                        start_offset + query_match.start()..start_offset + query_match.end();
 8728                    let display_range = offset_range.start.to_display_point(display_map)
 8729                        ..offset_range.end.to_display_point(display_map);
 8730
 8731                    if !select_next_state.wordwise
 8732                        || (!movement::is_inside_word(display_map, display_range.start)
 8733                            && !movement::is_inside_word(display_map, display_range.end))
 8734                    {
 8735                        // TODO: This is n^2, because we might check all the selections
 8736                        if !selections
 8737                            .iter()
 8738                            .any(|selection| selection.range().overlaps(&offset_range))
 8739                        {
 8740                            next_selected_range = Some(offset_range);
 8741                            break;
 8742                        }
 8743                    }
 8744                }
 8745
 8746                if let Some(next_selected_range) = next_selected_range {
 8747                    select_next_match_ranges(
 8748                        self,
 8749                        next_selected_range,
 8750                        replace_newest,
 8751                        autoscroll,
 8752                        cx,
 8753                    );
 8754                } else {
 8755                    select_next_state.done = true;
 8756                }
 8757            }
 8758
 8759            self.select_next_state = Some(select_next_state);
 8760        } else {
 8761            let mut only_carets = true;
 8762            let mut same_text_selected = true;
 8763            let mut selected_text = None;
 8764
 8765            let mut selections_iter = selections.iter().peekable();
 8766            while let Some(selection) = selections_iter.next() {
 8767                if selection.start != selection.end {
 8768                    only_carets = false;
 8769                }
 8770
 8771                if same_text_selected {
 8772                    if selected_text.is_none() {
 8773                        selected_text =
 8774                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8775                    }
 8776
 8777                    if let Some(next_selection) = selections_iter.peek() {
 8778                        if next_selection.range().len() == selection.range().len() {
 8779                            let next_selected_text = buffer
 8780                                .text_for_range(next_selection.range())
 8781                                .collect::<String>();
 8782                            if Some(next_selected_text) != selected_text {
 8783                                same_text_selected = false;
 8784                                selected_text = None;
 8785                            }
 8786                        } else {
 8787                            same_text_selected = false;
 8788                            selected_text = None;
 8789                        }
 8790                    }
 8791                }
 8792            }
 8793
 8794            if only_carets {
 8795                for selection in &mut selections {
 8796                    let word_range = movement::surrounding_word(
 8797                        display_map,
 8798                        selection.start.to_display_point(display_map),
 8799                    );
 8800                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8801                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8802                    selection.goal = SelectionGoal::None;
 8803                    selection.reversed = false;
 8804                    select_next_match_ranges(
 8805                        self,
 8806                        selection.start..selection.end,
 8807                        replace_newest,
 8808                        autoscroll,
 8809                        cx,
 8810                    );
 8811                }
 8812
 8813                if selections.len() == 1 {
 8814                    let selection = selections
 8815                        .last()
 8816                        .expect("ensured that there's only one selection");
 8817                    let query = buffer
 8818                        .text_for_range(selection.start..selection.end)
 8819                        .collect::<String>();
 8820                    let is_empty = query.is_empty();
 8821                    let select_state = SelectNextState {
 8822                        query: AhoCorasick::new(&[query])?,
 8823                        wordwise: true,
 8824                        done: is_empty,
 8825                    };
 8826                    self.select_next_state = Some(select_state);
 8827                } else {
 8828                    self.select_next_state = None;
 8829                }
 8830            } else if let Some(selected_text) = selected_text {
 8831                self.select_next_state = Some(SelectNextState {
 8832                    query: AhoCorasick::new(&[selected_text])?,
 8833                    wordwise: false,
 8834                    done: false,
 8835                });
 8836                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8837            }
 8838        }
 8839        Ok(())
 8840    }
 8841
 8842    pub fn select_all_matches(
 8843        &mut self,
 8844        _action: &SelectAllMatches,
 8845        cx: &mut ViewContext<Self>,
 8846    ) -> Result<()> {
 8847        self.push_to_selection_history();
 8848        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8849
 8850        self.select_next_match_internal(&display_map, false, None, cx)?;
 8851        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8852            return Ok(());
 8853        };
 8854        if select_next_state.done {
 8855            return Ok(());
 8856        }
 8857
 8858        let mut new_selections = self.selections.all::<usize>(cx);
 8859
 8860        let buffer = &display_map.buffer_snapshot;
 8861        let query_matches = select_next_state
 8862            .query
 8863            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8864
 8865        for query_match in query_matches {
 8866            let query_match = query_match.unwrap(); // can only fail due to I/O
 8867            let offset_range = query_match.start()..query_match.end();
 8868            let display_range = offset_range.start.to_display_point(&display_map)
 8869                ..offset_range.end.to_display_point(&display_map);
 8870
 8871            if !select_next_state.wordwise
 8872                || (!movement::is_inside_word(&display_map, display_range.start)
 8873                    && !movement::is_inside_word(&display_map, display_range.end))
 8874            {
 8875                self.selections.change_with(cx, |selections| {
 8876                    new_selections.push(Selection {
 8877                        id: selections.new_selection_id(),
 8878                        start: offset_range.start,
 8879                        end: offset_range.end,
 8880                        reversed: false,
 8881                        goal: SelectionGoal::None,
 8882                    });
 8883                });
 8884            }
 8885        }
 8886
 8887        new_selections.sort_by_key(|selection| selection.start);
 8888        let mut ix = 0;
 8889        while ix + 1 < new_selections.len() {
 8890            let current_selection = &new_selections[ix];
 8891            let next_selection = &new_selections[ix + 1];
 8892            if current_selection.range().overlaps(&next_selection.range()) {
 8893                if current_selection.id < next_selection.id {
 8894                    new_selections.remove(ix + 1);
 8895                } else {
 8896                    new_selections.remove(ix);
 8897                }
 8898            } else {
 8899                ix += 1;
 8900            }
 8901        }
 8902
 8903        select_next_state.done = true;
 8904        self.unfold_ranges(
 8905            &new_selections
 8906                .iter()
 8907                .map(|selection| selection.range())
 8908                .collect::<Vec<_>>(),
 8909            false,
 8910            false,
 8911            cx,
 8912        );
 8913        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8914            selections.select(new_selections)
 8915        });
 8916
 8917        Ok(())
 8918    }
 8919
 8920    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8921        self.push_to_selection_history();
 8922        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8923        self.select_next_match_internal(
 8924            &display_map,
 8925            action.replace_newest,
 8926            Some(Autoscroll::newest()),
 8927            cx,
 8928        )?;
 8929        Ok(())
 8930    }
 8931
 8932    pub fn select_previous(
 8933        &mut self,
 8934        action: &SelectPrevious,
 8935        cx: &mut ViewContext<Self>,
 8936    ) -> Result<()> {
 8937        self.push_to_selection_history();
 8938        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8939        let buffer = &display_map.buffer_snapshot;
 8940        let mut selections = self.selections.all::<usize>(cx);
 8941        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8942            let query = &select_prev_state.query;
 8943            if !select_prev_state.done {
 8944                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8945                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8946                let mut next_selected_range = None;
 8947                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8948                let bytes_before_last_selection =
 8949                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8950                let bytes_after_first_selection =
 8951                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8952                let query_matches = query
 8953                    .stream_find_iter(bytes_before_last_selection)
 8954                    .map(|result| (last_selection.start, result))
 8955                    .chain(
 8956                        query
 8957                            .stream_find_iter(bytes_after_first_selection)
 8958                            .map(|result| (buffer.len(), result)),
 8959                    );
 8960                for (end_offset, query_match) in query_matches {
 8961                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8962                    let offset_range =
 8963                        end_offset - query_match.end()..end_offset - query_match.start();
 8964                    let display_range = offset_range.start.to_display_point(&display_map)
 8965                        ..offset_range.end.to_display_point(&display_map);
 8966
 8967                    if !select_prev_state.wordwise
 8968                        || (!movement::is_inside_word(&display_map, display_range.start)
 8969                            && !movement::is_inside_word(&display_map, display_range.end))
 8970                    {
 8971                        next_selected_range = Some(offset_range);
 8972                        break;
 8973                    }
 8974                }
 8975
 8976                if let Some(next_selected_range) = next_selected_range {
 8977                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8978                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8979                        if action.replace_newest {
 8980                            s.delete(s.newest_anchor().id);
 8981                        }
 8982                        s.insert_range(next_selected_range);
 8983                    });
 8984                } else {
 8985                    select_prev_state.done = true;
 8986                }
 8987            }
 8988
 8989            self.select_prev_state = Some(select_prev_state);
 8990        } else {
 8991            let mut only_carets = true;
 8992            let mut same_text_selected = true;
 8993            let mut selected_text = None;
 8994
 8995            let mut selections_iter = selections.iter().peekable();
 8996            while let Some(selection) = selections_iter.next() {
 8997                if selection.start != selection.end {
 8998                    only_carets = false;
 8999                }
 9000
 9001                if same_text_selected {
 9002                    if selected_text.is_none() {
 9003                        selected_text =
 9004                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9005                    }
 9006
 9007                    if let Some(next_selection) = selections_iter.peek() {
 9008                        if next_selection.range().len() == selection.range().len() {
 9009                            let next_selected_text = buffer
 9010                                .text_for_range(next_selection.range())
 9011                                .collect::<String>();
 9012                            if Some(next_selected_text) != selected_text {
 9013                                same_text_selected = false;
 9014                                selected_text = None;
 9015                            }
 9016                        } else {
 9017                            same_text_selected = false;
 9018                            selected_text = None;
 9019                        }
 9020                    }
 9021                }
 9022            }
 9023
 9024            if only_carets {
 9025                for selection in &mut selections {
 9026                    let word_range = movement::surrounding_word(
 9027                        &display_map,
 9028                        selection.start.to_display_point(&display_map),
 9029                    );
 9030                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9031                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9032                    selection.goal = SelectionGoal::None;
 9033                    selection.reversed = false;
 9034                }
 9035                if selections.len() == 1 {
 9036                    let selection = selections
 9037                        .last()
 9038                        .expect("ensured that there's only one selection");
 9039                    let query = buffer
 9040                        .text_for_range(selection.start..selection.end)
 9041                        .collect::<String>();
 9042                    let is_empty = query.is_empty();
 9043                    let select_state = SelectNextState {
 9044                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9045                        wordwise: true,
 9046                        done: is_empty,
 9047                    };
 9048                    self.select_prev_state = Some(select_state);
 9049                } else {
 9050                    self.select_prev_state = None;
 9051                }
 9052
 9053                self.unfold_ranges(
 9054                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9055                    false,
 9056                    true,
 9057                    cx,
 9058                );
 9059                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 9060                    s.select(selections);
 9061                });
 9062            } else if let Some(selected_text) = selected_text {
 9063                self.select_prev_state = Some(SelectNextState {
 9064                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9065                    wordwise: false,
 9066                    done: false,
 9067                });
 9068                self.select_previous(action, cx)?;
 9069            }
 9070        }
 9071        Ok(())
 9072    }
 9073
 9074    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 9075        if self.read_only(cx) {
 9076            return;
 9077        }
 9078        let text_layout_details = &self.text_layout_details(cx);
 9079        self.transact(cx, |this, cx| {
 9080            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9081            let mut edits = Vec::new();
 9082            let mut selection_edit_ranges = Vec::new();
 9083            let mut last_toggled_row = None;
 9084            let snapshot = this.buffer.read(cx).read(cx);
 9085            let empty_str: Arc<str> = Arc::default();
 9086            let mut suffixes_inserted = Vec::new();
 9087            let ignore_indent = action.ignore_indent;
 9088
 9089            fn comment_prefix_range(
 9090                snapshot: &MultiBufferSnapshot,
 9091                row: MultiBufferRow,
 9092                comment_prefix: &str,
 9093                comment_prefix_whitespace: &str,
 9094                ignore_indent: bool,
 9095            ) -> Range<Point> {
 9096                let indent_size = if ignore_indent {
 9097                    0
 9098                } else {
 9099                    snapshot.indent_size_for_line(row).len
 9100                };
 9101
 9102                let start = Point::new(row.0, indent_size);
 9103
 9104                let mut line_bytes = snapshot
 9105                    .bytes_in_range(start..snapshot.max_point())
 9106                    .flatten()
 9107                    .copied();
 9108
 9109                // If this line currently begins with the line comment prefix, then record
 9110                // the range containing the prefix.
 9111                if line_bytes
 9112                    .by_ref()
 9113                    .take(comment_prefix.len())
 9114                    .eq(comment_prefix.bytes())
 9115                {
 9116                    // Include any whitespace that matches the comment prefix.
 9117                    let matching_whitespace_len = line_bytes
 9118                        .zip(comment_prefix_whitespace.bytes())
 9119                        .take_while(|(a, b)| a == b)
 9120                        .count() as u32;
 9121                    let end = Point::new(
 9122                        start.row,
 9123                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9124                    );
 9125                    start..end
 9126                } else {
 9127                    start..start
 9128                }
 9129            }
 9130
 9131            fn comment_suffix_range(
 9132                snapshot: &MultiBufferSnapshot,
 9133                row: MultiBufferRow,
 9134                comment_suffix: &str,
 9135                comment_suffix_has_leading_space: bool,
 9136            ) -> Range<Point> {
 9137                let end = Point::new(row.0, snapshot.line_len(row));
 9138                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9139
 9140                let mut line_end_bytes = snapshot
 9141                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9142                    .flatten()
 9143                    .copied();
 9144
 9145                let leading_space_len = if suffix_start_column > 0
 9146                    && line_end_bytes.next() == Some(b' ')
 9147                    && comment_suffix_has_leading_space
 9148                {
 9149                    1
 9150                } else {
 9151                    0
 9152                };
 9153
 9154                // If this line currently begins with the line comment prefix, then record
 9155                // the range containing the prefix.
 9156                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9157                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9158                    start..end
 9159                } else {
 9160                    end..end
 9161                }
 9162            }
 9163
 9164            // TODO: Handle selections that cross excerpts
 9165            for selection in &mut selections {
 9166                let start_column = snapshot
 9167                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9168                    .len;
 9169                let language = if let Some(language) =
 9170                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9171                {
 9172                    language
 9173                } else {
 9174                    continue;
 9175                };
 9176
 9177                selection_edit_ranges.clear();
 9178
 9179                // If multiple selections contain a given row, avoid processing that
 9180                // row more than once.
 9181                let mut start_row = MultiBufferRow(selection.start.row);
 9182                if last_toggled_row == Some(start_row) {
 9183                    start_row = start_row.next_row();
 9184                }
 9185                let end_row =
 9186                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9187                        MultiBufferRow(selection.end.row - 1)
 9188                    } else {
 9189                        MultiBufferRow(selection.end.row)
 9190                    };
 9191                last_toggled_row = Some(end_row);
 9192
 9193                if start_row > end_row {
 9194                    continue;
 9195                }
 9196
 9197                // If the language has line comments, toggle those.
 9198                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9199
 9200                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9201                if ignore_indent {
 9202                    full_comment_prefixes = full_comment_prefixes
 9203                        .into_iter()
 9204                        .map(|s| Arc::from(s.trim_end()))
 9205                        .collect();
 9206                }
 9207
 9208                if !full_comment_prefixes.is_empty() {
 9209                    let first_prefix = full_comment_prefixes
 9210                        .first()
 9211                        .expect("prefixes is non-empty");
 9212                    let prefix_trimmed_lengths = full_comment_prefixes
 9213                        .iter()
 9214                        .map(|p| p.trim_end_matches(' ').len())
 9215                        .collect::<SmallVec<[usize; 4]>>();
 9216
 9217                    let mut all_selection_lines_are_comments = true;
 9218
 9219                    for row in start_row.0..=end_row.0 {
 9220                        let row = MultiBufferRow(row);
 9221                        if start_row < end_row && snapshot.is_line_blank(row) {
 9222                            continue;
 9223                        }
 9224
 9225                        let prefix_range = full_comment_prefixes
 9226                            .iter()
 9227                            .zip(prefix_trimmed_lengths.iter().copied())
 9228                            .map(|(prefix, trimmed_prefix_len)| {
 9229                                comment_prefix_range(
 9230                                    snapshot.deref(),
 9231                                    row,
 9232                                    &prefix[..trimmed_prefix_len],
 9233                                    &prefix[trimmed_prefix_len..],
 9234                                    ignore_indent,
 9235                                )
 9236                            })
 9237                            .max_by_key(|range| range.end.column - range.start.column)
 9238                            .expect("prefixes is non-empty");
 9239
 9240                        if prefix_range.is_empty() {
 9241                            all_selection_lines_are_comments = false;
 9242                        }
 9243
 9244                        selection_edit_ranges.push(prefix_range);
 9245                    }
 9246
 9247                    if all_selection_lines_are_comments {
 9248                        edits.extend(
 9249                            selection_edit_ranges
 9250                                .iter()
 9251                                .cloned()
 9252                                .map(|range| (range, empty_str.clone())),
 9253                        );
 9254                    } else {
 9255                        let min_column = selection_edit_ranges
 9256                            .iter()
 9257                            .map(|range| range.start.column)
 9258                            .min()
 9259                            .unwrap_or(0);
 9260                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9261                            let position = Point::new(range.start.row, min_column);
 9262                            (position..position, first_prefix.clone())
 9263                        }));
 9264                    }
 9265                } else if let Some((full_comment_prefix, comment_suffix)) =
 9266                    language.block_comment_delimiters()
 9267                {
 9268                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9269                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9270                    let prefix_range = comment_prefix_range(
 9271                        snapshot.deref(),
 9272                        start_row,
 9273                        comment_prefix,
 9274                        comment_prefix_whitespace,
 9275                        ignore_indent,
 9276                    );
 9277                    let suffix_range = comment_suffix_range(
 9278                        snapshot.deref(),
 9279                        end_row,
 9280                        comment_suffix.trim_start_matches(' '),
 9281                        comment_suffix.starts_with(' '),
 9282                    );
 9283
 9284                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9285                        edits.push((
 9286                            prefix_range.start..prefix_range.start,
 9287                            full_comment_prefix.clone(),
 9288                        ));
 9289                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9290                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9291                    } else {
 9292                        edits.push((prefix_range, empty_str.clone()));
 9293                        edits.push((suffix_range, empty_str.clone()));
 9294                    }
 9295                } else {
 9296                    continue;
 9297                }
 9298            }
 9299
 9300            drop(snapshot);
 9301            this.buffer.update(cx, |buffer, cx| {
 9302                buffer.edit(edits, None, cx);
 9303            });
 9304
 9305            // Adjust selections so that they end before any comment suffixes that
 9306            // were inserted.
 9307            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9308            let mut selections = this.selections.all::<Point>(cx);
 9309            let snapshot = this.buffer.read(cx).read(cx);
 9310            for selection in &mut selections {
 9311                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9312                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9313                        Ordering::Less => {
 9314                            suffixes_inserted.next();
 9315                            continue;
 9316                        }
 9317                        Ordering::Greater => break,
 9318                        Ordering::Equal => {
 9319                            if selection.end.column == snapshot.line_len(row) {
 9320                                if selection.is_empty() {
 9321                                    selection.start.column -= suffix_len as u32;
 9322                                }
 9323                                selection.end.column -= suffix_len as u32;
 9324                            }
 9325                            break;
 9326                        }
 9327                    }
 9328                }
 9329            }
 9330
 9331            drop(snapshot);
 9332            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 9333
 9334            let selections = this.selections.all::<Point>(cx);
 9335            let selections_on_single_row = selections.windows(2).all(|selections| {
 9336                selections[0].start.row == selections[1].start.row
 9337                    && selections[0].end.row == selections[1].end.row
 9338                    && selections[0].start.row == selections[0].end.row
 9339            });
 9340            let selections_selecting = selections
 9341                .iter()
 9342                .any(|selection| selection.start != selection.end);
 9343            let advance_downwards = action.advance_downwards
 9344                && selections_on_single_row
 9345                && !selections_selecting
 9346                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9347
 9348            if advance_downwards {
 9349                let snapshot = this.buffer.read(cx).snapshot(cx);
 9350
 9351                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9352                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9353                        let mut point = display_point.to_point(display_snapshot);
 9354                        point.row += 1;
 9355                        point = snapshot.clip_point(point, Bias::Left);
 9356                        let display_point = point.to_display_point(display_snapshot);
 9357                        let goal = SelectionGoal::HorizontalPosition(
 9358                            display_snapshot
 9359                                .x_for_display_point(display_point, text_layout_details)
 9360                                .into(),
 9361                        );
 9362                        (display_point, goal)
 9363                    })
 9364                });
 9365            }
 9366        });
 9367    }
 9368
 9369    pub fn select_enclosing_symbol(
 9370        &mut self,
 9371        _: &SelectEnclosingSymbol,
 9372        cx: &mut ViewContext<Self>,
 9373    ) {
 9374        let buffer = self.buffer.read(cx).snapshot(cx);
 9375        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9376
 9377        fn update_selection(
 9378            selection: &Selection<usize>,
 9379            buffer_snap: &MultiBufferSnapshot,
 9380        ) -> Option<Selection<usize>> {
 9381            let cursor = selection.head();
 9382            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9383            for symbol in symbols.iter().rev() {
 9384                let start = symbol.range.start.to_offset(buffer_snap);
 9385                let end = symbol.range.end.to_offset(buffer_snap);
 9386                let new_range = start..end;
 9387                if start < selection.start || end > selection.end {
 9388                    return Some(Selection {
 9389                        id: selection.id,
 9390                        start: new_range.start,
 9391                        end: new_range.end,
 9392                        goal: SelectionGoal::None,
 9393                        reversed: selection.reversed,
 9394                    });
 9395                }
 9396            }
 9397            None
 9398        }
 9399
 9400        let mut selected_larger_symbol = false;
 9401        let new_selections = old_selections
 9402            .iter()
 9403            .map(|selection| match update_selection(selection, &buffer) {
 9404                Some(new_selection) => {
 9405                    if new_selection.range() != selection.range() {
 9406                        selected_larger_symbol = true;
 9407                    }
 9408                    new_selection
 9409                }
 9410                None => selection.clone(),
 9411            })
 9412            .collect::<Vec<_>>();
 9413
 9414        if selected_larger_symbol {
 9415            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9416                s.select(new_selections);
 9417            });
 9418        }
 9419    }
 9420
 9421    pub fn select_larger_syntax_node(
 9422        &mut self,
 9423        _: &SelectLargerSyntaxNode,
 9424        cx: &mut ViewContext<Self>,
 9425    ) {
 9426        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9427        let buffer = self.buffer.read(cx).snapshot(cx);
 9428        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9429
 9430        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9431        let mut selected_larger_node = false;
 9432        let new_selections = old_selections
 9433            .iter()
 9434            .map(|selection| {
 9435                let old_range = selection.start..selection.end;
 9436                let mut new_range = old_range.clone();
 9437                while let Some(containing_range) =
 9438                    buffer.range_for_syntax_ancestor(new_range.clone())
 9439                {
 9440                    new_range = containing_range;
 9441                    if !display_map.intersects_fold(new_range.start)
 9442                        && !display_map.intersects_fold(new_range.end)
 9443                    {
 9444                        break;
 9445                    }
 9446                }
 9447
 9448                selected_larger_node |= new_range != old_range;
 9449                Selection {
 9450                    id: selection.id,
 9451                    start: new_range.start,
 9452                    end: new_range.end,
 9453                    goal: SelectionGoal::None,
 9454                    reversed: selection.reversed,
 9455                }
 9456            })
 9457            .collect::<Vec<_>>();
 9458
 9459        if selected_larger_node {
 9460            stack.push(old_selections);
 9461            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9462                s.select(new_selections);
 9463            });
 9464        }
 9465        self.select_larger_syntax_node_stack = stack;
 9466    }
 9467
 9468    pub fn select_smaller_syntax_node(
 9469        &mut self,
 9470        _: &SelectSmallerSyntaxNode,
 9471        cx: &mut ViewContext<Self>,
 9472    ) {
 9473        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9474        if let Some(selections) = stack.pop() {
 9475            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9476                s.select(selections.to_vec());
 9477            });
 9478        }
 9479        self.select_larger_syntax_node_stack = stack;
 9480    }
 9481
 9482    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 9483        if !EditorSettings::get_global(cx).gutter.runnables {
 9484            self.clear_tasks();
 9485            return Task::ready(());
 9486        }
 9487        let project = self.project.as_ref().map(Model::downgrade);
 9488        cx.spawn(|this, mut cx| async move {
 9489            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9490            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9491                return;
 9492            };
 9493            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9494                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9495            }) else {
 9496                return;
 9497            };
 9498
 9499            let hide_runnables = project
 9500                .update(&mut cx, |project, cx| {
 9501                    // Do not display any test indicators in non-dev server remote projects.
 9502                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9503                })
 9504                .unwrap_or(true);
 9505            if hide_runnables {
 9506                return;
 9507            }
 9508            let new_rows =
 9509                cx.background_executor()
 9510                    .spawn({
 9511                        let snapshot = display_snapshot.clone();
 9512                        async move {
 9513                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9514                        }
 9515                    })
 9516                    .await;
 9517            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9518
 9519            this.update(&mut cx, |this, _| {
 9520                this.clear_tasks();
 9521                for (key, value) in rows {
 9522                    this.insert_tasks(key, value);
 9523                }
 9524            })
 9525            .ok();
 9526        })
 9527    }
 9528    fn fetch_runnable_ranges(
 9529        snapshot: &DisplaySnapshot,
 9530        range: Range<Anchor>,
 9531    ) -> Vec<language::RunnableRange> {
 9532        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9533    }
 9534
 9535    fn runnable_rows(
 9536        project: Model<Project>,
 9537        snapshot: DisplaySnapshot,
 9538        runnable_ranges: Vec<RunnableRange>,
 9539        mut cx: AsyncWindowContext,
 9540    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9541        runnable_ranges
 9542            .into_iter()
 9543            .filter_map(|mut runnable| {
 9544                let tasks = cx
 9545                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9546                    .ok()?;
 9547                if tasks.is_empty() {
 9548                    return None;
 9549                }
 9550
 9551                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9552
 9553                let row = snapshot
 9554                    .buffer_snapshot
 9555                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9556                    .1
 9557                    .start
 9558                    .row;
 9559
 9560                let context_range =
 9561                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9562                Some((
 9563                    (runnable.buffer_id, row),
 9564                    RunnableTasks {
 9565                        templates: tasks,
 9566                        offset: MultiBufferOffset(runnable.run_range.start),
 9567                        context_range,
 9568                        column: point.column,
 9569                        extra_variables: runnable.extra_captures,
 9570                    },
 9571                ))
 9572            })
 9573            .collect()
 9574    }
 9575
 9576    fn templates_with_tags(
 9577        project: &Model<Project>,
 9578        runnable: &mut Runnable,
 9579        cx: &WindowContext<'_>,
 9580    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9581        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9582            let (worktree_id, file) = project
 9583                .buffer_for_id(runnable.buffer, cx)
 9584                .and_then(|buffer| buffer.read(cx).file())
 9585                .map(|file| (file.worktree_id(cx), file.clone()))
 9586                .unzip();
 9587
 9588            (
 9589                project.task_store().read(cx).task_inventory().cloned(),
 9590                worktree_id,
 9591                file,
 9592            )
 9593        });
 9594
 9595        let tags = mem::take(&mut runnable.tags);
 9596        let mut tags: Vec<_> = tags
 9597            .into_iter()
 9598            .flat_map(|tag| {
 9599                let tag = tag.0.clone();
 9600                inventory
 9601                    .as_ref()
 9602                    .into_iter()
 9603                    .flat_map(|inventory| {
 9604                        inventory.read(cx).list_tasks(
 9605                            file.clone(),
 9606                            Some(runnable.language.clone()),
 9607                            worktree_id,
 9608                            cx,
 9609                        )
 9610                    })
 9611                    .filter(move |(_, template)| {
 9612                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9613                    })
 9614            })
 9615            .sorted_by_key(|(kind, _)| kind.to_owned())
 9616            .collect();
 9617        if let Some((leading_tag_source, _)) = tags.first() {
 9618            // Strongest source wins; if we have worktree tag binding, prefer that to
 9619            // global and language bindings;
 9620            // if we have a global binding, prefer that to language binding.
 9621            let first_mismatch = tags
 9622                .iter()
 9623                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9624            if let Some(index) = first_mismatch {
 9625                tags.truncate(index);
 9626            }
 9627        }
 9628
 9629        tags
 9630    }
 9631
 9632    pub fn move_to_enclosing_bracket(
 9633        &mut self,
 9634        _: &MoveToEnclosingBracket,
 9635        cx: &mut ViewContext<Self>,
 9636    ) {
 9637        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9638            s.move_offsets_with(|snapshot, selection| {
 9639                let Some(enclosing_bracket_ranges) =
 9640                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9641                else {
 9642                    return;
 9643                };
 9644
 9645                let mut best_length = usize::MAX;
 9646                let mut best_inside = false;
 9647                let mut best_in_bracket_range = false;
 9648                let mut best_destination = None;
 9649                for (open, close) in enclosing_bracket_ranges {
 9650                    let close = close.to_inclusive();
 9651                    let length = close.end() - open.start;
 9652                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9653                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9654                        || close.contains(&selection.head());
 9655
 9656                    // If best is next to a bracket and current isn't, skip
 9657                    if !in_bracket_range && best_in_bracket_range {
 9658                        continue;
 9659                    }
 9660
 9661                    // Prefer smaller lengths unless best is inside and current isn't
 9662                    if length > best_length && (best_inside || !inside) {
 9663                        continue;
 9664                    }
 9665
 9666                    best_length = length;
 9667                    best_inside = inside;
 9668                    best_in_bracket_range = in_bracket_range;
 9669                    best_destination = Some(
 9670                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9671                            if inside {
 9672                                open.end
 9673                            } else {
 9674                                open.start
 9675                            }
 9676                        } else if inside {
 9677                            *close.start()
 9678                        } else {
 9679                            *close.end()
 9680                        },
 9681                    );
 9682                }
 9683
 9684                if let Some(destination) = best_destination {
 9685                    selection.collapse_to(destination, SelectionGoal::None);
 9686                }
 9687            })
 9688        });
 9689    }
 9690
 9691    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9692        self.end_selection(cx);
 9693        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9694        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9695            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9696            self.select_next_state = entry.select_next_state;
 9697            self.select_prev_state = entry.select_prev_state;
 9698            self.add_selections_state = entry.add_selections_state;
 9699            self.request_autoscroll(Autoscroll::newest(), cx);
 9700        }
 9701        self.selection_history.mode = SelectionHistoryMode::Normal;
 9702    }
 9703
 9704    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9705        self.end_selection(cx);
 9706        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9707        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9708            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9709            self.select_next_state = entry.select_next_state;
 9710            self.select_prev_state = entry.select_prev_state;
 9711            self.add_selections_state = entry.add_selections_state;
 9712            self.request_autoscroll(Autoscroll::newest(), cx);
 9713        }
 9714        self.selection_history.mode = SelectionHistoryMode::Normal;
 9715    }
 9716
 9717    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9718        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9719    }
 9720
 9721    pub fn expand_excerpts_down(
 9722        &mut self,
 9723        action: &ExpandExcerptsDown,
 9724        cx: &mut ViewContext<Self>,
 9725    ) {
 9726        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9727    }
 9728
 9729    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9730        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9731    }
 9732
 9733    pub fn expand_excerpts_for_direction(
 9734        &mut self,
 9735        lines: u32,
 9736        direction: ExpandExcerptDirection,
 9737        cx: &mut ViewContext<Self>,
 9738    ) {
 9739        let selections = self.selections.disjoint_anchors();
 9740
 9741        let lines = if lines == 0 {
 9742            EditorSettings::get_global(cx).expand_excerpt_lines
 9743        } else {
 9744            lines
 9745        };
 9746
 9747        self.buffer.update(cx, |buffer, cx| {
 9748            buffer.expand_excerpts(
 9749                selections
 9750                    .iter()
 9751                    .map(|selection| selection.head().excerpt_id)
 9752                    .dedup(),
 9753                lines,
 9754                direction,
 9755                cx,
 9756            )
 9757        })
 9758    }
 9759
 9760    pub fn expand_excerpt(
 9761        &mut self,
 9762        excerpt: ExcerptId,
 9763        direction: ExpandExcerptDirection,
 9764        cx: &mut ViewContext<Self>,
 9765    ) {
 9766        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9767        self.buffer.update(cx, |buffer, cx| {
 9768            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9769        })
 9770    }
 9771
 9772    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9773        self.go_to_diagnostic_impl(Direction::Next, cx)
 9774    }
 9775
 9776    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9777        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9778    }
 9779
 9780    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9781        let buffer = self.buffer.read(cx).snapshot(cx);
 9782        let selection = self.selections.newest::<usize>(cx);
 9783
 9784        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9785        if direction == Direction::Next {
 9786            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9787                let (group_id, jump_to) = popover.activation_info();
 9788                if self.activate_diagnostics(group_id, cx) {
 9789                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9790                        let mut new_selection = s.newest_anchor().clone();
 9791                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9792                        s.select_anchors(vec![new_selection.clone()]);
 9793                    });
 9794                }
 9795                return;
 9796            }
 9797        }
 9798
 9799        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9800            active_diagnostics
 9801                .primary_range
 9802                .to_offset(&buffer)
 9803                .to_inclusive()
 9804        });
 9805        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9806            if active_primary_range.contains(&selection.head()) {
 9807                *active_primary_range.start()
 9808            } else {
 9809                selection.head()
 9810            }
 9811        } else {
 9812            selection.head()
 9813        };
 9814        let snapshot = self.snapshot(cx);
 9815        loop {
 9816            let diagnostics = if direction == Direction::Prev {
 9817                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9818            } else {
 9819                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9820            }
 9821            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9822            let group = diagnostics
 9823                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9824                // be sorted in a stable way
 9825                // skip until we are at current active diagnostic, if it exists
 9826                .skip_while(|entry| {
 9827                    (match direction {
 9828                        Direction::Prev => entry.range.start >= search_start,
 9829                        Direction::Next => entry.range.start <= search_start,
 9830                    }) && self
 9831                        .active_diagnostics
 9832                        .as_ref()
 9833                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9834                })
 9835                .find_map(|entry| {
 9836                    if entry.diagnostic.is_primary
 9837                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9838                        && !entry.range.is_empty()
 9839                        // if we match with the active diagnostic, skip it
 9840                        && Some(entry.diagnostic.group_id)
 9841                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9842                    {
 9843                        Some((entry.range, entry.diagnostic.group_id))
 9844                    } else {
 9845                        None
 9846                    }
 9847                });
 9848
 9849            if let Some((primary_range, group_id)) = group {
 9850                if self.activate_diagnostics(group_id, cx) {
 9851                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9852                        s.select(vec![Selection {
 9853                            id: selection.id,
 9854                            start: primary_range.start,
 9855                            end: primary_range.start,
 9856                            reversed: false,
 9857                            goal: SelectionGoal::None,
 9858                        }]);
 9859                    });
 9860                }
 9861                break;
 9862            } else {
 9863                // Cycle around to the start of the buffer, potentially moving back to the start of
 9864                // the currently active diagnostic.
 9865                active_primary_range.take();
 9866                if direction == Direction::Prev {
 9867                    if search_start == buffer.len() {
 9868                        break;
 9869                    } else {
 9870                        search_start = buffer.len();
 9871                    }
 9872                } else if search_start == 0 {
 9873                    break;
 9874                } else {
 9875                    search_start = 0;
 9876                }
 9877            }
 9878        }
 9879    }
 9880
 9881    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9882        let snapshot = self.snapshot(cx);
 9883        let selection = self.selections.newest::<Point>(cx);
 9884        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9885    }
 9886
 9887    fn go_to_hunk_after_position(
 9888        &mut self,
 9889        snapshot: &EditorSnapshot,
 9890        position: Point,
 9891        cx: &mut ViewContext<'_, Editor>,
 9892    ) -> Option<MultiBufferDiffHunk> {
 9893        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9894            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9895                snapshot,
 9896                position,
 9897                ix > 0,
 9898                snapshot.diff_map.diff_hunks_in_range(
 9899                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9900                    &snapshot.buffer_snapshot,
 9901                ),
 9902                cx,
 9903            ) {
 9904                return Some(hunk);
 9905            }
 9906        }
 9907        None
 9908    }
 9909
 9910    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9911        let snapshot = self.snapshot(cx);
 9912        let selection = self.selections.newest::<Point>(cx);
 9913        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9914    }
 9915
 9916    fn go_to_hunk_before_position(
 9917        &mut self,
 9918        snapshot: &EditorSnapshot,
 9919        position: Point,
 9920        cx: &mut ViewContext<'_, Editor>,
 9921    ) -> Option<MultiBufferDiffHunk> {
 9922        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9923            .into_iter()
 9924            .enumerate()
 9925        {
 9926            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9927                snapshot,
 9928                position,
 9929                ix > 0,
 9930                snapshot
 9931                    .diff_map
 9932                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9933                cx,
 9934            ) {
 9935                return Some(hunk);
 9936            }
 9937        }
 9938        None
 9939    }
 9940
 9941    fn go_to_next_hunk_in_direction(
 9942        &mut self,
 9943        snapshot: &DisplaySnapshot,
 9944        initial_point: Point,
 9945        is_wrapped: bool,
 9946        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9947        cx: &mut ViewContext<Editor>,
 9948    ) -> Option<MultiBufferDiffHunk> {
 9949        let display_point = initial_point.to_display_point(snapshot);
 9950        let mut hunks = hunks
 9951            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9952            .filter(|(display_hunk, _)| {
 9953                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9954            })
 9955            .dedup();
 9956
 9957        if let Some((display_hunk, hunk)) = hunks.next() {
 9958            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9959                let row = display_hunk.start_display_row();
 9960                let point = DisplayPoint::new(row, 0);
 9961                s.select_display_ranges([point..point]);
 9962            });
 9963
 9964            Some(hunk)
 9965        } else {
 9966            None
 9967        }
 9968    }
 9969
 9970    pub fn go_to_definition(
 9971        &mut self,
 9972        _: &GoToDefinition,
 9973        cx: &mut ViewContext<Self>,
 9974    ) -> Task<Result<Navigated>> {
 9975        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9976        cx.spawn(|editor, mut cx| async move {
 9977            if definition.await? == Navigated::Yes {
 9978                return Ok(Navigated::Yes);
 9979            }
 9980            match editor.update(&mut cx, |editor, cx| {
 9981                editor.find_all_references(&FindAllReferences, cx)
 9982            })? {
 9983                Some(references) => references.await,
 9984                None => Ok(Navigated::No),
 9985            }
 9986        })
 9987    }
 9988
 9989    pub fn go_to_declaration(
 9990        &mut self,
 9991        _: &GoToDeclaration,
 9992        cx: &mut ViewContext<Self>,
 9993    ) -> Task<Result<Navigated>> {
 9994        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9995    }
 9996
 9997    pub fn go_to_declaration_split(
 9998        &mut self,
 9999        _: &GoToDeclaration,
10000        cx: &mut ViewContext<Self>,
10001    ) -> Task<Result<Navigated>> {
10002        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
10003    }
10004
10005    pub fn go_to_implementation(
10006        &mut self,
10007        _: &GoToImplementation,
10008        cx: &mut ViewContext<Self>,
10009    ) -> Task<Result<Navigated>> {
10010        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
10011    }
10012
10013    pub fn go_to_implementation_split(
10014        &mut self,
10015        _: &GoToImplementationSplit,
10016        cx: &mut ViewContext<Self>,
10017    ) -> Task<Result<Navigated>> {
10018        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
10019    }
10020
10021    pub fn go_to_type_definition(
10022        &mut self,
10023        _: &GoToTypeDefinition,
10024        cx: &mut ViewContext<Self>,
10025    ) -> Task<Result<Navigated>> {
10026        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
10027    }
10028
10029    pub fn go_to_definition_split(
10030        &mut self,
10031        _: &GoToDefinitionSplit,
10032        cx: &mut ViewContext<Self>,
10033    ) -> Task<Result<Navigated>> {
10034        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
10035    }
10036
10037    pub fn go_to_type_definition_split(
10038        &mut self,
10039        _: &GoToTypeDefinitionSplit,
10040        cx: &mut ViewContext<Self>,
10041    ) -> Task<Result<Navigated>> {
10042        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
10043    }
10044
10045    fn go_to_definition_of_kind(
10046        &mut self,
10047        kind: GotoDefinitionKind,
10048        split: bool,
10049        cx: &mut ViewContext<Self>,
10050    ) -> Task<Result<Navigated>> {
10051        let Some(provider) = self.semantics_provider.clone() else {
10052            return Task::ready(Ok(Navigated::No));
10053        };
10054        let head = self.selections.newest::<usize>(cx).head();
10055        let buffer = self.buffer.read(cx);
10056        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10057            text_anchor
10058        } else {
10059            return Task::ready(Ok(Navigated::No));
10060        };
10061
10062        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10063            return Task::ready(Ok(Navigated::No));
10064        };
10065
10066        cx.spawn(|editor, mut cx| async move {
10067            let definitions = definitions.await?;
10068            let navigated = editor
10069                .update(&mut cx, |editor, cx| {
10070                    editor.navigate_to_hover_links(
10071                        Some(kind),
10072                        definitions
10073                            .into_iter()
10074                            .filter(|location| {
10075                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10076                            })
10077                            .map(HoverLink::Text)
10078                            .collect::<Vec<_>>(),
10079                        split,
10080                        cx,
10081                    )
10082                })?
10083                .await?;
10084            anyhow::Ok(navigated)
10085        })
10086    }
10087
10088    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
10089        let position = self.selections.newest_anchor().head();
10090        let Some((buffer, buffer_position)) =
10091            self.buffer.read(cx).text_anchor_for_position(position, cx)
10092        else {
10093            return;
10094        };
10095
10096        cx.spawn(|editor, mut cx| async move {
10097            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
10098                editor.update(&mut cx, |_, cx| {
10099                    cx.open_url(&url);
10100                })
10101            } else {
10102                Ok(())
10103            }
10104        })
10105        .detach();
10106    }
10107
10108    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
10109        let Some(workspace) = self.workspace() else {
10110            return;
10111        };
10112
10113        let position = self.selections.newest_anchor().head();
10114
10115        let Some((buffer, buffer_position)) =
10116            self.buffer.read(cx).text_anchor_for_position(position, cx)
10117        else {
10118            return;
10119        };
10120
10121        let project = self.project.clone();
10122
10123        cx.spawn(|_, mut cx| async move {
10124            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10125
10126            if let Some((_, path)) = result {
10127                workspace
10128                    .update(&mut cx, |workspace, cx| {
10129                        workspace.open_resolved_path(path, cx)
10130                    })?
10131                    .await?;
10132            }
10133            anyhow::Ok(())
10134        })
10135        .detach();
10136    }
10137
10138    pub(crate) fn navigate_to_hover_links(
10139        &mut self,
10140        kind: Option<GotoDefinitionKind>,
10141        mut definitions: Vec<HoverLink>,
10142        split: bool,
10143        cx: &mut ViewContext<Editor>,
10144    ) -> Task<Result<Navigated>> {
10145        // If there is one definition, just open it directly
10146        if definitions.len() == 1 {
10147            let definition = definitions.pop().unwrap();
10148
10149            enum TargetTaskResult {
10150                Location(Option<Location>),
10151                AlreadyNavigated,
10152            }
10153
10154            let target_task = match definition {
10155                HoverLink::Text(link) => {
10156                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10157                }
10158                HoverLink::InlayHint(lsp_location, server_id) => {
10159                    let computation = self.compute_target_location(lsp_location, server_id, cx);
10160                    cx.background_executor().spawn(async move {
10161                        let location = computation.await?;
10162                        Ok(TargetTaskResult::Location(location))
10163                    })
10164                }
10165                HoverLink::Url(url) => {
10166                    cx.open_url(&url);
10167                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10168                }
10169                HoverLink::File(path) => {
10170                    if let Some(workspace) = self.workspace() {
10171                        cx.spawn(|_, mut cx| async move {
10172                            workspace
10173                                .update(&mut cx, |workspace, cx| {
10174                                    workspace.open_resolved_path(path, cx)
10175                                })?
10176                                .await
10177                                .map(|_| TargetTaskResult::AlreadyNavigated)
10178                        })
10179                    } else {
10180                        Task::ready(Ok(TargetTaskResult::Location(None)))
10181                    }
10182                }
10183            };
10184            cx.spawn(|editor, mut cx| async move {
10185                let target = match target_task.await.context("target resolution task")? {
10186                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10187                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10188                    TargetTaskResult::Location(Some(target)) => target,
10189                };
10190
10191                editor.update(&mut cx, |editor, cx| {
10192                    let Some(workspace) = editor.workspace() else {
10193                        return Navigated::No;
10194                    };
10195                    let pane = workspace.read(cx).active_pane().clone();
10196
10197                    let range = target.range.to_offset(target.buffer.read(cx));
10198                    let range = editor.range_for_match(&range);
10199
10200                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10201                        let buffer = target.buffer.read(cx);
10202                        let range = check_multiline_range(buffer, range);
10203                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10204                            s.select_ranges([range]);
10205                        });
10206                    } else {
10207                        cx.window_context().defer(move |cx| {
10208                            let target_editor: View<Self> =
10209                                workspace.update(cx, |workspace, cx| {
10210                                    let pane = if split {
10211                                        workspace.adjacent_pane(cx)
10212                                    } else {
10213                                        workspace.active_pane().clone()
10214                                    };
10215
10216                                    workspace.open_project_item(
10217                                        pane,
10218                                        target.buffer.clone(),
10219                                        true,
10220                                        true,
10221                                        cx,
10222                                    )
10223                                });
10224                            target_editor.update(cx, |target_editor, cx| {
10225                                // When selecting a definition in a different buffer, disable the nav history
10226                                // to avoid creating a history entry at the previous cursor location.
10227                                pane.update(cx, |pane, _| pane.disable_history());
10228                                let buffer = target.buffer.read(cx);
10229                                let range = check_multiline_range(buffer, range);
10230                                target_editor.change_selections(
10231                                    Some(Autoscroll::focused()),
10232                                    cx,
10233                                    |s| {
10234                                        s.select_ranges([range]);
10235                                    },
10236                                );
10237                                pane.update(cx, |pane, _| pane.enable_history());
10238                            });
10239                        });
10240                    }
10241                    Navigated::Yes
10242                })
10243            })
10244        } else if !definitions.is_empty() {
10245            cx.spawn(|editor, mut cx| async move {
10246                let (title, location_tasks, workspace) = editor
10247                    .update(&mut cx, |editor, cx| {
10248                        let tab_kind = match kind {
10249                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10250                            _ => "Definitions",
10251                        };
10252                        let title = definitions
10253                            .iter()
10254                            .find_map(|definition| match definition {
10255                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10256                                    let buffer = origin.buffer.read(cx);
10257                                    format!(
10258                                        "{} for {}",
10259                                        tab_kind,
10260                                        buffer
10261                                            .text_for_range(origin.range.clone())
10262                                            .collect::<String>()
10263                                    )
10264                                }),
10265                                HoverLink::InlayHint(_, _) => None,
10266                                HoverLink::Url(_) => None,
10267                                HoverLink::File(_) => None,
10268                            })
10269                            .unwrap_or(tab_kind.to_string());
10270                        let location_tasks = definitions
10271                            .into_iter()
10272                            .map(|definition| match definition {
10273                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10274                                HoverLink::InlayHint(lsp_location, server_id) => {
10275                                    editor.compute_target_location(lsp_location, server_id, cx)
10276                                }
10277                                HoverLink::Url(_) => Task::ready(Ok(None)),
10278                                HoverLink::File(_) => Task::ready(Ok(None)),
10279                            })
10280                            .collect::<Vec<_>>();
10281                        (title, location_tasks, editor.workspace().clone())
10282                    })
10283                    .context("location tasks preparation")?;
10284
10285                let locations = future::join_all(location_tasks)
10286                    .await
10287                    .into_iter()
10288                    .filter_map(|location| location.transpose())
10289                    .collect::<Result<_>>()
10290                    .context("location tasks")?;
10291
10292                let Some(workspace) = workspace else {
10293                    return Ok(Navigated::No);
10294                };
10295                let opened = workspace
10296                    .update(&mut cx, |workspace, cx| {
10297                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10298                    })
10299                    .ok();
10300
10301                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10302            })
10303        } else {
10304            Task::ready(Ok(Navigated::No))
10305        }
10306    }
10307
10308    fn compute_target_location(
10309        &self,
10310        lsp_location: lsp::Location,
10311        server_id: LanguageServerId,
10312        cx: &mut ViewContext<Self>,
10313    ) -> Task<anyhow::Result<Option<Location>>> {
10314        let Some(project) = self.project.clone() else {
10315            return Task::Ready(Some(Ok(None)));
10316        };
10317
10318        cx.spawn(move |editor, mut cx| async move {
10319            let location_task = editor.update(&mut cx, |_, cx| {
10320                project.update(cx, |project, cx| {
10321                    let language_server_name = project
10322                        .language_server_statuses(cx)
10323                        .find(|(id, _)| server_id == *id)
10324                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10325                    language_server_name.map(|language_server_name| {
10326                        project.open_local_buffer_via_lsp(
10327                            lsp_location.uri.clone(),
10328                            server_id,
10329                            language_server_name,
10330                            cx,
10331                        )
10332                    })
10333                })
10334            })?;
10335            let location = match location_task {
10336                Some(task) => Some({
10337                    let target_buffer_handle = task.await.context("open local buffer")?;
10338                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10339                        let target_start = target_buffer
10340                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10341                        let target_end = target_buffer
10342                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10343                        target_buffer.anchor_after(target_start)
10344                            ..target_buffer.anchor_before(target_end)
10345                    })?;
10346                    Location {
10347                        buffer: target_buffer_handle,
10348                        range,
10349                    }
10350                }),
10351                None => None,
10352            };
10353            Ok(location)
10354        })
10355    }
10356
10357    pub fn find_all_references(
10358        &mut self,
10359        _: &FindAllReferences,
10360        cx: &mut ViewContext<Self>,
10361    ) -> Option<Task<Result<Navigated>>> {
10362        let selection = self.selections.newest::<usize>(cx);
10363        let multi_buffer = self.buffer.read(cx);
10364        let head = selection.head();
10365
10366        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10367        let head_anchor = multi_buffer_snapshot.anchor_at(
10368            head,
10369            if head < selection.tail() {
10370                Bias::Right
10371            } else {
10372                Bias::Left
10373            },
10374        );
10375
10376        match self
10377            .find_all_references_task_sources
10378            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10379        {
10380            Ok(_) => {
10381                log::info!(
10382                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10383                );
10384                return None;
10385            }
10386            Err(i) => {
10387                self.find_all_references_task_sources.insert(i, head_anchor);
10388            }
10389        }
10390
10391        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10392        let workspace = self.workspace()?;
10393        let project = workspace.read(cx).project().clone();
10394        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10395        Some(cx.spawn(|editor, mut cx| async move {
10396            let _cleanup = defer({
10397                let mut cx = cx.clone();
10398                move || {
10399                    let _ = editor.update(&mut cx, |editor, _| {
10400                        if let Ok(i) =
10401                            editor
10402                                .find_all_references_task_sources
10403                                .binary_search_by(|anchor| {
10404                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10405                                })
10406                        {
10407                            editor.find_all_references_task_sources.remove(i);
10408                        }
10409                    });
10410                }
10411            });
10412
10413            let locations = references.await?;
10414            if locations.is_empty() {
10415                return anyhow::Ok(Navigated::No);
10416            }
10417
10418            workspace.update(&mut cx, |workspace, cx| {
10419                let title = locations
10420                    .first()
10421                    .as_ref()
10422                    .map(|location| {
10423                        let buffer = location.buffer.read(cx);
10424                        format!(
10425                            "References to `{}`",
10426                            buffer
10427                                .text_for_range(location.range.clone())
10428                                .collect::<String>()
10429                        )
10430                    })
10431                    .unwrap();
10432                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10433                Navigated::Yes
10434            })
10435        }))
10436    }
10437
10438    /// Opens a multibuffer with the given project locations in it
10439    pub fn open_locations_in_multibuffer(
10440        workspace: &mut Workspace,
10441        mut locations: Vec<Location>,
10442        title: String,
10443        split: bool,
10444        cx: &mut ViewContext<Workspace>,
10445    ) {
10446        // If there are multiple definitions, open them in a multibuffer
10447        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10448        let mut locations = locations.into_iter().peekable();
10449        let mut ranges_to_highlight = Vec::new();
10450        let capability = workspace.project().read(cx).capability();
10451
10452        let excerpt_buffer = cx.new_model(|cx| {
10453            let mut multibuffer = MultiBuffer::new(capability);
10454            while let Some(location) = locations.next() {
10455                let buffer = location.buffer.read(cx);
10456                let mut ranges_for_buffer = Vec::new();
10457                let range = location.range.to_offset(buffer);
10458                ranges_for_buffer.push(range.clone());
10459
10460                while let Some(next_location) = locations.peek() {
10461                    if next_location.buffer == location.buffer {
10462                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10463                        locations.next();
10464                    } else {
10465                        break;
10466                    }
10467                }
10468
10469                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10470                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10471                    location.buffer.clone(),
10472                    ranges_for_buffer,
10473                    DEFAULT_MULTIBUFFER_CONTEXT,
10474                    cx,
10475                ))
10476            }
10477
10478            multibuffer.with_title(title)
10479        });
10480
10481        let editor = cx.new_view(|cx| {
10482            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10483        });
10484        editor.update(cx, |editor, cx| {
10485            if let Some(first_range) = ranges_to_highlight.first() {
10486                editor.change_selections(None, cx, |selections| {
10487                    selections.clear_disjoint();
10488                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10489                });
10490            }
10491            editor.highlight_background::<Self>(
10492                &ranges_to_highlight,
10493                |theme| theme.editor_highlighted_line_background,
10494                cx,
10495            );
10496        });
10497
10498        let item = Box::new(editor);
10499        let item_id = item.item_id();
10500
10501        if split {
10502            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10503        } else {
10504            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10505                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10506                    pane.close_current_preview_item(cx)
10507                } else {
10508                    None
10509                }
10510            });
10511            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10512        }
10513        workspace.active_pane().update(cx, |pane, cx| {
10514            pane.set_preview_item_id(Some(item_id), cx);
10515        });
10516    }
10517
10518    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10519        use language::ToOffset as _;
10520
10521        let provider = self.semantics_provider.clone()?;
10522        let selection = self.selections.newest_anchor().clone();
10523        let (cursor_buffer, cursor_buffer_position) = self
10524            .buffer
10525            .read(cx)
10526            .text_anchor_for_position(selection.head(), cx)?;
10527        let (tail_buffer, cursor_buffer_position_end) = self
10528            .buffer
10529            .read(cx)
10530            .text_anchor_for_position(selection.tail(), cx)?;
10531        if tail_buffer != cursor_buffer {
10532            return None;
10533        }
10534
10535        let snapshot = cursor_buffer.read(cx).snapshot();
10536        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10537        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10538        let prepare_rename = provider
10539            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10540            .unwrap_or_else(|| Task::ready(Ok(None)));
10541        drop(snapshot);
10542
10543        Some(cx.spawn(|this, mut cx| async move {
10544            let rename_range = if let Some(range) = prepare_rename.await? {
10545                Some(range)
10546            } else {
10547                this.update(&mut cx, |this, cx| {
10548                    let buffer = this.buffer.read(cx).snapshot(cx);
10549                    let mut buffer_highlights = this
10550                        .document_highlights_for_position(selection.head(), &buffer)
10551                        .filter(|highlight| {
10552                            highlight.start.excerpt_id == selection.head().excerpt_id
10553                                && highlight.end.excerpt_id == selection.head().excerpt_id
10554                        });
10555                    buffer_highlights
10556                        .next()
10557                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10558                })?
10559            };
10560            if let Some(rename_range) = rename_range {
10561                this.update(&mut cx, |this, cx| {
10562                    let snapshot = cursor_buffer.read(cx).snapshot();
10563                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10564                    let cursor_offset_in_rename_range =
10565                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10566                    let cursor_offset_in_rename_range_end =
10567                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10568
10569                    this.take_rename(false, cx);
10570                    let buffer = this.buffer.read(cx).read(cx);
10571                    let cursor_offset = selection.head().to_offset(&buffer);
10572                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10573                    let rename_end = rename_start + rename_buffer_range.len();
10574                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10575                    let mut old_highlight_id = None;
10576                    let old_name: Arc<str> = buffer
10577                        .chunks(rename_start..rename_end, true)
10578                        .map(|chunk| {
10579                            if old_highlight_id.is_none() {
10580                                old_highlight_id = chunk.syntax_highlight_id;
10581                            }
10582                            chunk.text
10583                        })
10584                        .collect::<String>()
10585                        .into();
10586
10587                    drop(buffer);
10588
10589                    // Position the selection in the rename editor so that it matches the current selection.
10590                    this.show_local_selections = false;
10591                    let rename_editor = cx.new_view(|cx| {
10592                        let mut editor = Editor::single_line(cx);
10593                        editor.buffer.update(cx, |buffer, cx| {
10594                            buffer.edit([(0..0, old_name.clone())], None, cx)
10595                        });
10596                        let rename_selection_range = match cursor_offset_in_rename_range
10597                            .cmp(&cursor_offset_in_rename_range_end)
10598                        {
10599                            Ordering::Equal => {
10600                                editor.select_all(&SelectAll, cx);
10601                                return editor;
10602                            }
10603                            Ordering::Less => {
10604                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10605                            }
10606                            Ordering::Greater => {
10607                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10608                            }
10609                        };
10610                        if rename_selection_range.end > old_name.len() {
10611                            editor.select_all(&SelectAll, cx);
10612                        } else {
10613                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10614                                s.select_ranges([rename_selection_range]);
10615                            });
10616                        }
10617                        editor
10618                    });
10619                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10620                        if e == &EditorEvent::Focused {
10621                            cx.emit(EditorEvent::FocusedIn)
10622                        }
10623                    })
10624                    .detach();
10625
10626                    let write_highlights =
10627                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10628                    let read_highlights =
10629                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10630                    let ranges = write_highlights
10631                        .iter()
10632                        .flat_map(|(_, ranges)| ranges.iter())
10633                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10634                        .cloned()
10635                        .collect();
10636
10637                    this.highlight_text::<Rename>(
10638                        ranges,
10639                        HighlightStyle {
10640                            fade_out: Some(0.6),
10641                            ..Default::default()
10642                        },
10643                        cx,
10644                    );
10645                    let rename_focus_handle = rename_editor.focus_handle(cx);
10646                    cx.focus(&rename_focus_handle);
10647                    let block_id = this.insert_blocks(
10648                        [BlockProperties {
10649                            style: BlockStyle::Flex,
10650                            placement: BlockPlacement::Below(range.start),
10651                            height: 1,
10652                            render: Arc::new({
10653                                let rename_editor = rename_editor.clone();
10654                                move |cx: &mut BlockContext| {
10655                                    let mut text_style = cx.editor_style.text.clone();
10656                                    if let Some(highlight_style) = old_highlight_id
10657                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10658                                    {
10659                                        text_style = text_style.highlight(highlight_style);
10660                                    }
10661                                    div()
10662                                        .block_mouse_down()
10663                                        .pl(cx.anchor_x)
10664                                        .child(EditorElement::new(
10665                                            &rename_editor,
10666                                            EditorStyle {
10667                                                background: cx.theme().system().transparent,
10668                                                local_player: cx.editor_style.local_player,
10669                                                text: text_style,
10670                                                scrollbar_width: cx.editor_style.scrollbar_width,
10671                                                syntax: cx.editor_style.syntax.clone(),
10672                                                status: cx.editor_style.status.clone(),
10673                                                inlay_hints_style: HighlightStyle {
10674                                                    font_weight: Some(FontWeight::BOLD),
10675                                                    ..make_inlay_hints_style(cx)
10676                                                },
10677                                                suggestions_style: HighlightStyle {
10678                                                    color: Some(cx.theme().status().predictive),
10679                                                    ..HighlightStyle::default()
10680                                                },
10681                                                ..EditorStyle::default()
10682                                            },
10683                                        ))
10684                                        .into_any_element()
10685                                }
10686                            }),
10687                            priority: 0,
10688                        }],
10689                        Some(Autoscroll::fit()),
10690                        cx,
10691                    )[0];
10692                    this.pending_rename = Some(RenameState {
10693                        range,
10694                        old_name,
10695                        editor: rename_editor,
10696                        block_id,
10697                    });
10698                })?;
10699            }
10700
10701            Ok(())
10702        }))
10703    }
10704
10705    pub fn confirm_rename(
10706        &mut self,
10707        _: &ConfirmRename,
10708        cx: &mut ViewContext<Self>,
10709    ) -> Option<Task<Result<()>>> {
10710        let rename = self.take_rename(false, cx)?;
10711        let workspace = self.workspace()?.downgrade();
10712        let (buffer, start) = self
10713            .buffer
10714            .read(cx)
10715            .text_anchor_for_position(rename.range.start, cx)?;
10716        let (end_buffer, _) = self
10717            .buffer
10718            .read(cx)
10719            .text_anchor_for_position(rename.range.end, cx)?;
10720        if buffer != end_buffer {
10721            return None;
10722        }
10723
10724        let old_name = rename.old_name;
10725        let new_name = rename.editor.read(cx).text(cx);
10726
10727        let rename = self.semantics_provider.as_ref()?.perform_rename(
10728            &buffer,
10729            start,
10730            new_name.clone(),
10731            cx,
10732        )?;
10733
10734        Some(cx.spawn(|editor, mut cx| async move {
10735            let project_transaction = rename.await?;
10736            Self::open_project_transaction(
10737                &editor,
10738                workspace,
10739                project_transaction,
10740                format!("Rename: {}{}", old_name, new_name),
10741                cx.clone(),
10742            )
10743            .await?;
10744
10745            editor.update(&mut cx, |editor, cx| {
10746                editor.refresh_document_highlights(cx);
10747            })?;
10748            Ok(())
10749        }))
10750    }
10751
10752    fn take_rename(
10753        &mut self,
10754        moving_cursor: bool,
10755        cx: &mut ViewContext<Self>,
10756    ) -> Option<RenameState> {
10757        let rename = self.pending_rename.take()?;
10758        if rename.editor.focus_handle(cx).is_focused(cx) {
10759            cx.focus(&self.focus_handle);
10760        }
10761
10762        self.remove_blocks(
10763            [rename.block_id].into_iter().collect(),
10764            Some(Autoscroll::fit()),
10765            cx,
10766        );
10767        self.clear_highlights::<Rename>(cx);
10768        self.show_local_selections = true;
10769
10770        if moving_cursor {
10771            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10772                editor.selections.newest::<usize>(cx).head()
10773            });
10774
10775            // Update the selection to match the position of the selection inside
10776            // the rename editor.
10777            let snapshot = self.buffer.read(cx).read(cx);
10778            let rename_range = rename.range.to_offset(&snapshot);
10779            let cursor_in_editor = snapshot
10780                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10781                .min(rename_range.end);
10782            drop(snapshot);
10783
10784            self.change_selections(None, cx, |s| {
10785                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10786            });
10787        } else {
10788            self.refresh_document_highlights(cx);
10789        }
10790
10791        Some(rename)
10792    }
10793
10794    pub fn pending_rename(&self) -> Option<&RenameState> {
10795        self.pending_rename.as_ref()
10796    }
10797
10798    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10799        let project = match &self.project {
10800            Some(project) => project.clone(),
10801            None => return None,
10802        };
10803
10804        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10805    }
10806
10807    fn format_selections(
10808        &mut self,
10809        _: &FormatSelections,
10810        cx: &mut ViewContext<Self>,
10811    ) -> Option<Task<Result<()>>> {
10812        let project = match &self.project {
10813            Some(project) => project.clone(),
10814            None => return None,
10815        };
10816
10817        let selections = self
10818            .selections
10819            .all_adjusted(cx)
10820            .into_iter()
10821            .filter(|s| !s.is_empty())
10822            .collect_vec();
10823
10824        Some(self.perform_format(
10825            project,
10826            FormatTrigger::Manual,
10827            FormatTarget::Ranges(selections),
10828            cx,
10829        ))
10830    }
10831
10832    fn perform_format(
10833        &mut self,
10834        project: Model<Project>,
10835        trigger: FormatTrigger,
10836        target: FormatTarget,
10837        cx: &mut ViewContext<Self>,
10838    ) -> Task<Result<()>> {
10839        let buffer = self.buffer().clone();
10840        let mut buffers = buffer.read(cx).all_buffers();
10841        if trigger == FormatTrigger::Save {
10842            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10843        }
10844
10845        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10846        let format = project.update(cx, |project, cx| {
10847            project.format(buffers, true, trigger, target, cx)
10848        });
10849
10850        cx.spawn(|_, mut cx| async move {
10851            let transaction = futures::select_biased! {
10852                () = timeout => {
10853                    log::warn!("timed out waiting for formatting");
10854                    None
10855                }
10856                transaction = format.log_err().fuse() => transaction,
10857            };
10858
10859            buffer
10860                .update(&mut cx, |buffer, cx| {
10861                    if let Some(transaction) = transaction {
10862                        if !buffer.is_singleton() {
10863                            buffer.push_transaction(&transaction.0, cx);
10864                        }
10865                    }
10866
10867                    cx.notify();
10868                })
10869                .ok();
10870
10871            Ok(())
10872        })
10873    }
10874
10875    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10876        if let Some(project) = self.project.clone() {
10877            self.buffer.update(cx, |multi_buffer, cx| {
10878                project.update(cx, |project, cx| {
10879                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10880                });
10881            })
10882        }
10883    }
10884
10885    fn cancel_language_server_work(
10886        &mut self,
10887        _: &actions::CancelLanguageServerWork,
10888        cx: &mut ViewContext<Self>,
10889    ) {
10890        if let Some(project) = self.project.clone() {
10891            self.buffer.update(cx, |multi_buffer, cx| {
10892                project.update(cx, |project, cx| {
10893                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10894                });
10895            })
10896        }
10897    }
10898
10899    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10900        cx.show_character_palette();
10901    }
10902
10903    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10904        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10905            let buffer = self.buffer.read(cx).snapshot(cx);
10906            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10907            let is_valid = buffer
10908                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10909                .any(|entry| {
10910                    entry.diagnostic.is_primary
10911                        && !entry.range.is_empty()
10912                        && entry.range.start == primary_range_start
10913                        && entry.diagnostic.message == active_diagnostics.primary_message
10914                });
10915
10916            if is_valid != active_diagnostics.is_valid {
10917                active_diagnostics.is_valid = is_valid;
10918                let mut new_styles = HashMap::default();
10919                for (block_id, diagnostic) in &active_diagnostics.blocks {
10920                    new_styles.insert(
10921                        *block_id,
10922                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10923                    );
10924                }
10925                self.display_map.update(cx, |display_map, _cx| {
10926                    display_map.replace_blocks(new_styles)
10927                });
10928            }
10929        }
10930    }
10931
10932    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10933        self.dismiss_diagnostics(cx);
10934        let snapshot = self.snapshot(cx);
10935        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10936            let buffer = self.buffer.read(cx).snapshot(cx);
10937
10938            let mut primary_range = None;
10939            let mut primary_message = None;
10940            let mut group_end = Point::zero();
10941            let diagnostic_group = buffer
10942                .diagnostic_group::<MultiBufferPoint>(group_id)
10943                .filter_map(|entry| {
10944                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10945                        && (entry.range.start.row == entry.range.end.row
10946                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10947                    {
10948                        return None;
10949                    }
10950                    if entry.range.end > group_end {
10951                        group_end = entry.range.end;
10952                    }
10953                    if entry.diagnostic.is_primary {
10954                        primary_range = Some(entry.range.clone());
10955                        primary_message = Some(entry.diagnostic.message.clone());
10956                    }
10957                    Some(entry)
10958                })
10959                .collect::<Vec<_>>();
10960            let primary_range = primary_range?;
10961            let primary_message = primary_message?;
10962            let primary_range =
10963                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10964
10965            let blocks = display_map
10966                .insert_blocks(
10967                    diagnostic_group.iter().map(|entry| {
10968                        let diagnostic = entry.diagnostic.clone();
10969                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10970                        BlockProperties {
10971                            style: BlockStyle::Fixed,
10972                            placement: BlockPlacement::Below(
10973                                buffer.anchor_after(entry.range.start),
10974                            ),
10975                            height: message_height,
10976                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10977                            priority: 0,
10978                        }
10979                    }),
10980                    cx,
10981                )
10982                .into_iter()
10983                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10984                .collect();
10985
10986            Some(ActiveDiagnosticGroup {
10987                primary_range,
10988                primary_message,
10989                group_id,
10990                blocks,
10991                is_valid: true,
10992            })
10993        });
10994        self.active_diagnostics.is_some()
10995    }
10996
10997    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10998        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10999            self.display_map.update(cx, |display_map, cx| {
11000                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11001            });
11002            cx.notify();
11003        }
11004    }
11005
11006    pub fn set_selections_from_remote(
11007        &mut self,
11008        selections: Vec<Selection<Anchor>>,
11009        pending_selection: Option<Selection<Anchor>>,
11010        cx: &mut ViewContext<Self>,
11011    ) {
11012        let old_cursor_position = self.selections.newest_anchor().head();
11013        self.selections.change_with(cx, |s| {
11014            s.select_anchors(selections);
11015            if let Some(pending_selection) = pending_selection {
11016                s.set_pending(pending_selection, SelectMode::Character);
11017            } else {
11018                s.clear_pending();
11019            }
11020        });
11021        self.selections_did_change(false, &old_cursor_position, true, cx);
11022    }
11023
11024    fn push_to_selection_history(&mut self) {
11025        self.selection_history.push(SelectionHistoryEntry {
11026            selections: self.selections.disjoint_anchors(),
11027            select_next_state: self.select_next_state.clone(),
11028            select_prev_state: self.select_prev_state.clone(),
11029            add_selections_state: self.add_selections_state.clone(),
11030        });
11031    }
11032
11033    pub fn transact(
11034        &mut self,
11035        cx: &mut ViewContext<Self>,
11036        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
11037    ) -> Option<TransactionId> {
11038        self.start_transaction_at(Instant::now(), cx);
11039        update(self, cx);
11040        self.end_transaction_at(Instant::now(), cx)
11041    }
11042
11043    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
11044        self.end_selection(cx);
11045        if let Some(tx_id) = self
11046            .buffer
11047            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11048        {
11049            self.selection_history
11050                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11051            cx.emit(EditorEvent::TransactionBegun {
11052                transaction_id: tx_id,
11053            })
11054        }
11055    }
11056
11057    fn end_transaction_at(
11058        &mut self,
11059        now: Instant,
11060        cx: &mut ViewContext<Self>,
11061    ) -> Option<TransactionId> {
11062        if let Some(transaction_id) = self
11063            .buffer
11064            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11065        {
11066            if let Some((_, end_selections)) =
11067                self.selection_history.transaction_mut(transaction_id)
11068            {
11069                *end_selections = Some(self.selections.disjoint_anchors());
11070            } else {
11071                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11072            }
11073
11074            cx.emit(EditorEvent::Edited { transaction_id });
11075            Some(transaction_id)
11076        } else {
11077            None
11078        }
11079    }
11080
11081    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
11082        let selection = self.selections.newest::<Point>(cx);
11083
11084        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11085        let range = if selection.is_empty() {
11086            let point = selection.head().to_display_point(&display_map);
11087            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11088            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11089                .to_point(&display_map);
11090            start..end
11091        } else {
11092            selection.range()
11093        };
11094        if display_map.folds_in_range(range).next().is_some() {
11095            self.unfold_lines(&Default::default(), cx)
11096        } else {
11097            self.fold(&Default::default(), cx)
11098        }
11099    }
11100
11101    pub fn toggle_fold_recursive(
11102        &mut self,
11103        _: &actions::ToggleFoldRecursive,
11104        cx: &mut ViewContext<Self>,
11105    ) {
11106        let selection = self.selections.newest::<Point>(cx);
11107
11108        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11109        let range = if selection.is_empty() {
11110            let point = selection.head().to_display_point(&display_map);
11111            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11112            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11113                .to_point(&display_map);
11114            start..end
11115        } else {
11116            selection.range()
11117        };
11118        if display_map.folds_in_range(range).next().is_some() {
11119            self.unfold_recursive(&Default::default(), cx)
11120        } else {
11121            self.fold_recursive(&Default::default(), cx)
11122        }
11123    }
11124
11125    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
11126        let mut to_fold = Vec::new();
11127        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11128        let selections = self.selections.all_adjusted(cx);
11129
11130        for selection in selections {
11131            let range = selection.range().sorted();
11132            let buffer_start_row = range.start.row;
11133
11134            if range.start.row != range.end.row {
11135                let mut found = false;
11136                let mut row = range.start.row;
11137                while row <= range.end.row {
11138                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11139                        found = true;
11140                        row = crease.range().end.row + 1;
11141                        to_fold.push(crease);
11142                    } else {
11143                        row += 1
11144                    }
11145                }
11146                if found {
11147                    continue;
11148                }
11149            }
11150
11151            for row in (0..=range.start.row).rev() {
11152                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11153                    if crease.range().end.row >= buffer_start_row {
11154                        to_fold.push(crease);
11155                        if row <= range.start.row {
11156                            break;
11157                        }
11158                    }
11159                }
11160            }
11161        }
11162
11163        self.fold_creases(to_fold, true, cx);
11164    }
11165
11166    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
11167        if !self.buffer.read(cx).is_singleton() {
11168            return;
11169        }
11170
11171        let fold_at_level = fold_at.level;
11172        let snapshot = self.buffer.read(cx).snapshot(cx);
11173        let mut to_fold = Vec::new();
11174        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11175
11176        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11177            while start_row < end_row {
11178                match self
11179                    .snapshot(cx)
11180                    .crease_for_buffer_row(MultiBufferRow(start_row))
11181                {
11182                    Some(crease) => {
11183                        let nested_start_row = crease.range().start.row + 1;
11184                        let nested_end_row = crease.range().end.row;
11185
11186                        if current_level < fold_at_level {
11187                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11188                        } else if current_level == fold_at_level {
11189                            to_fold.push(crease);
11190                        }
11191
11192                        start_row = nested_end_row + 1;
11193                    }
11194                    None => start_row += 1,
11195                }
11196            }
11197        }
11198
11199        self.fold_creases(to_fold, true, cx);
11200    }
11201
11202    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
11203        if !self.buffer.read(cx).is_singleton() {
11204            return;
11205        }
11206
11207        let mut fold_ranges = Vec::new();
11208        let snapshot = self.buffer.read(cx).snapshot(cx);
11209
11210        for row in 0..snapshot.max_row().0 {
11211            if let Some(foldable_range) =
11212                self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
11213            {
11214                fold_ranges.push(foldable_range);
11215            }
11216        }
11217
11218        self.fold_creases(fold_ranges, true, cx);
11219    }
11220
11221    pub fn fold_function_bodies(
11222        &mut self,
11223        _: &actions::FoldFunctionBodies,
11224        cx: &mut ViewContext<Self>,
11225    ) {
11226        let snapshot = self.buffer.read(cx).snapshot(cx);
11227        let Some((_, _, buffer)) = snapshot.as_singleton() else {
11228            return;
11229        };
11230        let creases = buffer
11231            .function_body_fold_ranges(0..buffer.len())
11232            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11233            .collect();
11234
11235        self.fold_creases(creases, true, cx);
11236    }
11237
11238    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
11239        let mut to_fold = Vec::new();
11240        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11241        let selections = self.selections.all_adjusted(cx);
11242
11243        for selection in selections {
11244            let range = selection.range().sorted();
11245            let buffer_start_row = range.start.row;
11246
11247            if range.start.row != range.end.row {
11248                let mut found = false;
11249                for row in range.start.row..=range.end.row {
11250                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11251                        found = true;
11252                        to_fold.push(crease);
11253                    }
11254                }
11255                if found {
11256                    continue;
11257                }
11258            }
11259
11260            for row in (0..=range.start.row).rev() {
11261                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11262                    if crease.range().end.row >= buffer_start_row {
11263                        to_fold.push(crease);
11264                    } else {
11265                        break;
11266                    }
11267                }
11268            }
11269        }
11270
11271        self.fold_creases(to_fold, true, cx);
11272    }
11273
11274    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11275        let buffer_row = fold_at.buffer_row;
11276        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11277
11278        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11279            let autoscroll = self
11280                .selections
11281                .all::<Point>(cx)
11282                .iter()
11283                .any(|selection| crease.range().overlaps(&selection.range()));
11284
11285            self.fold_creases(vec![crease], autoscroll, cx);
11286        }
11287    }
11288
11289    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11290        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11291        let buffer = &display_map.buffer_snapshot;
11292        let selections = self.selections.all::<Point>(cx);
11293        let ranges = selections
11294            .iter()
11295            .map(|s| {
11296                let range = s.display_range(&display_map).sorted();
11297                let mut start = range.start.to_point(&display_map);
11298                let mut end = range.end.to_point(&display_map);
11299                start.column = 0;
11300                end.column = buffer.line_len(MultiBufferRow(end.row));
11301                start..end
11302            })
11303            .collect::<Vec<_>>();
11304
11305        self.unfold_ranges(&ranges, true, true, cx);
11306    }
11307
11308    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11309        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11310        let selections = self.selections.all::<Point>(cx);
11311        let ranges = selections
11312            .iter()
11313            .map(|s| {
11314                let mut range = s.display_range(&display_map).sorted();
11315                *range.start.column_mut() = 0;
11316                *range.end.column_mut() = display_map.line_len(range.end.row());
11317                let start = range.start.to_point(&display_map);
11318                let end = range.end.to_point(&display_map);
11319                start..end
11320            })
11321            .collect::<Vec<_>>();
11322
11323        self.unfold_ranges(&ranges, true, true, cx);
11324    }
11325
11326    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11327        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11328
11329        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11330            ..Point::new(
11331                unfold_at.buffer_row.0,
11332                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11333            );
11334
11335        let autoscroll = self
11336            .selections
11337            .all::<Point>(cx)
11338            .iter()
11339            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11340
11341        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11342    }
11343
11344    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11345        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11346        self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11347    }
11348
11349    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11350        let selections = self.selections.all::<Point>(cx);
11351        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11352        let line_mode = self.selections.line_mode;
11353        let ranges = selections
11354            .into_iter()
11355            .map(|s| {
11356                if line_mode {
11357                    let start = Point::new(s.start.row, 0);
11358                    let end = Point::new(
11359                        s.end.row,
11360                        display_map
11361                            .buffer_snapshot
11362                            .line_len(MultiBufferRow(s.end.row)),
11363                    );
11364                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11365                } else {
11366                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11367                }
11368            })
11369            .collect::<Vec<_>>();
11370        self.fold_creases(ranges, true, cx);
11371    }
11372
11373    pub fn fold_creases<T: ToOffset + Clone>(
11374        &mut self,
11375        creases: Vec<Crease<T>>,
11376        auto_scroll: bool,
11377        cx: &mut ViewContext<Self>,
11378    ) {
11379        if creases.is_empty() {
11380            return;
11381        }
11382
11383        let mut buffers_affected = HashSet::default();
11384        let multi_buffer = self.buffer().read(cx);
11385        for crease in &creases {
11386            if let Some((_, buffer, _)) =
11387                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11388            {
11389                buffers_affected.insert(buffer.read(cx).remote_id());
11390            };
11391        }
11392
11393        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11394
11395        if auto_scroll {
11396            self.request_autoscroll(Autoscroll::fit(), cx);
11397        }
11398
11399        for buffer_id in buffers_affected {
11400            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11401        }
11402
11403        cx.notify();
11404
11405        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11406            // Clear diagnostics block when folding a range that contains it.
11407            let snapshot = self.snapshot(cx);
11408            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11409                drop(snapshot);
11410                self.active_diagnostics = Some(active_diagnostics);
11411                self.dismiss_diagnostics(cx);
11412            } else {
11413                self.active_diagnostics = Some(active_diagnostics);
11414            }
11415        }
11416
11417        self.scrollbar_marker_state.dirty = true;
11418    }
11419
11420    /// Removes any folds whose ranges intersect any of the given ranges.
11421    pub fn unfold_ranges<T: ToOffset + Clone>(
11422        &mut self,
11423        ranges: &[Range<T>],
11424        inclusive: bool,
11425        auto_scroll: bool,
11426        cx: &mut ViewContext<Self>,
11427    ) {
11428        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11429            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11430        });
11431    }
11432
11433    /// Removes any folds with the given ranges.
11434    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11435        &mut self,
11436        ranges: &[Range<T>],
11437        type_id: TypeId,
11438        auto_scroll: bool,
11439        cx: &mut ViewContext<Self>,
11440    ) {
11441        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11442            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11443        });
11444    }
11445
11446    fn remove_folds_with<T: ToOffset + Clone>(
11447        &mut self,
11448        ranges: &[Range<T>],
11449        auto_scroll: bool,
11450        cx: &mut ViewContext<Self>,
11451        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11452    ) {
11453        if ranges.is_empty() {
11454            return;
11455        }
11456
11457        let mut buffers_affected = HashSet::default();
11458        let multi_buffer = self.buffer().read(cx);
11459        for range in ranges {
11460            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11461                buffers_affected.insert(buffer.read(cx).remote_id());
11462            };
11463        }
11464
11465        self.display_map.update(cx, update);
11466
11467        if auto_scroll {
11468            self.request_autoscroll(Autoscroll::fit(), cx);
11469        }
11470
11471        for buffer_id in buffers_affected {
11472            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11473        }
11474
11475        cx.notify();
11476        self.scrollbar_marker_state.dirty = true;
11477        self.active_indent_guides_state.dirty = true;
11478    }
11479
11480    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11481        self.display_map.read(cx).fold_placeholder.clone()
11482    }
11483
11484    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11485        if hovered != self.gutter_hovered {
11486            self.gutter_hovered = hovered;
11487            cx.notify();
11488        }
11489    }
11490
11491    pub fn insert_blocks(
11492        &mut self,
11493        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11494        autoscroll: Option<Autoscroll>,
11495        cx: &mut ViewContext<Self>,
11496    ) -> Vec<CustomBlockId> {
11497        let blocks = self
11498            .display_map
11499            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11500        if let Some(autoscroll) = autoscroll {
11501            self.request_autoscroll(autoscroll, cx);
11502        }
11503        cx.notify();
11504        blocks
11505    }
11506
11507    pub fn resize_blocks(
11508        &mut self,
11509        heights: HashMap<CustomBlockId, u32>,
11510        autoscroll: Option<Autoscroll>,
11511        cx: &mut ViewContext<Self>,
11512    ) {
11513        self.display_map
11514            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11515        if let Some(autoscroll) = autoscroll {
11516            self.request_autoscroll(autoscroll, cx);
11517        }
11518        cx.notify();
11519    }
11520
11521    pub fn replace_blocks(
11522        &mut self,
11523        renderers: HashMap<CustomBlockId, RenderBlock>,
11524        autoscroll: Option<Autoscroll>,
11525        cx: &mut ViewContext<Self>,
11526    ) {
11527        self.display_map
11528            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11529        if let Some(autoscroll) = autoscroll {
11530            self.request_autoscroll(autoscroll, cx);
11531        }
11532        cx.notify();
11533    }
11534
11535    pub fn remove_blocks(
11536        &mut self,
11537        block_ids: HashSet<CustomBlockId>,
11538        autoscroll: Option<Autoscroll>,
11539        cx: &mut ViewContext<Self>,
11540    ) {
11541        self.display_map.update(cx, |display_map, cx| {
11542            display_map.remove_blocks(block_ids, cx)
11543        });
11544        if let Some(autoscroll) = autoscroll {
11545            self.request_autoscroll(autoscroll, cx);
11546        }
11547        cx.notify();
11548    }
11549
11550    pub fn row_for_block(
11551        &self,
11552        block_id: CustomBlockId,
11553        cx: &mut ViewContext<Self>,
11554    ) -> Option<DisplayRow> {
11555        self.display_map
11556            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11557    }
11558
11559    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11560        self.focused_block = Some(focused_block);
11561    }
11562
11563    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11564        self.focused_block.take()
11565    }
11566
11567    pub fn insert_creases(
11568        &mut self,
11569        creases: impl IntoIterator<Item = Crease<Anchor>>,
11570        cx: &mut ViewContext<Self>,
11571    ) -> Vec<CreaseId> {
11572        self.display_map
11573            .update(cx, |map, cx| map.insert_creases(creases, cx))
11574    }
11575
11576    pub fn remove_creases(
11577        &mut self,
11578        ids: impl IntoIterator<Item = CreaseId>,
11579        cx: &mut ViewContext<Self>,
11580    ) {
11581        self.display_map
11582            .update(cx, |map, cx| map.remove_creases(ids, cx));
11583    }
11584
11585    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11586        self.display_map
11587            .update(cx, |map, cx| map.snapshot(cx))
11588            .longest_row()
11589    }
11590
11591    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11592        self.display_map
11593            .update(cx, |map, cx| map.snapshot(cx))
11594            .max_point()
11595    }
11596
11597    pub fn text(&self, cx: &AppContext) -> String {
11598        self.buffer.read(cx).read(cx).text()
11599    }
11600
11601    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11602        let text = self.text(cx);
11603        let text = text.trim();
11604
11605        if text.is_empty() {
11606            return None;
11607        }
11608
11609        Some(text.to_string())
11610    }
11611
11612    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11613        self.transact(cx, |this, cx| {
11614            this.buffer
11615                .read(cx)
11616                .as_singleton()
11617                .expect("you can only call set_text on editors for singleton buffers")
11618                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11619        });
11620    }
11621
11622    pub fn display_text(&self, cx: &mut AppContext) -> String {
11623        self.display_map
11624            .update(cx, |map, cx| map.snapshot(cx))
11625            .text()
11626    }
11627
11628    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11629        let mut wrap_guides = smallvec::smallvec![];
11630
11631        if self.show_wrap_guides == Some(false) {
11632            return wrap_guides;
11633        }
11634
11635        let settings = self.buffer.read(cx).settings_at(0, cx);
11636        if settings.show_wrap_guides {
11637            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11638                wrap_guides.push((soft_wrap as usize, true));
11639            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11640                wrap_guides.push((soft_wrap as usize, true));
11641            }
11642            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11643        }
11644
11645        wrap_guides
11646    }
11647
11648    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11649        let settings = self.buffer.read(cx).settings_at(0, cx);
11650        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11651        match mode {
11652            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11653                SoftWrap::None
11654            }
11655            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11656            language_settings::SoftWrap::PreferredLineLength => {
11657                SoftWrap::Column(settings.preferred_line_length)
11658            }
11659            language_settings::SoftWrap::Bounded => {
11660                SoftWrap::Bounded(settings.preferred_line_length)
11661            }
11662        }
11663    }
11664
11665    pub fn set_soft_wrap_mode(
11666        &mut self,
11667        mode: language_settings::SoftWrap,
11668        cx: &mut ViewContext<Self>,
11669    ) {
11670        self.soft_wrap_mode_override = Some(mode);
11671        cx.notify();
11672    }
11673
11674    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11675        self.text_style_refinement = Some(style);
11676    }
11677
11678    /// called by the Element so we know what style we were most recently rendered with.
11679    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11680        let rem_size = cx.rem_size();
11681        self.display_map.update(cx, |map, cx| {
11682            map.set_font(
11683                style.text.font(),
11684                style.text.font_size.to_pixels(rem_size),
11685                cx,
11686            )
11687        });
11688        self.style = Some(style);
11689    }
11690
11691    pub fn style(&self) -> Option<&EditorStyle> {
11692        self.style.as_ref()
11693    }
11694
11695    // Called by the element. This method is not designed to be called outside of the editor
11696    // element's layout code because it does not notify when rewrapping is computed synchronously.
11697    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11698        self.display_map
11699            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11700    }
11701
11702    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11703        if self.soft_wrap_mode_override.is_some() {
11704            self.soft_wrap_mode_override.take();
11705        } else {
11706            let soft_wrap = match self.soft_wrap_mode(cx) {
11707                SoftWrap::GitDiff => return,
11708                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11709                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11710                    language_settings::SoftWrap::None
11711                }
11712            };
11713            self.soft_wrap_mode_override = Some(soft_wrap);
11714        }
11715        cx.notify();
11716    }
11717
11718    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11719        let Some(workspace) = self.workspace() else {
11720            return;
11721        };
11722        let fs = workspace.read(cx).app_state().fs.clone();
11723        let current_show = TabBarSettings::get_global(cx).show;
11724        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11725            setting.show = Some(!current_show);
11726        });
11727    }
11728
11729    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11730        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11731            self.buffer
11732                .read(cx)
11733                .settings_at(0, cx)
11734                .indent_guides
11735                .enabled
11736        });
11737        self.show_indent_guides = Some(!currently_enabled);
11738        cx.notify();
11739    }
11740
11741    fn should_show_indent_guides(&self) -> Option<bool> {
11742        self.show_indent_guides
11743    }
11744
11745    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11746        let mut editor_settings = EditorSettings::get_global(cx).clone();
11747        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11748        EditorSettings::override_global(editor_settings, cx);
11749    }
11750
11751    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11752        self.use_relative_line_numbers
11753            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11754    }
11755
11756    pub fn toggle_relative_line_numbers(
11757        &mut self,
11758        _: &ToggleRelativeLineNumbers,
11759        cx: &mut ViewContext<Self>,
11760    ) {
11761        let is_relative = self.should_use_relative_line_numbers(cx);
11762        self.set_relative_line_number(Some(!is_relative), cx)
11763    }
11764
11765    pub fn set_relative_line_number(
11766        &mut self,
11767        is_relative: Option<bool>,
11768        cx: &mut ViewContext<Self>,
11769    ) {
11770        self.use_relative_line_numbers = is_relative;
11771        cx.notify();
11772    }
11773
11774    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11775        self.show_gutter = show_gutter;
11776        cx.notify();
11777    }
11778
11779    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11780        self.show_line_numbers = Some(show_line_numbers);
11781        cx.notify();
11782    }
11783
11784    pub fn set_show_git_diff_gutter(
11785        &mut self,
11786        show_git_diff_gutter: bool,
11787        cx: &mut ViewContext<Self>,
11788    ) {
11789        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11790        cx.notify();
11791    }
11792
11793    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11794        self.show_code_actions = Some(show_code_actions);
11795        cx.notify();
11796    }
11797
11798    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11799        self.show_runnables = Some(show_runnables);
11800        cx.notify();
11801    }
11802
11803    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11804        if self.display_map.read(cx).masked != masked {
11805            self.display_map.update(cx, |map, _| map.masked = masked);
11806        }
11807        cx.notify()
11808    }
11809
11810    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11811        self.show_wrap_guides = Some(show_wrap_guides);
11812        cx.notify();
11813    }
11814
11815    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11816        self.show_indent_guides = Some(show_indent_guides);
11817        cx.notify();
11818    }
11819
11820    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11821        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11822            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11823                if let Some(dir) = file.abs_path(cx).parent() {
11824                    return Some(dir.to_owned());
11825                }
11826            }
11827
11828            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11829                return Some(project_path.path.to_path_buf());
11830            }
11831        }
11832
11833        None
11834    }
11835
11836    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11837        self.active_excerpt(cx)?
11838            .1
11839            .read(cx)
11840            .file()
11841            .and_then(|f| f.as_local())
11842    }
11843
11844    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11845        if let Some(target) = self.target_file(cx) {
11846            cx.reveal_path(&target.abs_path(cx));
11847        }
11848    }
11849
11850    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11851        if let Some(file) = self.target_file(cx) {
11852            if let Some(path) = file.abs_path(cx).to_str() {
11853                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11854            }
11855        }
11856    }
11857
11858    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11859        if let Some(file) = self.target_file(cx) {
11860            if let Some(path) = file.path().to_str() {
11861                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11862            }
11863        }
11864    }
11865
11866    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11867        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11868
11869        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11870            self.start_git_blame(true, cx);
11871        }
11872
11873        cx.notify();
11874    }
11875
11876    pub fn toggle_git_blame_inline(
11877        &mut self,
11878        _: &ToggleGitBlameInline,
11879        cx: &mut ViewContext<Self>,
11880    ) {
11881        self.toggle_git_blame_inline_internal(true, cx);
11882        cx.notify();
11883    }
11884
11885    pub fn git_blame_inline_enabled(&self) -> bool {
11886        self.git_blame_inline_enabled
11887    }
11888
11889    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11890        self.show_selection_menu = self
11891            .show_selection_menu
11892            .map(|show_selections_menu| !show_selections_menu)
11893            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11894
11895        cx.notify();
11896    }
11897
11898    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11899        self.show_selection_menu
11900            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11901    }
11902
11903    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11904        if let Some(project) = self.project.as_ref() {
11905            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11906                return;
11907            };
11908
11909            if buffer.read(cx).file().is_none() {
11910                return;
11911            }
11912
11913            let focused = self.focus_handle(cx).contains_focused(cx);
11914
11915            let project = project.clone();
11916            let blame =
11917                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11918            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11919            self.blame = Some(blame);
11920        }
11921    }
11922
11923    fn toggle_git_blame_inline_internal(
11924        &mut self,
11925        user_triggered: bool,
11926        cx: &mut ViewContext<Self>,
11927    ) {
11928        if self.git_blame_inline_enabled {
11929            self.git_blame_inline_enabled = false;
11930            self.show_git_blame_inline = false;
11931            self.show_git_blame_inline_delay_task.take();
11932        } else {
11933            self.git_blame_inline_enabled = true;
11934            self.start_git_blame_inline(user_triggered, cx);
11935        }
11936
11937        cx.notify();
11938    }
11939
11940    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11941        self.start_git_blame(user_triggered, cx);
11942
11943        if ProjectSettings::get_global(cx)
11944            .git
11945            .inline_blame_delay()
11946            .is_some()
11947        {
11948            self.start_inline_blame_timer(cx);
11949        } else {
11950            self.show_git_blame_inline = true
11951        }
11952    }
11953
11954    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11955        self.blame.as_ref()
11956    }
11957
11958    pub fn show_git_blame_gutter(&self) -> bool {
11959        self.show_git_blame_gutter
11960    }
11961
11962    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11963        self.show_git_blame_gutter && self.has_blame_entries(cx)
11964    }
11965
11966    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11967        self.show_git_blame_inline
11968            && self.focus_handle.is_focused(cx)
11969            && !self.newest_selection_head_on_empty_line(cx)
11970            && self.has_blame_entries(cx)
11971    }
11972
11973    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11974        self.blame()
11975            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11976    }
11977
11978    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11979        let cursor_anchor = self.selections.newest_anchor().head();
11980
11981        let snapshot = self.buffer.read(cx).snapshot(cx);
11982        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11983
11984        snapshot.line_len(buffer_row) == 0
11985    }
11986
11987    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11988        let buffer_and_selection = maybe!({
11989            let selection = self.selections.newest::<Point>(cx);
11990            let selection_range = selection.range();
11991
11992            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11993                (buffer, selection_range.start.row..selection_range.end.row)
11994            } else {
11995                let buffer_ranges = self
11996                    .buffer()
11997                    .read(cx)
11998                    .range_to_buffer_ranges(selection_range, cx);
11999
12000                let (buffer, range, _) = if selection.reversed {
12001                    buffer_ranges.first()
12002                } else {
12003                    buffer_ranges.last()
12004                }?;
12005
12006                let snapshot = buffer.read(cx).snapshot();
12007                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
12008                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
12009                (buffer.clone(), selection)
12010            };
12011
12012            Some((buffer, selection))
12013        });
12014
12015        let Some((buffer, selection)) = buffer_and_selection else {
12016            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12017        };
12018
12019        let Some(project) = self.project.as_ref() else {
12020            return Task::ready(Err(anyhow!("editor does not have project")));
12021        };
12022
12023        project.update(cx, |project, cx| {
12024            project.get_permalink_to_line(&buffer, selection, cx)
12025        })
12026    }
12027
12028    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
12029        let permalink_task = self.get_permalink_to_line(cx);
12030        let workspace = self.workspace();
12031
12032        cx.spawn(|_, mut cx| async move {
12033            match permalink_task.await {
12034                Ok(permalink) => {
12035                    cx.update(|cx| {
12036                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12037                    })
12038                    .ok();
12039                }
12040                Err(err) => {
12041                    let message = format!("Failed to copy permalink: {err}");
12042
12043                    Err::<(), anyhow::Error>(err).log_err();
12044
12045                    if let Some(workspace) = workspace {
12046                        workspace
12047                            .update(&mut cx, |workspace, cx| {
12048                                struct CopyPermalinkToLine;
12049
12050                                workspace.show_toast(
12051                                    Toast::new(
12052                                        NotificationId::unique::<CopyPermalinkToLine>(),
12053                                        message,
12054                                    ),
12055                                    cx,
12056                                )
12057                            })
12058                            .ok();
12059                    }
12060                }
12061            }
12062        })
12063        .detach();
12064    }
12065
12066    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
12067        let selection = self.selections.newest::<Point>(cx).start.row + 1;
12068        if let Some(file) = self.target_file(cx) {
12069            if let Some(path) = file.path().to_str() {
12070                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12071            }
12072        }
12073    }
12074
12075    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
12076        let permalink_task = self.get_permalink_to_line(cx);
12077        let workspace = self.workspace();
12078
12079        cx.spawn(|_, mut cx| async move {
12080            match permalink_task.await {
12081                Ok(permalink) => {
12082                    cx.update(|cx| {
12083                        cx.open_url(permalink.as_ref());
12084                    })
12085                    .ok();
12086                }
12087                Err(err) => {
12088                    let message = format!("Failed to open permalink: {err}");
12089
12090                    Err::<(), anyhow::Error>(err).log_err();
12091
12092                    if let Some(workspace) = workspace {
12093                        workspace
12094                            .update(&mut cx, |workspace, cx| {
12095                                struct OpenPermalinkToLine;
12096
12097                                workspace.show_toast(
12098                                    Toast::new(
12099                                        NotificationId::unique::<OpenPermalinkToLine>(),
12100                                        message,
12101                                    ),
12102                                    cx,
12103                                )
12104                            })
12105                            .ok();
12106                    }
12107                }
12108            }
12109        })
12110        .detach();
12111    }
12112
12113    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
12114        self.insert_uuid(UuidVersion::V4, cx);
12115    }
12116
12117    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
12118        self.insert_uuid(UuidVersion::V7, cx);
12119    }
12120
12121    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
12122        self.transact(cx, |this, cx| {
12123            let edits = this
12124                .selections
12125                .all::<Point>(cx)
12126                .into_iter()
12127                .map(|selection| {
12128                    let uuid = match version {
12129                        UuidVersion::V4 => uuid::Uuid::new_v4(),
12130                        UuidVersion::V7 => uuid::Uuid::now_v7(),
12131                    };
12132
12133                    (selection.range(), uuid.to_string())
12134                });
12135            this.edit(edits, cx);
12136            this.refresh_inline_completion(true, false, cx);
12137        });
12138    }
12139
12140    /// Adds a row highlight for the given range. If a row has multiple highlights, the
12141    /// last highlight added will be used.
12142    ///
12143    /// If the range ends at the beginning of a line, then that line will not be highlighted.
12144    pub fn highlight_rows<T: 'static>(
12145        &mut self,
12146        range: Range<Anchor>,
12147        color: Hsla,
12148        should_autoscroll: bool,
12149        cx: &mut ViewContext<Self>,
12150    ) {
12151        let snapshot = self.buffer().read(cx).snapshot(cx);
12152        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12153        let ix = row_highlights.binary_search_by(|highlight| {
12154            Ordering::Equal
12155                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12156                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12157        });
12158
12159        if let Err(mut ix) = ix {
12160            let index = post_inc(&mut self.highlight_order);
12161
12162            // If this range intersects with the preceding highlight, then merge it with
12163            // the preceding highlight. Otherwise insert a new highlight.
12164            let mut merged = false;
12165            if ix > 0 {
12166                let prev_highlight = &mut row_highlights[ix - 1];
12167                if prev_highlight
12168                    .range
12169                    .end
12170                    .cmp(&range.start, &snapshot)
12171                    .is_ge()
12172                {
12173                    ix -= 1;
12174                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12175                        prev_highlight.range.end = range.end;
12176                    }
12177                    merged = true;
12178                    prev_highlight.index = index;
12179                    prev_highlight.color = color;
12180                    prev_highlight.should_autoscroll = should_autoscroll;
12181                }
12182            }
12183
12184            if !merged {
12185                row_highlights.insert(
12186                    ix,
12187                    RowHighlight {
12188                        range: range.clone(),
12189                        index,
12190                        color,
12191                        should_autoscroll,
12192                    },
12193                );
12194            }
12195
12196            // If any of the following highlights intersect with this one, merge them.
12197            while let Some(next_highlight) = row_highlights.get(ix + 1) {
12198                let highlight = &row_highlights[ix];
12199                if next_highlight
12200                    .range
12201                    .start
12202                    .cmp(&highlight.range.end, &snapshot)
12203                    .is_le()
12204                {
12205                    if next_highlight
12206                        .range
12207                        .end
12208                        .cmp(&highlight.range.end, &snapshot)
12209                        .is_gt()
12210                    {
12211                        row_highlights[ix].range.end = next_highlight.range.end;
12212                    }
12213                    row_highlights.remove(ix + 1);
12214                } else {
12215                    break;
12216                }
12217            }
12218        }
12219    }
12220
12221    /// Remove any highlighted row ranges of the given type that intersect the
12222    /// given ranges.
12223    pub fn remove_highlighted_rows<T: 'static>(
12224        &mut self,
12225        ranges_to_remove: Vec<Range<Anchor>>,
12226        cx: &mut ViewContext<Self>,
12227    ) {
12228        let snapshot = self.buffer().read(cx).snapshot(cx);
12229        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12230        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12231        row_highlights.retain(|highlight| {
12232            while let Some(range_to_remove) = ranges_to_remove.peek() {
12233                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12234                    Ordering::Less | Ordering::Equal => {
12235                        ranges_to_remove.next();
12236                    }
12237                    Ordering::Greater => {
12238                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12239                            Ordering::Less | Ordering::Equal => {
12240                                return false;
12241                            }
12242                            Ordering::Greater => break,
12243                        }
12244                    }
12245                }
12246            }
12247
12248            true
12249        })
12250    }
12251
12252    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12253    pub fn clear_row_highlights<T: 'static>(&mut self) {
12254        self.highlighted_rows.remove(&TypeId::of::<T>());
12255    }
12256
12257    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12258    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12259        self.highlighted_rows
12260            .get(&TypeId::of::<T>())
12261            .map_or(&[] as &[_], |vec| vec.as_slice())
12262            .iter()
12263            .map(|highlight| (highlight.range.clone(), highlight.color))
12264    }
12265
12266    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12267    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
12268    /// Allows to ignore certain kinds of highlights.
12269    pub fn highlighted_display_rows(
12270        &mut self,
12271        cx: &mut WindowContext,
12272    ) -> BTreeMap<DisplayRow, Hsla> {
12273        let snapshot = self.snapshot(cx);
12274        let mut used_highlight_orders = HashMap::default();
12275        self.highlighted_rows
12276            .iter()
12277            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12278            .fold(
12279                BTreeMap::<DisplayRow, Hsla>::new(),
12280                |mut unique_rows, highlight| {
12281                    let start = highlight.range.start.to_display_point(&snapshot);
12282                    let end = highlight.range.end.to_display_point(&snapshot);
12283                    let start_row = start.row().0;
12284                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12285                        && end.column() == 0
12286                    {
12287                        end.row().0.saturating_sub(1)
12288                    } else {
12289                        end.row().0
12290                    };
12291                    for row in start_row..=end_row {
12292                        let used_index =
12293                            used_highlight_orders.entry(row).or_insert(highlight.index);
12294                        if highlight.index >= *used_index {
12295                            *used_index = highlight.index;
12296                            unique_rows.insert(DisplayRow(row), highlight.color);
12297                        }
12298                    }
12299                    unique_rows
12300                },
12301            )
12302    }
12303
12304    pub fn highlighted_display_row_for_autoscroll(
12305        &self,
12306        snapshot: &DisplaySnapshot,
12307    ) -> Option<DisplayRow> {
12308        self.highlighted_rows
12309            .values()
12310            .flat_map(|highlighted_rows| highlighted_rows.iter())
12311            .filter_map(|highlight| {
12312                if highlight.should_autoscroll {
12313                    Some(highlight.range.start.to_display_point(snapshot).row())
12314                } else {
12315                    None
12316                }
12317            })
12318            .min()
12319    }
12320
12321    pub fn set_search_within_ranges(
12322        &mut self,
12323        ranges: &[Range<Anchor>],
12324        cx: &mut ViewContext<Self>,
12325    ) {
12326        self.highlight_background::<SearchWithinRange>(
12327            ranges,
12328            |colors| colors.editor_document_highlight_read_background,
12329            cx,
12330        )
12331    }
12332
12333    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12334        self.breadcrumb_header = Some(new_header);
12335    }
12336
12337    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12338        self.clear_background_highlights::<SearchWithinRange>(cx);
12339    }
12340
12341    pub fn highlight_background<T: 'static>(
12342        &mut self,
12343        ranges: &[Range<Anchor>],
12344        color_fetcher: fn(&ThemeColors) -> Hsla,
12345        cx: &mut ViewContext<Self>,
12346    ) {
12347        self.background_highlights
12348            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12349        self.scrollbar_marker_state.dirty = true;
12350        cx.notify();
12351    }
12352
12353    pub fn clear_background_highlights<T: 'static>(
12354        &mut self,
12355        cx: &mut ViewContext<Self>,
12356    ) -> Option<BackgroundHighlight> {
12357        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12358        if !text_highlights.1.is_empty() {
12359            self.scrollbar_marker_state.dirty = true;
12360            cx.notify();
12361        }
12362        Some(text_highlights)
12363    }
12364
12365    pub fn highlight_gutter<T: 'static>(
12366        &mut self,
12367        ranges: &[Range<Anchor>],
12368        color_fetcher: fn(&AppContext) -> Hsla,
12369        cx: &mut ViewContext<Self>,
12370    ) {
12371        self.gutter_highlights
12372            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12373        cx.notify();
12374    }
12375
12376    pub fn clear_gutter_highlights<T: 'static>(
12377        &mut self,
12378        cx: &mut ViewContext<Self>,
12379    ) -> Option<GutterHighlight> {
12380        cx.notify();
12381        self.gutter_highlights.remove(&TypeId::of::<T>())
12382    }
12383
12384    #[cfg(feature = "test-support")]
12385    pub fn all_text_background_highlights(
12386        &mut self,
12387        cx: &mut ViewContext<Self>,
12388    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12389        let snapshot = self.snapshot(cx);
12390        let buffer = &snapshot.buffer_snapshot;
12391        let start = buffer.anchor_before(0);
12392        let end = buffer.anchor_after(buffer.len());
12393        let theme = cx.theme().colors();
12394        self.background_highlights_in_range(start..end, &snapshot, theme)
12395    }
12396
12397    #[cfg(feature = "test-support")]
12398    pub fn search_background_highlights(
12399        &mut self,
12400        cx: &mut ViewContext<Self>,
12401    ) -> Vec<Range<Point>> {
12402        let snapshot = self.buffer().read(cx).snapshot(cx);
12403
12404        let highlights = self
12405            .background_highlights
12406            .get(&TypeId::of::<items::BufferSearchHighlights>());
12407
12408        if let Some((_color, ranges)) = highlights {
12409            ranges
12410                .iter()
12411                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12412                .collect_vec()
12413        } else {
12414            vec![]
12415        }
12416    }
12417
12418    fn document_highlights_for_position<'a>(
12419        &'a self,
12420        position: Anchor,
12421        buffer: &'a MultiBufferSnapshot,
12422    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12423        let read_highlights = self
12424            .background_highlights
12425            .get(&TypeId::of::<DocumentHighlightRead>())
12426            .map(|h| &h.1);
12427        let write_highlights = self
12428            .background_highlights
12429            .get(&TypeId::of::<DocumentHighlightWrite>())
12430            .map(|h| &h.1);
12431        let left_position = position.bias_left(buffer);
12432        let right_position = position.bias_right(buffer);
12433        read_highlights
12434            .into_iter()
12435            .chain(write_highlights)
12436            .flat_map(move |ranges| {
12437                let start_ix = match ranges.binary_search_by(|probe| {
12438                    let cmp = probe.end.cmp(&left_position, buffer);
12439                    if cmp.is_ge() {
12440                        Ordering::Greater
12441                    } else {
12442                        Ordering::Less
12443                    }
12444                }) {
12445                    Ok(i) | Err(i) => i,
12446                };
12447
12448                ranges[start_ix..]
12449                    .iter()
12450                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12451            })
12452    }
12453
12454    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12455        self.background_highlights
12456            .get(&TypeId::of::<T>())
12457            .map_or(false, |(_, highlights)| !highlights.is_empty())
12458    }
12459
12460    pub fn background_highlights_in_range(
12461        &self,
12462        search_range: Range<Anchor>,
12463        display_snapshot: &DisplaySnapshot,
12464        theme: &ThemeColors,
12465    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12466        let mut results = Vec::new();
12467        for (color_fetcher, ranges) in self.background_highlights.values() {
12468            let color = color_fetcher(theme);
12469            let start_ix = match ranges.binary_search_by(|probe| {
12470                let cmp = probe
12471                    .end
12472                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12473                if cmp.is_gt() {
12474                    Ordering::Greater
12475                } else {
12476                    Ordering::Less
12477                }
12478            }) {
12479                Ok(i) | Err(i) => i,
12480            };
12481            for range in &ranges[start_ix..] {
12482                if range
12483                    .start
12484                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12485                    .is_ge()
12486                {
12487                    break;
12488                }
12489
12490                let start = range.start.to_display_point(display_snapshot);
12491                let end = range.end.to_display_point(display_snapshot);
12492                results.push((start..end, color))
12493            }
12494        }
12495        results
12496    }
12497
12498    pub fn background_highlight_row_ranges<T: 'static>(
12499        &self,
12500        search_range: Range<Anchor>,
12501        display_snapshot: &DisplaySnapshot,
12502        count: usize,
12503    ) -> Vec<RangeInclusive<DisplayPoint>> {
12504        let mut results = Vec::new();
12505        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12506            return vec![];
12507        };
12508
12509        let start_ix = match ranges.binary_search_by(|probe| {
12510            let cmp = probe
12511                .end
12512                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12513            if cmp.is_gt() {
12514                Ordering::Greater
12515            } else {
12516                Ordering::Less
12517            }
12518        }) {
12519            Ok(i) | Err(i) => i,
12520        };
12521        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12522            if let (Some(start_display), Some(end_display)) = (start, end) {
12523                results.push(
12524                    start_display.to_display_point(display_snapshot)
12525                        ..=end_display.to_display_point(display_snapshot),
12526                );
12527            }
12528        };
12529        let mut start_row: Option<Point> = None;
12530        let mut end_row: Option<Point> = None;
12531        if ranges.len() > count {
12532            return Vec::new();
12533        }
12534        for range in &ranges[start_ix..] {
12535            if range
12536                .start
12537                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12538                .is_ge()
12539            {
12540                break;
12541            }
12542            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12543            if let Some(current_row) = &end_row {
12544                if end.row == current_row.row {
12545                    continue;
12546                }
12547            }
12548            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12549            if start_row.is_none() {
12550                assert_eq!(end_row, None);
12551                start_row = Some(start);
12552                end_row = Some(end);
12553                continue;
12554            }
12555            if let Some(current_end) = end_row.as_mut() {
12556                if start.row > current_end.row + 1 {
12557                    push_region(start_row, end_row);
12558                    start_row = Some(start);
12559                    end_row = Some(end);
12560                } else {
12561                    // Merge two hunks.
12562                    *current_end = end;
12563                }
12564            } else {
12565                unreachable!();
12566            }
12567        }
12568        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12569        push_region(start_row, end_row);
12570        results
12571    }
12572
12573    pub fn gutter_highlights_in_range(
12574        &self,
12575        search_range: Range<Anchor>,
12576        display_snapshot: &DisplaySnapshot,
12577        cx: &AppContext,
12578    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12579        let mut results = Vec::new();
12580        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12581            let color = color_fetcher(cx);
12582            let start_ix = match ranges.binary_search_by(|probe| {
12583                let cmp = probe
12584                    .end
12585                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12586                if cmp.is_gt() {
12587                    Ordering::Greater
12588                } else {
12589                    Ordering::Less
12590                }
12591            }) {
12592                Ok(i) | Err(i) => i,
12593            };
12594            for range in &ranges[start_ix..] {
12595                if range
12596                    .start
12597                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12598                    .is_ge()
12599                {
12600                    break;
12601                }
12602
12603                let start = range.start.to_display_point(display_snapshot);
12604                let end = range.end.to_display_point(display_snapshot);
12605                results.push((start..end, color))
12606            }
12607        }
12608        results
12609    }
12610
12611    /// Get the text ranges corresponding to the redaction query
12612    pub fn redacted_ranges(
12613        &self,
12614        search_range: Range<Anchor>,
12615        display_snapshot: &DisplaySnapshot,
12616        cx: &WindowContext,
12617    ) -> Vec<Range<DisplayPoint>> {
12618        display_snapshot
12619            .buffer_snapshot
12620            .redacted_ranges(search_range, |file| {
12621                if let Some(file) = file {
12622                    file.is_private()
12623                        && EditorSettings::get(
12624                            Some(SettingsLocation {
12625                                worktree_id: file.worktree_id(cx),
12626                                path: file.path().as_ref(),
12627                            }),
12628                            cx,
12629                        )
12630                        .redact_private_values
12631                } else {
12632                    false
12633                }
12634            })
12635            .map(|range| {
12636                range.start.to_display_point(display_snapshot)
12637                    ..range.end.to_display_point(display_snapshot)
12638            })
12639            .collect()
12640    }
12641
12642    pub fn highlight_text<T: 'static>(
12643        &mut self,
12644        ranges: Vec<Range<Anchor>>,
12645        style: HighlightStyle,
12646        cx: &mut ViewContext<Self>,
12647    ) {
12648        self.display_map.update(cx, |map, _| {
12649            map.highlight_text(TypeId::of::<T>(), ranges, style)
12650        });
12651        cx.notify();
12652    }
12653
12654    pub(crate) fn highlight_inlays<T: 'static>(
12655        &mut self,
12656        highlights: Vec<InlayHighlight>,
12657        style: HighlightStyle,
12658        cx: &mut ViewContext<Self>,
12659    ) {
12660        self.display_map.update(cx, |map, _| {
12661            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12662        });
12663        cx.notify();
12664    }
12665
12666    pub fn text_highlights<'a, T: 'static>(
12667        &'a self,
12668        cx: &'a AppContext,
12669    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12670        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12671    }
12672
12673    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12674        let cleared = self
12675            .display_map
12676            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12677        if cleared {
12678            cx.notify();
12679        }
12680    }
12681
12682    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12683        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12684            && self.focus_handle.is_focused(cx)
12685    }
12686
12687    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12688        self.show_cursor_when_unfocused = is_enabled;
12689        cx.notify();
12690    }
12691
12692    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12693        cx.notify();
12694    }
12695
12696    fn on_buffer_event(
12697        &mut self,
12698        multibuffer: Model<MultiBuffer>,
12699        event: &multi_buffer::Event,
12700        cx: &mut ViewContext<Self>,
12701    ) {
12702        match event {
12703            multi_buffer::Event::Edited {
12704                singleton_buffer_edited,
12705            } => {
12706                self.scrollbar_marker_state.dirty = true;
12707                self.active_indent_guides_state.dirty = true;
12708                self.refresh_active_diagnostics(cx);
12709                self.refresh_code_actions(cx);
12710                if self.has_active_inline_completion() {
12711                    self.update_visible_inline_completion(cx);
12712                }
12713                cx.emit(EditorEvent::BufferEdited);
12714                cx.emit(SearchEvent::MatchesInvalidated);
12715                if *singleton_buffer_edited {
12716                    if let Some(project) = &self.project {
12717                        let project = project.read(cx);
12718                        #[allow(clippy::mutable_key_type)]
12719                        let languages_affected = multibuffer
12720                            .read(cx)
12721                            .all_buffers()
12722                            .into_iter()
12723                            .filter_map(|buffer| {
12724                                let buffer = buffer.read(cx);
12725                                let language = buffer.language()?;
12726                                if project.is_local()
12727                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
12728                                {
12729                                    None
12730                                } else {
12731                                    Some(language)
12732                                }
12733                            })
12734                            .cloned()
12735                            .collect::<HashSet<_>>();
12736                        if !languages_affected.is_empty() {
12737                            self.refresh_inlay_hints(
12738                                InlayHintRefreshReason::BufferEdited(languages_affected),
12739                                cx,
12740                            );
12741                        }
12742                    }
12743                }
12744
12745                let Some(project) = &self.project else { return };
12746                let (telemetry, is_via_ssh) = {
12747                    let project = project.read(cx);
12748                    let telemetry = project.client().telemetry().clone();
12749                    let is_via_ssh = project.is_via_ssh();
12750                    (telemetry, is_via_ssh)
12751                };
12752                refresh_linked_ranges(self, cx);
12753                telemetry.log_edit_event("editor", is_via_ssh);
12754            }
12755            multi_buffer::Event::ExcerptsAdded {
12756                buffer,
12757                predecessor,
12758                excerpts,
12759            } => {
12760                self.tasks_update_task = Some(self.refresh_runnables(cx));
12761                let buffer_id = buffer.read(cx).remote_id();
12762                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12763                    if let Some(project) = &self.project {
12764                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12765                    }
12766                }
12767                cx.emit(EditorEvent::ExcerptsAdded {
12768                    buffer: buffer.clone(),
12769                    predecessor: *predecessor,
12770                    excerpts: excerpts.clone(),
12771                });
12772                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12773            }
12774            multi_buffer::Event::ExcerptsRemoved { ids } => {
12775                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12776                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12777            }
12778            multi_buffer::Event::ExcerptsEdited { ids } => {
12779                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12780            }
12781            multi_buffer::Event::ExcerptsExpanded { ids } => {
12782                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12783            }
12784            multi_buffer::Event::Reparsed(buffer_id) => {
12785                self.tasks_update_task = Some(self.refresh_runnables(cx));
12786
12787                cx.emit(EditorEvent::Reparsed(*buffer_id));
12788            }
12789            multi_buffer::Event::LanguageChanged(buffer_id) => {
12790                linked_editing_ranges::refresh_linked_ranges(self, cx);
12791                cx.emit(EditorEvent::Reparsed(*buffer_id));
12792                cx.notify();
12793            }
12794            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12795            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12796            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12797                cx.emit(EditorEvent::TitleChanged)
12798            }
12799            // multi_buffer::Event::DiffBaseChanged => {
12800            //     self.scrollbar_marker_state.dirty = true;
12801            //     cx.emit(EditorEvent::DiffBaseChanged);
12802            //     cx.notify();
12803            // }
12804            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12805            multi_buffer::Event::DiagnosticsUpdated => {
12806                self.refresh_active_diagnostics(cx);
12807                self.scrollbar_marker_state.dirty = true;
12808                cx.notify();
12809            }
12810            _ => {}
12811        };
12812    }
12813
12814    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12815        cx.notify();
12816    }
12817
12818    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12819        self.tasks_update_task = Some(self.refresh_runnables(cx));
12820        self.refresh_inline_completion(true, false, cx);
12821        self.refresh_inlay_hints(
12822            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12823                self.selections.newest_anchor().head(),
12824                &self.buffer.read(cx).snapshot(cx),
12825                cx,
12826            )),
12827            cx,
12828        );
12829
12830        let old_cursor_shape = self.cursor_shape;
12831
12832        {
12833            let editor_settings = EditorSettings::get_global(cx);
12834            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12835            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12836            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12837        }
12838
12839        if old_cursor_shape != self.cursor_shape {
12840            cx.emit(EditorEvent::CursorShapeChanged);
12841        }
12842
12843        let project_settings = ProjectSettings::get_global(cx);
12844        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12845
12846        if self.mode == EditorMode::Full {
12847            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12848            if self.git_blame_inline_enabled != inline_blame_enabled {
12849                self.toggle_git_blame_inline_internal(false, cx);
12850            }
12851        }
12852
12853        cx.notify();
12854    }
12855
12856    pub fn set_searchable(&mut self, searchable: bool) {
12857        self.searchable = searchable;
12858    }
12859
12860    pub fn searchable(&self) -> bool {
12861        self.searchable
12862    }
12863
12864    fn open_proposed_changes_editor(
12865        &mut self,
12866        _: &OpenProposedChangesEditor,
12867        cx: &mut ViewContext<Self>,
12868    ) {
12869        let Some(workspace) = self.workspace() else {
12870            cx.propagate();
12871            return;
12872        };
12873
12874        let selections = self.selections.all::<usize>(cx);
12875        let buffer = self.buffer.read(cx);
12876        let mut new_selections_by_buffer = HashMap::default();
12877        for selection in selections {
12878            for (buffer, range, _) in
12879                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12880            {
12881                let mut range = range.to_point(buffer.read(cx));
12882                range.start.column = 0;
12883                range.end.column = buffer.read(cx).line_len(range.end.row);
12884                new_selections_by_buffer
12885                    .entry(buffer)
12886                    .or_insert(Vec::new())
12887                    .push(range)
12888            }
12889        }
12890
12891        let proposed_changes_buffers = new_selections_by_buffer
12892            .into_iter()
12893            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12894            .collect::<Vec<_>>();
12895        let proposed_changes_editor = cx.new_view(|cx| {
12896            ProposedChangesEditor::new(
12897                "Proposed changes",
12898                proposed_changes_buffers,
12899                self.project.clone(),
12900                cx,
12901            )
12902        });
12903
12904        cx.window_context().defer(move |cx| {
12905            workspace.update(cx, |workspace, cx| {
12906                workspace.active_pane().update(cx, |pane, cx| {
12907                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12908                });
12909            });
12910        });
12911    }
12912
12913    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12914        self.open_excerpts_common(None, true, cx)
12915    }
12916
12917    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12918        self.open_excerpts_common(None, false, cx)
12919    }
12920
12921    fn open_excerpts_common(
12922        &mut self,
12923        jump_data: Option<JumpData>,
12924        split: bool,
12925        cx: &mut ViewContext<Self>,
12926    ) {
12927        let Some(workspace) = self.workspace() else {
12928            cx.propagate();
12929            return;
12930        };
12931
12932        if self.buffer.read(cx).is_singleton() {
12933            cx.propagate();
12934            return;
12935        }
12936
12937        let mut new_selections_by_buffer = HashMap::default();
12938        match &jump_data {
12939            Some(jump_data) => {
12940                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12941                if let Some(buffer) = multi_buffer_snapshot
12942                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12943                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12944                {
12945                    let buffer_snapshot = buffer.read(cx).snapshot();
12946                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12947                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12948                    } else {
12949                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12950                    };
12951                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12952                    new_selections_by_buffer.insert(
12953                        buffer,
12954                        (
12955                            vec![jump_to_offset..jump_to_offset],
12956                            Some(jump_data.line_offset_from_top),
12957                        ),
12958                    );
12959                }
12960            }
12961            None => {
12962                let selections = self.selections.all::<usize>(cx);
12963                let buffer = self.buffer.read(cx);
12964                for selection in selections {
12965                    for (mut buffer_handle, mut range, _) in
12966                        buffer.range_to_buffer_ranges(selection.range(), cx)
12967                    {
12968                        // When editing branch buffers, jump to the corresponding location
12969                        // in their base buffer.
12970                        let buffer = buffer_handle.read(cx);
12971                        if let Some(base_buffer) = buffer.base_buffer() {
12972                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12973                            buffer_handle = base_buffer;
12974                        }
12975
12976                        if selection.reversed {
12977                            mem::swap(&mut range.start, &mut range.end);
12978                        }
12979                        new_selections_by_buffer
12980                            .entry(buffer_handle)
12981                            .or_insert((Vec::new(), None))
12982                            .0
12983                            .push(range)
12984                    }
12985                }
12986            }
12987        }
12988
12989        if new_selections_by_buffer.is_empty() {
12990            return;
12991        }
12992
12993        // We defer the pane interaction because we ourselves are a workspace item
12994        // and activating a new item causes the pane to call a method on us reentrantly,
12995        // which panics if we're on the stack.
12996        cx.window_context().defer(move |cx| {
12997            workspace.update(cx, |workspace, cx| {
12998                let pane = if split {
12999                    workspace.adjacent_pane(cx)
13000                } else {
13001                    workspace.active_pane().clone()
13002                };
13003
13004                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
13005                    let editor = buffer
13006                        .read(cx)
13007                        .file()
13008                        .is_none()
13009                        .then(|| {
13010                            // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
13011                            // so `workspace.open_project_item` will never find them, always opening a new editor.
13012                            // Instead, we try to activate the existing editor in the pane first.
13013                            let (editor, pane_item_index) =
13014                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
13015                                    let editor = item.downcast::<Editor>()?;
13016                                    let singleton_buffer =
13017                                        editor.read(cx).buffer().read(cx).as_singleton()?;
13018                                    if singleton_buffer == buffer {
13019                                        Some((editor, i))
13020                                    } else {
13021                                        None
13022                                    }
13023                                })?;
13024                            pane.update(cx, |pane, cx| {
13025                                pane.activate_item(pane_item_index, true, true, cx)
13026                            });
13027                            Some(editor)
13028                        })
13029                        .flatten()
13030                        .unwrap_or_else(|| {
13031                            workspace.open_project_item::<Self>(
13032                                pane.clone(),
13033                                buffer,
13034                                true,
13035                                true,
13036                                cx,
13037                            )
13038                        });
13039
13040                    editor.update(cx, |editor, cx| {
13041                        let autoscroll = match scroll_offset {
13042                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
13043                            None => Autoscroll::newest(),
13044                        };
13045                        let nav_history = editor.nav_history.take();
13046                        editor.change_selections(Some(autoscroll), cx, |s| {
13047                            s.select_ranges(ranges);
13048                        });
13049                        editor.nav_history = nav_history;
13050                    });
13051                }
13052            })
13053        });
13054    }
13055
13056    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
13057        let snapshot = self.buffer.read(cx).read(cx);
13058        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
13059        Some(
13060            ranges
13061                .iter()
13062                .map(move |range| {
13063                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
13064                })
13065                .collect(),
13066        )
13067    }
13068
13069    fn selection_replacement_ranges(
13070        &self,
13071        range: Range<OffsetUtf16>,
13072        cx: &mut AppContext,
13073    ) -> Vec<Range<OffsetUtf16>> {
13074        let selections = self.selections.all::<OffsetUtf16>(cx);
13075        let newest_selection = selections
13076            .iter()
13077            .max_by_key(|selection| selection.id)
13078            .unwrap();
13079        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
13080        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
13081        let snapshot = self.buffer.read(cx).read(cx);
13082        selections
13083            .into_iter()
13084            .map(|mut selection| {
13085                selection.start.0 =
13086                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
13087                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
13088                snapshot.clip_offset_utf16(selection.start, Bias::Left)
13089                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
13090            })
13091            .collect()
13092    }
13093
13094    fn report_editor_event(
13095        &self,
13096        operation: &'static str,
13097        file_extension: Option<String>,
13098        cx: &AppContext,
13099    ) {
13100        if cfg!(any(test, feature = "test-support")) {
13101            return;
13102        }
13103
13104        let Some(project) = &self.project else { return };
13105
13106        // If None, we are in a file without an extension
13107        let file = self
13108            .buffer
13109            .read(cx)
13110            .as_singleton()
13111            .and_then(|b| b.read(cx).file());
13112        let file_extension = file_extension.or(file
13113            .as_ref()
13114            .and_then(|file| Path::new(file.file_name(cx)).extension())
13115            .and_then(|e| e.to_str())
13116            .map(|a| a.to_string()));
13117
13118        let vim_mode = cx
13119            .global::<SettingsStore>()
13120            .raw_user_settings()
13121            .get("vim_mode")
13122            == Some(&serde_json::Value::Bool(true));
13123
13124        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
13125            == language::language_settings::InlineCompletionProvider::Copilot;
13126        let copilot_enabled_for_language = self
13127            .buffer
13128            .read(cx)
13129            .settings_at(0, cx)
13130            .show_inline_completions;
13131
13132        let project = project.read(cx);
13133        let telemetry = project.client().telemetry().clone();
13134        telemetry.report_editor_event(
13135            file_extension,
13136            vim_mode,
13137            operation,
13138            copilot_enabled,
13139            copilot_enabled_for_language,
13140            project.is_via_ssh(),
13141        )
13142    }
13143
13144    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
13145    /// with each line being an array of {text, highlight} objects.
13146    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
13147        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
13148            return;
13149        };
13150
13151        #[derive(Serialize)]
13152        struct Chunk<'a> {
13153            text: String,
13154            highlight: Option<&'a str>,
13155        }
13156
13157        let snapshot = buffer.read(cx).snapshot();
13158        let range = self
13159            .selected_text_range(false, cx)
13160            .and_then(|selection| {
13161                if selection.range.is_empty() {
13162                    None
13163                } else {
13164                    Some(selection.range)
13165                }
13166            })
13167            .unwrap_or_else(|| 0..snapshot.len());
13168
13169        let chunks = snapshot.chunks(range, true);
13170        let mut lines = Vec::new();
13171        let mut line: VecDeque<Chunk> = VecDeque::new();
13172
13173        let Some(style) = self.style.as_ref() else {
13174            return;
13175        };
13176
13177        for chunk in chunks {
13178            let highlight = chunk
13179                .syntax_highlight_id
13180                .and_then(|id| id.name(&style.syntax));
13181            let mut chunk_lines = chunk.text.split('\n').peekable();
13182            while let Some(text) = chunk_lines.next() {
13183                let mut merged_with_last_token = false;
13184                if let Some(last_token) = line.back_mut() {
13185                    if last_token.highlight == highlight {
13186                        last_token.text.push_str(text);
13187                        merged_with_last_token = true;
13188                    }
13189                }
13190
13191                if !merged_with_last_token {
13192                    line.push_back(Chunk {
13193                        text: text.into(),
13194                        highlight,
13195                    });
13196                }
13197
13198                if chunk_lines.peek().is_some() {
13199                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
13200                        line.pop_front();
13201                    }
13202                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
13203                        line.pop_back();
13204                    }
13205
13206                    lines.push(mem::take(&mut line));
13207                }
13208            }
13209        }
13210
13211        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13212            return;
13213        };
13214        cx.write_to_clipboard(ClipboardItem::new_string(lines));
13215    }
13216
13217    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
13218        self.request_autoscroll(Autoscroll::newest(), cx);
13219        let position = self.selections.newest_display(cx).start;
13220        mouse_context_menu::deploy_context_menu(self, None, position, cx);
13221    }
13222
13223    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13224        &self.inlay_hint_cache
13225    }
13226
13227    pub fn replay_insert_event(
13228        &mut self,
13229        text: &str,
13230        relative_utf16_range: Option<Range<isize>>,
13231        cx: &mut ViewContext<Self>,
13232    ) {
13233        if !self.input_enabled {
13234            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13235            return;
13236        }
13237        if let Some(relative_utf16_range) = relative_utf16_range {
13238            let selections = self.selections.all::<OffsetUtf16>(cx);
13239            self.change_selections(None, cx, |s| {
13240                let new_ranges = selections.into_iter().map(|range| {
13241                    let start = OffsetUtf16(
13242                        range
13243                            .head()
13244                            .0
13245                            .saturating_add_signed(relative_utf16_range.start),
13246                    );
13247                    let end = OffsetUtf16(
13248                        range
13249                            .head()
13250                            .0
13251                            .saturating_add_signed(relative_utf16_range.end),
13252                    );
13253                    start..end
13254                });
13255                s.select_ranges(new_ranges);
13256            });
13257        }
13258
13259        self.handle_input(text, cx);
13260    }
13261
13262    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13263        let Some(provider) = self.semantics_provider.as_ref() else {
13264            return false;
13265        };
13266
13267        let mut supports = false;
13268        self.buffer().read(cx).for_each_buffer(|buffer| {
13269            supports |= provider.supports_inlay_hints(buffer, cx);
13270        });
13271        supports
13272    }
13273
13274    pub fn focus(&self, cx: &mut WindowContext) {
13275        cx.focus(&self.focus_handle)
13276    }
13277
13278    pub fn is_focused(&self, cx: &WindowContext) -> bool {
13279        self.focus_handle.is_focused(cx)
13280    }
13281
13282    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13283        cx.emit(EditorEvent::Focused);
13284
13285        if let Some(descendant) = self
13286            .last_focused_descendant
13287            .take()
13288            .and_then(|descendant| descendant.upgrade())
13289        {
13290            cx.focus(&descendant);
13291        } else {
13292            if let Some(blame) = self.blame.as_ref() {
13293                blame.update(cx, GitBlame::focus)
13294            }
13295
13296            self.blink_manager.update(cx, BlinkManager::enable);
13297            self.show_cursor_names(cx);
13298            self.buffer.update(cx, |buffer, cx| {
13299                buffer.finalize_last_transaction(cx);
13300                if self.leader_peer_id.is_none() {
13301                    buffer.set_active_selections(
13302                        &self.selections.disjoint_anchors(),
13303                        self.selections.line_mode,
13304                        self.cursor_shape,
13305                        cx,
13306                    );
13307                }
13308            });
13309        }
13310    }
13311
13312    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13313        cx.emit(EditorEvent::FocusedIn)
13314    }
13315
13316    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13317        if event.blurred != self.focus_handle {
13318            self.last_focused_descendant = Some(event.blurred);
13319        }
13320    }
13321
13322    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13323        self.blink_manager.update(cx, BlinkManager::disable);
13324        self.buffer
13325            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13326
13327        if let Some(blame) = self.blame.as_ref() {
13328            blame.update(cx, GitBlame::blur)
13329        }
13330        if !self.hover_state.focused(cx) {
13331            hide_hover(self, cx);
13332        }
13333
13334        self.hide_context_menu(cx);
13335        cx.emit(EditorEvent::Blurred);
13336        cx.notify();
13337    }
13338
13339    pub fn register_action<A: Action>(
13340        &mut self,
13341        listener: impl Fn(&A, &mut WindowContext) + 'static,
13342    ) -> Subscription {
13343        let id = self.next_editor_action_id.post_inc();
13344        let listener = Arc::new(listener);
13345        self.editor_actions.borrow_mut().insert(
13346            id,
13347            Box::new(move |cx| {
13348                let cx = cx.window_context();
13349                let listener = listener.clone();
13350                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13351                    let action = action.downcast_ref().unwrap();
13352                    if phase == DispatchPhase::Bubble {
13353                        listener(action, cx)
13354                    }
13355                })
13356            }),
13357        );
13358
13359        let editor_actions = self.editor_actions.clone();
13360        Subscription::new(move || {
13361            editor_actions.borrow_mut().remove(&id);
13362        })
13363    }
13364
13365    pub fn file_header_size(&self) -> u32 {
13366        FILE_HEADER_HEIGHT
13367    }
13368
13369    pub fn revert(
13370        &mut self,
13371        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13372        cx: &mut ViewContext<Self>,
13373    ) {
13374        self.buffer().update(cx, |multi_buffer, cx| {
13375            for (buffer_id, changes) in revert_changes {
13376                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13377                    buffer.update(cx, |buffer, cx| {
13378                        buffer.edit(
13379                            changes.into_iter().map(|(range, text)| {
13380                                (range, text.to_string().map(Arc::<str>::from))
13381                            }),
13382                            None,
13383                            cx,
13384                        );
13385                    });
13386                }
13387            }
13388        });
13389        self.change_selections(None, cx, |selections| selections.refresh());
13390    }
13391
13392    pub fn to_pixel_point(
13393        &mut self,
13394        source: multi_buffer::Anchor,
13395        editor_snapshot: &EditorSnapshot,
13396        cx: &mut ViewContext<Self>,
13397    ) -> Option<gpui::Point<Pixels>> {
13398        let source_point = source.to_display_point(editor_snapshot);
13399        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13400    }
13401
13402    pub fn display_to_pixel_point(
13403        &self,
13404        source: DisplayPoint,
13405        editor_snapshot: &EditorSnapshot,
13406        cx: &WindowContext,
13407    ) -> Option<gpui::Point<Pixels>> {
13408        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13409        let text_layout_details = self.text_layout_details(cx);
13410        let scroll_top = text_layout_details
13411            .scroll_anchor
13412            .scroll_position(editor_snapshot)
13413            .y;
13414
13415        if source.row().as_f32() < scroll_top.floor() {
13416            return None;
13417        }
13418        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13419        let source_y = line_height * (source.row().as_f32() - scroll_top);
13420        Some(gpui::Point::new(source_x, source_y))
13421    }
13422
13423    pub fn has_active_completions_menu(&self) -> bool {
13424        self.context_menu.read().as_ref().map_or(false, |menu| {
13425            menu.visible() && matches!(menu, ContextMenu::Completions(_))
13426        })
13427    }
13428
13429    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13430        self.addons
13431            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13432    }
13433
13434    pub fn unregister_addon<T: Addon>(&mut self) {
13435        self.addons.remove(&std::any::TypeId::of::<T>());
13436    }
13437
13438    pub fn addon<T: Addon>(&self) -> Option<&T> {
13439        let type_id = std::any::TypeId::of::<T>();
13440        self.addons
13441            .get(&type_id)
13442            .and_then(|item| item.to_any().downcast_ref::<T>())
13443    }
13444
13445    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13446        let text_layout_details = self.text_layout_details(cx);
13447        let style = &text_layout_details.editor_style;
13448        let font_id = cx.text_system().resolve_font(&style.text.font());
13449        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13450        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13451
13452        let em_width = cx
13453            .text_system()
13454            .typographic_bounds(font_id, font_size, 'm')
13455            .unwrap()
13456            .size
13457            .width;
13458
13459        gpui::Point::new(em_width, line_height)
13460    }
13461}
13462
13463fn get_unstaged_changes_for_buffers(
13464    project: &Model<Project>,
13465    buffers: impl IntoIterator<Item = Model<Buffer>>,
13466    cx: &mut ViewContext<Editor>,
13467) {
13468    let mut tasks = Vec::new();
13469    project.update(cx, |project, cx| {
13470        for buffer in buffers {
13471            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13472        }
13473    });
13474    cx.spawn(|this, mut cx| async move {
13475        let change_sets = futures::future::join_all(tasks).await;
13476        this.update(&mut cx, |this, cx| {
13477            for change_set in change_sets {
13478                if let Some(change_set) = change_set.log_err() {
13479                    this.diff_map.add_change_set(change_set, cx);
13480                }
13481            }
13482        })
13483        .ok();
13484    })
13485    .detach();
13486}
13487
13488fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13489    let tab_size = tab_size.get() as usize;
13490    let mut width = offset;
13491
13492    for ch in text.chars() {
13493        width += if ch == '\t' {
13494            tab_size - (width % tab_size)
13495        } else {
13496            1
13497        };
13498    }
13499
13500    width - offset
13501}
13502
13503#[cfg(test)]
13504mod tests {
13505    use super::*;
13506
13507    #[test]
13508    fn test_string_size_with_expanded_tabs() {
13509        let nz = |val| NonZeroU32::new(val).unwrap();
13510        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13511        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13512        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13513        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13514        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13515        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13516        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13517        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13518    }
13519}
13520
13521/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13522struct WordBreakingTokenizer<'a> {
13523    input: &'a str,
13524}
13525
13526impl<'a> WordBreakingTokenizer<'a> {
13527    fn new(input: &'a str) -> Self {
13528        Self { input }
13529    }
13530}
13531
13532fn is_char_ideographic(ch: char) -> bool {
13533    use unicode_script::Script::*;
13534    use unicode_script::UnicodeScript;
13535    matches!(ch.script(), Han | Tangut | Yi)
13536}
13537
13538fn is_grapheme_ideographic(text: &str) -> bool {
13539    text.chars().any(is_char_ideographic)
13540}
13541
13542fn is_grapheme_whitespace(text: &str) -> bool {
13543    text.chars().any(|x| x.is_whitespace())
13544}
13545
13546fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13547    text.chars().next().map_or(false, |ch| {
13548        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13549    })
13550}
13551
13552#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13553struct WordBreakToken<'a> {
13554    token: &'a str,
13555    grapheme_len: usize,
13556    is_whitespace: bool,
13557}
13558
13559impl<'a> Iterator for WordBreakingTokenizer<'a> {
13560    /// Yields a span, the count of graphemes in the token, and whether it was
13561    /// whitespace. Note that it also breaks at word boundaries.
13562    type Item = WordBreakToken<'a>;
13563
13564    fn next(&mut self) -> Option<Self::Item> {
13565        use unicode_segmentation::UnicodeSegmentation;
13566        if self.input.is_empty() {
13567            return None;
13568        }
13569
13570        let mut iter = self.input.graphemes(true).peekable();
13571        let mut offset = 0;
13572        let mut graphemes = 0;
13573        if let Some(first_grapheme) = iter.next() {
13574            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13575            offset += first_grapheme.len();
13576            graphemes += 1;
13577            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13578                if let Some(grapheme) = iter.peek().copied() {
13579                    if should_stay_with_preceding_ideograph(grapheme) {
13580                        offset += grapheme.len();
13581                        graphemes += 1;
13582                    }
13583                }
13584            } else {
13585                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13586                let mut next_word_bound = words.peek().copied();
13587                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13588                    next_word_bound = words.next();
13589                }
13590                while let Some(grapheme) = iter.peek().copied() {
13591                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13592                        break;
13593                    };
13594                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13595                        break;
13596                    };
13597                    offset += grapheme.len();
13598                    graphemes += 1;
13599                    iter.next();
13600                }
13601            }
13602            let token = &self.input[..offset];
13603            self.input = &self.input[offset..];
13604            if is_whitespace {
13605                Some(WordBreakToken {
13606                    token: " ",
13607                    grapheme_len: 1,
13608                    is_whitespace: true,
13609                })
13610            } else {
13611                Some(WordBreakToken {
13612                    token,
13613                    grapheme_len: graphemes,
13614                    is_whitespace: false,
13615                })
13616            }
13617        } else {
13618            None
13619        }
13620    }
13621}
13622
13623#[test]
13624fn test_word_breaking_tokenizer() {
13625    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13626        ("", &[]),
13627        ("  ", &[(" ", 1, true)]),
13628        ("Ʒ", &[("Ʒ", 1, false)]),
13629        ("Ǽ", &[("Ǽ", 1, false)]),
13630        ("", &[("", 1, false)]),
13631        ("⋑⋑", &[("⋑⋑", 2, false)]),
13632        (
13633            "原理,进而",
13634            &[
13635                ("", 1, false),
13636                ("理,", 2, false),
13637                ("", 1, false),
13638                ("", 1, false),
13639            ],
13640        ),
13641        (
13642            "hello world",
13643            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13644        ),
13645        (
13646            "hello, world",
13647            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13648        ),
13649        (
13650            "  hello world",
13651            &[
13652                (" ", 1, true),
13653                ("hello", 5, false),
13654                (" ", 1, true),
13655                ("world", 5, false),
13656            ],
13657        ),
13658        (
13659            "这是什么 \n 钢笔",
13660            &[
13661                ("", 1, false),
13662                ("", 1, false),
13663                ("", 1, false),
13664                ("", 1, false),
13665                (" ", 1, true),
13666                ("", 1, false),
13667                ("", 1, false),
13668            ],
13669        ),
13670        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13671    ];
13672
13673    for (input, result) in tests {
13674        assert_eq!(
13675            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13676            result
13677                .iter()
13678                .copied()
13679                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13680                    token,
13681                    grapheme_len,
13682                    is_whitespace,
13683                })
13684                .collect::<Vec<_>>()
13685        );
13686    }
13687}
13688
13689fn wrap_with_prefix(
13690    line_prefix: String,
13691    unwrapped_text: String,
13692    wrap_column: usize,
13693    tab_size: NonZeroU32,
13694) -> String {
13695    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13696    let mut wrapped_text = String::new();
13697    let mut current_line = line_prefix.clone();
13698
13699    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13700    let mut current_line_len = line_prefix_len;
13701    for WordBreakToken {
13702        token,
13703        grapheme_len,
13704        is_whitespace,
13705    } in tokenizer
13706    {
13707        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13708            wrapped_text.push_str(current_line.trim_end());
13709            wrapped_text.push('\n');
13710            current_line.truncate(line_prefix.len());
13711            current_line_len = line_prefix_len;
13712            if !is_whitespace {
13713                current_line.push_str(token);
13714                current_line_len += grapheme_len;
13715            }
13716        } else if !is_whitespace {
13717            current_line.push_str(token);
13718            current_line_len += grapheme_len;
13719        } else if current_line_len != line_prefix_len {
13720            current_line.push(' ');
13721            current_line_len += 1;
13722        }
13723    }
13724
13725    if !current_line.is_empty() {
13726        wrapped_text.push_str(&current_line);
13727    }
13728    wrapped_text
13729}
13730
13731#[test]
13732fn test_wrap_with_prefix() {
13733    assert_eq!(
13734        wrap_with_prefix(
13735            "# ".to_string(),
13736            "abcdefg".to_string(),
13737            4,
13738            NonZeroU32::new(4).unwrap()
13739        ),
13740        "# abcdefg"
13741    );
13742    assert_eq!(
13743        wrap_with_prefix(
13744            "".to_string(),
13745            "\thello world".to_string(),
13746            8,
13747            NonZeroU32::new(4).unwrap()
13748        ),
13749        "hello\nworld"
13750    );
13751    assert_eq!(
13752        wrap_with_prefix(
13753            "// ".to_string(),
13754            "xx \nyy zz aa bb cc".to_string(),
13755            12,
13756            NonZeroU32::new(4).unwrap()
13757        ),
13758        "// xx yy zz\n// aa bb cc"
13759    );
13760    assert_eq!(
13761        wrap_with_prefix(
13762            String::new(),
13763            "这是什么 \n 钢笔".to_string(),
13764            3,
13765            NonZeroU32::new(4).unwrap()
13766        ),
13767        "这是什\n么 钢\n"
13768    );
13769}
13770
13771fn hunks_for_selections(
13772    snapshot: &EditorSnapshot,
13773    selections: &[Selection<Point>],
13774) -> Vec<MultiBufferDiffHunk> {
13775    hunks_for_ranges(
13776        selections.iter().map(|selection| selection.range()),
13777        snapshot,
13778    )
13779}
13780
13781pub fn hunks_for_ranges(
13782    ranges: impl Iterator<Item = Range<Point>>,
13783    snapshot: &EditorSnapshot,
13784) -> Vec<MultiBufferDiffHunk> {
13785    let mut hunks = Vec::new();
13786    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13787        HashMap::default();
13788    for query_range in ranges {
13789        let query_rows =
13790            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13791        for hunk in snapshot.diff_map.diff_hunks_in_range(
13792            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13793            &snapshot.buffer_snapshot,
13794        ) {
13795            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13796            // when the caret is just above or just below the deleted hunk.
13797            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13798            let related_to_selection = if allow_adjacent {
13799                hunk.row_range.overlaps(&query_rows)
13800                    || hunk.row_range.start == query_rows.end
13801                    || hunk.row_range.end == query_rows.start
13802            } else {
13803                hunk.row_range.overlaps(&query_rows)
13804            };
13805            if related_to_selection {
13806                if !processed_buffer_rows
13807                    .entry(hunk.buffer_id)
13808                    .or_default()
13809                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13810                {
13811                    continue;
13812                }
13813                hunks.push(hunk);
13814            }
13815        }
13816    }
13817
13818    hunks
13819}
13820
13821pub trait CollaborationHub {
13822    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13823    fn user_participant_indices<'a>(
13824        &self,
13825        cx: &'a AppContext,
13826    ) -> &'a HashMap<u64, ParticipantIndex>;
13827    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13828}
13829
13830impl CollaborationHub for Model<Project> {
13831    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13832        self.read(cx).collaborators()
13833    }
13834
13835    fn user_participant_indices<'a>(
13836        &self,
13837        cx: &'a AppContext,
13838    ) -> &'a HashMap<u64, ParticipantIndex> {
13839        self.read(cx).user_store().read(cx).participant_indices()
13840    }
13841
13842    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13843        let this = self.read(cx);
13844        let user_ids = this.collaborators().values().map(|c| c.user_id);
13845        this.user_store().read_with(cx, |user_store, cx| {
13846            user_store.participant_names(user_ids, cx)
13847        })
13848    }
13849}
13850
13851pub trait SemanticsProvider {
13852    fn hover(
13853        &self,
13854        buffer: &Model<Buffer>,
13855        position: text::Anchor,
13856        cx: &mut AppContext,
13857    ) -> Option<Task<Vec<project::Hover>>>;
13858
13859    fn inlay_hints(
13860        &self,
13861        buffer_handle: Model<Buffer>,
13862        range: Range<text::Anchor>,
13863        cx: &mut AppContext,
13864    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13865
13866    fn resolve_inlay_hint(
13867        &self,
13868        hint: InlayHint,
13869        buffer_handle: Model<Buffer>,
13870        server_id: LanguageServerId,
13871        cx: &mut AppContext,
13872    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13873
13874    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13875
13876    fn document_highlights(
13877        &self,
13878        buffer: &Model<Buffer>,
13879        position: text::Anchor,
13880        cx: &mut AppContext,
13881    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13882
13883    fn definitions(
13884        &self,
13885        buffer: &Model<Buffer>,
13886        position: text::Anchor,
13887        kind: GotoDefinitionKind,
13888        cx: &mut AppContext,
13889    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13890
13891    fn range_for_rename(
13892        &self,
13893        buffer: &Model<Buffer>,
13894        position: text::Anchor,
13895        cx: &mut AppContext,
13896    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13897
13898    fn perform_rename(
13899        &self,
13900        buffer: &Model<Buffer>,
13901        position: text::Anchor,
13902        new_name: String,
13903        cx: &mut AppContext,
13904    ) -> Option<Task<Result<ProjectTransaction>>>;
13905}
13906
13907pub trait CompletionProvider {
13908    fn completions(
13909        &self,
13910        buffer: &Model<Buffer>,
13911        buffer_position: text::Anchor,
13912        trigger: CompletionContext,
13913        cx: &mut ViewContext<Editor>,
13914    ) -> Task<Result<Vec<Completion>>>;
13915
13916    fn resolve_completions(
13917        &self,
13918        buffer: Model<Buffer>,
13919        completion_indices: Vec<usize>,
13920        completions: Arc<RwLock<Box<[Completion]>>>,
13921        cx: &mut ViewContext<Editor>,
13922    ) -> Task<Result<bool>>;
13923
13924    fn apply_additional_edits_for_completion(
13925        &self,
13926        buffer: Model<Buffer>,
13927        completion: Completion,
13928        push_to_history: bool,
13929        cx: &mut ViewContext<Editor>,
13930    ) -> Task<Result<Option<language::Transaction>>>;
13931
13932    fn is_completion_trigger(
13933        &self,
13934        buffer: &Model<Buffer>,
13935        position: language::Anchor,
13936        text: &str,
13937        trigger_in_words: bool,
13938        cx: &mut ViewContext<Editor>,
13939    ) -> bool;
13940
13941    fn sort_completions(&self) -> bool {
13942        true
13943    }
13944}
13945
13946pub trait CodeActionProvider {
13947    fn code_actions(
13948        &self,
13949        buffer: &Model<Buffer>,
13950        range: Range<text::Anchor>,
13951        cx: &mut WindowContext,
13952    ) -> Task<Result<Vec<CodeAction>>>;
13953
13954    fn apply_code_action(
13955        &self,
13956        buffer_handle: Model<Buffer>,
13957        action: CodeAction,
13958        excerpt_id: ExcerptId,
13959        push_to_history: bool,
13960        cx: &mut WindowContext,
13961    ) -> Task<Result<ProjectTransaction>>;
13962}
13963
13964impl CodeActionProvider for Model<Project> {
13965    fn code_actions(
13966        &self,
13967        buffer: &Model<Buffer>,
13968        range: Range<text::Anchor>,
13969        cx: &mut WindowContext,
13970    ) -> Task<Result<Vec<CodeAction>>> {
13971        self.update(cx, |project, cx| {
13972            project.code_actions(buffer, range, None, cx)
13973        })
13974    }
13975
13976    fn apply_code_action(
13977        &self,
13978        buffer_handle: Model<Buffer>,
13979        action: CodeAction,
13980        _excerpt_id: ExcerptId,
13981        push_to_history: bool,
13982        cx: &mut WindowContext,
13983    ) -> Task<Result<ProjectTransaction>> {
13984        self.update(cx, |project, cx| {
13985            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13986        })
13987    }
13988}
13989
13990fn snippet_completions(
13991    project: &Project,
13992    buffer: &Model<Buffer>,
13993    buffer_position: text::Anchor,
13994    cx: &mut AppContext,
13995) -> Task<Result<Vec<Completion>>> {
13996    let language = buffer.read(cx).language_at(buffer_position);
13997    let language_name = language.as_ref().map(|language| language.lsp_id());
13998    let snippet_store = project.snippets().read(cx);
13999    let snippets = snippet_store.snippets_for(language_name, cx);
14000
14001    if snippets.is_empty() {
14002        return Task::ready(Ok(vec![]));
14003    }
14004    let snapshot = buffer.read(cx).text_snapshot();
14005    let chars: String = snapshot
14006        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
14007        .collect();
14008
14009    let scope = language.map(|language| language.default_scope());
14010    let executor = cx.background_executor().clone();
14011
14012    cx.background_executor().spawn(async move {
14013        let classifier = CharClassifier::new(scope).for_completion(true);
14014        let mut last_word = chars
14015            .chars()
14016            .take_while(|c| classifier.is_word(*c))
14017            .collect::<String>();
14018        last_word = last_word.chars().rev().collect();
14019
14020        if last_word.is_empty() {
14021            return Ok(vec![]);
14022        }
14023
14024        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
14025        let to_lsp = |point: &text::Anchor| {
14026            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
14027            point_to_lsp(end)
14028        };
14029        let lsp_end = to_lsp(&buffer_position);
14030
14031        let candidates = snippets
14032            .iter()
14033            .enumerate()
14034            .flat_map(|(ix, snippet)| {
14035                snippet
14036                    .prefix
14037                    .iter()
14038                    .map(move |prefix| StringMatchCandidate::new(ix, prefix.clone()))
14039            })
14040            .collect::<Vec<StringMatchCandidate>>();
14041
14042        let mut matches = fuzzy::match_strings(
14043            &candidates,
14044            &last_word,
14045            last_word.chars().any(|c| c.is_uppercase()),
14046            100,
14047            &Default::default(),
14048            executor,
14049        )
14050        .await;
14051
14052        // Remove all candidates where the query's start does not match the start of any word in the candidate
14053        if let Some(query_start) = last_word.chars().next() {
14054            matches.retain(|string_match| {
14055                split_words(&string_match.string).any(|word| {
14056                    // Check that the first codepoint of the word as lowercase matches the first
14057                    // codepoint of the query as lowercase
14058                    word.chars()
14059                        .flat_map(|codepoint| codepoint.to_lowercase())
14060                        .zip(query_start.to_lowercase())
14061                        .all(|(word_cp, query_cp)| word_cp == query_cp)
14062                })
14063            });
14064        }
14065
14066        let matched_strings = matches
14067            .into_iter()
14068            .map(|m| m.string)
14069            .collect::<HashSet<_>>();
14070
14071        let result: Vec<Completion> = snippets
14072            .into_iter()
14073            .filter_map(|snippet| {
14074                let matching_prefix = snippet
14075                    .prefix
14076                    .iter()
14077                    .find(|prefix| matched_strings.contains(*prefix))?;
14078                let start = as_offset - last_word.len();
14079                let start = snapshot.anchor_before(start);
14080                let range = start..buffer_position;
14081                let lsp_start = to_lsp(&start);
14082                let lsp_range = lsp::Range {
14083                    start: lsp_start,
14084                    end: lsp_end,
14085                };
14086                Some(Completion {
14087                    old_range: range,
14088                    new_text: snippet.body.clone(),
14089                    label: CodeLabel {
14090                        text: matching_prefix.clone(),
14091                        runs: vec![],
14092                        filter_range: 0..matching_prefix.len(),
14093                    },
14094                    server_id: LanguageServerId(usize::MAX),
14095                    documentation: snippet.description.clone().map(Documentation::SingleLine),
14096                    lsp_completion: lsp::CompletionItem {
14097                        label: snippet.prefix.first().unwrap().clone(),
14098                        kind: Some(CompletionItemKind::SNIPPET),
14099                        label_details: snippet.description.as_ref().map(|description| {
14100                            lsp::CompletionItemLabelDetails {
14101                                detail: Some(description.clone()),
14102                                description: None,
14103                            }
14104                        }),
14105                        insert_text_format: Some(InsertTextFormat::SNIPPET),
14106                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
14107                            lsp::InsertReplaceEdit {
14108                                new_text: snippet.body.clone(),
14109                                insert: lsp_range,
14110                                replace: lsp_range,
14111                            },
14112                        )),
14113                        filter_text: Some(snippet.body.clone()),
14114                        sort_text: Some(char::MAX.to_string()),
14115                        ..Default::default()
14116                    },
14117                    confirm: None,
14118                })
14119            })
14120            .collect();
14121
14122        Ok(result)
14123    })
14124}
14125
14126impl CompletionProvider for Model<Project> {
14127    fn completions(
14128        &self,
14129        buffer: &Model<Buffer>,
14130        buffer_position: text::Anchor,
14131        options: CompletionContext,
14132        cx: &mut ViewContext<Editor>,
14133    ) -> Task<Result<Vec<Completion>>> {
14134        self.update(cx, |project, cx| {
14135            let snippets = snippet_completions(project, buffer, buffer_position, cx);
14136            let project_completions = project.completions(buffer, buffer_position, options, cx);
14137            cx.background_executor().spawn(async move {
14138                let mut completions = project_completions.await?;
14139                let snippets_completions = snippets.await?;
14140                completions.extend(snippets_completions);
14141                Ok(completions)
14142            })
14143        })
14144    }
14145
14146    fn resolve_completions(
14147        &self,
14148        buffer: Model<Buffer>,
14149        completion_indices: Vec<usize>,
14150        completions: Arc<RwLock<Box<[Completion]>>>,
14151        cx: &mut ViewContext<Editor>,
14152    ) -> Task<Result<bool>> {
14153        self.update(cx, |project, cx| {
14154            project.resolve_completions(buffer, completion_indices, completions, cx)
14155        })
14156    }
14157
14158    fn apply_additional_edits_for_completion(
14159        &self,
14160        buffer: Model<Buffer>,
14161        completion: Completion,
14162        push_to_history: bool,
14163        cx: &mut ViewContext<Editor>,
14164    ) -> Task<Result<Option<language::Transaction>>> {
14165        self.update(cx, |project, cx| {
14166            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
14167        })
14168    }
14169
14170    fn is_completion_trigger(
14171        &self,
14172        buffer: &Model<Buffer>,
14173        position: language::Anchor,
14174        text: &str,
14175        trigger_in_words: bool,
14176        cx: &mut ViewContext<Editor>,
14177    ) -> bool {
14178        if !EditorSettings::get_global(cx).show_completions_on_input {
14179            return false;
14180        }
14181
14182        let mut chars = text.chars();
14183        let char = if let Some(char) = chars.next() {
14184            char
14185        } else {
14186            return false;
14187        };
14188        if chars.next().is_some() {
14189            return false;
14190        }
14191
14192        let buffer = buffer.read(cx);
14193        let classifier = buffer
14194            .snapshot()
14195            .char_classifier_at(position)
14196            .for_completion(true);
14197        if trigger_in_words && classifier.is_word(char) {
14198            return true;
14199        }
14200
14201        buffer.completion_triggers().contains(text)
14202    }
14203}
14204
14205impl SemanticsProvider for Model<Project> {
14206    fn hover(
14207        &self,
14208        buffer: &Model<Buffer>,
14209        position: text::Anchor,
14210        cx: &mut AppContext,
14211    ) -> Option<Task<Vec<project::Hover>>> {
14212        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
14213    }
14214
14215    fn document_highlights(
14216        &self,
14217        buffer: &Model<Buffer>,
14218        position: text::Anchor,
14219        cx: &mut AppContext,
14220    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14221        Some(self.update(cx, |project, cx| {
14222            project.document_highlights(buffer, position, cx)
14223        }))
14224    }
14225
14226    fn definitions(
14227        &self,
14228        buffer: &Model<Buffer>,
14229        position: text::Anchor,
14230        kind: GotoDefinitionKind,
14231        cx: &mut AppContext,
14232    ) -> Option<Task<Result<Vec<LocationLink>>>> {
14233        Some(self.update(cx, |project, cx| match kind {
14234            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14235            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14236            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14237            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14238        }))
14239    }
14240
14241    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
14242        // TODO: make this work for remote projects
14243        self.read(cx)
14244            .language_servers_for_buffer(buffer.read(cx), cx)
14245            .any(
14246                |(_, server)| match server.capabilities().inlay_hint_provider {
14247                    Some(lsp::OneOf::Left(enabled)) => enabled,
14248                    Some(lsp::OneOf::Right(_)) => true,
14249                    None => false,
14250                },
14251            )
14252    }
14253
14254    fn inlay_hints(
14255        &self,
14256        buffer_handle: Model<Buffer>,
14257        range: Range<text::Anchor>,
14258        cx: &mut AppContext,
14259    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14260        Some(self.update(cx, |project, cx| {
14261            project.inlay_hints(buffer_handle, range, cx)
14262        }))
14263    }
14264
14265    fn resolve_inlay_hint(
14266        &self,
14267        hint: InlayHint,
14268        buffer_handle: Model<Buffer>,
14269        server_id: LanguageServerId,
14270        cx: &mut AppContext,
14271    ) -> Option<Task<anyhow::Result<InlayHint>>> {
14272        Some(self.update(cx, |project, cx| {
14273            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14274        }))
14275    }
14276
14277    fn range_for_rename(
14278        &self,
14279        buffer: &Model<Buffer>,
14280        position: text::Anchor,
14281        cx: &mut AppContext,
14282    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14283        Some(self.update(cx, |project, cx| {
14284            project.prepare_rename(buffer.clone(), position, cx)
14285        }))
14286    }
14287
14288    fn perform_rename(
14289        &self,
14290        buffer: &Model<Buffer>,
14291        position: text::Anchor,
14292        new_name: String,
14293        cx: &mut AppContext,
14294    ) -> Option<Task<Result<ProjectTransaction>>> {
14295        Some(self.update(cx, |project, cx| {
14296            project.perform_rename(buffer.clone(), position, new_name, cx)
14297        }))
14298    }
14299}
14300
14301fn inlay_hint_settings(
14302    location: Anchor,
14303    snapshot: &MultiBufferSnapshot,
14304    cx: &mut ViewContext<'_, Editor>,
14305) -> InlayHintSettings {
14306    let file = snapshot.file_at(location);
14307    let language = snapshot.language_at(location).map(|l| l.name());
14308    language_settings(language, file, cx).inlay_hints
14309}
14310
14311fn consume_contiguous_rows(
14312    contiguous_row_selections: &mut Vec<Selection<Point>>,
14313    selection: &Selection<Point>,
14314    display_map: &DisplaySnapshot,
14315    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14316) -> (MultiBufferRow, MultiBufferRow) {
14317    contiguous_row_selections.push(selection.clone());
14318    let start_row = MultiBufferRow(selection.start.row);
14319    let mut end_row = ending_row(selection, display_map);
14320
14321    while let Some(next_selection) = selections.peek() {
14322        if next_selection.start.row <= end_row.0 {
14323            end_row = ending_row(next_selection, display_map);
14324            contiguous_row_selections.push(selections.next().unwrap().clone());
14325        } else {
14326            break;
14327        }
14328    }
14329    (start_row, end_row)
14330}
14331
14332fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14333    if next_selection.end.column > 0 || next_selection.is_empty() {
14334        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14335    } else {
14336        MultiBufferRow(next_selection.end.row)
14337    }
14338}
14339
14340impl EditorSnapshot {
14341    pub fn remote_selections_in_range<'a>(
14342        &'a self,
14343        range: &'a Range<Anchor>,
14344        collaboration_hub: &dyn CollaborationHub,
14345        cx: &'a AppContext,
14346    ) -> impl 'a + Iterator<Item = RemoteSelection> {
14347        let participant_names = collaboration_hub.user_names(cx);
14348        let participant_indices = collaboration_hub.user_participant_indices(cx);
14349        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14350        let collaborators_by_replica_id = collaborators_by_peer_id
14351            .iter()
14352            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14353            .collect::<HashMap<_, _>>();
14354        self.buffer_snapshot
14355            .selections_in_range(range, false)
14356            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14357                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14358                let participant_index = participant_indices.get(&collaborator.user_id).copied();
14359                let user_name = participant_names.get(&collaborator.user_id).cloned();
14360                Some(RemoteSelection {
14361                    replica_id,
14362                    selection,
14363                    cursor_shape,
14364                    line_mode,
14365                    participant_index,
14366                    peer_id: collaborator.peer_id,
14367                    user_name,
14368                })
14369            })
14370    }
14371
14372    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14373        self.display_snapshot.buffer_snapshot.language_at(position)
14374    }
14375
14376    pub fn is_focused(&self) -> bool {
14377        self.is_focused
14378    }
14379
14380    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14381        self.placeholder_text.as_ref()
14382    }
14383
14384    pub fn scroll_position(&self) -> gpui::Point<f32> {
14385        self.scroll_anchor.scroll_position(&self.display_snapshot)
14386    }
14387
14388    fn gutter_dimensions(
14389        &self,
14390        font_id: FontId,
14391        font_size: Pixels,
14392        em_width: Pixels,
14393        em_advance: Pixels,
14394        max_line_number_width: Pixels,
14395        cx: &AppContext,
14396    ) -> GutterDimensions {
14397        if !self.show_gutter {
14398            return GutterDimensions::default();
14399        }
14400        let descent = cx.text_system().descent(font_id, font_size);
14401
14402        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14403            matches!(
14404                ProjectSettings::get_global(cx).git.git_gutter,
14405                Some(GitGutterSetting::TrackedFiles)
14406            )
14407        });
14408        let gutter_settings = EditorSettings::get_global(cx).gutter;
14409        let show_line_numbers = self
14410            .show_line_numbers
14411            .unwrap_or(gutter_settings.line_numbers);
14412        let line_gutter_width = if show_line_numbers {
14413            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14414            let min_width_for_number_on_gutter = em_advance * 4.0;
14415            max_line_number_width.max(min_width_for_number_on_gutter)
14416        } else {
14417            0.0.into()
14418        };
14419
14420        let show_code_actions = self
14421            .show_code_actions
14422            .unwrap_or(gutter_settings.code_actions);
14423
14424        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14425
14426        let git_blame_entries_width =
14427            self.git_blame_gutter_max_author_length
14428                .map(|max_author_length| {
14429                    // Length of the author name, but also space for the commit hash,
14430                    // the spacing and the timestamp.
14431                    let max_char_count = max_author_length
14432                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14433                        + 7 // length of commit sha
14434                        + 14 // length of max relative timestamp ("60 minutes ago")
14435                        + 4; // gaps and margins
14436
14437                    em_advance * max_char_count
14438                });
14439
14440        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14441        left_padding += if show_code_actions || show_runnables {
14442            em_width * 3.0
14443        } else if show_git_gutter && show_line_numbers {
14444            em_width * 2.0
14445        } else if show_git_gutter || show_line_numbers {
14446            em_width
14447        } else {
14448            px(0.)
14449        };
14450
14451        let right_padding = if gutter_settings.folds && show_line_numbers {
14452            em_width * 4.0
14453        } else if gutter_settings.folds {
14454            em_width * 3.0
14455        } else if show_line_numbers {
14456            em_width
14457        } else {
14458            px(0.)
14459        };
14460
14461        GutterDimensions {
14462            left_padding,
14463            right_padding,
14464            width: line_gutter_width + left_padding + right_padding,
14465            margin: -descent,
14466            git_blame_entries_width,
14467        }
14468    }
14469
14470    pub fn render_crease_toggle(
14471        &self,
14472        buffer_row: MultiBufferRow,
14473        row_contains_cursor: bool,
14474        editor: View<Editor>,
14475        cx: &mut WindowContext,
14476    ) -> Option<AnyElement> {
14477        let folded = self.is_line_folded(buffer_row);
14478        let mut is_foldable = false;
14479
14480        if let Some(crease) = self
14481            .crease_snapshot
14482            .query_row(buffer_row, &self.buffer_snapshot)
14483        {
14484            is_foldable = true;
14485            match crease {
14486                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14487                    if let Some(render_toggle) = render_toggle {
14488                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14489                            if folded {
14490                                editor.update(cx, |editor, cx| {
14491                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14492                                });
14493                            } else {
14494                                editor.update(cx, |editor, cx| {
14495                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14496                                });
14497                            }
14498                        });
14499                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14500                    }
14501                }
14502            }
14503        }
14504
14505        is_foldable |= self.starts_indent(buffer_row);
14506
14507        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14508            Some(
14509                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14510                    .selected(folded)
14511                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14512                        if folded {
14513                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14514                        } else {
14515                            this.fold_at(&FoldAt { buffer_row }, cx);
14516                        }
14517                    }))
14518                    .into_any_element(),
14519            )
14520        } else {
14521            None
14522        }
14523    }
14524
14525    pub fn render_crease_trailer(
14526        &self,
14527        buffer_row: MultiBufferRow,
14528        cx: &mut WindowContext,
14529    ) -> Option<AnyElement> {
14530        let folded = self.is_line_folded(buffer_row);
14531        if let Crease::Inline { render_trailer, .. } = self
14532            .crease_snapshot
14533            .query_row(buffer_row, &self.buffer_snapshot)?
14534        {
14535            let render_trailer = render_trailer.as_ref()?;
14536            Some(render_trailer(buffer_row, folded, cx))
14537        } else {
14538            None
14539        }
14540    }
14541}
14542
14543impl Deref for EditorSnapshot {
14544    type Target = DisplaySnapshot;
14545
14546    fn deref(&self) -> &Self::Target {
14547        &self.display_snapshot
14548    }
14549}
14550
14551#[derive(Clone, Debug, PartialEq, Eq)]
14552pub enum EditorEvent {
14553    InputIgnored {
14554        text: Arc<str>,
14555    },
14556    InputHandled {
14557        utf16_range_to_replace: Option<Range<isize>>,
14558        text: Arc<str>,
14559    },
14560    ExcerptsAdded {
14561        buffer: Model<Buffer>,
14562        predecessor: ExcerptId,
14563        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14564    },
14565    ExcerptsRemoved {
14566        ids: Vec<ExcerptId>,
14567    },
14568    ExcerptsEdited {
14569        ids: Vec<ExcerptId>,
14570    },
14571    ExcerptsExpanded {
14572        ids: Vec<ExcerptId>,
14573    },
14574    BufferEdited,
14575    Edited {
14576        transaction_id: clock::Lamport,
14577    },
14578    Reparsed(BufferId),
14579    Focused,
14580    FocusedIn,
14581    Blurred,
14582    DirtyChanged,
14583    Saved,
14584    TitleChanged,
14585    DiffBaseChanged,
14586    SelectionsChanged {
14587        local: bool,
14588    },
14589    ScrollPositionChanged {
14590        local: bool,
14591        autoscroll: bool,
14592    },
14593    Closed,
14594    TransactionUndone {
14595        transaction_id: clock::Lamport,
14596    },
14597    TransactionBegun {
14598        transaction_id: clock::Lamport,
14599    },
14600    Reloaded,
14601    CursorShapeChanged,
14602}
14603
14604impl EventEmitter<EditorEvent> for Editor {}
14605
14606impl FocusableView for Editor {
14607    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14608        self.focus_handle.clone()
14609    }
14610}
14611
14612impl Render for Editor {
14613    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14614        let settings = ThemeSettings::get_global(cx);
14615
14616        let mut text_style = match self.mode {
14617            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14618                color: cx.theme().colors().editor_foreground,
14619                font_family: settings.ui_font.family.clone(),
14620                font_features: settings.ui_font.features.clone(),
14621                font_fallbacks: settings.ui_font.fallbacks.clone(),
14622                font_size: rems(0.875).into(),
14623                font_weight: settings.ui_font.weight,
14624                line_height: relative(settings.buffer_line_height.value()),
14625                ..Default::default()
14626            },
14627            EditorMode::Full => TextStyle {
14628                color: cx.theme().colors().editor_foreground,
14629                font_family: settings.buffer_font.family.clone(),
14630                font_features: settings.buffer_font.features.clone(),
14631                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14632                font_size: settings.buffer_font_size(cx).into(),
14633                font_weight: settings.buffer_font.weight,
14634                line_height: relative(settings.buffer_line_height.value()),
14635                ..Default::default()
14636            },
14637        };
14638        if let Some(text_style_refinement) = &self.text_style_refinement {
14639            text_style.refine(text_style_refinement)
14640        }
14641
14642        let background = match self.mode {
14643            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14644            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14645            EditorMode::Full => cx.theme().colors().editor_background,
14646        };
14647
14648        EditorElement::new(
14649            cx.view(),
14650            EditorStyle {
14651                background,
14652                local_player: cx.theme().players().local(),
14653                text: text_style,
14654                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14655                syntax: cx.theme().syntax().clone(),
14656                status: cx.theme().status().clone(),
14657                inlay_hints_style: make_inlay_hints_style(cx),
14658                suggestions_style: HighlightStyle {
14659                    color: Some(cx.theme().status().predictive),
14660                    ..HighlightStyle::default()
14661                },
14662                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14663            },
14664        )
14665    }
14666}
14667
14668impl ViewInputHandler for Editor {
14669    fn text_for_range(
14670        &mut self,
14671        range_utf16: Range<usize>,
14672        adjusted_range: &mut Option<Range<usize>>,
14673        cx: &mut ViewContext<Self>,
14674    ) -> Option<String> {
14675        let snapshot = self.buffer.read(cx).read(cx);
14676        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14677        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14678        if (start.0..end.0) != range_utf16 {
14679            adjusted_range.replace(start.0..end.0);
14680        }
14681        Some(snapshot.text_for_range(start..end).collect())
14682    }
14683
14684    fn selected_text_range(
14685        &mut self,
14686        ignore_disabled_input: bool,
14687        cx: &mut ViewContext<Self>,
14688    ) -> Option<UTF16Selection> {
14689        // Prevent the IME menu from appearing when holding down an alphabetic key
14690        // while input is disabled.
14691        if !ignore_disabled_input && !self.input_enabled {
14692            return None;
14693        }
14694
14695        let selection = self.selections.newest::<OffsetUtf16>(cx);
14696        let range = selection.range();
14697
14698        Some(UTF16Selection {
14699            range: range.start.0..range.end.0,
14700            reversed: selection.reversed,
14701        })
14702    }
14703
14704    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14705        let snapshot = self.buffer.read(cx).read(cx);
14706        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14707        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14708    }
14709
14710    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14711        self.clear_highlights::<InputComposition>(cx);
14712        self.ime_transaction.take();
14713    }
14714
14715    fn replace_text_in_range(
14716        &mut self,
14717        range_utf16: Option<Range<usize>>,
14718        text: &str,
14719        cx: &mut ViewContext<Self>,
14720    ) {
14721        if !self.input_enabled {
14722            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14723            return;
14724        }
14725
14726        self.transact(cx, |this, cx| {
14727            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14728                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14729                Some(this.selection_replacement_ranges(range_utf16, cx))
14730            } else {
14731                this.marked_text_ranges(cx)
14732            };
14733
14734            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14735                let newest_selection_id = this.selections.newest_anchor().id;
14736                this.selections
14737                    .all::<OffsetUtf16>(cx)
14738                    .iter()
14739                    .zip(ranges_to_replace.iter())
14740                    .find_map(|(selection, range)| {
14741                        if selection.id == newest_selection_id {
14742                            Some(
14743                                (range.start.0 as isize - selection.head().0 as isize)
14744                                    ..(range.end.0 as isize - selection.head().0 as isize),
14745                            )
14746                        } else {
14747                            None
14748                        }
14749                    })
14750            });
14751
14752            cx.emit(EditorEvent::InputHandled {
14753                utf16_range_to_replace: range_to_replace,
14754                text: text.into(),
14755            });
14756
14757            if let Some(new_selected_ranges) = new_selected_ranges {
14758                this.change_selections(None, cx, |selections| {
14759                    selections.select_ranges(new_selected_ranges)
14760                });
14761                this.backspace(&Default::default(), cx);
14762            }
14763
14764            this.handle_input(text, cx);
14765        });
14766
14767        if let Some(transaction) = self.ime_transaction {
14768            self.buffer.update(cx, |buffer, cx| {
14769                buffer.group_until_transaction(transaction, cx);
14770            });
14771        }
14772
14773        self.unmark_text(cx);
14774    }
14775
14776    fn replace_and_mark_text_in_range(
14777        &mut self,
14778        range_utf16: Option<Range<usize>>,
14779        text: &str,
14780        new_selected_range_utf16: Option<Range<usize>>,
14781        cx: &mut ViewContext<Self>,
14782    ) {
14783        if !self.input_enabled {
14784            return;
14785        }
14786
14787        let transaction = self.transact(cx, |this, cx| {
14788            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14789                let snapshot = this.buffer.read(cx).read(cx);
14790                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14791                    for marked_range in &mut marked_ranges {
14792                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14793                        marked_range.start.0 += relative_range_utf16.start;
14794                        marked_range.start =
14795                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14796                        marked_range.end =
14797                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14798                    }
14799                }
14800                Some(marked_ranges)
14801            } else if let Some(range_utf16) = range_utf16 {
14802                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14803                Some(this.selection_replacement_ranges(range_utf16, cx))
14804            } else {
14805                None
14806            };
14807
14808            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14809                let newest_selection_id = this.selections.newest_anchor().id;
14810                this.selections
14811                    .all::<OffsetUtf16>(cx)
14812                    .iter()
14813                    .zip(ranges_to_replace.iter())
14814                    .find_map(|(selection, range)| {
14815                        if selection.id == newest_selection_id {
14816                            Some(
14817                                (range.start.0 as isize - selection.head().0 as isize)
14818                                    ..(range.end.0 as isize - selection.head().0 as isize),
14819                            )
14820                        } else {
14821                            None
14822                        }
14823                    })
14824            });
14825
14826            cx.emit(EditorEvent::InputHandled {
14827                utf16_range_to_replace: range_to_replace,
14828                text: text.into(),
14829            });
14830
14831            if let Some(ranges) = ranges_to_replace {
14832                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14833            }
14834
14835            let marked_ranges = {
14836                let snapshot = this.buffer.read(cx).read(cx);
14837                this.selections
14838                    .disjoint_anchors()
14839                    .iter()
14840                    .map(|selection| {
14841                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14842                    })
14843                    .collect::<Vec<_>>()
14844            };
14845
14846            if text.is_empty() {
14847                this.unmark_text(cx);
14848            } else {
14849                this.highlight_text::<InputComposition>(
14850                    marked_ranges.clone(),
14851                    HighlightStyle {
14852                        underline: Some(UnderlineStyle {
14853                            thickness: px(1.),
14854                            color: None,
14855                            wavy: false,
14856                        }),
14857                        ..Default::default()
14858                    },
14859                    cx,
14860                );
14861            }
14862
14863            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14864            let use_autoclose = this.use_autoclose;
14865            let use_auto_surround = this.use_auto_surround;
14866            this.set_use_autoclose(false);
14867            this.set_use_auto_surround(false);
14868            this.handle_input(text, cx);
14869            this.set_use_autoclose(use_autoclose);
14870            this.set_use_auto_surround(use_auto_surround);
14871
14872            if let Some(new_selected_range) = new_selected_range_utf16 {
14873                let snapshot = this.buffer.read(cx).read(cx);
14874                let new_selected_ranges = marked_ranges
14875                    .into_iter()
14876                    .map(|marked_range| {
14877                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14878                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14879                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14880                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14881                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14882                    })
14883                    .collect::<Vec<_>>();
14884
14885                drop(snapshot);
14886                this.change_selections(None, cx, |selections| {
14887                    selections.select_ranges(new_selected_ranges)
14888                });
14889            }
14890        });
14891
14892        self.ime_transaction = self.ime_transaction.or(transaction);
14893        if let Some(transaction) = self.ime_transaction {
14894            self.buffer.update(cx, |buffer, cx| {
14895                buffer.group_until_transaction(transaction, cx);
14896            });
14897        }
14898
14899        if self.text_highlights::<InputComposition>(cx).is_none() {
14900            self.ime_transaction.take();
14901        }
14902    }
14903
14904    fn bounds_for_range(
14905        &mut self,
14906        range_utf16: Range<usize>,
14907        element_bounds: gpui::Bounds<Pixels>,
14908        cx: &mut ViewContext<Self>,
14909    ) -> Option<gpui::Bounds<Pixels>> {
14910        let text_layout_details = self.text_layout_details(cx);
14911        let gpui::Point {
14912            x: em_width,
14913            y: line_height,
14914        } = self.character_size(cx);
14915
14916        let snapshot = self.snapshot(cx);
14917        let scroll_position = snapshot.scroll_position();
14918        let scroll_left = scroll_position.x * em_width;
14919
14920        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14921        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14922            + self.gutter_dimensions.width
14923            + self.gutter_dimensions.margin;
14924        let y = line_height * (start.row().as_f32() - scroll_position.y);
14925
14926        Some(Bounds {
14927            origin: element_bounds.origin + point(x, y),
14928            size: size(em_width, line_height),
14929        })
14930    }
14931}
14932
14933trait SelectionExt {
14934    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14935    fn spanned_rows(
14936        &self,
14937        include_end_if_at_line_start: bool,
14938        map: &DisplaySnapshot,
14939    ) -> Range<MultiBufferRow>;
14940}
14941
14942impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14943    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14944        let start = self
14945            .start
14946            .to_point(&map.buffer_snapshot)
14947            .to_display_point(map);
14948        let end = self
14949            .end
14950            .to_point(&map.buffer_snapshot)
14951            .to_display_point(map);
14952        if self.reversed {
14953            end..start
14954        } else {
14955            start..end
14956        }
14957    }
14958
14959    fn spanned_rows(
14960        &self,
14961        include_end_if_at_line_start: bool,
14962        map: &DisplaySnapshot,
14963    ) -> Range<MultiBufferRow> {
14964        let start = self.start.to_point(&map.buffer_snapshot);
14965        let mut end = self.end.to_point(&map.buffer_snapshot);
14966        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14967            end.row -= 1;
14968        }
14969
14970        let buffer_start = map.prev_line_boundary(start).0;
14971        let buffer_end = map.next_line_boundary(end).0;
14972        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14973    }
14974}
14975
14976impl<T: InvalidationRegion> InvalidationStack<T> {
14977    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14978    where
14979        S: Clone + ToOffset,
14980    {
14981        while let Some(region) = self.last() {
14982            let all_selections_inside_invalidation_ranges =
14983                if selections.len() == region.ranges().len() {
14984                    selections
14985                        .iter()
14986                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14987                        .all(|(selection, invalidation_range)| {
14988                            let head = selection.head().to_offset(buffer);
14989                            invalidation_range.start <= head && invalidation_range.end >= head
14990                        })
14991                } else {
14992                    false
14993                };
14994
14995            if all_selections_inside_invalidation_ranges {
14996                break;
14997            } else {
14998                self.pop();
14999            }
15000        }
15001    }
15002}
15003
15004impl<T> Default for InvalidationStack<T> {
15005    fn default() -> Self {
15006        Self(Default::default())
15007    }
15008}
15009
15010impl<T> Deref for InvalidationStack<T> {
15011    type Target = Vec<T>;
15012
15013    fn deref(&self) -> &Self::Target {
15014        &self.0
15015    }
15016}
15017
15018impl<T> DerefMut for InvalidationStack<T> {
15019    fn deref_mut(&mut self) -> &mut Self::Target {
15020        &mut self.0
15021    }
15022}
15023
15024impl InvalidationRegion for SnippetState {
15025    fn ranges(&self) -> &[Range<Anchor>] {
15026        &self.ranges[self.active_index]
15027    }
15028}
15029
15030pub fn diagnostic_block_renderer(
15031    diagnostic: Diagnostic,
15032    max_message_rows: Option<u8>,
15033    allow_closing: bool,
15034    _is_valid: bool,
15035) -> RenderBlock {
15036    let (text_without_backticks, code_ranges) =
15037        highlight_diagnostic_message(&diagnostic, max_message_rows);
15038
15039    Arc::new(move |cx: &mut BlockContext| {
15040        let group_id: SharedString = cx.block_id.to_string().into();
15041
15042        let mut text_style = cx.text_style().clone();
15043        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
15044        let theme_settings = ThemeSettings::get_global(cx);
15045        text_style.font_family = theme_settings.buffer_font.family.clone();
15046        text_style.font_style = theme_settings.buffer_font.style;
15047        text_style.font_features = theme_settings.buffer_font.features.clone();
15048        text_style.font_weight = theme_settings.buffer_font.weight;
15049
15050        let multi_line_diagnostic = diagnostic.message.contains('\n');
15051
15052        let buttons = |diagnostic: &Diagnostic| {
15053            if multi_line_diagnostic {
15054                v_flex()
15055            } else {
15056                h_flex()
15057            }
15058            .when(allow_closing, |div| {
15059                div.children(diagnostic.is_primary.then(|| {
15060                    IconButton::new("close-block", IconName::XCircle)
15061                        .icon_color(Color::Muted)
15062                        .size(ButtonSize::Compact)
15063                        .style(ButtonStyle::Transparent)
15064                        .visible_on_hover(group_id.clone())
15065                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
15066                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
15067                }))
15068            })
15069            .child(
15070                IconButton::new("copy-block", IconName::Copy)
15071                    .icon_color(Color::Muted)
15072                    .size(ButtonSize::Compact)
15073                    .style(ButtonStyle::Transparent)
15074                    .visible_on_hover(group_id.clone())
15075                    .on_click({
15076                        let message = diagnostic.message.clone();
15077                        move |_click, cx| {
15078                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
15079                        }
15080                    })
15081                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
15082            )
15083        };
15084
15085        let icon_size = buttons(&diagnostic)
15086            .into_any_element()
15087            .layout_as_root(AvailableSpace::min_size(), cx);
15088
15089        h_flex()
15090            .id(cx.block_id)
15091            .group(group_id.clone())
15092            .relative()
15093            .size_full()
15094            .block_mouse_down()
15095            .pl(cx.gutter_dimensions.width)
15096            .w(cx.max_width - cx.gutter_dimensions.full_width())
15097            .child(
15098                div()
15099                    .flex()
15100                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
15101                    .flex_shrink(),
15102            )
15103            .child(buttons(&diagnostic))
15104            .child(div().flex().flex_shrink_0().child(
15105                StyledText::new(text_without_backticks.clone()).with_highlights(
15106                    &text_style,
15107                    code_ranges.iter().map(|range| {
15108                        (
15109                            range.clone(),
15110                            HighlightStyle {
15111                                font_weight: Some(FontWeight::BOLD),
15112                                ..Default::default()
15113                            },
15114                        )
15115                    }),
15116                ),
15117            ))
15118            .into_any_element()
15119    })
15120}
15121
15122pub fn highlight_diagnostic_message(
15123    diagnostic: &Diagnostic,
15124    mut max_message_rows: Option<u8>,
15125) -> (SharedString, Vec<Range<usize>>) {
15126    let mut text_without_backticks = String::new();
15127    let mut code_ranges = Vec::new();
15128
15129    if let Some(source) = &diagnostic.source {
15130        text_without_backticks.push_str(source);
15131        code_ranges.push(0..source.len());
15132        text_without_backticks.push_str(": ");
15133    }
15134
15135    let mut prev_offset = 0;
15136    let mut in_code_block = false;
15137    let has_row_limit = max_message_rows.is_some();
15138    let mut newline_indices = diagnostic
15139        .message
15140        .match_indices('\n')
15141        .filter(|_| has_row_limit)
15142        .map(|(ix, _)| ix)
15143        .fuse()
15144        .peekable();
15145
15146    for (quote_ix, _) in diagnostic
15147        .message
15148        .match_indices('`')
15149        .chain([(diagnostic.message.len(), "")])
15150    {
15151        let mut first_newline_ix = None;
15152        let mut last_newline_ix = None;
15153        while let Some(newline_ix) = newline_indices.peek() {
15154            if *newline_ix < quote_ix {
15155                if first_newline_ix.is_none() {
15156                    first_newline_ix = Some(*newline_ix);
15157                }
15158                last_newline_ix = Some(*newline_ix);
15159
15160                if let Some(rows_left) = &mut max_message_rows {
15161                    if *rows_left == 0 {
15162                        break;
15163                    } else {
15164                        *rows_left -= 1;
15165                    }
15166                }
15167                let _ = newline_indices.next();
15168            } else {
15169                break;
15170            }
15171        }
15172        let prev_len = text_without_backticks.len();
15173        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
15174        text_without_backticks.push_str(new_text);
15175        if in_code_block {
15176            code_ranges.push(prev_len..text_without_backticks.len());
15177        }
15178        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15179        in_code_block = !in_code_block;
15180        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15181            text_without_backticks.push_str("...");
15182            break;
15183        }
15184    }
15185
15186    (text_without_backticks.into(), code_ranges)
15187}
15188
15189fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15190    match severity {
15191        DiagnosticSeverity::ERROR => colors.error,
15192        DiagnosticSeverity::WARNING => colors.warning,
15193        DiagnosticSeverity::INFORMATION => colors.info,
15194        DiagnosticSeverity::HINT => colors.info,
15195        _ => colors.ignored,
15196    }
15197}
15198
15199pub fn styled_runs_for_code_label<'a>(
15200    label: &'a CodeLabel,
15201    syntax_theme: &'a theme::SyntaxTheme,
15202) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15203    let fade_out = HighlightStyle {
15204        fade_out: Some(0.35),
15205        ..Default::default()
15206    };
15207
15208    let mut prev_end = label.filter_range.end;
15209    label
15210        .runs
15211        .iter()
15212        .enumerate()
15213        .flat_map(move |(ix, (range, highlight_id))| {
15214            let style = if let Some(style) = highlight_id.style(syntax_theme) {
15215                style
15216            } else {
15217                return Default::default();
15218            };
15219            let mut muted_style = style;
15220            muted_style.highlight(fade_out);
15221
15222            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15223            if range.start >= label.filter_range.end {
15224                if range.start > prev_end {
15225                    runs.push((prev_end..range.start, fade_out));
15226                }
15227                runs.push((range.clone(), muted_style));
15228            } else if range.end <= label.filter_range.end {
15229                runs.push((range.clone(), style));
15230            } else {
15231                runs.push((range.start..label.filter_range.end, style));
15232                runs.push((label.filter_range.end..range.end, muted_style));
15233            }
15234            prev_end = cmp::max(prev_end, range.end);
15235
15236            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15237                runs.push((prev_end..label.text.len(), fade_out));
15238            }
15239
15240            runs
15241        })
15242}
15243
15244pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15245    let mut prev_index = 0;
15246    let mut prev_codepoint: Option<char> = None;
15247    text.char_indices()
15248        .chain([(text.len(), '\0')])
15249        .filter_map(move |(index, codepoint)| {
15250            let prev_codepoint = prev_codepoint.replace(codepoint)?;
15251            let is_boundary = index == text.len()
15252                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15253                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15254            if is_boundary {
15255                let chunk = &text[prev_index..index];
15256                prev_index = index;
15257                Some(chunk)
15258            } else {
15259                None
15260            }
15261        })
15262}
15263
15264pub trait RangeToAnchorExt: Sized {
15265    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15266
15267    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15268        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15269        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15270    }
15271}
15272
15273impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15274    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15275        let start_offset = self.start.to_offset(snapshot);
15276        let end_offset = self.end.to_offset(snapshot);
15277        if start_offset == end_offset {
15278            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15279        } else {
15280            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15281        }
15282    }
15283}
15284
15285pub trait RowExt {
15286    fn as_f32(&self) -> f32;
15287
15288    fn next_row(&self) -> Self;
15289
15290    fn previous_row(&self) -> Self;
15291
15292    fn minus(&self, other: Self) -> u32;
15293}
15294
15295impl RowExt for DisplayRow {
15296    fn as_f32(&self) -> f32 {
15297        self.0 as f32
15298    }
15299
15300    fn next_row(&self) -> Self {
15301        Self(self.0 + 1)
15302    }
15303
15304    fn previous_row(&self) -> Self {
15305        Self(self.0.saturating_sub(1))
15306    }
15307
15308    fn minus(&self, other: Self) -> u32 {
15309        self.0 - other.0
15310    }
15311}
15312
15313impl RowExt for MultiBufferRow {
15314    fn as_f32(&self) -> f32 {
15315        self.0 as f32
15316    }
15317
15318    fn next_row(&self) -> Self {
15319        Self(self.0 + 1)
15320    }
15321
15322    fn previous_row(&self) -> Self {
15323        Self(self.0.saturating_sub(1))
15324    }
15325
15326    fn minus(&self, other: Self) -> u32 {
15327        self.0 - other.0
15328    }
15329}
15330
15331trait RowRangeExt {
15332    type Row;
15333
15334    fn len(&self) -> usize;
15335
15336    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15337}
15338
15339impl RowRangeExt for Range<MultiBufferRow> {
15340    type Row = MultiBufferRow;
15341
15342    fn len(&self) -> usize {
15343        (self.end.0 - self.start.0) as usize
15344    }
15345
15346    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15347        (self.start.0..self.end.0).map(MultiBufferRow)
15348    }
15349}
15350
15351impl RowRangeExt for Range<DisplayRow> {
15352    type Row = DisplayRow;
15353
15354    fn len(&self) -> usize {
15355        (self.end.0 - self.start.0) as usize
15356    }
15357
15358    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15359        (self.start.0..self.end.0).map(DisplayRow)
15360    }
15361}
15362
15363fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15364    if hunk.diff_base_byte_range.is_empty() {
15365        DiffHunkStatus::Added
15366    } else if hunk.row_range.is_empty() {
15367        DiffHunkStatus::Removed
15368    } else {
15369        DiffHunkStatus::Modified
15370    }
15371}
15372
15373/// If select range has more than one line, we
15374/// just point the cursor to range.start.
15375fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15376    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15377        range
15378    } else {
15379        range.start..range.start
15380    }
15381}
15382
15383pub struct KillRing(ClipboardItem);
15384impl Global for KillRing {}
15385
15386const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);