editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod debounced_delay;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod hunk_diff;
   29mod indent_guides;
   30mod inlay_hint_cache;
   31mod inline_completion_provider;
   32pub mod items;
   33mod linked_editing_ranges;
   34mod lsp_ext;
   35mod mouse_context_menu;
   36pub mod movement;
   37mod persistence;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45mod signature_help;
   46#[cfg(any(test, feature = "test-support"))]
   47pub mod test;
   48
   49use ::git::diff::{DiffHunk, DiffHunkStatus};
   50use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
   51pub(crate) use actions::*;
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use client::{Collaborator, ParticipantIndex};
   56use clock::ReplicaId;
   57use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   58use convert_case::{Case, Casing};
   59use debounced_delay::DebouncedDelay;
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings,
   64};
   65pub use editor_settings_controls::*;
   66use element::LineWithInvisibles;
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::FutureExt;
   71use fuzzy::{StringMatch, StringMatchCandidate};
   72use git::blame::GitBlame;
   73use git::diff_hunk_to_display;
   74use gpui::{
   75    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   76    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
   77    ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
   78    FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
   79    KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
   80    SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
   81    UTF16Selection, UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler,
   82    VisualContext, WeakFocusHandle, WeakView, WindowContext,
   83};
   84use highlight_matching_bracket::refresh_matching_bracket_highlights;
   85use hover_popover::{hide_hover, HoverState};
   86use hunk_diff::ExpandedHunks;
   87pub(crate) use hunk_diff::HoveredHunk;
   88use indent_guides::ActiveIndentGuidesState;
   89use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   90pub use inline_completion_provider::*;
   91pub use items::MAX_TAB_TITLE_LEN;
   92use itertools::Itertools;
   93use language::{
   94    language_settings::{self, all_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;
  101use similar::{ChangeTag, TextDiff};
  102use task::{ResolvedTask, TaskTemplate, TaskVariables};
  103
  104use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  105pub use lsp::CompletionContext;
  106use lsp::{
  107    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  108    LanguageServerId,
  109};
  110use mouse_context_menu::MouseContextMenu;
  111use movement::TextLayoutDetails;
  112pub use multi_buffer::{
  113    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  114    ToPoint,
  115};
  116use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
  117use ordered_float::OrderedFloat;
  118use parking_lot::{Mutex, RwLock};
  119use project::project_settings::{GitGutterSetting, ProjectSettings};
  120use project::{
  121    CodeAction, Completion, CompletionIntent, FormatTrigger, Item, Location, Project, ProjectPath,
  122    ProjectTransaction, TaskSourceKind,
  123};
  124use rand::prelude::*;
  125use rpc::{proto::*, ErrorExt};
  126use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  127use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  128use serde::{Deserialize, Serialize};
  129use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  130use smallvec::SmallVec;
  131use snippet::Snippet;
  132use std::{
  133    any::TypeId,
  134    borrow::Cow,
  135    cell::RefCell,
  136    cmp::{self, Ordering, Reverse},
  137    mem,
  138    num::NonZeroU32,
  139    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  140    path::{Path, PathBuf},
  141    rc::Rc,
  142    sync::Arc,
  143    time::{Duration, Instant},
  144};
  145pub use sum_tree::Bias;
  146use sum_tree::TreeMap;
  147use text::{BufferId, OffsetUtf16, Rope};
  148use theme::{
  149    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  150    ThemeColors, ThemeSettings,
  151};
  152use ui::{
  153    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  154    ListItem, Popover, Tooltip,
  155};
  156use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  157use workspace::item::{ItemHandle, PreviewTabsSettings};
  158use workspace::notifications::{DetachAndPromptErr, NotificationId};
  159use workspace::{
  160    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  161};
  162use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  163
  164use crate::hover_links::find_url;
  165use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  166
  167pub const FILE_HEADER_HEIGHT: u32 = 1;
  168pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  169pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  170pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  171const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  172const MAX_LINE_LEN: usize = 1024;
  173const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  174const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  175pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  176#[doc(hidden)]
  177pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  178#[doc(hidden)]
  179pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  180
  181pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  182pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  183
  184pub fn render_parsed_markdown(
  185    element_id: impl Into<ElementId>,
  186    parsed: &language::ParsedMarkdown,
  187    editor_style: &EditorStyle,
  188    workspace: Option<WeakView<Workspace>>,
  189    cx: &mut WindowContext,
  190) -> InteractiveText {
  191    let code_span_background_color = cx
  192        .theme()
  193        .colors()
  194        .editor_document_highlight_read_background;
  195
  196    let highlights = gpui::combine_highlights(
  197        parsed.highlights.iter().filter_map(|(range, highlight)| {
  198            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  199            Some((range.clone(), highlight))
  200        }),
  201        parsed
  202            .regions
  203            .iter()
  204            .zip(&parsed.region_ranges)
  205            .filter_map(|(region, range)| {
  206                if region.code {
  207                    Some((
  208                        range.clone(),
  209                        HighlightStyle {
  210                            background_color: Some(code_span_background_color),
  211                            ..Default::default()
  212                        },
  213                    ))
  214                } else {
  215                    None
  216                }
  217            }),
  218    );
  219
  220    let mut links = Vec::new();
  221    let mut link_ranges = Vec::new();
  222    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  223        if let Some(link) = region.link.clone() {
  224            links.push(link);
  225            link_ranges.push(range.clone());
  226        }
  227    }
  228
  229    InteractiveText::new(
  230        element_id,
  231        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  232    )
  233    .on_click(link_ranges, move |clicked_range_ix, cx| {
  234        match &links[clicked_range_ix] {
  235            markdown::Link::Web { url } => cx.open_url(url),
  236            markdown::Link::Path { path } => {
  237                if let Some(workspace) = &workspace {
  238                    _ = workspace.update(cx, |workspace, cx| {
  239                        workspace.open_abs_path(path.clone(), false, cx).detach();
  240                    });
  241                }
  242            }
  243        }
  244    })
  245}
  246
  247#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  248pub(crate) enum InlayId {
  249    Suggestion(usize),
  250    Hint(usize),
  251}
  252
  253impl InlayId {
  254    fn id(&self) -> usize {
  255        match self {
  256            Self::Suggestion(id) => *id,
  257            Self::Hint(id) => *id,
  258        }
  259    }
  260}
  261
  262enum DiffRowHighlight {}
  263enum DocumentHighlightRead {}
  264enum DocumentHighlightWrite {}
  265enum InputComposition {}
  266
  267#[derive(Copy, Clone, PartialEq, Eq)]
  268pub enum Direction {
  269    Prev,
  270    Next,
  271}
  272
  273#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  274pub enum Navigated {
  275    Yes,
  276    No,
  277}
  278
  279impl Navigated {
  280    pub fn from_bool(yes: bool) -> Navigated {
  281        if yes {
  282            Navigated::Yes
  283        } else {
  284            Navigated::No
  285        }
  286    }
  287}
  288
  289pub fn init_settings(cx: &mut AppContext) {
  290    EditorSettings::register(cx);
  291}
  292
  293pub fn init(cx: &mut AppContext) {
  294    init_settings(cx);
  295
  296    workspace::register_project_item::<Editor>(cx);
  297    workspace::FollowableViewRegistry::register::<Editor>(cx);
  298    workspace::register_serializable_item::<Editor>(cx);
  299
  300    cx.observe_new_views(
  301        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  302            workspace.register_action(Editor::new_file);
  303            workspace.register_action(Editor::new_file_vertical);
  304            workspace.register_action(Editor::new_file_horizontal);
  305        },
  306    )
  307    .detach();
  308
  309    cx.on_action(move |_: &workspace::NewFile, cx| {
  310        let app_state = workspace::AppState::global(cx);
  311        if let Some(app_state) = app_state.upgrade() {
  312            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  313                Editor::new_file(workspace, &Default::default(), cx)
  314            })
  315            .detach();
  316        }
  317    });
  318    cx.on_action(move |_: &workspace::NewWindow, cx| {
  319        let app_state = workspace::AppState::global(cx);
  320        if let Some(app_state) = app_state.upgrade() {
  321            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  322                Editor::new_file(workspace, &Default::default(), cx)
  323            })
  324            .detach();
  325        }
  326    });
  327}
  328
  329pub struct SearchWithinRange;
  330
  331trait InvalidationRegion {
  332    fn ranges(&self) -> &[Range<Anchor>];
  333}
  334
  335#[derive(Clone, Debug, PartialEq)]
  336pub enum SelectPhase {
  337    Begin {
  338        position: DisplayPoint,
  339        add: bool,
  340        click_count: usize,
  341    },
  342    BeginColumnar {
  343        position: DisplayPoint,
  344        reset: bool,
  345        goal_column: u32,
  346    },
  347    Extend {
  348        position: DisplayPoint,
  349        click_count: usize,
  350    },
  351    Update {
  352        position: DisplayPoint,
  353        goal_column: u32,
  354        scroll_delta: gpui::Point<f32>,
  355    },
  356    End,
  357}
  358
  359#[derive(Clone, Debug)]
  360pub enum SelectMode {
  361    Character,
  362    Word(Range<Anchor>),
  363    Line(Range<Anchor>),
  364    All,
  365}
  366
  367#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  368pub enum EditorMode {
  369    SingleLine { auto_width: bool },
  370    AutoHeight { max_lines: usize },
  371    Full,
  372}
  373
  374#[derive(Clone, Debug)]
  375pub enum SoftWrap {
  376    None,
  377    PreferLine,
  378    EditorWidth,
  379    Column(u32),
  380    Bounded(u32),
  381}
  382
  383#[derive(Clone)]
  384pub struct EditorStyle {
  385    pub background: Hsla,
  386    pub local_player: PlayerColor,
  387    pub text: TextStyle,
  388    pub scrollbar_width: Pixels,
  389    pub syntax: Arc<SyntaxTheme>,
  390    pub status: StatusColors,
  391    pub inlay_hints_style: HighlightStyle,
  392    pub suggestions_style: HighlightStyle,
  393    pub unnecessary_code_fade: f32,
  394}
  395
  396impl Default for EditorStyle {
  397    fn default() -> Self {
  398        Self {
  399            background: Hsla::default(),
  400            local_player: PlayerColor::default(),
  401            text: TextStyle::default(),
  402            scrollbar_width: Pixels::default(),
  403            syntax: Default::default(),
  404            // HACK: Status colors don't have a real default.
  405            // We should look into removing the status colors from the editor
  406            // style and retrieve them directly from the theme.
  407            status: StatusColors::dark(),
  408            inlay_hints_style: HighlightStyle::default(),
  409            suggestions_style: HighlightStyle::default(),
  410            unnecessary_code_fade: Default::default(),
  411        }
  412    }
  413}
  414
  415pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  416    let show_background = all_language_settings(None, cx)
  417        .language(None)
  418        .inlay_hints
  419        .show_background;
  420
  421    HighlightStyle {
  422        color: Some(cx.theme().status().hint),
  423        background_color: show_background.then(|| cx.theme().status().hint_background),
  424        ..HighlightStyle::default()
  425    }
  426}
  427
  428type CompletionId = usize;
  429
  430#[derive(Clone, Debug)]
  431struct CompletionState {
  432    // render_inlay_ids represents the inlay hints that are inserted
  433    // for rendering the inline completions. They may be discontinuous
  434    // in the event that the completion provider returns some intersection
  435    // with the existing content.
  436    render_inlay_ids: Vec<InlayId>,
  437    // text is the resulting rope that is inserted when the user accepts a completion.
  438    text: Rope,
  439    // position is the position of the cursor when the completion was triggered.
  440    position: multi_buffer::Anchor,
  441    // delete_range is the range of text that this completion state covers.
  442    // if the completion is accepted, this range should be deleted.
  443    delete_range: Option<Range<multi_buffer::Anchor>>,
  444}
  445
  446#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  447struct EditorActionId(usize);
  448
  449impl EditorActionId {
  450    pub fn post_inc(&mut self) -> Self {
  451        let answer = self.0;
  452
  453        *self = Self(answer + 1);
  454
  455        Self(answer)
  456    }
  457}
  458
  459// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  460// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  461
  462type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  463type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  464
  465#[derive(Default)]
  466struct ScrollbarMarkerState {
  467    scrollbar_size: Size<Pixels>,
  468    dirty: bool,
  469    markers: Arc<[PaintQuad]>,
  470    pending_refresh: Option<Task<Result<()>>>,
  471}
  472
  473impl ScrollbarMarkerState {
  474    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  475        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  476    }
  477}
  478
  479#[derive(Clone, Debug)]
  480struct RunnableTasks {
  481    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  482    offset: MultiBufferOffset,
  483    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  484    column: u32,
  485    // Values of all named captures, including those starting with '_'
  486    extra_variables: HashMap<String, String>,
  487    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  488    context_range: Range<BufferOffset>,
  489}
  490
  491#[derive(Clone)]
  492struct ResolvedTasks {
  493    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  494    position: Anchor,
  495}
  496#[derive(Copy, Clone, Debug)]
  497struct MultiBufferOffset(usize);
  498#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  499struct BufferOffset(usize);
  500
  501// Addons allow storing per-editor state in other crates (e.g. Vim)
  502pub trait Addon: 'static {
  503    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  504
  505    fn to_any(&self) -> &dyn std::any::Any;
  506}
  507
  508/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  509///
  510/// See the [module level documentation](self) for more information.
  511pub struct Editor {
  512    focus_handle: FocusHandle,
  513    last_focused_descendant: Option<WeakFocusHandle>,
  514    /// The text buffer being edited
  515    buffer: Model<MultiBuffer>,
  516    /// Map of how text in the buffer should be displayed.
  517    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  518    pub display_map: Model<DisplayMap>,
  519    pub selections: SelectionsCollection,
  520    pub scroll_manager: ScrollManager,
  521    /// When inline assist editors are linked, they all render cursors because
  522    /// typing enters text into each of them, even the ones that aren't focused.
  523    pub(crate) show_cursor_when_unfocused: bool,
  524    columnar_selection_tail: Option<Anchor>,
  525    add_selections_state: Option<AddSelectionsState>,
  526    select_next_state: Option<SelectNextState>,
  527    select_prev_state: Option<SelectNextState>,
  528    selection_history: SelectionHistory,
  529    autoclose_regions: Vec<AutocloseRegion>,
  530    snippet_stack: InvalidationStack<SnippetState>,
  531    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  532    ime_transaction: Option<TransactionId>,
  533    active_diagnostics: Option<ActiveDiagnosticGroup>,
  534    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  535    project: Option<Model<Project>>,
  536    completion_provider: Option<Box<dyn CompletionProvider>>,
  537    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  538    blink_manager: Model<BlinkManager>,
  539    show_cursor_names: bool,
  540    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  541    pub show_local_selections: bool,
  542    mode: EditorMode,
  543    show_breadcrumbs: bool,
  544    show_gutter: bool,
  545    show_line_numbers: Option<bool>,
  546    use_relative_line_numbers: Option<bool>,
  547    show_git_diff_gutter: Option<bool>,
  548    show_code_actions: Option<bool>,
  549    show_runnables: Option<bool>,
  550    show_wrap_guides: Option<bool>,
  551    show_indent_guides: Option<bool>,
  552    placeholder_text: Option<Arc<str>>,
  553    highlight_order: usize,
  554    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  555    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  556    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  557    scrollbar_marker_state: ScrollbarMarkerState,
  558    active_indent_guides_state: ActiveIndentGuidesState,
  559    nav_history: Option<ItemNavHistory>,
  560    context_menu: RwLock<Option<ContextMenu>>,
  561    mouse_context_menu: Option<MouseContextMenu>,
  562    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  563    signature_help_state: SignatureHelpState,
  564    auto_signature_help: Option<bool>,
  565    find_all_references_task_sources: Vec<Anchor>,
  566    next_completion_id: CompletionId,
  567    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  568    available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
  569    code_actions_task: Option<Task<()>>,
  570    document_highlights_task: Option<Task<()>>,
  571    linked_editing_range_task: Option<Task<Option<()>>>,
  572    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  573    pending_rename: Option<RenameState>,
  574    searchable: bool,
  575    cursor_shape: CursorShape,
  576    current_line_highlight: Option<CurrentLineHighlight>,
  577    collapse_matches: bool,
  578    autoindent_mode: Option<AutoindentMode>,
  579    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  580    input_enabled: bool,
  581    use_modal_editing: bool,
  582    read_only: bool,
  583    leader_peer_id: Option<PeerId>,
  584    remote_id: Option<ViewId>,
  585    hover_state: HoverState,
  586    gutter_hovered: bool,
  587    hovered_link_state: Option<HoveredLinkState>,
  588    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  589    active_inline_completion: Option<CompletionState>,
  590    // enable_inline_completions is a switch that Vim can use to disable
  591    // inline completions based on its mode.
  592    enable_inline_completions: bool,
  593    show_inline_completions_override: Option<bool>,
  594    inlay_hint_cache: InlayHintCache,
  595    expanded_hunks: ExpandedHunks,
  596    next_inlay_id: usize,
  597    _subscriptions: Vec<Subscription>,
  598    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  599    gutter_dimensions: GutterDimensions,
  600    style: Option<EditorStyle>,
  601    next_editor_action_id: EditorActionId,
  602    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  603    use_autoclose: bool,
  604    use_auto_surround: bool,
  605    auto_replace_emoji_shortcode: bool,
  606    show_git_blame_gutter: bool,
  607    show_git_blame_inline: bool,
  608    show_git_blame_inline_delay_task: Option<Task<()>>,
  609    git_blame_inline_enabled: bool,
  610    serialize_dirty_buffers: bool,
  611    show_selection_menu: Option<bool>,
  612    blame: Option<Model<GitBlame>>,
  613    blame_subscription: Option<Subscription>,
  614    custom_context_menu: Option<
  615        Box<
  616            dyn 'static
  617                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  618        >,
  619    >,
  620    last_bounds: Option<Bounds<Pixels>>,
  621    expect_bounds_change: Option<Bounds<Pixels>>,
  622    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  623    tasks_update_task: Option<Task<()>>,
  624    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  625    file_header_size: u32,
  626    breadcrumb_header: Option<String>,
  627    focused_block: Option<FocusedBlock>,
  628    next_scroll_position: NextScrollCursorCenterTopBottom,
  629    addons: HashMap<TypeId, Box<dyn Addon>>,
  630    _scroll_cursor_center_top_bottom_task: Task<()>,
  631}
  632
  633#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  634enum NextScrollCursorCenterTopBottom {
  635    #[default]
  636    Center,
  637    Top,
  638    Bottom,
  639}
  640
  641impl NextScrollCursorCenterTopBottom {
  642    fn next(&self) -> Self {
  643        match self {
  644            Self::Center => Self::Top,
  645            Self::Top => Self::Bottom,
  646            Self::Bottom => Self::Center,
  647        }
  648    }
  649}
  650
  651#[derive(Clone)]
  652pub struct EditorSnapshot {
  653    pub mode: EditorMode,
  654    show_gutter: bool,
  655    show_line_numbers: Option<bool>,
  656    show_git_diff_gutter: Option<bool>,
  657    show_code_actions: Option<bool>,
  658    show_runnables: Option<bool>,
  659    render_git_blame_gutter: bool,
  660    pub display_snapshot: DisplaySnapshot,
  661    pub placeholder_text: Option<Arc<str>>,
  662    is_focused: bool,
  663    scroll_anchor: ScrollAnchor,
  664    ongoing_scroll: OngoingScroll,
  665    current_line_highlight: CurrentLineHighlight,
  666    gutter_hovered: bool,
  667}
  668
  669const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
  670
  671#[derive(Default, Debug, Clone, Copy)]
  672pub struct GutterDimensions {
  673    pub left_padding: Pixels,
  674    pub right_padding: Pixels,
  675    pub width: Pixels,
  676    pub margin: Pixels,
  677    pub git_blame_entries_width: Option<Pixels>,
  678}
  679
  680impl GutterDimensions {
  681    /// The full width of the space taken up by the gutter.
  682    pub fn full_width(&self) -> Pixels {
  683        self.margin + self.width
  684    }
  685
  686    /// The width of the space reserved for the fold indicators,
  687    /// use alongside 'justify_end' and `gutter_width` to
  688    /// right align content with the line numbers
  689    pub fn fold_area_width(&self) -> Pixels {
  690        self.margin + self.right_padding
  691    }
  692}
  693
  694#[derive(Debug)]
  695pub struct RemoteSelection {
  696    pub replica_id: ReplicaId,
  697    pub selection: Selection<Anchor>,
  698    pub cursor_shape: CursorShape,
  699    pub peer_id: PeerId,
  700    pub line_mode: bool,
  701    pub participant_index: Option<ParticipantIndex>,
  702    pub user_name: Option<SharedString>,
  703}
  704
  705#[derive(Clone, Debug)]
  706struct SelectionHistoryEntry {
  707    selections: Arc<[Selection<Anchor>]>,
  708    select_next_state: Option<SelectNextState>,
  709    select_prev_state: Option<SelectNextState>,
  710    add_selections_state: Option<AddSelectionsState>,
  711}
  712
  713enum SelectionHistoryMode {
  714    Normal,
  715    Undoing,
  716    Redoing,
  717}
  718
  719#[derive(Clone, PartialEq, Eq, Hash)]
  720struct HoveredCursor {
  721    replica_id: u16,
  722    selection_id: usize,
  723}
  724
  725impl Default for SelectionHistoryMode {
  726    fn default() -> Self {
  727        Self::Normal
  728    }
  729}
  730
  731#[derive(Default)]
  732struct SelectionHistory {
  733    #[allow(clippy::type_complexity)]
  734    selections_by_transaction:
  735        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  736    mode: SelectionHistoryMode,
  737    undo_stack: VecDeque<SelectionHistoryEntry>,
  738    redo_stack: VecDeque<SelectionHistoryEntry>,
  739}
  740
  741impl SelectionHistory {
  742    fn insert_transaction(
  743        &mut self,
  744        transaction_id: TransactionId,
  745        selections: Arc<[Selection<Anchor>]>,
  746    ) {
  747        self.selections_by_transaction
  748            .insert(transaction_id, (selections, None));
  749    }
  750
  751    #[allow(clippy::type_complexity)]
  752    fn transaction(
  753        &self,
  754        transaction_id: TransactionId,
  755    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  756        self.selections_by_transaction.get(&transaction_id)
  757    }
  758
  759    #[allow(clippy::type_complexity)]
  760    fn transaction_mut(
  761        &mut self,
  762        transaction_id: TransactionId,
  763    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  764        self.selections_by_transaction.get_mut(&transaction_id)
  765    }
  766
  767    fn push(&mut self, entry: SelectionHistoryEntry) {
  768        if !entry.selections.is_empty() {
  769            match self.mode {
  770                SelectionHistoryMode::Normal => {
  771                    self.push_undo(entry);
  772                    self.redo_stack.clear();
  773                }
  774                SelectionHistoryMode::Undoing => self.push_redo(entry),
  775                SelectionHistoryMode::Redoing => self.push_undo(entry),
  776            }
  777        }
  778    }
  779
  780    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  781        if self
  782            .undo_stack
  783            .back()
  784            .map_or(true, |e| e.selections != entry.selections)
  785        {
  786            self.undo_stack.push_back(entry);
  787            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  788                self.undo_stack.pop_front();
  789            }
  790        }
  791    }
  792
  793    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  794        if self
  795            .redo_stack
  796            .back()
  797            .map_or(true, |e| e.selections != entry.selections)
  798        {
  799            self.redo_stack.push_back(entry);
  800            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  801                self.redo_stack.pop_front();
  802            }
  803        }
  804    }
  805}
  806
  807struct RowHighlight {
  808    index: usize,
  809    range: RangeInclusive<Anchor>,
  810    color: Option<Hsla>,
  811    should_autoscroll: bool,
  812}
  813
  814#[derive(Clone, Debug)]
  815struct AddSelectionsState {
  816    above: bool,
  817    stack: Vec<usize>,
  818}
  819
  820#[derive(Clone)]
  821struct SelectNextState {
  822    query: AhoCorasick,
  823    wordwise: bool,
  824    done: bool,
  825}
  826
  827impl std::fmt::Debug for SelectNextState {
  828    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  829        f.debug_struct(std::any::type_name::<Self>())
  830            .field("wordwise", &self.wordwise)
  831            .field("done", &self.done)
  832            .finish()
  833    }
  834}
  835
  836#[derive(Debug)]
  837struct AutocloseRegion {
  838    selection_id: usize,
  839    range: Range<Anchor>,
  840    pair: BracketPair,
  841}
  842
  843#[derive(Debug)]
  844struct SnippetState {
  845    ranges: Vec<Vec<Range<Anchor>>>,
  846    active_index: usize,
  847}
  848
  849#[doc(hidden)]
  850pub struct RenameState {
  851    pub range: Range<Anchor>,
  852    pub old_name: Arc<str>,
  853    pub editor: View<Editor>,
  854    block_id: CustomBlockId,
  855}
  856
  857struct InvalidationStack<T>(Vec<T>);
  858
  859struct RegisteredInlineCompletionProvider {
  860    provider: Arc<dyn InlineCompletionProviderHandle>,
  861    _subscription: Subscription,
  862}
  863
  864enum ContextMenu {
  865    Completions(CompletionsMenu),
  866    CodeActions(CodeActionsMenu),
  867}
  868
  869impl ContextMenu {
  870    fn select_first(
  871        &mut self,
  872        project: Option<&Model<Project>>,
  873        cx: &mut ViewContext<Editor>,
  874    ) -> bool {
  875        if self.visible() {
  876            match self {
  877                ContextMenu::Completions(menu) => menu.select_first(project, cx),
  878                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  879            }
  880            true
  881        } else {
  882            false
  883        }
  884    }
  885
  886    fn select_prev(
  887        &mut self,
  888        project: Option<&Model<Project>>,
  889        cx: &mut ViewContext<Editor>,
  890    ) -> bool {
  891        if self.visible() {
  892            match self {
  893                ContextMenu::Completions(menu) => menu.select_prev(project, cx),
  894                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  895            }
  896            true
  897        } else {
  898            false
  899        }
  900    }
  901
  902    fn select_next(
  903        &mut self,
  904        project: Option<&Model<Project>>,
  905        cx: &mut ViewContext<Editor>,
  906    ) -> bool {
  907        if self.visible() {
  908            match self {
  909                ContextMenu::Completions(menu) => menu.select_next(project, cx),
  910                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  911            }
  912            true
  913        } else {
  914            false
  915        }
  916    }
  917
  918    fn select_last(
  919        &mut self,
  920        project: Option<&Model<Project>>,
  921        cx: &mut ViewContext<Editor>,
  922    ) -> bool {
  923        if self.visible() {
  924            match self {
  925                ContextMenu::Completions(menu) => menu.select_last(project, cx),
  926                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  927            }
  928            true
  929        } else {
  930            false
  931        }
  932    }
  933
  934    fn visible(&self) -> bool {
  935        match self {
  936            ContextMenu::Completions(menu) => menu.visible(),
  937            ContextMenu::CodeActions(menu) => menu.visible(),
  938        }
  939    }
  940
  941    fn render(
  942        &self,
  943        cursor_position: DisplayPoint,
  944        style: &EditorStyle,
  945        max_height: Pixels,
  946        workspace: Option<WeakView<Workspace>>,
  947        cx: &mut ViewContext<Editor>,
  948    ) -> (ContextMenuOrigin, AnyElement) {
  949        match self {
  950            ContextMenu::Completions(menu) => (
  951                ContextMenuOrigin::EditorPoint(cursor_position),
  952                menu.render(style, max_height, workspace, cx),
  953            ),
  954            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  955        }
  956    }
  957}
  958
  959enum ContextMenuOrigin {
  960    EditorPoint(DisplayPoint),
  961    GutterIndicator(DisplayRow),
  962}
  963
  964#[derive(Clone)]
  965struct CompletionsMenu {
  966    id: CompletionId,
  967    sort_completions: bool,
  968    initial_position: Anchor,
  969    buffer: Model<Buffer>,
  970    completions: Arc<RwLock<Box<[Completion]>>>,
  971    match_candidates: Arc<[StringMatchCandidate]>,
  972    matches: Arc<[StringMatch]>,
  973    selected_item: usize,
  974    scroll_handle: UniformListScrollHandle,
  975    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  976}
  977
  978impl CompletionsMenu {
  979    fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  980        self.selected_item = 0;
  981        self.scroll_handle.scroll_to_item(self.selected_item);
  982        self.attempt_resolve_selected_completion_documentation(project, cx);
  983        cx.notify();
  984    }
  985
  986    fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  987        if self.selected_item > 0 {
  988            self.selected_item -= 1;
  989        } else {
  990            self.selected_item = self.matches.len() - 1;
  991        }
  992        self.scroll_handle.scroll_to_item(self.selected_item);
  993        self.attempt_resolve_selected_completion_documentation(project, cx);
  994        cx.notify();
  995    }
  996
  997    fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  998        if self.selected_item + 1 < self.matches.len() {
  999            self.selected_item += 1;
 1000        } else {
 1001            self.selected_item = 0;
 1002        }
 1003        self.scroll_handle.scroll_to_item(self.selected_item);
 1004        self.attempt_resolve_selected_completion_documentation(project, cx);
 1005        cx.notify();
 1006    }
 1007
 1008    fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
 1009        self.selected_item = self.matches.len() - 1;
 1010        self.scroll_handle.scroll_to_item(self.selected_item);
 1011        self.attempt_resolve_selected_completion_documentation(project, cx);
 1012        cx.notify();
 1013    }
 1014
 1015    fn pre_resolve_completion_documentation(
 1016        buffer: Model<Buffer>,
 1017        completions: Arc<RwLock<Box<[Completion]>>>,
 1018        matches: Arc<[StringMatch]>,
 1019        editor: &Editor,
 1020        cx: &mut ViewContext<Editor>,
 1021    ) -> Task<()> {
 1022        let settings = EditorSettings::get_global(cx);
 1023        if !settings.show_completion_documentation {
 1024            return Task::ready(());
 1025        }
 1026
 1027        let Some(provider) = editor.completion_provider.as_ref() else {
 1028            return Task::ready(());
 1029        };
 1030
 1031        let resolve_task = provider.resolve_completions(
 1032            buffer,
 1033            matches.iter().map(|m| m.candidate_id).collect(),
 1034            completions.clone(),
 1035            cx,
 1036        );
 1037
 1038        cx.spawn(move |this, mut cx| async move {
 1039            if let Some(true) = resolve_task.await.log_err() {
 1040                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1041            }
 1042        })
 1043    }
 1044
 1045    fn attempt_resolve_selected_completion_documentation(
 1046        &mut self,
 1047        project: Option<&Model<Project>>,
 1048        cx: &mut ViewContext<Editor>,
 1049    ) {
 1050        let settings = EditorSettings::get_global(cx);
 1051        if !settings.show_completion_documentation {
 1052            return;
 1053        }
 1054
 1055        let completion_index = self.matches[self.selected_item].candidate_id;
 1056        let Some(project) = project else {
 1057            return;
 1058        };
 1059
 1060        let resolve_task = project.update(cx, |project, cx| {
 1061            project.resolve_completions(
 1062                self.buffer.clone(),
 1063                vec![completion_index],
 1064                self.completions.clone(),
 1065                cx,
 1066            )
 1067        });
 1068
 1069        let delay_ms =
 1070            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1071        let delay = Duration::from_millis(delay_ms);
 1072
 1073        self.selected_completion_documentation_resolve_debounce
 1074            .lock()
 1075            .fire_new(delay, cx, |_, cx| {
 1076                cx.spawn(move |this, mut cx| async move {
 1077                    if let Some(true) = resolve_task.await.log_err() {
 1078                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1079                    }
 1080                })
 1081            });
 1082    }
 1083
 1084    fn visible(&self) -> bool {
 1085        !self.matches.is_empty()
 1086    }
 1087
 1088    fn render(
 1089        &self,
 1090        style: &EditorStyle,
 1091        max_height: Pixels,
 1092        workspace: Option<WeakView<Workspace>>,
 1093        cx: &mut ViewContext<Editor>,
 1094    ) -> AnyElement {
 1095        let settings = EditorSettings::get_global(cx);
 1096        let show_completion_documentation = settings.show_completion_documentation;
 1097
 1098        let widest_completion_ix = self
 1099            .matches
 1100            .iter()
 1101            .enumerate()
 1102            .max_by_key(|(_, mat)| {
 1103                let completions = self.completions.read();
 1104                let completion = &completions[mat.candidate_id];
 1105                let documentation = &completion.documentation;
 1106
 1107                let mut len = completion.label.text.chars().count();
 1108                if let Some(Documentation::SingleLine(text)) = documentation {
 1109                    if show_completion_documentation {
 1110                        len += text.chars().count();
 1111                    }
 1112                }
 1113
 1114                len
 1115            })
 1116            .map(|(ix, _)| ix);
 1117
 1118        let completions = self.completions.clone();
 1119        let matches = self.matches.clone();
 1120        let selected_item = self.selected_item;
 1121        let style = style.clone();
 1122
 1123        let multiline_docs = if show_completion_documentation {
 1124            let mat = &self.matches[selected_item];
 1125            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1126                Some(Documentation::MultiLinePlainText(text)) => {
 1127                    Some(div().child(SharedString::from(text.clone())))
 1128                }
 1129                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1130                    Some(div().child(render_parsed_markdown(
 1131                        "completions_markdown",
 1132                        parsed,
 1133                        &style,
 1134                        workspace,
 1135                        cx,
 1136                    )))
 1137                }
 1138                _ => None,
 1139            };
 1140            multiline_docs.map(|div| {
 1141                div.id("multiline_docs")
 1142                    .max_h(max_height)
 1143                    .flex_1()
 1144                    .px_1p5()
 1145                    .py_1()
 1146                    .min_w(px(260.))
 1147                    .max_w(px(640.))
 1148                    .w(px(500.))
 1149                    .overflow_y_scroll()
 1150                    .occlude()
 1151            })
 1152        } else {
 1153            None
 1154        };
 1155
 1156        let list = uniform_list(
 1157            cx.view().clone(),
 1158            "completions",
 1159            matches.len(),
 1160            move |_editor, range, cx| {
 1161                let start_ix = range.start;
 1162                let completions_guard = completions.read();
 1163
 1164                matches[range]
 1165                    .iter()
 1166                    .enumerate()
 1167                    .map(|(ix, mat)| {
 1168                        let item_ix = start_ix + ix;
 1169                        let candidate_id = mat.candidate_id;
 1170                        let completion = &completions_guard[candidate_id];
 1171
 1172                        let documentation = if show_completion_documentation {
 1173                            &completion.documentation
 1174                        } else {
 1175                            &None
 1176                        };
 1177
 1178                        let highlights = gpui::combine_highlights(
 1179                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1180                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1181                                |(range, mut highlight)| {
 1182                                    // Ignore font weight for syntax highlighting, as we'll use it
 1183                                    // for fuzzy matches.
 1184                                    highlight.font_weight = None;
 1185
 1186                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1187                                        highlight.strikethrough = Some(StrikethroughStyle {
 1188                                            thickness: 1.0.into(),
 1189                                            ..Default::default()
 1190                                        });
 1191                                        highlight.color = Some(cx.theme().colors().text_muted);
 1192                                    }
 1193
 1194                                    (range, highlight)
 1195                                },
 1196                            ),
 1197                        );
 1198                        let completion_label = StyledText::new(completion.label.text.clone())
 1199                            .with_highlights(&style.text, highlights);
 1200                        let documentation_label =
 1201                            if let Some(Documentation::SingleLine(text)) = documentation {
 1202                                if text.trim().is_empty() {
 1203                                    None
 1204                                } else {
 1205                                    Some(
 1206                                        Label::new(text.clone())
 1207                                            .ml_4()
 1208                                            .size(LabelSize::Small)
 1209                                            .color(Color::Muted),
 1210                                    )
 1211                                }
 1212                            } else {
 1213                                None
 1214                            };
 1215
 1216                        div().min_w(px(220.)).max_w(px(540.)).child(
 1217                            ListItem::new(mat.candidate_id)
 1218                                .inset(true)
 1219                                .selected(item_ix == selected_item)
 1220                                .on_click(cx.listener(move |editor, _event, cx| {
 1221                                    cx.stop_propagation();
 1222                                    if let Some(task) = editor.confirm_completion(
 1223                                        &ConfirmCompletion {
 1224                                            item_ix: Some(item_ix),
 1225                                        },
 1226                                        cx,
 1227                                    ) {
 1228                                        task.detach_and_log_err(cx)
 1229                                    }
 1230                                }))
 1231                                .child(h_flex().overflow_hidden().child(completion_label))
 1232                                .end_slot::<Label>(documentation_label),
 1233                        )
 1234                    })
 1235                    .collect()
 1236            },
 1237        )
 1238        .occlude()
 1239        .max_h(max_height)
 1240        .track_scroll(self.scroll_handle.clone())
 1241        .with_width_from_item(widest_completion_ix)
 1242        .with_sizing_behavior(ListSizingBehavior::Infer);
 1243
 1244        Popover::new()
 1245            .child(list)
 1246            .when_some(multiline_docs, |popover, multiline_docs| {
 1247                popover.aside(multiline_docs)
 1248            })
 1249            .into_any_element()
 1250    }
 1251
 1252    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1253        let mut matches = if let Some(query) = query {
 1254            fuzzy::match_strings(
 1255                &self.match_candidates,
 1256                query,
 1257                query.chars().any(|c| c.is_uppercase()),
 1258                100,
 1259                &Default::default(),
 1260                executor,
 1261            )
 1262            .await
 1263        } else {
 1264            self.match_candidates
 1265                .iter()
 1266                .enumerate()
 1267                .map(|(candidate_id, candidate)| StringMatch {
 1268                    candidate_id,
 1269                    score: Default::default(),
 1270                    positions: Default::default(),
 1271                    string: candidate.string.clone(),
 1272                })
 1273                .collect()
 1274        };
 1275
 1276        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1277        if let Some(query) = query {
 1278            if let Some(query_start) = query.chars().next() {
 1279                matches.retain(|string_match| {
 1280                    split_words(&string_match.string).any(|word| {
 1281                        // Check that the first codepoint of the word as lowercase matches the first
 1282                        // codepoint of the query as lowercase
 1283                        word.chars()
 1284                            .flat_map(|codepoint| codepoint.to_lowercase())
 1285                            .zip(query_start.to_lowercase())
 1286                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1287                    })
 1288                });
 1289            }
 1290        }
 1291
 1292        let completions = self.completions.read();
 1293        if self.sort_completions {
 1294            matches.sort_unstable_by_key(|mat| {
 1295                // We do want to strike a balance here between what the language server tells us
 1296                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1297                // `Creat` and there is a local variable called `CreateComponent`).
 1298                // So what we do is: we bucket all matches into two buckets
 1299                // - Strong matches
 1300                // - Weak matches
 1301                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1302                // and the Weak matches are the rest.
 1303                //
 1304                // For the strong matches, we sort by the language-servers score first and for the weak
 1305                // matches, we prefer our fuzzy finder first.
 1306                //
 1307                // The thinking behind that: it's useless to take the sort_text the language-server gives
 1308                // us into account when it's obviously a bad match.
 1309
 1310                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1311                enum MatchScore<'a> {
 1312                    Strong {
 1313                        sort_text: Option<&'a str>,
 1314                        score: Reverse<OrderedFloat<f64>>,
 1315                        sort_key: (usize, &'a str),
 1316                    },
 1317                    Weak {
 1318                        score: Reverse<OrderedFloat<f64>>,
 1319                        sort_text: Option<&'a str>,
 1320                        sort_key: (usize, &'a str),
 1321                    },
 1322                }
 1323
 1324                let completion = &completions[mat.candidate_id];
 1325                let sort_key = completion.sort_key();
 1326                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1327                let score = Reverse(OrderedFloat(mat.score));
 1328
 1329                if mat.score >= 0.2 {
 1330                    MatchScore::Strong {
 1331                        sort_text,
 1332                        score,
 1333                        sort_key,
 1334                    }
 1335                } else {
 1336                    MatchScore::Weak {
 1337                        score,
 1338                        sort_text,
 1339                        sort_key,
 1340                    }
 1341                }
 1342            });
 1343        }
 1344
 1345        for mat in &mut matches {
 1346            let completion = &completions[mat.candidate_id];
 1347            mat.string.clone_from(&completion.label.text);
 1348            for position in &mut mat.positions {
 1349                *position += completion.label.filter_range.start;
 1350            }
 1351        }
 1352        drop(completions);
 1353
 1354        self.matches = matches.into();
 1355        self.selected_item = 0;
 1356    }
 1357}
 1358
 1359#[derive(Clone)]
 1360struct CodeActionContents {
 1361    tasks: Option<Arc<ResolvedTasks>>,
 1362    actions: Option<Arc<[CodeAction]>>,
 1363}
 1364
 1365impl CodeActionContents {
 1366    fn len(&self) -> usize {
 1367        match (&self.tasks, &self.actions) {
 1368            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1369            (Some(tasks), None) => tasks.templates.len(),
 1370            (None, Some(actions)) => actions.len(),
 1371            (None, None) => 0,
 1372        }
 1373    }
 1374
 1375    fn is_empty(&self) -> bool {
 1376        match (&self.tasks, &self.actions) {
 1377            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1378            (Some(tasks), None) => tasks.templates.is_empty(),
 1379            (None, Some(actions)) => actions.is_empty(),
 1380            (None, None) => true,
 1381        }
 1382    }
 1383
 1384    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1385        self.tasks
 1386            .iter()
 1387            .flat_map(|tasks| {
 1388                tasks
 1389                    .templates
 1390                    .iter()
 1391                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1392            })
 1393            .chain(self.actions.iter().flat_map(|actions| {
 1394                actions
 1395                    .iter()
 1396                    .map(|action| CodeActionsItem::CodeAction(action.clone()))
 1397            }))
 1398    }
 1399    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1400        match (&self.tasks, &self.actions) {
 1401            (Some(tasks), Some(actions)) => {
 1402                if index < tasks.templates.len() {
 1403                    tasks
 1404                        .templates
 1405                        .get(index)
 1406                        .cloned()
 1407                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1408                } else {
 1409                    actions
 1410                        .get(index - tasks.templates.len())
 1411                        .cloned()
 1412                        .map(CodeActionsItem::CodeAction)
 1413                }
 1414            }
 1415            (Some(tasks), None) => tasks
 1416                .templates
 1417                .get(index)
 1418                .cloned()
 1419                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1420            (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
 1421            (None, None) => None,
 1422        }
 1423    }
 1424}
 1425
 1426#[allow(clippy::large_enum_variant)]
 1427#[derive(Clone)]
 1428enum CodeActionsItem {
 1429    Task(TaskSourceKind, ResolvedTask),
 1430    CodeAction(CodeAction),
 1431}
 1432
 1433impl CodeActionsItem {
 1434    fn as_task(&self) -> Option<&ResolvedTask> {
 1435        let Self::Task(_, task) = self else {
 1436            return None;
 1437        };
 1438        Some(task)
 1439    }
 1440    fn as_code_action(&self) -> Option<&CodeAction> {
 1441        let Self::CodeAction(action) = self else {
 1442            return None;
 1443        };
 1444        Some(action)
 1445    }
 1446    fn label(&self) -> String {
 1447        match self {
 1448            Self::CodeAction(action) => action.lsp_action.title.clone(),
 1449            Self::Task(_, task) => task.resolved_label.clone(),
 1450        }
 1451    }
 1452}
 1453
 1454struct CodeActionsMenu {
 1455    actions: CodeActionContents,
 1456    buffer: Model<Buffer>,
 1457    selected_item: usize,
 1458    scroll_handle: UniformListScrollHandle,
 1459    deployed_from_indicator: Option<DisplayRow>,
 1460}
 1461
 1462impl CodeActionsMenu {
 1463    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1464        self.selected_item = 0;
 1465        self.scroll_handle.scroll_to_item(self.selected_item);
 1466        cx.notify()
 1467    }
 1468
 1469    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1470        if self.selected_item > 0 {
 1471            self.selected_item -= 1;
 1472        } else {
 1473            self.selected_item = self.actions.len() - 1;
 1474        }
 1475        self.scroll_handle.scroll_to_item(self.selected_item);
 1476        cx.notify();
 1477    }
 1478
 1479    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1480        if self.selected_item + 1 < self.actions.len() {
 1481            self.selected_item += 1;
 1482        } else {
 1483            self.selected_item = 0;
 1484        }
 1485        self.scroll_handle.scroll_to_item(self.selected_item);
 1486        cx.notify();
 1487    }
 1488
 1489    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1490        self.selected_item = self.actions.len() - 1;
 1491        self.scroll_handle.scroll_to_item(self.selected_item);
 1492        cx.notify()
 1493    }
 1494
 1495    fn visible(&self) -> bool {
 1496        !self.actions.is_empty()
 1497    }
 1498
 1499    fn render(
 1500        &self,
 1501        cursor_position: DisplayPoint,
 1502        _style: &EditorStyle,
 1503        max_height: Pixels,
 1504        cx: &mut ViewContext<Editor>,
 1505    ) -> (ContextMenuOrigin, AnyElement) {
 1506        let actions = self.actions.clone();
 1507        let selected_item = self.selected_item;
 1508        let element = uniform_list(
 1509            cx.view().clone(),
 1510            "code_actions_menu",
 1511            self.actions.len(),
 1512            move |_this, range, cx| {
 1513                actions
 1514                    .iter()
 1515                    .skip(range.start)
 1516                    .take(range.end - range.start)
 1517                    .enumerate()
 1518                    .map(|(ix, action)| {
 1519                        let item_ix = range.start + ix;
 1520                        let selected = selected_item == item_ix;
 1521                        let colors = cx.theme().colors();
 1522                        div()
 1523                            .px_1()
 1524                            .rounded_md()
 1525                            .text_color(colors.text)
 1526                            .when(selected, |style| {
 1527                                style
 1528                                    .bg(colors.element_active)
 1529                                    .text_color(colors.text_accent)
 1530                            })
 1531                            .hover(|style| {
 1532                                style
 1533                                    .bg(colors.element_hover)
 1534                                    .text_color(colors.text_accent)
 1535                            })
 1536                            .whitespace_nowrap()
 1537                            .when_some(action.as_code_action(), |this, action| {
 1538                                this.on_mouse_down(
 1539                                    MouseButton::Left,
 1540                                    cx.listener(move |editor, _, cx| {
 1541                                        cx.stop_propagation();
 1542                                        if let Some(task) = editor.confirm_code_action(
 1543                                            &ConfirmCodeAction {
 1544                                                item_ix: Some(item_ix),
 1545                                            },
 1546                                            cx,
 1547                                        ) {
 1548                                            task.detach_and_log_err(cx)
 1549                                        }
 1550                                    }),
 1551                                )
 1552                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1553                                .child(SharedString::from(action.lsp_action.title.clone()))
 1554                            })
 1555                            .when_some(action.as_task(), |this, task| {
 1556                                this.on_mouse_down(
 1557                                    MouseButton::Left,
 1558                                    cx.listener(move |editor, _, cx| {
 1559                                        cx.stop_propagation();
 1560                                        if let Some(task) = editor.confirm_code_action(
 1561                                            &ConfirmCodeAction {
 1562                                                item_ix: Some(item_ix),
 1563                                            },
 1564                                            cx,
 1565                                        ) {
 1566                                            task.detach_and_log_err(cx)
 1567                                        }
 1568                                    }),
 1569                                )
 1570                                .child(SharedString::from(task.resolved_label.clone()))
 1571                            })
 1572                    })
 1573                    .collect()
 1574            },
 1575        )
 1576        .elevation_1(cx)
 1577        .p_1()
 1578        .max_h(max_height)
 1579        .occlude()
 1580        .track_scroll(self.scroll_handle.clone())
 1581        .with_width_from_item(
 1582            self.actions
 1583                .iter()
 1584                .enumerate()
 1585                .max_by_key(|(_, action)| match action {
 1586                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1587                    CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
 1588                })
 1589                .map(|(ix, _)| ix),
 1590        )
 1591        .with_sizing_behavior(ListSizingBehavior::Infer)
 1592        .into_any_element();
 1593
 1594        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1595            ContextMenuOrigin::GutterIndicator(row)
 1596        } else {
 1597            ContextMenuOrigin::EditorPoint(cursor_position)
 1598        };
 1599
 1600        (cursor_position, element)
 1601    }
 1602}
 1603
 1604#[derive(Debug)]
 1605struct ActiveDiagnosticGroup {
 1606    primary_range: Range<Anchor>,
 1607    primary_message: String,
 1608    group_id: usize,
 1609    blocks: HashMap<CustomBlockId, Diagnostic>,
 1610    is_valid: bool,
 1611}
 1612
 1613#[derive(Serialize, Deserialize, Clone, Debug)]
 1614pub struct ClipboardSelection {
 1615    pub len: usize,
 1616    pub is_entire_line: bool,
 1617    pub first_line_indent: u32,
 1618}
 1619
 1620#[derive(Debug)]
 1621pub(crate) struct NavigationData {
 1622    cursor_anchor: Anchor,
 1623    cursor_position: Point,
 1624    scroll_anchor: ScrollAnchor,
 1625    scroll_top_row: u32,
 1626}
 1627
 1628#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1629enum GotoDefinitionKind {
 1630    Symbol,
 1631    Declaration,
 1632    Type,
 1633    Implementation,
 1634}
 1635
 1636#[derive(Debug, Clone)]
 1637enum InlayHintRefreshReason {
 1638    Toggle(bool),
 1639    SettingsChange(InlayHintSettings),
 1640    NewLinesShown,
 1641    BufferEdited(HashSet<Arc<Language>>),
 1642    RefreshRequested,
 1643    ExcerptsRemoved(Vec<ExcerptId>),
 1644}
 1645
 1646impl InlayHintRefreshReason {
 1647    fn description(&self) -> &'static str {
 1648        match self {
 1649            Self::Toggle(_) => "toggle",
 1650            Self::SettingsChange(_) => "settings change",
 1651            Self::NewLinesShown => "new lines shown",
 1652            Self::BufferEdited(_) => "buffer edited",
 1653            Self::RefreshRequested => "refresh requested",
 1654            Self::ExcerptsRemoved(_) => "excerpts removed",
 1655        }
 1656    }
 1657}
 1658
 1659pub(crate) struct FocusedBlock {
 1660    id: BlockId,
 1661    focus_handle: WeakFocusHandle,
 1662}
 1663
 1664impl Editor {
 1665    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1666        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1667        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1668        Self::new(
 1669            EditorMode::SingleLine { auto_width: false },
 1670            buffer,
 1671            None,
 1672            false,
 1673            cx,
 1674        )
 1675    }
 1676
 1677    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1678        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1679        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1680        Self::new(EditorMode::Full, buffer, None, false, cx)
 1681    }
 1682
 1683    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1684        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1685        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1686        Self::new(
 1687            EditorMode::SingleLine { auto_width: true },
 1688            buffer,
 1689            None,
 1690            false,
 1691            cx,
 1692        )
 1693    }
 1694
 1695    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1696        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1697        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1698        Self::new(
 1699            EditorMode::AutoHeight { max_lines },
 1700            buffer,
 1701            None,
 1702            false,
 1703            cx,
 1704        )
 1705    }
 1706
 1707    pub fn for_buffer(
 1708        buffer: Model<Buffer>,
 1709        project: Option<Model<Project>>,
 1710        cx: &mut ViewContext<Self>,
 1711    ) -> Self {
 1712        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1713        Self::new(EditorMode::Full, buffer, project, false, cx)
 1714    }
 1715
 1716    pub fn for_multibuffer(
 1717        buffer: Model<MultiBuffer>,
 1718        project: Option<Model<Project>>,
 1719        show_excerpt_controls: bool,
 1720        cx: &mut ViewContext<Self>,
 1721    ) -> Self {
 1722        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1723    }
 1724
 1725    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1726        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1727        let mut clone = Self::new(
 1728            self.mode,
 1729            self.buffer.clone(),
 1730            self.project.clone(),
 1731            show_excerpt_controls,
 1732            cx,
 1733        );
 1734        self.display_map.update(cx, |display_map, cx| {
 1735            let snapshot = display_map.snapshot(cx);
 1736            clone.display_map.update(cx, |display_map, cx| {
 1737                display_map.set_state(&snapshot, cx);
 1738            });
 1739        });
 1740        clone.selections.clone_state(&self.selections);
 1741        clone.scroll_manager.clone_state(&self.scroll_manager);
 1742        clone.searchable = self.searchable;
 1743        clone
 1744    }
 1745
 1746    pub fn new(
 1747        mode: EditorMode,
 1748        buffer: Model<MultiBuffer>,
 1749        project: Option<Model<Project>>,
 1750        show_excerpt_controls: bool,
 1751        cx: &mut ViewContext<Self>,
 1752    ) -> Self {
 1753        let style = cx.text_style();
 1754        let font_size = style.font_size.to_pixels(cx.rem_size());
 1755        let editor = cx.view().downgrade();
 1756        let fold_placeholder = FoldPlaceholder {
 1757            constrain_width: true,
 1758            render: Arc::new(move |fold_id, fold_range, cx| {
 1759                let editor = editor.clone();
 1760                div()
 1761                    .id(fold_id)
 1762                    .bg(cx.theme().colors().ghost_element_background)
 1763                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1764                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1765                    .rounded_sm()
 1766                    .size_full()
 1767                    .cursor_pointer()
 1768                    .child("")
 1769                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1770                    .on_click(move |_, cx| {
 1771                        editor
 1772                            .update(cx, |editor, cx| {
 1773                                editor.unfold_ranges(
 1774                                    [fold_range.start..fold_range.end],
 1775                                    true,
 1776                                    false,
 1777                                    cx,
 1778                                );
 1779                                cx.stop_propagation();
 1780                            })
 1781                            .ok();
 1782                    })
 1783                    .into_any()
 1784            }),
 1785            merge_adjacent: true,
 1786        };
 1787        let file_header_size = if show_excerpt_controls { 3 } else { 2 };
 1788        let display_map = cx.new_model(|cx| {
 1789            DisplayMap::new(
 1790                buffer.clone(),
 1791                style.font(),
 1792                font_size,
 1793                None,
 1794                show_excerpt_controls,
 1795                file_header_size,
 1796                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1797                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1798                fold_placeholder,
 1799                cx,
 1800            )
 1801        });
 1802
 1803        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1804
 1805        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1806
 1807        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1808            .then(|| language_settings::SoftWrap::PreferLine);
 1809
 1810        let mut project_subscriptions = Vec::new();
 1811        if mode == EditorMode::Full {
 1812            if let Some(project) = project.as_ref() {
 1813                if buffer.read(cx).is_singleton() {
 1814                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1815                        cx.emit(EditorEvent::TitleChanged);
 1816                    }));
 1817                }
 1818                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1819                    if let project::Event::RefreshInlayHints = event {
 1820                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1821                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1822                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1823                            let focus_handle = editor.focus_handle(cx);
 1824                            if focus_handle.is_focused(cx) {
 1825                                let snapshot = buffer.read(cx).snapshot();
 1826                                for (range, snippet) in snippet_edits {
 1827                                    let editor_range =
 1828                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1829                                    editor
 1830                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1831                                        .ok();
 1832                                }
 1833                            }
 1834                        }
 1835                    }
 1836                }));
 1837                let task_inventory = project.read(cx).task_inventory().clone();
 1838                project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1839                    editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1840                }));
 1841            }
 1842        }
 1843
 1844        let inlay_hint_settings = inlay_hint_settings(
 1845            selections.newest_anchor().head(),
 1846            &buffer.read(cx).snapshot(cx),
 1847            cx,
 1848        );
 1849        let focus_handle = cx.focus_handle();
 1850        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1851        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1852            .detach();
 1853        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1854            .detach();
 1855        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1856
 1857        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1858            Some(false)
 1859        } else {
 1860            None
 1861        };
 1862
 1863        let mut this = Self {
 1864            focus_handle,
 1865            show_cursor_when_unfocused: false,
 1866            last_focused_descendant: None,
 1867            buffer: buffer.clone(),
 1868            display_map: display_map.clone(),
 1869            selections,
 1870            scroll_manager: ScrollManager::new(cx),
 1871            columnar_selection_tail: None,
 1872            add_selections_state: None,
 1873            select_next_state: None,
 1874            select_prev_state: None,
 1875            selection_history: Default::default(),
 1876            autoclose_regions: Default::default(),
 1877            snippet_stack: Default::default(),
 1878            select_larger_syntax_node_stack: Vec::new(),
 1879            ime_transaction: Default::default(),
 1880            active_diagnostics: None,
 1881            soft_wrap_mode_override,
 1882            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1883            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1884            project,
 1885            blink_manager: blink_manager.clone(),
 1886            show_local_selections: true,
 1887            mode,
 1888            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1889            show_gutter: mode == EditorMode::Full,
 1890            show_line_numbers: None,
 1891            use_relative_line_numbers: None,
 1892            show_git_diff_gutter: None,
 1893            show_code_actions: None,
 1894            show_runnables: None,
 1895            show_wrap_guides: None,
 1896            show_indent_guides,
 1897            placeholder_text: None,
 1898            highlight_order: 0,
 1899            highlighted_rows: HashMap::default(),
 1900            background_highlights: Default::default(),
 1901            gutter_highlights: TreeMap::default(),
 1902            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1903            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1904            nav_history: None,
 1905            context_menu: RwLock::new(None),
 1906            mouse_context_menu: None,
 1907            completion_tasks: Default::default(),
 1908            signature_help_state: SignatureHelpState::default(),
 1909            auto_signature_help: None,
 1910            find_all_references_task_sources: Vec::new(),
 1911            next_completion_id: 0,
 1912            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1913            next_inlay_id: 0,
 1914            available_code_actions: Default::default(),
 1915            code_actions_task: Default::default(),
 1916            document_highlights_task: Default::default(),
 1917            linked_editing_range_task: Default::default(),
 1918            pending_rename: Default::default(),
 1919            searchable: true,
 1920            cursor_shape: EditorSettings::get_global(cx)
 1921                .cursor_shape
 1922                .unwrap_or_default(),
 1923            current_line_highlight: None,
 1924            autoindent_mode: Some(AutoindentMode::EachLine),
 1925            collapse_matches: false,
 1926            workspace: None,
 1927            input_enabled: true,
 1928            use_modal_editing: mode == EditorMode::Full,
 1929            read_only: false,
 1930            use_autoclose: true,
 1931            use_auto_surround: true,
 1932            auto_replace_emoji_shortcode: false,
 1933            leader_peer_id: None,
 1934            remote_id: None,
 1935            hover_state: Default::default(),
 1936            hovered_link_state: Default::default(),
 1937            inline_completion_provider: None,
 1938            active_inline_completion: None,
 1939            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1940            expanded_hunks: ExpandedHunks::default(),
 1941            gutter_hovered: false,
 1942            pixel_position_of_newest_cursor: None,
 1943            last_bounds: None,
 1944            expect_bounds_change: None,
 1945            gutter_dimensions: GutterDimensions::default(),
 1946            style: None,
 1947            show_cursor_names: false,
 1948            hovered_cursors: Default::default(),
 1949            next_editor_action_id: EditorActionId::default(),
 1950            editor_actions: Rc::default(),
 1951            show_inline_completions_override: None,
 1952            enable_inline_completions: true,
 1953            custom_context_menu: None,
 1954            show_git_blame_gutter: false,
 1955            show_git_blame_inline: false,
 1956            show_selection_menu: None,
 1957            show_git_blame_inline_delay_task: None,
 1958            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1959            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1960                .session
 1961                .restore_unsaved_buffers,
 1962            blame: None,
 1963            blame_subscription: None,
 1964            file_header_size,
 1965            tasks: Default::default(),
 1966            _subscriptions: vec![
 1967                cx.observe(&buffer, Self::on_buffer_changed),
 1968                cx.subscribe(&buffer, Self::on_buffer_event),
 1969                cx.observe(&display_map, Self::on_display_map_changed),
 1970                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1971                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1972                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1973                cx.observe_window_activation(|editor, cx| {
 1974                    let active = cx.is_window_active();
 1975                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1976                        if active {
 1977                            blink_manager.enable(cx);
 1978                        } else {
 1979                            blink_manager.disable(cx);
 1980                        }
 1981                    });
 1982                }),
 1983            ],
 1984            tasks_update_task: None,
 1985            linked_edit_ranges: Default::default(),
 1986            previous_search_ranges: None,
 1987            breadcrumb_header: None,
 1988            focused_block: None,
 1989            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1990            addons: HashMap::default(),
 1991            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1992        };
 1993        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1994        this._subscriptions.extend(project_subscriptions);
 1995
 1996        this.end_selection(cx);
 1997        this.scroll_manager.show_scrollbar(cx);
 1998
 1999        if mode == EditorMode::Full {
 2000            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 2001            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 2002
 2003            if this.git_blame_inline_enabled {
 2004                this.git_blame_inline_enabled = true;
 2005                this.start_git_blame_inline(false, cx);
 2006            }
 2007        }
 2008
 2009        this.report_editor_event("open", None, cx);
 2010        this
 2011    }
 2012
 2013    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 2014        self.mouse_context_menu
 2015            .as_ref()
 2016            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2017    }
 2018
 2019    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2020        let mut key_context = KeyContext::new_with_defaults();
 2021        key_context.add("Editor");
 2022        let mode = match self.mode {
 2023            EditorMode::SingleLine { .. } => "single_line",
 2024            EditorMode::AutoHeight { .. } => "auto_height",
 2025            EditorMode::Full => "full",
 2026        };
 2027
 2028        if EditorSettings::jupyter_enabled(cx) {
 2029            key_context.add("jupyter");
 2030        }
 2031
 2032        key_context.set("mode", mode);
 2033        if self.pending_rename.is_some() {
 2034            key_context.add("renaming");
 2035        }
 2036        if self.context_menu_visible() {
 2037            match self.context_menu.read().as_ref() {
 2038                Some(ContextMenu::Completions(_)) => {
 2039                    key_context.add("menu");
 2040                    key_context.add("showing_completions")
 2041                }
 2042                Some(ContextMenu::CodeActions(_)) => {
 2043                    key_context.add("menu");
 2044                    key_context.add("showing_code_actions")
 2045                }
 2046                None => {}
 2047            }
 2048        }
 2049
 2050        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2051        if !self.focus_handle(cx).contains_focused(cx)
 2052            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2053        {
 2054            for addon in self.addons.values() {
 2055                addon.extend_key_context(&mut key_context, cx)
 2056            }
 2057        }
 2058
 2059        if let Some(extension) = self
 2060            .buffer
 2061            .read(cx)
 2062            .as_singleton()
 2063            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2064        {
 2065            key_context.set("extension", extension.to_string());
 2066        }
 2067
 2068        if self.has_active_inline_completion(cx) {
 2069            key_context.add("copilot_suggestion");
 2070            key_context.add("inline_completion");
 2071        }
 2072
 2073        key_context
 2074    }
 2075
 2076    pub fn new_file(
 2077        workspace: &mut Workspace,
 2078        _: &workspace::NewFile,
 2079        cx: &mut ViewContext<Workspace>,
 2080    ) {
 2081        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2082            "Failed to create buffer",
 2083            cx,
 2084            |e, _| match e.error_code() {
 2085                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2086                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2087                e.error_tag("required").unwrap_or("the latest version")
 2088            )),
 2089                _ => None,
 2090            },
 2091        );
 2092    }
 2093
 2094    pub fn new_in_workspace(
 2095        workspace: &mut Workspace,
 2096        cx: &mut ViewContext<Workspace>,
 2097    ) -> Task<Result<View<Editor>>> {
 2098        let project = workspace.project().clone();
 2099        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2100
 2101        cx.spawn(|workspace, mut cx| async move {
 2102            let buffer = create.await?;
 2103            workspace.update(&mut cx, |workspace, cx| {
 2104                let editor =
 2105                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2106                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2107                editor
 2108            })
 2109        })
 2110    }
 2111
 2112    fn new_file_vertical(
 2113        workspace: &mut Workspace,
 2114        _: &workspace::NewFileSplitVertical,
 2115        cx: &mut ViewContext<Workspace>,
 2116    ) {
 2117        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2118    }
 2119
 2120    fn new_file_horizontal(
 2121        workspace: &mut Workspace,
 2122        _: &workspace::NewFileSplitHorizontal,
 2123        cx: &mut ViewContext<Workspace>,
 2124    ) {
 2125        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2126    }
 2127
 2128    fn new_file_in_direction(
 2129        workspace: &mut Workspace,
 2130        direction: SplitDirection,
 2131        cx: &mut ViewContext<Workspace>,
 2132    ) {
 2133        let project = workspace.project().clone();
 2134        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2135
 2136        cx.spawn(|workspace, mut cx| async move {
 2137            let buffer = create.await?;
 2138            workspace.update(&mut cx, move |workspace, cx| {
 2139                workspace.split_item(
 2140                    direction,
 2141                    Box::new(
 2142                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2143                    ),
 2144                    cx,
 2145                )
 2146            })?;
 2147            anyhow::Ok(())
 2148        })
 2149        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2150            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2151                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2152                e.error_tag("required").unwrap_or("the latest version")
 2153            )),
 2154            _ => None,
 2155        });
 2156    }
 2157
 2158    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2159        self.leader_peer_id
 2160    }
 2161
 2162    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2163        &self.buffer
 2164    }
 2165
 2166    pub fn workspace(&self) -> Option<View<Workspace>> {
 2167        self.workspace.as_ref()?.0.upgrade()
 2168    }
 2169
 2170    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2171        self.buffer().read(cx).title(cx)
 2172    }
 2173
 2174    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2175        EditorSnapshot {
 2176            mode: self.mode,
 2177            show_gutter: self.show_gutter,
 2178            show_line_numbers: self.show_line_numbers,
 2179            show_git_diff_gutter: self.show_git_diff_gutter,
 2180            show_code_actions: self.show_code_actions,
 2181            show_runnables: self.show_runnables,
 2182            render_git_blame_gutter: self.render_git_blame_gutter(cx),
 2183            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2184            scroll_anchor: self.scroll_manager.anchor(),
 2185            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2186            placeholder_text: self.placeholder_text.clone(),
 2187            is_focused: self.focus_handle.is_focused(cx),
 2188            current_line_highlight: self
 2189                .current_line_highlight
 2190                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2191            gutter_hovered: self.gutter_hovered,
 2192        }
 2193    }
 2194
 2195    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2196        self.buffer.read(cx).language_at(point, cx)
 2197    }
 2198
 2199    pub fn file_at<T: ToOffset>(
 2200        &self,
 2201        point: T,
 2202        cx: &AppContext,
 2203    ) -> Option<Arc<dyn language::File>> {
 2204        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2205    }
 2206
 2207    pub fn active_excerpt(
 2208        &self,
 2209        cx: &AppContext,
 2210    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2211        self.buffer
 2212            .read(cx)
 2213            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2214    }
 2215
 2216    pub fn mode(&self) -> EditorMode {
 2217        self.mode
 2218    }
 2219
 2220    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2221        self.collaboration_hub.as_deref()
 2222    }
 2223
 2224    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2225        self.collaboration_hub = Some(hub);
 2226    }
 2227
 2228    pub fn set_custom_context_menu(
 2229        &mut self,
 2230        f: impl 'static
 2231            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2232    ) {
 2233        self.custom_context_menu = Some(Box::new(f))
 2234    }
 2235
 2236    pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
 2237        self.completion_provider = Some(provider);
 2238    }
 2239
 2240    pub fn set_inline_completion_provider<T>(
 2241        &mut self,
 2242        provider: Option<Model<T>>,
 2243        cx: &mut ViewContext<Self>,
 2244    ) where
 2245        T: InlineCompletionProvider,
 2246    {
 2247        self.inline_completion_provider =
 2248            provider.map(|provider| RegisteredInlineCompletionProvider {
 2249                _subscription: cx.observe(&provider, |this, _, cx| {
 2250                    if this.focus_handle.is_focused(cx) {
 2251                        this.update_visible_inline_completion(cx);
 2252                    }
 2253                }),
 2254                provider: Arc::new(provider),
 2255            });
 2256        self.refresh_inline_completion(false, false, cx);
 2257    }
 2258
 2259    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2260        self.placeholder_text.as_deref()
 2261    }
 2262
 2263    pub fn set_placeholder_text(
 2264        &mut self,
 2265        placeholder_text: impl Into<Arc<str>>,
 2266        cx: &mut ViewContext<Self>,
 2267    ) {
 2268        let placeholder_text = Some(placeholder_text.into());
 2269        if self.placeholder_text != placeholder_text {
 2270            self.placeholder_text = placeholder_text;
 2271            cx.notify();
 2272        }
 2273    }
 2274
 2275    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2276        self.cursor_shape = cursor_shape;
 2277
 2278        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2279        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2280
 2281        cx.notify();
 2282    }
 2283
 2284    pub fn set_current_line_highlight(
 2285        &mut self,
 2286        current_line_highlight: Option<CurrentLineHighlight>,
 2287    ) {
 2288        self.current_line_highlight = current_line_highlight;
 2289    }
 2290
 2291    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2292        self.collapse_matches = collapse_matches;
 2293    }
 2294
 2295    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2296        if self.collapse_matches {
 2297            return range.start..range.start;
 2298        }
 2299        range.clone()
 2300    }
 2301
 2302    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2303        if self.display_map.read(cx).clip_at_line_ends != clip {
 2304            self.display_map
 2305                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2306        }
 2307    }
 2308
 2309    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2310        self.input_enabled = input_enabled;
 2311    }
 2312
 2313    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2314        self.enable_inline_completions = enabled;
 2315    }
 2316
 2317    pub fn set_autoindent(&mut self, autoindent: bool) {
 2318        if autoindent {
 2319            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2320        } else {
 2321            self.autoindent_mode = None;
 2322        }
 2323    }
 2324
 2325    pub fn read_only(&self, cx: &AppContext) -> bool {
 2326        self.read_only || self.buffer.read(cx).read_only()
 2327    }
 2328
 2329    pub fn set_read_only(&mut self, read_only: bool) {
 2330        self.read_only = read_only;
 2331    }
 2332
 2333    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2334        self.use_autoclose = autoclose;
 2335    }
 2336
 2337    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2338        self.use_auto_surround = auto_surround;
 2339    }
 2340
 2341    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2342        self.auto_replace_emoji_shortcode = auto_replace;
 2343    }
 2344
 2345    pub fn toggle_inline_completions(
 2346        &mut self,
 2347        _: &ToggleInlineCompletions,
 2348        cx: &mut ViewContext<Self>,
 2349    ) {
 2350        if self.show_inline_completions_override.is_some() {
 2351            self.set_show_inline_completions(None, cx);
 2352        } else {
 2353            let cursor = self.selections.newest_anchor().head();
 2354            if let Some((buffer, cursor_buffer_position)) =
 2355                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2356            {
 2357                let show_inline_completions =
 2358                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2359                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2360            }
 2361        }
 2362    }
 2363
 2364    pub fn set_show_inline_completions(
 2365        &mut self,
 2366        show_inline_completions: Option<bool>,
 2367        cx: &mut ViewContext<Self>,
 2368    ) {
 2369        self.show_inline_completions_override = show_inline_completions;
 2370        self.refresh_inline_completion(false, true, cx);
 2371    }
 2372
 2373    fn should_show_inline_completions(
 2374        &self,
 2375        buffer: &Model<Buffer>,
 2376        buffer_position: language::Anchor,
 2377        cx: &AppContext,
 2378    ) -> bool {
 2379        if let Some(provider) = self.inline_completion_provider() {
 2380            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2381                show_inline_completions
 2382            } else {
 2383                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2384            }
 2385        } else {
 2386            false
 2387        }
 2388    }
 2389
 2390    pub fn set_use_modal_editing(&mut self, to: bool) {
 2391        self.use_modal_editing = to;
 2392    }
 2393
 2394    pub fn use_modal_editing(&self) -> bool {
 2395        self.use_modal_editing
 2396    }
 2397
 2398    fn selections_did_change(
 2399        &mut self,
 2400        local: bool,
 2401        old_cursor_position: &Anchor,
 2402        show_completions: bool,
 2403        cx: &mut ViewContext<Self>,
 2404    ) {
 2405        cx.invalidate_character_coordinates();
 2406
 2407        // Copy selections to primary selection buffer
 2408        #[cfg(target_os = "linux")]
 2409        if local {
 2410            let selections = self.selections.all::<usize>(cx);
 2411            let buffer_handle = self.buffer.read(cx).read(cx);
 2412
 2413            let mut text = String::new();
 2414            for (index, selection) in selections.iter().enumerate() {
 2415                let text_for_selection = buffer_handle
 2416                    .text_for_range(selection.start..selection.end)
 2417                    .collect::<String>();
 2418
 2419                text.push_str(&text_for_selection);
 2420                if index != selections.len() - 1 {
 2421                    text.push('\n');
 2422                }
 2423            }
 2424
 2425            if !text.is_empty() {
 2426                cx.write_to_primary(ClipboardItem::new_string(text));
 2427            }
 2428        }
 2429
 2430        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2431            self.buffer.update(cx, |buffer, cx| {
 2432                buffer.set_active_selections(
 2433                    &self.selections.disjoint_anchors(),
 2434                    self.selections.line_mode,
 2435                    self.cursor_shape,
 2436                    cx,
 2437                )
 2438            });
 2439        }
 2440        let display_map = self
 2441            .display_map
 2442            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2443        let buffer = &display_map.buffer_snapshot;
 2444        self.add_selections_state = None;
 2445        self.select_next_state = None;
 2446        self.select_prev_state = None;
 2447        self.select_larger_syntax_node_stack.clear();
 2448        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2449        self.snippet_stack
 2450            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2451        self.take_rename(false, cx);
 2452
 2453        let new_cursor_position = self.selections.newest_anchor().head();
 2454
 2455        self.push_to_nav_history(
 2456            *old_cursor_position,
 2457            Some(new_cursor_position.to_point(buffer)),
 2458            cx,
 2459        );
 2460
 2461        if local {
 2462            let new_cursor_position = self.selections.newest_anchor().head();
 2463            let mut context_menu = self.context_menu.write();
 2464            let completion_menu = match context_menu.as_ref() {
 2465                Some(ContextMenu::Completions(menu)) => Some(menu),
 2466
 2467                _ => {
 2468                    *context_menu = None;
 2469                    None
 2470                }
 2471            };
 2472
 2473            if let Some(completion_menu) = completion_menu {
 2474                let cursor_position = new_cursor_position.to_offset(buffer);
 2475                let (word_range, kind) =
 2476                    buffer.surrounding_word(completion_menu.initial_position, true);
 2477                if kind == Some(CharKind::Word)
 2478                    && word_range.to_inclusive().contains(&cursor_position)
 2479                {
 2480                    let mut completion_menu = completion_menu.clone();
 2481                    drop(context_menu);
 2482
 2483                    let query = Self::completion_query(buffer, cursor_position);
 2484                    cx.spawn(move |this, mut cx| async move {
 2485                        completion_menu
 2486                            .filter(query.as_deref(), cx.background_executor().clone())
 2487                            .await;
 2488
 2489                        this.update(&mut cx, |this, cx| {
 2490                            let mut context_menu = this.context_menu.write();
 2491                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2492                                return;
 2493                            };
 2494
 2495                            if menu.id > completion_menu.id {
 2496                                return;
 2497                            }
 2498
 2499                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2500                            drop(context_menu);
 2501                            cx.notify();
 2502                        })
 2503                    })
 2504                    .detach();
 2505
 2506                    if show_completions {
 2507                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2508                    }
 2509                } else {
 2510                    drop(context_menu);
 2511                    self.hide_context_menu(cx);
 2512                }
 2513            } else {
 2514                drop(context_menu);
 2515            }
 2516
 2517            hide_hover(self, cx);
 2518
 2519            if old_cursor_position.to_display_point(&display_map).row()
 2520                != new_cursor_position.to_display_point(&display_map).row()
 2521            {
 2522                self.available_code_actions.take();
 2523            }
 2524            self.refresh_code_actions(cx);
 2525            self.refresh_document_highlights(cx);
 2526            refresh_matching_bracket_highlights(self, cx);
 2527            self.discard_inline_completion(false, cx);
 2528            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2529            if self.git_blame_inline_enabled {
 2530                self.start_inline_blame_timer(cx);
 2531            }
 2532        }
 2533
 2534        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2535        cx.emit(EditorEvent::SelectionsChanged { local });
 2536
 2537        if self.selections.disjoint_anchors().len() == 1 {
 2538            cx.emit(SearchEvent::ActiveMatchChanged)
 2539        }
 2540        cx.notify();
 2541    }
 2542
 2543    pub fn change_selections<R>(
 2544        &mut self,
 2545        autoscroll: Option<Autoscroll>,
 2546        cx: &mut ViewContext<Self>,
 2547        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2548    ) -> R {
 2549        self.change_selections_inner(autoscroll, true, cx, change)
 2550    }
 2551
 2552    pub fn change_selections_inner<R>(
 2553        &mut self,
 2554        autoscroll: Option<Autoscroll>,
 2555        request_completions: bool,
 2556        cx: &mut ViewContext<Self>,
 2557        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2558    ) -> R {
 2559        let old_cursor_position = self.selections.newest_anchor().head();
 2560        self.push_to_selection_history();
 2561
 2562        let (changed, result) = self.selections.change_with(cx, change);
 2563
 2564        if changed {
 2565            if let Some(autoscroll) = autoscroll {
 2566                self.request_autoscroll(autoscroll, cx);
 2567            }
 2568            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2569
 2570            if self.should_open_signature_help_automatically(
 2571                &old_cursor_position,
 2572                self.signature_help_state.backspace_pressed(),
 2573                cx,
 2574            ) {
 2575                self.show_signature_help(&ShowSignatureHelp, cx);
 2576            }
 2577            self.signature_help_state.set_backspace_pressed(false);
 2578        }
 2579
 2580        result
 2581    }
 2582
 2583    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2584    where
 2585        I: IntoIterator<Item = (Range<S>, T)>,
 2586        S: ToOffset,
 2587        T: Into<Arc<str>>,
 2588    {
 2589        if self.read_only(cx) {
 2590            return;
 2591        }
 2592
 2593        self.buffer
 2594            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2595    }
 2596
 2597    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2598    where
 2599        I: IntoIterator<Item = (Range<S>, T)>,
 2600        S: ToOffset,
 2601        T: Into<Arc<str>>,
 2602    {
 2603        if self.read_only(cx) {
 2604            return;
 2605        }
 2606
 2607        self.buffer.update(cx, |buffer, cx| {
 2608            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2609        });
 2610    }
 2611
 2612    pub fn edit_with_block_indent<I, S, T>(
 2613        &mut self,
 2614        edits: I,
 2615        original_indent_columns: Vec<u32>,
 2616        cx: &mut ViewContext<Self>,
 2617    ) where
 2618        I: IntoIterator<Item = (Range<S>, T)>,
 2619        S: ToOffset,
 2620        T: Into<Arc<str>>,
 2621    {
 2622        if self.read_only(cx) {
 2623            return;
 2624        }
 2625
 2626        self.buffer.update(cx, |buffer, cx| {
 2627            buffer.edit(
 2628                edits,
 2629                Some(AutoindentMode::Block {
 2630                    original_indent_columns,
 2631                }),
 2632                cx,
 2633            )
 2634        });
 2635    }
 2636
 2637    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2638        self.hide_context_menu(cx);
 2639
 2640        match phase {
 2641            SelectPhase::Begin {
 2642                position,
 2643                add,
 2644                click_count,
 2645            } => self.begin_selection(position, add, click_count, cx),
 2646            SelectPhase::BeginColumnar {
 2647                position,
 2648                goal_column,
 2649                reset,
 2650            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2651            SelectPhase::Extend {
 2652                position,
 2653                click_count,
 2654            } => self.extend_selection(position, click_count, cx),
 2655            SelectPhase::Update {
 2656                position,
 2657                goal_column,
 2658                scroll_delta,
 2659            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2660            SelectPhase::End => self.end_selection(cx),
 2661        }
 2662    }
 2663
 2664    fn extend_selection(
 2665        &mut self,
 2666        position: DisplayPoint,
 2667        click_count: usize,
 2668        cx: &mut ViewContext<Self>,
 2669    ) {
 2670        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2671        let tail = self.selections.newest::<usize>(cx).tail();
 2672        self.begin_selection(position, false, click_count, cx);
 2673
 2674        let position = position.to_offset(&display_map, Bias::Left);
 2675        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2676
 2677        let mut pending_selection = self
 2678            .selections
 2679            .pending_anchor()
 2680            .expect("extend_selection not called with pending selection");
 2681        if position >= tail {
 2682            pending_selection.start = tail_anchor;
 2683        } else {
 2684            pending_selection.end = tail_anchor;
 2685            pending_selection.reversed = true;
 2686        }
 2687
 2688        let mut pending_mode = self.selections.pending_mode().unwrap();
 2689        match &mut pending_mode {
 2690            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2691            _ => {}
 2692        }
 2693
 2694        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2695            s.set_pending(pending_selection, pending_mode)
 2696        });
 2697    }
 2698
 2699    fn begin_selection(
 2700        &mut self,
 2701        position: DisplayPoint,
 2702        add: bool,
 2703        click_count: usize,
 2704        cx: &mut ViewContext<Self>,
 2705    ) {
 2706        if !self.focus_handle.is_focused(cx) {
 2707            self.last_focused_descendant = None;
 2708            cx.focus(&self.focus_handle);
 2709        }
 2710
 2711        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2712        let buffer = &display_map.buffer_snapshot;
 2713        let newest_selection = self.selections.newest_anchor().clone();
 2714        let position = display_map.clip_point(position, Bias::Left);
 2715
 2716        let start;
 2717        let end;
 2718        let mode;
 2719        let auto_scroll;
 2720        match click_count {
 2721            1 => {
 2722                start = buffer.anchor_before(position.to_point(&display_map));
 2723                end = start;
 2724                mode = SelectMode::Character;
 2725                auto_scroll = true;
 2726            }
 2727            2 => {
 2728                let range = movement::surrounding_word(&display_map, position);
 2729                start = buffer.anchor_before(range.start.to_point(&display_map));
 2730                end = buffer.anchor_before(range.end.to_point(&display_map));
 2731                mode = SelectMode::Word(start..end);
 2732                auto_scroll = true;
 2733            }
 2734            3 => {
 2735                let position = display_map
 2736                    .clip_point(position, Bias::Left)
 2737                    .to_point(&display_map);
 2738                let line_start = display_map.prev_line_boundary(position).0;
 2739                let next_line_start = buffer.clip_point(
 2740                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2741                    Bias::Left,
 2742                );
 2743                start = buffer.anchor_before(line_start);
 2744                end = buffer.anchor_before(next_line_start);
 2745                mode = SelectMode::Line(start..end);
 2746                auto_scroll = true;
 2747            }
 2748            _ => {
 2749                start = buffer.anchor_before(0);
 2750                end = buffer.anchor_before(buffer.len());
 2751                mode = SelectMode::All;
 2752                auto_scroll = false;
 2753            }
 2754        }
 2755
 2756        let point_to_delete: Option<usize> = {
 2757            let selected_points: Vec<Selection<Point>> =
 2758                self.selections.disjoint_in_range(start..end, cx);
 2759
 2760            if !add || click_count > 1 {
 2761                None
 2762            } else if !selected_points.is_empty() {
 2763                Some(selected_points[0].id)
 2764            } else {
 2765                let clicked_point_already_selected =
 2766                    self.selections.disjoint.iter().find(|selection| {
 2767                        selection.start.to_point(buffer) == start.to_point(buffer)
 2768                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2769                    });
 2770
 2771                clicked_point_already_selected.map(|selection| selection.id)
 2772            }
 2773        };
 2774
 2775        let selections_count = self.selections.count();
 2776
 2777        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2778            if let Some(point_to_delete) = point_to_delete {
 2779                s.delete(point_to_delete);
 2780
 2781                if selections_count == 1 {
 2782                    s.set_pending_anchor_range(start..end, mode);
 2783                }
 2784            } else {
 2785                if !add {
 2786                    s.clear_disjoint();
 2787                } else if click_count > 1 {
 2788                    s.delete(newest_selection.id)
 2789                }
 2790
 2791                s.set_pending_anchor_range(start..end, mode);
 2792            }
 2793        });
 2794    }
 2795
 2796    fn begin_columnar_selection(
 2797        &mut self,
 2798        position: DisplayPoint,
 2799        goal_column: u32,
 2800        reset: bool,
 2801        cx: &mut ViewContext<Self>,
 2802    ) {
 2803        if !self.focus_handle.is_focused(cx) {
 2804            self.last_focused_descendant = None;
 2805            cx.focus(&self.focus_handle);
 2806        }
 2807
 2808        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2809
 2810        if reset {
 2811            let pointer_position = display_map
 2812                .buffer_snapshot
 2813                .anchor_before(position.to_point(&display_map));
 2814
 2815            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2816                s.clear_disjoint();
 2817                s.set_pending_anchor_range(
 2818                    pointer_position..pointer_position,
 2819                    SelectMode::Character,
 2820                );
 2821            });
 2822        }
 2823
 2824        let tail = self.selections.newest::<Point>(cx).tail();
 2825        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2826
 2827        if !reset {
 2828            self.select_columns(
 2829                tail.to_display_point(&display_map),
 2830                position,
 2831                goal_column,
 2832                &display_map,
 2833                cx,
 2834            );
 2835        }
 2836    }
 2837
 2838    fn update_selection(
 2839        &mut self,
 2840        position: DisplayPoint,
 2841        goal_column: u32,
 2842        scroll_delta: gpui::Point<f32>,
 2843        cx: &mut ViewContext<Self>,
 2844    ) {
 2845        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2846
 2847        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2848            let tail = tail.to_display_point(&display_map);
 2849            self.select_columns(tail, position, goal_column, &display_map, cx);
 2850        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2851            let buffer = self.buffer.read(cx).snapshot(cx);
 2852            let head;
 2853            let tail;
 2854            let mode = self.selections.pending_mode().unwrap();
 2855            match &mode {
 2856                SelectMode::Character => {
 2857                    head = position.to_point(&display_map);
 2858                    tail = pending.tail().to_point(&buffer);
 2859                }
 2860                SelectMode::Word(original_range) => {
 2861                    let original_display_range = original_range.start.to_display_point(&display_map)
 2862                        ..original_range.end.to_display_point(&display_map);
 2863                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2864                        ..original_display_range.end.to_point(&display_map);
 2865                    if movement::is_inside_word(&display_map, position)
 2866                        || original_display_range.contains(&position)
 2867                    {
 2868                        let word_range = movement::surrounding_word(&display_map, position);
 2869                        if word_range.start < original_display_range.start {
 2870                            head = word_range.start.to_point(&display_map);
 2871                        } else {
 2872                            head = word_range.end.to_point(&display_map);
 2873                        }
 2874                    } else {
 2875                        head = position.to_point(&display_map);
 2876                    }
 2877
 2878                    if head <= original_buffer_range.start {
 2879                        tail = original_buffer_range.end;
 2880                    } else {
 2881                        tail = original_buffer_range.start;
 2882                    }
 2883                }
 2884                SelectMode::Line(original_range) => {
 2885                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2886
 2887                    let position = display_map
 2888                        .clip_point(position, Bias::Left)
 2889                        .to_point(&display_map);
 2890                    let line_start = display_map.prev_line_boundary(position).0;
 2891                    let next_line_start = buffer.clip_point(
 2892                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2893                        Bias::Left,
 2894                    );
 2895
 2896                    if line_start < original_range.start {
 2897                        head = line_start
 2898                    } else {
 2899                        head = next_line_start
 2900                    }
 2901
 2902                    if head <= original_range.start {
 2903                        tail = original_range.end;
 2904                    } else {
 2905                        tail = original_range.start;
 2906                    }
 2907                }
 2908                SelectMode::All => {
 2909                    return;
 2910                }
 2911            };
 2912
 2913            if head < tail {
 2914                pending.start = buffer.anchor_before(head);
 2915                pending.end = buffer.anchor_before(tail);
 2916                pending.reversed = true;
 2917            } else {
 2918                pending.start = buffer.anchor_before(tail);
 2919                pending.end = buffer.anchor_before(head);
 2920                pending.reversed = false;
 2921            }
 2922
 2923            self.change_selections(None, cx, |s| {
 2924                s.set_pending(pending, mode);
 2925            });
 2926        } else {
 2927            log::error!("update_selection dispatched with no pending selection");
 2928            return;
 2929        }
 2930
 2931        self.apply_scroll_delta(scroll_delta, cx);
 2932        cx.notify();
 2933    }
 2934
 2935    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2936        self.columnar_selection_tail.take();
 2937        if self.selections.pending_anchor().is_some() {
 2938            let selections = self.selections.all::<usize>(cx);
 2939            self.change_selections(None, cx, |s| {
 2940                s.select(selections);
 2941                s.clear_pending();
 2942            });
 2943        }
 2944    }
 2945
 2946    fn select_columns(
 2947        &mut self,
 2948        tail: DisplayPoint,
 2949        head: DisplayPoint,
 2950        goal_column: u32,
 2951        display_map: &DisplaySnapshot,
 2952        cx: &mut ViewContext<Self>,
 2953    ) {
 2954        let start_row = cmp::min(tail.row(), head.row());
 2955        let end_row = cmp::max(tail.row(), head.row());
 2956        let start_column = cmp::min(tail.column(), goal_column);
 2957        let end_column = cmp::max(tail.column(), goal_column);
 2958        let reversed = start_column < tail.column();
 2959
 2960        let selection_ranges = (start_row.0..=end_row.0)
 2961            .map(DisplayRow)
 2962            .filter_map(|row| {
 2963                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2964                    let start = display_map
 2965                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2966                        .to_point(display_map);
 2967                    let end = display_map
 2968                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2969                        .to_point(display_map);
 2970                    if reversed {
 2971                        Some(end..start)
 2972                    } else {
 2973                        Some(start..end)
 2974                    }
 2975                } else {
 2976                    None
 2977                }
 2978            })
 2979            .collect::<Vec<_>>();
 2980
 2981        self.change_selections(None, cx, |s| {
 2982            s.select_ranges(selection_ranges);
 2983        });
 2984        cx.notify();
 2985    }
 2986
 2987    pub fn has_pending_nonempty_selection(&self) -> bool {
 2988        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2989            Some(Selection { start, end, .. }) => start != end,
 2990            None => false,
 2991        };
 2992
 2993        pending_nonempty_selection
 2994            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2995    }
 2996
 2997    pub fn has_pending_selection(&self) -> bool {
 2998        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2999    }
 3000
 3001    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 3002        if self.clear_clicked_diff_hunks(cx) {
 3003            cx.notify();
 3004            return;
 3005        }
 3006        if self.dismiss_menus_and_popups(true, cx) {
 3007            return;
 3008        }
 3009
 3010        if self.mode == EditorMode::Full
 3011            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3012        {
 3013            return;
 3014        }
 3015
 3016        cx.propagate();
 3017    }
 3018
 3019    pub fn dismiss_menus_and_popups(
 3020        &mut self,
 3021        should_report_inline_completion_event: bool,
 3022        cx: &mut ViewContext<Self>,
 3023    ) -> bool {
 3024        if self.take_rename(false, cx).is_some() {
 3025            return true;
 3026        }
 3027
 3028        if hide_hover(self, cx) {
 3029            return true;
 3030        }
 3031
 3032        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3033            return true;
 3034        }
 3035
 3036        if self.hide_context_menu(cx).is_some() {
 3037            return true;
 3038        }
 3039
 3040        if self.mouse_context_menu.take().is_some() {
 3041            return true;
 3042        }
 3043
 3044        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3045            return true;
 3046        }
 3047
 3048        if self.snippet_stack.pop().is_some() {
 3049            return true;
 3050        }
 3051
 3052        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3053            self.dismiss_diagnostics(cx);
 3054            return true;
 3055        }
 3056
 3057        false
 3058    }
 3059
 3060    fn linked_editing_ranges_for(
 3061        &self,
 3062        selection: Range<text::Anchor>,
 3063        cx: &AppContext,
 3064    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3065        if self.linked_edit_ranges.is_empty() {
 3066            return None;
 3067        }
 3068        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3069            selection.end.buffer_id.and_then(|end_buffer_id| {
 3070                if selection.start.buffer_id != Some(end_buffer_id) {
 3071                    return None;
 3072                }
 3073                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3074                let snapshot = buffer.read(cx).snapshot();
 3075                self.linked_edit_ranges
 3076                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3077                    .map(|ranges| (ranges, snapshot, buffer))
 3078            })?;
 3079        use text::ToOffset as TO;
 3080        // find offset from the start of current range to current cursor position
 3081        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3082
 3083        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3084        let start_difference = start_offset - start_byte_offset;
 3085        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3086        let end_difference = end_offset - start_byte_offset;
 3087        // Current range has associated linked ranges.
 3088        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3089        for range in linked_ranges.iter() {
 3090            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3091            let end_offset = start_offset + end_difference;
 3092            let start_offset = start_offset + start_difference;
 3093            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3094                continue;
 3095            }
 3096            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3097                if s.start.buffer_id != selection.start.buffer_id
 3098                    || s.end.buffer_id != selection.end.buffer_id
 3099                {
 3100                    return false;
 3101                }
 3102                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3103                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3104            }) {
 3105                continue;
 3106            }
 3107            let start = buffer_snapshot.anchor_after(start_offset);
 3108            let end = buffer_snapshot.anchor_after(end_offset);
 3109            linked_edits
 3110                .entry(buffer.clone())
 3111                .or_default()
 3112                .push(start..end);
 3113        }
 3114        Some(linked_edits)
 3115    }
 3116
 3117    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3118        let text: Arc<str> = text.into();
 3119
 3120        if self.read_only(cx) {
 3121            return;
 3122        }
 3123
 3124        let selections = self.selections.all_adjusted(cx);
 3125        let mut bracket_inserted = false;
 3126        let mut edits = Vec::new();
 3127        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3128        let mut new_selections = Vec::with_capacity(selections.len());
 3129        let mut new_autoclose_regions = Vec::new();
 3130        let snapshot = self.buffer.read(cx).read(cx);
 3131
 3132        for (selection, autoclose_region) in
 3133            self.selections_with_autoclose_regions(selections, &snapshot)
 3134        {
 3135            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3136                // Determine if the inserted text matches the opening or closing
 3137                // bracket of any of this language's bracket pairs.
 3138                let mut bracket_pair = None;
 3139                let mut is_bracket_pair_start = false;
 3140                let mut is_bracket_pair_end = false;
 3141                if !text.is_empty() {
 3142                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3143                    //  and they are removing the character that triggered IME popup.
 3144                    for (pair, enabled) in scope.brackets() {
 3145                        if !pair.close && !pair.surround {
 3146                            continue;
 3147                        }
 3148
 3149                        if enabled && pair.start.ends_with(text.as_ref()) {
 3150                            bracket_pair = Some(pair.clone());
 3151                            is_bracket_pair_start = true;
 3152                            break;
 3153                        }
 3154                        if pair.end.as_str() == text.as_ref() {
 3155                            bracket_pair = Some(pair.clone());
 3156                            is_bracket_pair_end = true;
 3157                            break;
 3158                        }
 3159                    }
 3160                }
 3161
 3162                if let Some(bracket_pair) = bracket_pair {
 3163                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3164                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3165                    let auto_surround =
 3166                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3167                    if selection.is_empty() {
 3168                        if is_bracket_pair_start {
 3169                            let prefix_len = bracket_pair.start.len() - text.len();
 3170
 3171                            // If the inserted text is a suffix of an opening bracket and the
 3172                            // selection is preceded by the rest of the opening bracket, then
 3173                            // insert the closing bracket.
 3174                            let following_text_allows_autoclose = snapshot
 3175                                .chars_at(selection.start)
 3176                                .next()
 3177                                .map_or(true, |c| scope.should_autoclose_before(c));
 3178                            let preceding_text_matches_prefix = prefix_len == 0
 3179                                || (selection.start.column >= (prefix_len as u32)
 3180                                    && snapshot.contains_str_at(
 3181                                        Point::new(
 3182                                            selection.start.row,
 3183                                            selection.start.column - (prefix_len as u32),
 3184                                        ),
 3185                                        &bracket_pair.start[..prefix_len],
 3186                                    ));
 3187
 3188                            if autoclose
 3189                                && bracket_pair.close
 3190                                && following_text_allows_autoclose
 3191                                && preceding_text_matches_prefix
 3192                            {
 3193                                let anchor = snapshot.anchor_before(selection.end);
 3194                                new_selections.push((selection.map(|_| anchor), text.len()));
 3195                                new_autoclose_regions.push((
 3196                                    anchor,
 3197                                    text.len(),
 3198                                    selection.id,
 3199                                    bracket_pair.clone(),
 3200                                ));
 3201                                edits.push((
 3202                                    selection.range(),
 3203                                    format!("{}{}", text, bracket_pair.end).into(),
 3204                                ));
 3205                                bracket_inserted = true;
 3206                                continue;
 3207                            }
 3208                        }
 3209
 3210                        if let Some(region) = autoclose_region {
 3211                            // If the selection is followed by an auto-inserted closing bracket,
 3212                            // then don't insert that closing bracket again; just move the selection
 3213                            // past the closing bracket.
 3214                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3215                                && text.as_ref() == region.pair.end.as_str();
 3216                            if should_skip {
 3217                                let anchor = snapshot.anchor_after(selection.end);
 3218                                new_selections
 3219                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3220                                continue;
 3221                            }
 3222                        }
 3223
 3224                        let always_treat_brackets_as_autoclosed = snapshot
 3225                            .settings_at(selection.start, cx)
 3226                            .always_treat_brackets_as_autoclosed;
 3227                        if always_treat_brackets_as_autoclosed
 3228                            && is_bracket_pair_end
 3229                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3230                        {
 3231                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3232                            // and the inserted text is a closing bracket and the selection is followed
 3233                            // by the closing bracket then move the selection past the closing bracket.
 3234                            let anchor = snapshot.anchor_after(selection.end);
 3235                            new_selections.push((selection.map(|_| anchor), text.len()));
 3236                            continue;
 3237                        }
 3238                    }
 3239                    // If an opening bracket is 1 character long and is typed while
 3240                    // text is selected, then surround that text with the bracket pair.
 3241                    else if auto_surround
 3242                        && bracket_pair.surround
 3243                        && is_bracket_pair_start
 3244                        && bracket_pair.start.chars().count() == 1
 3245                    {
 3246                        edits.push((selection.start..selection.start, text.clone()));
 3247                        edits.push((
 3248                            selection.end..selection.end,
 3249                            bracket_pair.end.as_str().into(),
 3250                        ));
 3251                        bracket_inserted = true;
 3252                        new_selections.push((
 3253                            Selection {
 3254                                id: selection.id,
 3255                                start: snapshot.anchor_after(selection.start),
 3256                                end: snapshot.anchor_before(selection.end),
 3257                                reversed: selection.reversed,
 3258                                goal: selection.goal,
 3259                            },
 3260                            0,
 3261                        ));
 3262                        continue;
 3263                    }
 3264                }
 3265            }
 3266
 3267            if self.auto_replace_emoji_shortcode
 3268                && selection.is_empty()
 3269                && text.as_ref().ends_with(':')
 3270            {
 3271                if let Some(possible_emoji_short_code) =
 3272                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3273                {
 3274                    if !possible_emoji_short_code.is_empty() {
 3275                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3276                            let emoji_shortcode_start = Point::new(
 3277                                selection.start.row,
 3278                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3279                            );
 3280
 3281                            // Remove shortcode from buffer
 3282                            edits.push((
 3283                                emoji_shortcode_start..selection.start,
 3284                                "".to_string().into(),
 3285                            ));
 3286                            new_selections.push((
 3287                                Selection {
 3288                                    id: selection.id,
 3289                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3290                                    end: snapshot.anchor_before(selection.start),
 3291                                    reversed: selection.reversed,
 3292                                    goal: selection.goal,
 3293                                },
 3294                                0,
 3295                            ));
 3296
 3297                            // Insert emoji
 3298                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3299                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3300                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3301
 3302                            continue;
 3303                        }
 3304                    }
 3305                }
 3306            }
 3307
 3308            // If not handling any auto-close operation, then just replace the selected
 3309            // text with the given input and move the selection to the end of the
 3310            // newly inserted text.
 3311            let anchor = snapshot.anchor_after(selection.end);
 3312            if !self.linked_edit_ranges.is_empty() {
 3313                let start_anchor = snapshot.anchor_before(selection.start);
 3314
 3315                let is_word_char = text.chars().next().map_or(true, |char| {
 3316                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3317                    classifier.is_word(char)
 3318                });
 3319
 3320                if is_word_char {
 3321                    if let Some(ranges) = self
 3322                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3323                    {
 3324                        for (buffer, edits) in ranges {
 3325                            linked_edits
 3326                                .entry(buffer.clone())
 3327                                .or_default()
 3328                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3329                        }
 3330                    }
 3331                }
 3332            }
 3333
 3334            new_selections.push((selection.map(|_| anchor), 0));
 3335            edits.push((selection.start..selection.end, text.clone()));
 3336        }
 3337
 3338        drop(snapshot);
 3339
 3340        self.transact(cx, |this, cx| {
 3341            this.buffer.update(cx, |buffer, cx| {
 3342                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3343            });
 3344            for (buffer, edits) in linked_edits {
 3345                buffer.update(cx, |buffer, cx| {
 3346                    let snapshot = buffer.snapshot();
 3347                    let edits = edits
 3348                        .into_iter()
 3349                        .map(|(range, text)| {
 3350                            use text::ToPoint as TP;
 3351                            let end_point = TP::to_point(&range.end, &snapshot);
 3352                            let start_point = TP::to_point(&range.start, &snapshot);
 3353                            (start_point..end_point, text)
 3354                        })
 3355                        .sorted_by_key(|(range, _)| range.start)
 3356                        .collect::<Vec<_>>();
 3357                    buffer.edit(edits, None, cx);
 3358                })
 3359            }
 3360            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3361            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3362            let snapshot = this.buffer.read(cx).read(cx);
 3363            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3364                .zip(new_selection_deltas)
 3365                .map(|(selection, delta)| Selection {
 3366                    id: selection.id,
 3367                    start: selection.start + delta,
 3368                    end: selection.end + delta,
 3369                    reversed: selection.reversed,
 3370                    goal: SelectionGoal::None,
 3371                })
 3372                .collect::<Vec<_>>();
 3373
 3374            let mut i = 0;
 3375            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3376                let position = position.to_offset(&snapshot) + delta;
 3377                let start = snapshot.anchor_before(position);
 3378                let end = snapshot.anchor_after(position);
 3379                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3380                    match existing_state.range.start.cmp(&start, &snapshot) {
 3381                        Ordering::Less => i += 1,
 3382                        Ordering::Greater => break,
 3383                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3384                            Ordering::Less => i += 1,
 3385                            Ordering::Equal => break,
 3386                            Ordering::Greater => break,
 3387                        },
 3388                    }
 3389                }
 3390                this.autoclose_regions.insert(
 3391                    i,
 3392                    AutocloseRegion {
 3393                        selection_id,
 3394                        range: start..end,
 3395                        pair,
 3396                    },
 3397                );
 3398            }
 3399
 3400            drop(snapshot);
 3401            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3402            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3403                s.select(new_selections)
 3404            });
 3405
 3406            if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
 3407                if let Some(on_type_format_task) =
 3408                    this.trigger_on_type_formatting(text.to_string(), cx)
 3409                {
 3410                    on_type_format_task.detach_and_log_err(cx);
 3411                }
 3412            }
 3413
 3414            let editor_settings = EditorSettings::get_global(cx);
 3415            if bracket_inserted
 3416                && (editor_settings.auto_signature_help
 3417                    || editor_settings.show_signature_help_after_edits)
 3418            {
 3419                this.show_signature_help(&ShowSignatureHelp, cx);
 3420            }
 3421
 3422            let trigger_in_words = !had_active_inline_completion;
 3423            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3424            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3425            this.refresh_inline_completion(true, false, cx);
 3426        });
 3427    }
 3428
 3429    fn find_possible_emoji_shortcode_at_position(
 3430        snapshot: &MultiBufferSnapshot,
 3431        position: Point,
 3432    ) -> Option<String> {
 3433        let mut chars = Vec::new();
 3434        let mut found_colon = false;
 3435        for char in snapshot.reversed_chars_at(position).take(100) {
 3436            // Found a possible emoji shortcode in the middle of the buffer
 3437            if found_colon {
 3438                if char.is_whitespace() {
 3439                    chars.reverse();
 3440                    return Some(chars.iter().collect());
 3441                }
 3442                // If the previous character is not a whitespace, we are in the middle of a word
 3443                // and we only want to complete the shortcode if the word is made up of other emojis
 3444                let mut containing_word = String::new();
 3445                for ch in snapshot
 3446                    .reversed_chars_at(position)
 3447                    .skip(chars.len() + 1)
 3448                    .take(100)
 3449                {
 3450                    if ch.is_whitespace() {
 3451                        break;
 3452                    }
 3453                    containing_word.push(ch);
 3454                }
 3455                let containing_word = containing_word.chars().rev().collect::<String>();
 3456                if util::word_consists_of_emojis(containing_word.as_str()) {
 3457                    chars.reverse();
 3458                    return Some(chars.iter().collect());
 3459                }
 3460            }
 3461
 3462            if char.is_whitespace() || !char.is_ascii() {
 3463                return None;
 3464            }
 3465            if char == ':' {
 3466                found_colon = true;
 3467            } else {
 3468                chars.push(char);
 3469            }
 3470        }
 3471        // Found a possible emoji shortcode at the beginning of the buffer
 3472        chars.reverse();
 3473        Some(chars.iter().collect())
 3474    }
 3475
 3476    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3477        self.transact(cx, |this, cx| {
 3478            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3479                let selections = this.selections.all::<usize>(cx);
 3480                let multi_buffer = this.buffer.read(cx);
 3481                let buffer = multi_buffer.snapshot(cx);
 3482                selections
 3483                    .iter()
 3484                    .map(|selection| {
 3485                        let start_point = selection.start.to_point(&buffer);
 3486                        let mut indent =
 3487                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3488                        indent.len = cmp::min(indent.len, start_point.column);
 3489                        let start = selection.start;
 3490                        let end = selection.end;
 3491                        let selection_is_empty = start == end;
 3492                        let language_scope = buffer.language_scope_at(start);
 3493                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3494                            &language_scope
 3495                        {
 3496                            let leading_whitespace_len = buffer
 3497                                .reversed_chars_at(start)
 3498                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3499                                .map(|c| c.len_utf8())
 3500                                .sum::<usize>();
 3501
 3502                            let trailing_whitespace_len = buffer
 3503                                .chars_at(end)
 3504                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3505                                .map(|c| c.len_utf8())
 3506                                .sum::<usize>();
 3507
 3508                            let insert_extra_newline =
 3509                                language.brackets().any(|(pair, enabled)| {
 3510                                    let pair_start = pair.start.trim_end();
 3511                                    let pair_end = pair.end.trim_start();
 3512
 3513                                    enabled
 3514                                        && pair.newline
 3515                                        && buffer.contains_str_at(
 3516                                            end + trailing_whitespace_len,
 3517                                            pair_end,
 3518                                        )
 3519                                        && buffer.contains_str_at(
 3520                                            (start - leading_whitespace_len)
 3521                                                .saturating_sub(pair_start.len()),
 3522                                            pair_start,
 3523                                        )
 3524                                });
 3525
 3526                            // Comment extension on newline is allowed only for cursor selections
 3527                            let comment_delimiter = maybe!({
 3528                                if !selection_is_empty {
 3529                                    return None;
 3530                                }
 3531
 3532                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3533                                    return None;
 3534                                }
 3535
 3536                                let delimiters = language.line_comment_prefixes();
 3537                                let max_len_of_delimiter =
 3538                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3539                                let (snapshot, range) =
 3540                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3541
 3542                                let mut index_of_first_non_whitespace = 0;
 3543                                let comment_candidate = snapshot
 3544                                    .chars_for_range(range)
 3545                                    .skip_while(|c| {
 3546                                        let should_skip = c.is_whitespace();
 3547                                        if should_skip {
 3548                                            index_of_first_non_whitespace += 1;
 3549                                        }
 3550                                        should_skip
 3551                                    })
 3552                                    .take(max_len_of_delimiter)
 3553                                    .collect::<String>();
 3554                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3555                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3556                                })?;
 3557                                let cursor_is_placed_after_comment_marker =
 3558                                    index_of_first_non_whitespace + comment_prefix.len()
 3559                                        <= start_point.column as usize;
 3560                                if cursor_is_placed_after_comment_marker {
 3561                                    Some(comment_prefix.clone())
 3562                                } else {
 3563                                    None
 3564                                }
 3565                            });
 3566                            (comment_delimiter, insert_extra_newline)
 3567                        } else {
 3568                            (None, false)
 3569                        };
 3570
 3571                        let capacity_for_delimiter = comment_delimiter
 3572                            .as_deref()
 3573                            .map(str::len)
 3574                            .unwrap_or_default();
 3575                        let mut new_text =
 3576                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3577                        new_text.push('\n');
 3578                        new_text.extend(indent.chars());
 3579                        if let Some(delimiter) = &comment_delimiter {
 3580                            new_text.push_str(delimiter);
 3581                        }
 3582                        if insert_extra_newline {
 3583                            new_text = new_text.repeat(2);
 3584                        }
 3585
 3586                        let anchor = buffer.anchor_after(end);
 3587                        let new_selection = selection.map(|_| anchor);
 3588                        (
 3589                            (start..end, new_text),
 3590                            (insert_extra_newline, new_selection),
 3591                        )
 3592                    })
 3593                    .unzip()
 3594            };
 3595
 3596            this.edit_with_autoindent(edits, cx);
 3597            let buffer = this.buffer.read(cx).snapshot(cx);
 3598            let new_selections = selection_fixup_info
 3599                .into_iter()
 3600                .map(|(extra_newline_inserted, new_selection)| {
 3601                    let mut cursor = new_selection.end.to_point(&buffer);
 3602                    if extra_newline_inserted {
 3603                        cursor.row -= 1;
 3604                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3605                    }
 3606                    new_selection.map(|_| cursor)
 3607                })
 3608                .collect();
 3609
 3610            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3611            this.refresh_inline_completion(true, false, cx);
 3612        });
 3613    }
 3614
 3615    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3616        let buffer = self.buffer.read(cx);
 3617        let snapshot = buffer.snapshot(cx);
 3618
 3619        let mut edits = Vec::new();
 3620        let mut rows = Vec::new();
 3621
 3622        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3623            let cursor = selection.head();
 3624            let row = cursor.row;
 3625
 3626            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3627
 3628            let newline = "\n".to_string();
 3629            edits.push((start_of_line..start_of_line, newline));
 3630
 3631            rows.push(row + rows_inserted as u32);
 3632        }
 3633
 3634        self.transact(cx, |editor, cx| {
 3635            editor.edit(edits, cx);
 3636
 3637            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3638                let mut index = 0;
 3639                s.move_cursors_with(|map, _, _| {
 3640                    let row = rows[index];
 3641                    index += 1;
 3642
 3643                    let point = Point::new(row, 0);
 3644                    let boundary = map.next_line_boundary(point).1;
 3645                    let clipped = map.clip_point(boundary, Bias::Left);
 3646
 3647                    (clipped, SelectionGoal::None)
 3648                });
 3649            });
 3650
 3651            let mut indent_edits = Vec::new();
 3652            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3653            for row in rows {
 3654                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3655                for (row, indent) in indents {
 3656                    if indent.len == 0 {
 3657                        continue;
 3658                    }
 3659
 3660                    let text = match indent.kind {
 3661                        IndentKind::Space => " ".repeat(indent.len as usize),
 3662                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3663                    };
 3664                    let point = Point::new(row.0, 0);
 3665                    indent_edits.push((point..point, text));
 3666                }
 3667            }
 3668            editor.edit(indent_edits, cx);
 3669        });
 3670    }
 3671
 3672    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3673        let buffer = self.buffer.read(cx);
 3674        let snapshot = buffer.snapshot(cx);
 3675
 3676        let mut edits = Vec::new();
 3677        let mut rows = Vec::new();
 3678        let mut rows_inserted = 0;
 3679
 3680        for selection in self.selections.all_adjusted(cx) {
 3681            let cursor = selection.head();
 3682            let row = cursor.row;
 3683
 3684            let point = Point::new(row + 1, 0);
 3685            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3686
 3687            let newline = "\n".to_string();
 3688            edits.push((start_of_line..start_of_line, newline));
 3689
 3690            rows_inserted += 1;
 3691            rows.push(row + rows_inserted);
 3692        }
 3693
 3694        self.transact(cx, |editor, cx| {
 3695            editor.edit(edits, cx);
 3696
 3697            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3698                let mut index = 0;
 3699                s.move_cursors_with(|map, _, _| {
 3700                    let row = rows[index];
 3701                    index += 1;
 3702
 3703                    let point = Point::new(row, 0);
 3704                    let boundary = map.next_line_boundary(point).1;
 3705                    let clipped = map.clip_point(boundary, Bias::Left);
 3706
 3707                    (clipped, SelectionGoal::None)
 3708                });
 3709            });
 3710
 3711            let mut indent_edits = Vec::new();
 3712            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3713            for row in rows {
 3714                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3715                for (row, indent) in indents {
 3716                    if indent.len == 0 {
 3717                        continue;
 3718                    }
 3719
 3720                    let text = match indent.kind {
 3721                        IndentKind::Space => " ".repeat(indent.len as usize),
 3722                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3723                    };
 3724                    let point = Point::new(row.0, 0);
 3725                    indent_edits.push((point..point, text));
 3726                }
 3727            }
 3728            editor.edit(indent_edits, cx);
 3729        });
 3730    }
 3731
 3732    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3733        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3734            original_indent_columns: Vec::new(),
 3735        });
 3736        self.insert_with_autoindent_mode(text, autoindent, cx);
 3737    }
 3738
 3739    fn insert_with_autoindent_mode(
 3740        &mut self,
 3741        text: &str,
 3742        autoindent_mode: Option<AutoindentMode>,
 3743        cx: &mut ViewContext<Self>,
 3744    ) {
 3745        if self.read_only(cx) {
 3746            return;
 3747        }
 3748
 3749        let text: Arc<str> = text.into();
 3750        self.transact(cx, |this, cx| {
 3751            let old_selections = this.selections.all_adjusted(cx);
 3752            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3753                let anchors = {
 3754                    let snapshot = buffer.read(cx);
 3755                    old_selections
 3756                        .iter()
 3757                        .map(|s| {
 3758                            let anchor = snapshot.anchor_after(s.head());
 3759                            s.map(|_| anchor)
 3760                        })
 3761                        .collect::<Vec<_>>()
 3762                };
 3763                buffer.edit(
 3764                    old_selections
 3765                        .iter()
 3766                        .map(|s| (s.start..s.end, text.clone())),
 3767                    autoindent_mode,
 3768                    cx,
 3769                );
 3770                anchors
 3771            });
 3772
 3773            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3774                s.select_anchors(selection_anchors);
 3775            })
 3776        });
 3777    }
 3778
 3779    fn trigger_completion_on_input(
 3780        &mut self,
 3781        text: &str,
 3782        trigger_in_words: bool,
 3783        cx: &mut ViewContext<Self>,
 3784    ) {
 3785        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3786            self.show_completions(
 3787                &ShowCompletions {
 3788                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3789                },
 3790                cx,
 3791            );
 3792        } else {
 3793            self.hide_context_menu(cx);
 3794        }
 3795    }
 3796
 3797    fn is_completion_trigger(
 3798        &self,
 3799        text: &str,
 3800        trigger_in_words: bool,
 3801        cx: &mut ViewContext<Self>,
 3802    ) -> bool {
 3803        let position = self.selections.newest_anchor().head();
 3804        let multibuffer = self.buffer.read(cx);
 3805        let Some(buffer) = position
 3806            .buffer_id
 3807            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3808        else {
 3809            return false;
 3810        };
 3811
 3812        if let Some(completion_provider) = &self.completion_provider {
 3813            completion_provider.is_completion_trigger(
 3814                &buffer,
 3815                position.text_anchor,
 3816                text,
 3817                trigger_in_words,
 3818                cx,
 3819            )
 3820        } else {
 3821            false
 3822        }
 3823    }
 3824
 3825    /// If any empty selections is touching the start of its innermost containing autoclose
 3826    /// region, expand it to select the brackets.
 3827    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3828        let selections = self.selections.all::<usize>(cx);
 3829        let buffer = self.buffer.read(cx).read(cx);
 3830        let new_selections = self
 3831            .selections_with_autoclose_regions(selections, &buffer)
 3832            .map(|(mut selection, region)| {
 3833                if !selection.is_empty() {
 3834                    return selection;
 3835                }
 3836
 3837                if let Some(region) = region {
 3838                    let mut range = region.range.to_offset(&buffer);
 3839                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3840                        range.start -= region.pair.start.len();
 3841                        if buffer.contains_str_at(range.start, &region.pair.start)
 3842                            && buffer.contains_str_at(range.end, &region.pair.end)
 3843                        {
 3844                            range.end += region.pair.end.len();
 3845                            selection.start = range.start;
 3846                            selection.end = range.end;
 3847
 3848                            return selection;
 3849                        }
 3850                    }
 3851                }
 3852
 3853                let always_treat_brackets_as_autoclosed = buffer
 3854                    .settings_at(selection.start, cx)
 3855                    .always_treat_brackets_as_autoclosed;
 3856
 3857                if !always_treat_brackets_as_autoclosed {
 3858                    return selection;
 3859                }
 3860
 3861                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3862                    for (pair, enabled) in scope.brackets() {
 3863                        if !enabled || !pair.close {
 3864                            continue;
 3865                        }
 3866
 3867                        if buffer.contains_str_at(selection.start, &pair.end) {
 3868                            let pair_start_len = pair.start.len();
 3869                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3870                            {
 3871                                selection.start -= pair_start_len;
 3872                                selection.end += pair.end.len();
 3873
 3874                                return selection;
 3875                            }
 3876                        }
 3877                    }
 3878                }
 3879
 3880                selection
 3881            })
 3882            .collect();
 3883
 3884        drop(buffer);
 3885        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3886    }
 3887
 3888    /// Iterate the given selections, and for each one, find the smallest surrounding
 3889    /// autoclose region. This uses the ordering of the selections and the autoclose
 3890    /// regions to avoid repeated comparisons.
 3891    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3892        &'a self,
 3893        selections: impl IntoIterator<Item = Selection<D>>,
 3894        buffer: &'a MultiBufferSnapshot,
 3895    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3896        let mut i = 0;
 3897        let mut regions = self.autoclose_regions.as_slice();
 3898        selections.into_iter().map(move |selection| {
 3899            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3900
 3901            let mut enclosing = None;
 3902            while let Some(pair_state) = regions.get(i) {
 3903                if pair_state.range.end.to_offset(buffer) < range.start {
 3904                    regions = &regions[i + 1..];
 3905                    i = 0;
 3906                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3907                    break;
 3908                } else {
 3909                    if pair_state.selection_id == selection.id {
 3910                        enclosing = Some(pair_state);
 3911                    }
 3912                    i += 1;
 3913                }
 3914            }
 3915
 3916            (selection.clone(), enclosing)
 3917        })
 3918    }
 3919
 3920    /// Remove any autoclose regions that no longer contain their selection.
 3921    fn invalidate_autoclose_regions(
 3922        &mut self,
 3923        mut selections: &[Selection<Anchor>],
 3924        buffer: &MultiBufferSnapshot,
 3925    ) {
 3926        self.autoclose_regions.retain(|state| {
 3927            let mut i = 0;
 3928            while let Some(selection) = selections.get(i) {
 3929                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3930                    selections = &selections[1..];
 3931                    continue;
 3932                }
 3933                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3934                    break;
 3935                }
 3936                if selection.id == state.selection_id {
 3937                    return true;
 3938                } else {
 3939                    i += 1;
 3940                }
 3941            }
 3942            false
 3943        });
 3944    }
 3945
 3946    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3947        let offset = position.to_offset(buffer);
 3948        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3949        if offset > word_range.start && kind == Some(CharKind::Word) {
 3950            Some(
 3951                buffer
 3952                    .text_for_range(word_range.start..offset)
 3953                    .collect::<String>(),
 3954            )
 3955        } else {
 3956            None
 3957        }
 3958    }
 3959
 3960    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3961        self.refresh_inlay_hints(
 3962            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3963            cx,
 3964        );
 3965    }
 3966
 3967    pub fn inlay_hints_enabled(&self) -> bool {
 3968        self.inlay_hint_cache.enabled
 3969    }
 3970
 3971    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3972        if self.project.is_none() || self.mode != EditorMode::Full {
 3973            return;
 3974        }
 3975
 3976        let reason_description = reason.description();
 3977        let ignore_debounce = matches!(
 3978            reason,
 3979            InlayHintRefreshReason::SettingsChange(_)
 3980                | InlayHintRefreshReason::Toggle(_)
 3981                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3982        );
 3983        let (invalidate_cache, required_languages) = match reason {
 3984            InlayHintRefreshReason::Toggle(enabled) => {
 3985                self.inlay_hint_cache.enabled = enabled;
 3986                if enabled {
 3987                    (InvalidationStrategy::RefreshRequested, None)
 3988                } else {
 3989                    self.inlay_hint_cache.clear();
 3990                    self.splice_inlays(
 3991                        self.visible_inlay_hints(cx)
 3992                            .iter()
 3993                            .map(|inlay| inlay.id)
 3994                            .collect(),
 3995                        Vec::new(),
 3996                        cx,
 3997                    );
 3998                    return;
 3999                }
 4000            }
 4001            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4002                match self.inlay_hint_cache.update_settings(
 4003                    &self.buffer,
 4004                    new_settings,
 4005                    self.visible_inlay_hints(cx),
 4006                    cx,
 4007                ) {
 4008                    ControlFlow::Break(Some(InlaySplice {
 4009                        to_remove,
 4010                        to_insert,
 4011                    })) => {
 4012                        self.splice_inlays(to_remove, to_insert, cx);
 4013                        return;
 4014                    }
 4015                    ControlFlow::Break(None) => return,
 4016                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4017                }
 4018            }
 4019            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4020                if let Some(InlaySplice {
 4021                    to_remove,
 4022                    to_insert,
 4023                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4024                {
 4025                    self.splice_inlays(to_remove, to_insert, cx);
 4026                }
 4027                return;
 4028            }
 4029            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4030            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4031                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4032            }
 4033            InlayHintRefreshReason::RefreshRequested => {
 4034                (InvalidationStrategy::RefreshRequested, None)
 4035            }
 4036        };
 4037
 4038        if let Some(InlaySplice {
 4039            to_remove,
 4040            to_insert,
 4041        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4042            reason_description,
 4043            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4044            invalidate_cache,
 4045            ignore_debounce,
 4046            cx,
 4047        ) {
 4048            self.splice_inlays(to_remove, to_insert, cx);
 4049        }
 4050    }
 4051
 4052    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4053        self.display_map
 4054            .read(cx)
 4055            .current_inlays()
 4056            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4057            .cloned()
 4058            .collect()
 4059    }
 4060
 4061    pub fn excerpts_for_inlay_hints_query(
 4062        &self,
 4063        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4064        cx: &mut ViewContext<Editor>,
 4065    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4066        let Some(project) = self.project.as_ref() else {
 4067            return HashMap::default();
 4068        };
 4069        let project = project.read(cx);
 4070        let multi_buffer = self.buffer().read(cx);
 4071        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4072        let multi_buffer_visible_start = self
 4073            .scroll_manager
 4074            .anchor()
 4075            .anchor
 4076            .to_point(&multi_buffer_snapshot);
 4077        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4078            multi_buffer_visible_start
 4079                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4080            Bias::Left,
 4081        );
 4082        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4083        multi_buffer
 4084            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4085            .into_iter()
 4086            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4087            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4088                let buffer = buffer_handle.read(cx);
 4089                let buffer_file = project::File::from_dyn(buffer.file())?;
 4090                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4091                let worktree_entry = buffer_worktree
 4092                    .read(cx)
 4093                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4094                if worktree_entry.is_ignored {
 4095                    return None;
 4096                }
 4097
 4098                let language = buffer.language()?;
 4099                if let Some(restrict_to_languages) = restrict_to_languages {
 4100                    if !restrict_to_languages.contains(language) {
 4101                        return None;
 4102                    }
 4103                }
 4104                Some((
 4105                    excerpt_id,
 4106                    (
 4107                        buffer_handle,
 4108                        buffer.version().clone(),
 4109                        excerpt_visible_range,
 4110                    ),
 4111                ))
 4112            })
 4113            .collect()
 4114    }
 4115
 4116    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4117        TextLayoutDetails {
 4118            text_system: cx.text_system().clone(),
 4119            editor_style: self.style.clone().unwrap(),
 4120            rem_size: cx.rem_size(),
 4121            scroll_anchor: self.scroll_manager.anchor(),
 4122            visible_rows: self.visible_line_count(),
 4123            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4124        }
 4125    }
 4126
 4127    fn splice_inlays(
 4128        &self,
 4129        to_remove: Vec<InlayId>,
 4130        to_insert: Vec<Inlay>,
 4131        cx: &mut ViewContext<Self>,
 4132    ) {
 4133        self.display_map.update(cx, |display_map, cx| {
 4134            display_map.splice_inlays(to_remove, to_insert, cx);
 4135        });
 4136        cx.notify();
 4137    }
 4138
 4139    fn trigger_on_type_formatting(
 4140        &self,
 4141        input: String,
 4142        cx: &mut ViewContext<Self>,
 4143    ) -> Option<Task<Result<()>>> {
 4144        if input.len() != 1 {
 4145            return None;
 4146        }
 4147
 4148        let project = self.project.as_ref()?;
 4149        let position = self.selections.newest_anchor().head();
 4150        let (buffer, buffer_position) = self
 4151            .buffer
 4152            .read(cx)
 4153            .text_anchor_for_position(position, cx)?;
 4154
 4155        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4156        // hence we do LSP request & edit on host side only — add formats to host's history.
 4157        let push_to_lsp_host_history = true;
 4158        // If this is not the host, append its history with new edits.
 4159        let push_to_client_history = project.read(cx).is_via_collab();
 4160
 4161        let on_type_formatting = project.update(cx, |project, cx| {
 4162            project.on_type_format(
 4163                buffer.clone(),
 4164                buffer_position,
 4165                input,
 4166                push_to_lsp_host_history,
 4167                cx,
 4168            )
 4169        });
 4170        Some(cx.spawn(|editor, mut cx| async move {
 4171            if let Some(transaction) = on_type_formatting.await? {
 4172                if push_to_client_history {
 4173                    buffer
 4174                        .update(&mut cx, |buffer, _| {
 4175                            buffer.push_transaction(transaction, Instant::now());
 4176                        })
 4177                        .ok();
 4178                }
 4179                editor.update(&mut cx, |editor, cx| {
 4180                    editor.refresh_document_highlights(cx);
 4181                })?;
 4182            }
 4183            Ok(())
 4184        }))
 4185    }
 4186
 4187    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4188        if self.pending_rename.is_some() {
 4189            return;
 4190        }
 4191
 4192        let Some(provider) = self.completion_provider.as_ref() else {
 4193            return;
 4194        };
 4195
 4196        let position = self.selections.newest_anchor().head();
 4197        let (buffer, buffer_position) =
 4198            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4199                output
 4200            } else {
 4201                return;
 4202            };
 4203
 4204        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4205        let is_followup_invoke = {
 4206            let context_menu_state = self.context_menu.read();
 4207            matches!(
 4208                context_menu_state.deref(),
 4209                Some(ContextMenu::Completions(_))
 4210            )
 4211        };
 4212        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4213            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4214            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4215                CompletionTriggerKind::TRIGGER_CHARACTER
 4216            }
 4217
 4218            _ => CompletionTriggerKind::INVOKED,
 4219        };
 4220        let completion_context = CompletionContext {
 4221            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4222                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4223                    Some(String::from(trigger))
 4224                } else {
 4225                    None
 4226                }
 4227            }),
 4228            trigger_kind,
 4229        };
 4230        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4231        let sort_completions = provider.sort_completions();
 4232
 4233        let id = post_inc(&mut self.next_completion_id);
 4234        let task = cx.spawn(|this, mut cx| {
 4235            async move {
 4236                this.update(&mut cx, |this, _| {
 4237                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4238                })?;
 4239                let completions = completions.await.log_err();
 4240                let menu = if let Some(completions) = completions {
 4241                    let mut menu = CompletionsMenu {
 4242                        id,
 4243                        sort_completions,
 4244                        initial_position: position,
 4245                        match_candidates: completions
 4246                            .iter()
 4247                            .enumerate()
 4248                            .map(|(id, completion)| {
 4249                                StringMatchCandidate::new(
 4250                                    id,
 4251                                    completion.label.text[completion.label.filter_range.clone()]
 4252                                        .into(),
 4253                                )
 4254                            })
 4255                            .collect(),
 4256                        buffer: buffer.clone(),
 4257                        completions: Arc::new(RwLock::new(completions.into())),
 4258                        matches: Vec::new().into(),
 4259                        selected_item: 0,
 4260                        scroll_handle: UniformListScrollHandle::new(),
 4261                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4262                            DebouncedDelay::new(),
 4263                        )),
 4264                    };
 4265                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4266                        .await;
 4267
 4268                    if menu.matches.is_empty() {
 4269                        None
 4270                    } else {
 4271                        this.update(&mut cx, |editor, cx| {
 4272                            let completions = menu.completions.clone();
 4273                            let matches = menu.matches.clone();
 4274
 4275                            let delay_ms = EditorSettings::get_global(cx)
 4276                                .completion_documentation_secondary_query_debounce;
 4277                            let delay = Duration::from_millis(delay_ms);
 4278                            editor
 4279                                .completion_documentation_pre_resolve_debounce
 4280                                .fire_new(delay, cx, |editor, cx| {
 4281                                    CompletionsMenu::pre_resolve_completion_documentation(
 4282                                        buffer,
 4283                                        completions,
 4284                                        matches,
 4285                                        editor,
 4286                                        cx,
 4287                                    )
 4288                                });
 4289                        })
 4290                        .ok();
 4291                        Some(menu)
 4292                    }
 4293                } else {
 4294                    None
 4295                };
 4296
 4297                this.update(&mut cx, |this, cx| {
 4298                    let mut context_menu = this.context_menu.write();
 4299                    match context_menu.as_ref() {
 4300                        None => {}
 4301
 4302                        Some(ContextMenu::Completions(prev_menu)) => {
 4303                            if prev_menu.id > id {
 4304                                return;
 4305                            }
 4306                        }
 4307
 4308                        _ => return,
 4309                    }
 4310
 4311                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4312                        let menu = menu.unwrap();
 4313                        *context_menu = Some(ContextMenu::Completions(menu));
 4314                        drop(context_menu);
 4315                        this.discard_inline_completion(false, cx);
 4316                        cx.notify();
 4317                    } else if this.completion_tasks.len() <= 1 {
 4318                        // If there are no more completion tasks and the last menu was
 4319                        // empty, we should hide it. If it was already hidden, we should
 4320                        // also show the copilot completion when available.
 4321                        drop(context_menu);
 4322                        if this.hide_context_menu(cx).is_none() {
 4323                            this.update_visible_inline_completion(cx);
 4324                        }
 4325                    }
 4326                })?;
 4327
 4328                Ok::<_, anyhow::Error>(())
 4329            }
 4330            .log_err()
 4331        });
 4332
 4333        self.completion_tasks.push((id, task));
 4334    }
 4335
 4336    pub fn confirm_completion(
 4337        &mut self,
 4338        action: &ConfirmCompletion,
 4339        cx: &mut ViewContext<Self>,
 4340    ) -> Option<Task<Result<()>>> {
 4341        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4342    }
 4343
 4344    pub fn compose_completion(
 4345        &mut self,
 4346        action: &ComposeCompletion,
 4347        cx: &mut ViewContext<Self>,
 4348    ) -> Option<Task<Result<()>>> {
 4349        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4350    }
 4351
 4352    fn do_completion(
 4353        &mut self,
 4354        item_ix: Option<usize>,
 4355        intent: CompletionIntent,
 4356        cx: &mut ViewContext<Editor>,
 4357    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4358        use language::ToOffset as _;
 4359
 4360        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4361            menu
 4362        } else {
 4363            return None;
 4364        };
 4365
 4366        let mat = completions_menu
 4367            .matches
 4368            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4369        let buffer_handle = completions_menu.buffer;
 4370        let completions = completions_menu.completions.read();
 4371        let completion = completions.get(mat.candidate_id)?;
 4372        cx.stop_propagation();
 4373
 4374        let snippet;
 4375        let text;
 4376
 4377        if completion.is_snippet() {
 4378            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4379            text = snippet.as_ref().unwrap().text.clone();
 4380        } else {
 4381            snippet = None;
 4382            text = completion.new_text.clone();
 4383        };
 4384        let selections = self.selections.all::<usize>(cx);
 4385        let buffer = buffer_handle.read(cx);
 4386        let old_range = completion.old_range.to_offset(buffer);
 4387        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4388
 4389        let newest_selection = self.selections.newest_anchor();
 4390        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4391            return None;
 4392        }
 4393
 4394        let lookbehind = newest_selection
 4395            .start
 4396            .text_anchor
 4397            .to_offset(buffer)
 4398            .saturating_sub(old_range.start);
 4399        let lookahead = old_range
 4400            .end
 4401            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4402        let mut common_prefix_len = old_text
 4403            .bytes()
 4404            .zip(text.bytes())
 4405            .take_while(|(a, b)| a == b)
 4406            .count();
 4407
 4408        let snapshot = self.buffer.read(cx).snapshot(cx);
 4409        let mut range_to_replace: Option<Range<isize>> = None;
 4410        let mut ranges = Vec::new();
 4411        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4412        for selection in &selections {
 4413            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4414                let start = selection.start.saturating_sub(lookbehind);
 4415                let end = selection.end + lookahead;
 4416                if selection.id == newest_selection.id {
 4417                    range_to_replace = Some(
 4418                        ((start + common_prefix_len) as isize - selection.start as isize)
 4419                            ..(end as isize - selection.start as isize),
 4420                    );
 4421                }
 4422                ranges.push(start + common_prefix_len..end);
 4423            } else {
 4424                common_prefix_len = 0;
 4425                ranges.clear();
 4426                ranges.extend(selections.iter().map(|s| {
 4427                    if s.id == newest_selection.id {
 4428                        range_to_replace = Some(
 4429                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4430                                - selection.start as isize
 4431                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4432                                    - selection.start as isize,
 4433                        );
 4434                        old_range.clone()
 4435                    } else {
 4436                        s.start..s.end
 4437                    }
 4438                }));
 4439                break;
 4440            }
 4441            if !self.linked_edit_ranges.is_empty() {
 4442                let start_anchor = snapshot.anchor_before(selection.head());
 4443                let end_anchor = snapshot.anchor_after(selection.tail());
 4444                if let Some(ranges) = self
 4445                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4446                {
 4447                    for (buffer, edits) in ranges {
 4448                        linked_edits.entry(buffer.clone()).or_default().extend(
 4449                            edits
 4450                                .into_iter()
 4451                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4452                        );
 4453                    }
 4454                }
 4455            }
 4456        }
 4457        let text = &text[common_prefix_len..];
 4458
 4459        cx.emit(EditorEvent::InputHandled {
 4460            utf16_range_to_replace: range_to_replace,
 4461            text: text.into(),
 4462        });
 4463
 4464        self.transact(cx, |this, cx| {
 4465            if let Some(mut snippet) = snippet {
 4466                snippet.text = text.to_string();
 4467                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4468                    tabstop.start -= common_prefix_len as isize;
 4469                    tabstop.end -= common_prefix_len as isize;
 4470                }
 4471
 4472                this.insert_snippet(&ranges, snippet, cx).log_err();
 4473            } else {
 4474                this.buffer.update(cx, |buffer, cx| {
 4475                    buffer.edit(
 4476                        ranges.iter().map(|range| (range.clone(), text)),
 4477                        this.autoindent_mode.clone(),
 4478                        cx,
 4479                    );
 4480                });
 4481            }
 4482            for (buffer, edits) in linked_edits {
 4483                buffer.update(cx, |buffer, cx| {
 4484                    let snapshot = buffer.snapshot();
 4485                    let edits = edits
 4486                        .into_iter()
 4487                        .map(|(range, text)| {
 4488                            use text::ToPoint as TP;
 4489                            let end_point = TP::to_point(&range.end, &snapshot);
 4490                            let start_point = TP::to_point(&range.start, &snapshot);
 4491                            (start_point..end_point, text)
 4492                        })
 4493                        .sorted_by_key(|(range, _)| range.start)
 4494                        .collect::<Vec<_>>();
 4495                    buffer.edit(edits, None, cx);
 4496                })
 4497            }
 4498
 4499            this.refresh_inline_completion(true, false, cx);
 4500        });
 4501
 4502        let show_new_completions_on_confirm = completion
 4503            .confirm
 4504            .as_ref()
 4505            .map_or(false, |confirm| confirm(intent, cx));
 4506        if show_new_completions_on_confirm {
 4507            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4508        }
 4509
 4510        let provider = self.completion_provider.as_ref()?;
 4511        let apply_edits = provider.apply_additional_edits_for_completion(
 4512            buffer_handle,
 4513            completion.clone(),
 4514            true,
 4515            cx,
 4516        );
 4517
 4518        let editor_settings = EditorSettings::get_global(cx);
 4519        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4520            // After the code completion is finished, users often want to know what signatures are needed.
 4521            // so we should automatically call signature_help
 4522            self.show_signature_help(&ShowSignatureHelp, cx);
 4523        }
 4524
 4525        Some(cx.foreground_executor().spawn(async move {
 4526            apply_edits.await?;
 4527            Ok(())
 4528        }))
 4529    }
 4530
 4531    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4532        let mut context_menu = self.context_menu.write();
 4533        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4534            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4535                // Toggle if we're selecting the same one
 4536                *context_menu = None;
 4537                cx.notify();
 4538                return;
 4539            } else {
 4540                // Otherwise, clear it and start a new one
 4541                *context_menu = None;
 4542                cx.notify();
 4543            }
 4544        }
 4545        drop(context_menu);
 4546        let snapshot = self.snapshot(cx);
 4547        let deployed_from_indicator = action.deployed_from_indicator;
 4548        let mut task = self.code_actions_task.take();
 4549        let action = action.clone();
 4550        cx.spawn(|editor, mut cx| async move {
 4551            while let Some(prev_task) = task {
 4552                prev_task.await;
 4553                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4554            }
 4555
 4556            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4557                if editor.focus_handle.is_focused(cx) {
 4558                    let multibuffer_point = action
 4559                        .deployed_from_indicator
 4560                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4561                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4562                    let (buffer, buffer_row) = snapshot
 4563                        .buffer_snapshot
 4564                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4565                        .and_then(|(buffer_snapshot, range)| {
 4566                            editor
 4567                                .buffer
 4568                                .read(cx)
 4569                                .buffer(buffer_snapshot.remote_id())
 4570                                .map(|buffer| (buffer, range.start.row))
 4571                        })?;
 4572                    let (_, code_actions) = editor
 4573                        .available_code_actions
 4574                        .clone()
 4575                        .and_then(|(location, code_actions)| {
 4576                            let snapshot = location.buffer.read(cx).snapshot();
 4577                            let point_range = location.range.to_point(&snapshot);
 4578                            let point_range = point_range.start.row..=point_range.end.row;
 4579                            if point_range.contains(&buffer_row) {
 4580                                Some((location, code_actions))
 4581                            } else {
 4582                                None
 4583                            }
 4584                        })
 4585                        .unzip();
 4586                    let buffer_id = buffer.read(cx).remote_id();
 4587                    let tasks = editor
 4588                        .tasks
 4589                        .get(&(buffer_id, buffer_row))
 4590                        .map(|t| Arc::new(t.to_owned()));
 4591                    if tasks.is_none() && code_actions.is_none() {
 4592                        return None;
 4593                    }
 4594
 4595                    editor.completion_tasks.clear();
 4596                    editor.discard_inline_completion(false, cx);
 4597                    let task_context =
 4598                        tasks
 4599                            .as_ref()
 4600                            .zip(editor.project.clone())
 4601                            .map(|(tasks, project)| {
 4602                                let position = Point::new(buffer_row, tasks.column);
 4603                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4604                                let location = Location {
 4605                                    buffer: buffer.clone(),
 4606                                    range: range_start..range_start,
 4607                                };
 4608                                // Fill in the environmental variables from the tree-sitter captures
 4609                                let mut captured_task_variables = TaskVariables::default();
 4610                                for (capture_name, value) in tasks.extra_variables.clone() {
 4611                                    captured_task_variables.insert(
 4612                                        task::VariableName::Custom(capture_name.into()),
 4613                                        value.clone(),
 4614                                    );
 4615                                }
 4616                                project.update(cx, |project, cx| {
 4617                                    project.task_context_for_location(
 4618                                        captured_task_variables,
 4619                                        location,
 4620                                        cx,
 4621                                    )
 4622                                })
 4623                            });
 4624
 4625                    Some(cx.spawn(|editor, mut cx| async move {
 4626                        let task_context = match task_context {
 4627                            Some(task_context) => task_context.await,
 4628                            None => None,
 4629                        };
 4630                        let resolved_tasks =
 4631                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4632                                Arc::new(ResolvedTasks {
 4633                                    templates: tasks
 4634                                        .templates
 4635                                        .iter()
 4636                                        .filter_map(|(kind, template)| {
 4637                                            template
 4638                                                .resolve_task(&kind.to_id_base(), &task_context)
 4639                                                .map(|task| (kind.clone(), task))
 4640                                        })
 4641                                        .collect(),
 4642                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4643                                        multibuffer_point.row,
 4644                                        tasks.column,
 4645                                    )),
 4646                                })
 4647                            });
 4648                        let spawn_straight_away = resolved_tasks
 4649                            .as_ref()
 4650                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4651                            && code_actions
 4652                                .as_ref()
 4653                                .map_or(true, |actions| actions.is_empty());
 4654                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4655                            *editor.context_menu.write() =
 4656                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4657                                    buffer,
 4658                                    actions: CodeActionContents {
 4659                                        tasks: resolved_tasks,
 4660                                        actions: code_actions,
 4661                                    },
 4662                                    selected_item: Default::default(),
 4663                                    scroll_handle: UniformListScrollHandle::default(),
 4664                                    deployed_from_indicator,
 4665                                }));
 4666                            if spawn_straight_away {
 4667                                if let Some(task) = editor.confirm_code_action(
 4668                                    &ConfirmCodeAction { item_ix: Some(0) },
 4669                                    cx,
 4670                                ) {
 4671                                    cx.notify();
 4672                                    return task;
 4673                                }
 4674                            }
 4675                            cx.notify();
 4676                            Task::ready(Ok(()))
 4677                        }) {
 4678                            task.await
 4679                        } else {
 4680                            Ok(())
 4681                        }
 4682                    }))
 4683                } else {
 4684                    Some(Task::ready(Ok(())))
 4685                }
 4686            })?;
 4687            if let Some(task) = spawned_test_task {
 4688                task.await?;
 4689            }
 4690
 4691            Ok::<_, anyhow::Error>(())
 4692        })
 4693        .detach_and_log_err(cx);
 4694    }
 4695
 4696    pub fn confirm_code_action(
 4697        &mut self,
 4698        action: &ConfirmCodeAction,
 4699        cx: &mut ViewContext<Self>,
 4700    ) -> Option<Task<Result<()>>> {
 4701        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4702            menu
 4703        } else {
 4704            return None;
 4705        };
 4706        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4707        let action = actions_menu.actions.get(action_ix)?;
 4708        let title = action.label();
 4709        let buffer = actions_menu.buffer;
 4710        let workspace = self.workspace()?;
 4711
 4712        match action {
 4713            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4714                workspace.update(cx, |workspace, cx| {
 4715                    workspace::tasks::schedule_resolved_task(
 4716                        workspace,
 4717                        task_source_kind,
 4718                        resolved_task,
 4719                        false,
 4720                        cx,
 4721                    );
 4722
 4723                    Some(Task::ready(Ok(())))
 4724                })
 4725            }
 4726            CodeActionsItem::CodeAction(action) => {
 4727                let apply_code_actions = workspace
 4728                    .read(cx)
 4729                    .project()
 4730                    .clone()
 4731                    .update(cx, |project, cx| {
 4732                        project.apply_code_action(buffer, action, true, cx)
 4733                    });
 4734                let workspace = workspace.downgrade();
 4735                Some(cx.spawn(|editor, cx| async move {
 4736                    let project_transaction = apply_code_actions.await?;
 4737                    Self::open_project_transaction(
 4738                        &editor,
 4739                        workspace,
 4740                        project_transaction,
 4741                        title,
 4742                        cx,
 4743                    )
 4744                    .await
 4745                }))
 4746            }
 4747        }
 4748    }
 4749
 4750    pub async fn open_project_transaction(
 4751        this: &WeakView<Editor>,
 4752        workspace: WeakView<Workspace>,
 4753        transaction: ProjectTransaction,
 4754        title: String,
 4755        mut cx: AsyncWindowContext,
 4756    ) -> Result<()> {
 4757        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4758        cx.update(|cx| {
 4759            entries.sort_unstable_by_key(|(buffer, _)| {
 4760                buffer.read(cx).file().map(|f| f.path().clone())
 4761            });
 4762        })?;
 4763
 4764        // If the project transaction's edits are all contained within this editor, then
 4765        // avoid opening a new editor to display them.
 4766
 4767        if let Some((buffer, transaction)) = entries.first() {
 4768            if entries.len() == 1 {
 4769                let excerpt = this.update(&mut cx, |editor, cx| {
 4770                    editor
 4771                        .buffer()
 4772                        .read(cx)
 4773                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4774                })?;
 4775                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4776                    if excerpted_buffer == *buffer {
 4777                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4778                            let excerpt_range = excerpt_range.to_offset(buffer);
 4779                            buffer
 4780                                .edited_ranges_for_transaction::<usize>(transaction)
 4781                                .all(|range| {
 4782                                    excerpt_range.start <= range.start
 4783                                        && excerpt_range.end >= range.end
 4784                                })
 4785                        })?;
 4786
 4787                        if all_edits_within_excerpt {
 4788                            return Ok(());
 4789                        }
 4790                    }
 4791                }
 4792            }
 4793        } else {
 4794            return Ok(());
 4795        }
 4796
 4797        let mut ranges_to_highlight = Vec::new();
 4798        let excerpt_buffer = cx.new_model(|cx| {
 4799            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4800            for (buffer_handle, transaction) in &entries {
 4801                let buffer = buffer_handle.read(cx);
 4802                ranges_to_highlight.extend(
 4803                    multibuffer.push_excerpts_with_context_lines(
 4804                        buffer_handle.clone(),
 4805                        buffer
 4806                            .edited_ranges_for_transaction::<usize>(transaction)
 4807                            .collect(),
 4808                        DEFAULT_MULTIBUFFER_CONTEXT,
 4809                        cx,
 4810                    ),
 4811                );
 4812            }
 4813            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4814            multibuffer
 4815        })?;
 4816
 4817        workspace.update(&mut cx, |workspace, cx| {
 4818            let project = workspace.project().clone();
 4819            let editor =
 4820                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4821            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4822            editor.update(cx, |editor, cx| {
 4823                editor.highlight_background::<Self>(
 4824                    &ranges_to_highlight,
 4825                    |theme| theme.editor_highlighted_line_background,
 4826                    cx,
 4827                );
 4828            });
 4829        })?;
 4830
 4831        Ok(())
 4832    }
 4833
 4834    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4835        let project = self.project.clone()?;
 4836        let buffer = self.buffer.read(cx);
 4837        let newest_selection = self.selections.newest_anchor().clone();
 4838        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4839        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4840        if start_buffer != end_buffer {
 4841            return None;
 4842        }
 4843
 4844        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4845            cx.background_executor()
 4846                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4847                .await;
 4848
 4849            let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
 4850                project.code_actions(&start_buffer, start..end, cx)
 4851            }) {
 4852                code_actions.await
 4853            } else {
 4854                Vec::new()
 4855            };
 4856
 4857            this.update(&mut cx, |this, cx| {
 4858                this.available_code_actions = if actions.is_empty() {
 4859                    None
 4860                } else {
 4861                    Some((
 4862                        Location {
 4863                            buffer: start_buffer,
 4864                            range: start..end,
 4865                        },
 4866                        actions.into(),
 4867                    ))
 4868                };
 4869                cx.notify();
 4870            })
 4871            .log_err();
 4872        }));
 4873        None
 4874    }
 4875
 4876    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4877        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4878            self.show_git_blame_inline = false;
 4879
 4880            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4881                cx.background_executor().timer(delay).await;
 4882
 4883                this.update(&mut cx, |this, cx| {
 4884                    this.show_git_blame_inline = true;
 4885                    cx.notify();
 4886                })
 4887                .log_err();
 4888            }));
 4889        }
 4890    }
 4891
 4892    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4893        if self.pending_rename.is_some() {
 4894            return None;
 4895        }
 4896
 4897        let project = self.project.clone()?;
 4898        let buffer = self.buffer.read(cx);
 4899        let newest_selection = self.selections.newest_anchor().clone();
 4900        let cursor_position = newest_selection.head();
 4901        let (cursor_buffer, cursor_buffer_position) =
 4902            buffer.text_anchor_for_position(cursor_position, cx)?;
 4903        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4904        if cursor_buffer != tail_buffer {
 4905            return None;
 4906        }
 4907
 4908        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4909            cx.background_executor()
 4910                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 4911                .await;
 4912
 4913            let highlights = if let Some(highlights) = project
 4914                .update(&mut cx, |project, cx| {
 4915                    project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4916                })
 4917                .log_err()
 4918            {
 4919                highlights.await.log_err()
 4920            } else {
 4921                None
 4922            };
 4923
 4924            if let Some(highlights) = highlights {
 4925                this.update(&mut cx, |this, cx| {
 4926                    if this.pending_rename.is_some() {
 4927                        return;
 4928                    }
 4929
 4930                    let buffer_id = cursor_position.buffer_id;
 4931                    let buffer = this.buffer.read(cx);
 4932                    if !buffer
 4933                        .text_anchor_for_position(cursor_position, cx)
 4934                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4935                    {
 4936                        return;
 4937                    }
 4938
 4939                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4940                    let mut write_ranges = Vec::new();
 4941                    let mut read_ranges = Vec::new();
 4942                    for highlight in highlights {
 4943                        for (excerpt_id, excerpt_range) in
 4944                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4945                        {
 4946                            let start = highlight
 4947                                .range
 4948                                .start
 4949                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4950                            let end = highlight
 4951                                .range
 4952                                .end
 4953                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4954                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4955                                continue;
 4956                            }
 4957
 4958                            let range = Anchor {
 4959                                buffer_id,
 4960                                excerpt_id,
 4961                                text_anchor: start,
 4962                            }..Anchor {
 4963                                buffer_id,
 4964                                excerpt_id,
 4965                                text_anchor: end,
 4966                            };
 4967                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4968                                write_ranges.push(range);
 4969                            } else {
 4970                                read_ranges.push(range);
 4971                            }
 4972                        }
 4973                    }
 4974
 4975                    this.highlight_background::<DocumentHighlightRead>(
 4976                        &read_ranges,
 4977                        |theme| theme.editor_document_highlight_read_background,
 4978                        cx,
 4979                    );
 4980                    this.highlight_background::<DocumentHighlightWrite>(
 4981                        &write_ranges,
 4982                        |theme| theme.editor_document_highlight_write_background,
 4983                        cx,
 4984                    );
 4985                    cx.notify();
 4986                })
 4987                .log_err();
 4988            }
 4989        }));
 4990        None
 4991    }
 4992
 4993    pub fn refresh_inline_completion(
 4994        &mut self,
 4995        debounce: bool,
 4996        user_requested: bool,
 4997        cx: &mut ViewContext<Self>,
 4998    ) -> Option<()> {
 4999        let provider = self.inline_completion_provider()?;
 5000        let cursor = self.selections.newest_anchor().head();
 5001        let (buffer, cursor_buffer_position) =
 5002            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5003
 5004        if !user_requested
 5005            && (!self.enable_inline_completions
 5006                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 5007        {
 5008            self.discard_inline_completion(false, cx);
 5009            return None;
 5010        }
 5011
 5012        self.update_visible_inline_completion(cx);
 5013        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5014        Some(())
 5015    }
 5016
 5017    fn cycle_inline_completion(
 5018        &mut self,
 5019        direction: Direction,
 5020        cx: &mut ViewContext<Self>,
 5021    ) -> Option<()> {
 5022        let provider = self.inline_completion_provider()?;
 5023        let cursor = self.selections.newest_anchor().head();
 5024        let (buffer, cursor_buffer_position) =
 5025            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5026        if !self.enable_inline_completions
 5027            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5028        {
 5029            return None;
 5030        }
 5031
 5032        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5033        self.update_visible_inline_completion(cx);
 5034
 5035        Some(())
 5036    }
 5037
 5038    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5039        if !self.has_active_inline_completion(cx) {
 5040            self.refresh_inline_completion(false, true, cx);
 5041            return;
 5042        }
 5043
 5044        self.update_visible_inline_completion(cx);
 5045    }
 5046
 5047    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5048        self.show_cursor_names(cx);
 5049    }
 5050
 5051    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5052        self.show_cursor_names = true;
 5053        cx.notify();
 5054        cx.spawn(|this, mut cx| async move {
 5055            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5056            this.update(&mut cx, |this, cx| {
 5057                this.show_cursor_names = false;
 5058                cx.notify()
 5059            })
 5060            .ok()
 5061        })
 5062        .detach();
 5063    }
 5064
 5065    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5066        if self.has_active_inline_completion(cx) {
 5067            self.cycle_inline_completion(Direction::Next, cx);
 5068        } else {
 5069            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5070            if is_copilot_disabled {
 5071                cx.propagate();
 5072            }
 5073        }
 5074    }
 5075
 5076    pub fn previous_inline_completion(
 5077        &mut self,
 5078        _: &PreviousInlineCompletion,
 5079        cx: &mut ViewContext<Self>,
 5080    ) {
 5081        if self.has_active_inline_completion(cx) {
 5082            self.cycle_inline_completion(Direction::Prev, cx);
 5083        } else {
 5084            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5085            if is_copilot_disabled {
 5086                cx.propagate();
 5087            }
 5088        }
 5089    }
 5090
 5091    pub fn accept_inline_completion(
 5092        &mut self,
 5093        _: &AcceptInlineCompletion,
 5094        cx: &mut ViewContext<Self>,
 5095    ) {
 5096        let Some(completion) = self.take_active_inline_completion(cx) else {
 5097            return;
 5098        };
 5099        if let Some(provider) = self.inline_completion_provider() {
 5100            provider.accept(cx);
 5101        }
 5102
 5103        cx.emit(EditorEvent::InputHandled {
 5104            utf16_range_to_replace: None,
 5105            text: completion.text.to_string().into(),
 5106        });
 5107
 5108        if let Some(range) = completion.delete_range {
 5109            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5110        }
 5111        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5112        self.refresh_inline_completion(true, true, cx);
 5113        cx.notify();
 5114    }
 5115
 5116    pub fn accept_partial_inline_completion(
 5117        &mut self,
 5118        _: &AcceptPartialInlineCompletion,
 5119        cx: &mut ViewContext<Self>,
 5120    ) {
 5121        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5122            if let Some(completion) = self.take_active_inline_completion(cx) {
 5123                let mut partial_completion = completion
 5124                    .text
 5125                    .chars()
 5126                    .by_ref()
 5127                    .take_while(|c| c.is_alphabetic())
 5128                    .collect::<String>();
 5129                if partial_completion.is_empty() {
 5130                    partial_completion = completion
 5131                        .text
 5132                        .chars()
 5133                        .by_ref()
 5134                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5135                        .collect::<String>();
 5136                }
 5137
 5138                cx.emit(EditorEvent::InputHandled {
 5139                    utf16_range_to_replace: None,
 5140                    text: partial_completion.clone().into(),
 5141                });
 5142
 5143                if let Some(range) = completion.delete_range {
 5144                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5145                }
 5146                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5147
 5148                self.refresh_inline_completion(true, true, cx);
 5149                cx.notify();
 5150            }
 5151        }
 5152    }
 5153
 5154    fn discard_inline_completion(
 5155        &mut self,
 5156        should_report_inline_completion_event: bool,
 5157        cx: &mut ViewContext<Self>,
 5158    ) -> bool {
 5159        if let Some(provider) = self.inline_completion_provider() {
 5160            provider.discard(should_report_inline_completion_event, cx);
 5161        }
 5162
 5163        self.take_active_inline_completion(cx).is_some()
 5164    }
 5165
 5166    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5167        if let Some(completion) = self.active_inline_completion.as_ref() {
 5168            let buffer = self.buffer.read(cx).read(cx);
 5169            completion.position.is_valid(&buffer)
 5170        } else {
 5171            false
 5172        }
 5173    }
 5174
 5175    fn take_active_inline_completion(
 5176        &mut self,
 5177        cx: &mut ViewContext<Self>,
 5178    ) -> Option<CompletionState> {
 5179        let completion = self.active_inline_completion.take()?;
 5180        let render_inlay_ids = completion.render_inlay_ids.clone();
 5181        self.display_map.update(cx, |map, cx| {
 5182            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5183        });
 5184        let buffer = self.buffer.read(cx).read(cx);
 5185
 5186        if completion.position.is_valid(&buffer) {
 5187            Some(completion)
 5188        } else {
 5189            None
 5190        }
 5191    }
 5192
 5193    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5194        let selection = self.selections.newest_anchor();
 5195        let cursor = selection.head();
 5196
 5197        let excerpt_id = cursor.excerpt_id;
 5198
 5199        if self.context_menu.read().is_none()
 5200            && self.completion_tasks.is_empty()
 5201            && selection.start == selection.end
 5202        {
 5203            if let Some(provider) = self.inline_completion_provider() {
 5204                if let Some((buffer, cursor_buffer_position)) =
 5205                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5206                {
 5207                    if let Some(proposal) =
 5208                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5209                    {
 5210                        let mut to_remove = Vec::new();
 5211                        if let Some(completion) = self.active_inline_completion.take() {
 5212                            to_remove.extend(completion.render_inlay_ids.iter());
 5213                        }
 5214
 5215                        let to_add = proposal
 5216                            .inlays
 5217                            .iter()
 5218                            .filter_map(|inlay| {
 5219                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5220                                let id = post_inc(&mut self.next_inlay_id);
 5221                                match inlay {
 5222                                    InlayProposal::Hint(position, hint) => {
 5223                                        let position =
 5224                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5225                                        Some(Inlay::hint(id, position, hint))
 5226                                    }
 5227                                    InlayProposal::Suggestion(position, text) => {
 5228                                        let position =
 5229                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5230                                        Some(Inlay::suggestion(id, position, text.clone()))
 5231                                    }
 5232                                }
 5233                            })
 5234                            .collect_vec();
 5235
 5236                        self.active_inline_completion = Some(CompletionState {
 5237                            position: cursor,
 5238                            text: proposal.text,
 5239                            delete_range: proposal.delete_range.and_then(|range| {
 5240                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5241                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5242                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5243                                Some(start?..end?)
 5244                            }),
 5245                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5246                        });
 5247
 5248                        self.display_map
 5249                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5250
 5251                        cx.notify();
 5252                        return;
 5253                    }
 5254                }
 5255            }
 5256        }
 5257
 5258        self.discard_inline_completion(false, cx);
 5259    }
 5260
 5261    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5262        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5263    }
 5264
 5265    fn render_code_actions_indicator(
 5266        &self,
 5267        _style: &EditorStyle,
 5268        row: DisplayRow,
 5269        is_active: bool,
 5270        cx: &mut ViewContext<Self>,
 5271    ) -> Option<IconButton> {
 5272        if self.available_code_actions.is_some() {
 5273            Some(
 5274                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5275                    .shape(ui::IconButtonShape::Square)
 5276                    .icon_size(IconSize::XSmall)
 5277                    .icon_color(Color::Muted)
 5278                    .selected(is_active)
 5279                    .on_click(cx.listener(move |editor, _e, cx| {
 5280                        editor.focus(cx);
 5281                        editor.toggle_code_actions(
 5282                            &ToggleCodeActions {
 5283                                deployed_from_indicator: Some(row),
 5284                            },
 5285                            cx,
 5286                        );
 5287                    })),
 5288            )
 5289        } else {
 5290            None
 5291        }
 5292    }
 5293
 5294    fn clear_tasks(&mut self) {
 5295        self.tasks.clear()
 5296    }
 5297
 5298    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5299        if self.tasks.insert(key, value).is_some() {
 5300            // This case should hopefully be rare, but just in case...
 5301            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5302        }
 5303    }
 5304
 5305    fn render_run_indicator(
 5306        &self,
 5307        _style: &EditorStyle,
 5308        is_active: bool,
 5309        row: DisplayRow,
 5310        cx: &mut ViewContext<Self>,
 5311    ) -> IconButton {
 5312        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5313            .shape(ui::IconButtonShape::Square)
 5314            .icon_size(IconSize::XSmall)
 5315            .icon_color(Color::Muted)
 5316            .selected(is_active)
 5317            .on_click(cx.listener(move |editor, _e, cx| {
 5318                editor.focus(cx);
 5319                editor.toggle_code_actions(
 5320                    &ToggleCodeActions {
 5321                        deployed_from_indicator: Some(row),
 5322                    },
 5323                    cx,
 5324                );
 5325            }))
 5326    }
 5327
 5328    fn close_hunk_diff_button(
 5329        &self,
 5330        hunk: HoveredHunk,
 5331        row: DisplayRow,
 5332        cx: &mut ViewContext<Self>,
 5333    ) -> IconButton {
 5334        IconButton::new(
 5335            ("close_hunk_diff_indicator", row.0 as usize),
 5336            ui::IconName::Close,
 5337        )
 5338        .shape(ui::IconButtonShape::Square)
 5339        .icon_size(IconSize::XSmall)
 5340        .icon_color(Color::Muted)
 5341        .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
 5342        .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
 5343    }
 5344
 5345    pub fn context_menu_visible(&self) -> bool {
 5346        self.context_menu
 5347            .read()
 5348            .as_ref()
 5349            .map_or(false, |menu| menu.visible())
 5350    }
 5351
 5352    fn render_context_menu(
 5353        &self,
 5354        cursor_position: DisplayPoint,
 5355        style: &EditorStyle,
 5356        max_height: Pixels,
 5357        cx: &mut ViewContext<Editor>,
 5358    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5359        self.context_menu.read().as_ref().map(|menu| {
 5360            menu.render(
 5361                cursor_position,
 5362                style,
 5363                max_height,
 5364                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5365                cx,
 5366            )
 5367        })
 5368    }
 5369
 5370    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5371        cx.notify();
 5372        self.completion_tasks.clear();
 5373        let context_menu = self.context_menu.write().take();
 5374        if context_menu.is_some() {
 5375            self.update_visible_inline_completion(cx);
 5376        }
 5377        context_menu
 5378    }
 5379
 5380    pub fn insert_snippet(
 5381        &mut self,
 5382        insertion_ranges: &[Range<usize>],
 5383        snippet: Snippet,
 5384        cx: &mut ViewContext<Self>,
 5385    ) -> Result<()> {
 5386        struct Tabstop<T> {
 5387            is_end_tabstop: bool,
 5388            ranges: Vec<Range<T>>,
 5389        }
 5390
 5391        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5392            let snippet_text: Arc<str> = snippet.text.clone().into();
 5393            buffer.edit(
 5394                insertion_ranges
 5395                    .iter()
 5396                    .cloned()
 5397                    .map(|range| (range, snippet_text.clone())),
 5398                Some(AutoindentMode::EachLine),
 5399                cx,
 5400            );
 5401
 5402            let snapshot = &*buffer.read(cx);
 5403            let snippet = &snippet;
 5404            snippet
 5405                .tabstops
 5406                .iter()
 5407                .map(|tabstop| {
 5408                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5409                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5410                    });
 5411                    let mut tabstop_ranges = tabstop
 5412                        .iter()
 5413                        .flat_map(|tabstop_range| {
 5414                            let mut delta = 0_isize;
 5415                            insertion_ranges.iter().map(move |insertion_range| {
 5416                                let insertion_start = insertion_range.start as isize + delta;
 5417                                delta +=
 5418                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5419
 5420                                let start = ((insertion_start + tabstop_range.start) as usize)
 5421                                    .min(snapshot.len());
 5422                                let end = ((insertion_start + tabstop_range.end) as usize)
 5423                                    .min(snapshot.len());
 5424                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5425                            })
 5426                        })
 5427                        .collect::<Vec<_>>();
 5428                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5429
 5430                    Tabstop {
 5431                        is_end_tabstop,
 5432                        ranges: tabstop_ranges,
 5433                    }
 5434                })
 5435                .collect::<Vec<_>>()
 5436        });
 5437        if let Some(tabstop) = tabstops.first() {
 5438            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5439                s.select_ranges(tabstop.ranges.iter().cloned());
 5440            });
 5441
 5442            // If we're already at the last tabstop and it's at the end of the snippet,
 5443            // we're done, we don't need to keep the state around.
 5444            if !tabstop.is_end_tabstop {
 5445                let ranges = tabstops
 5446                    .into_iter()
 5447                    .map(|tabstop| tabstop.ranges)
 5448                    .collect::<Vec<_>>();
 5449                self.snippet_stack.push(SnippetState {
 5450                    active_index: 0,
 5451                    ranges,
 5452                });
 5453            }
 5454
 5455            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5456            if self.autoclose_regions.is_empty() {
 5457                let snapshot = self.buffer.read(cx).snapshot(cx);
 5458                for selection in &mut self.selections.all::<Point>(cx) {
 5459                    let selection_head = selection.head();
 5460                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5461                        continue;
 5462                    };
 5463
 5464                    let mut bracket_pair = None;
 5465                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5466                    let prev_chars = snapshot
 5467                        .reversed_chars_at(selection_head)
 5468                        .collect::<String>();
 5469                    for (pair, enabled) in scope.brackets() {
 5470                        if enabled
 5471                            && pair.close
 5472                            && prev_chars.starts_with(pair.start.as_str())
 5473                            && next_chars.starts_with(pair.end.as_str())
 5474                        {
 5475                            bracket_pair = Some(pair.clone());
 5476                            break;
 5477                        }
 5478                    }
 5479                    if let Some(pair) = bracket_pair {
 5480                        let start = snapshot.anchor_after(selection_head);
 5481                        let end = snapshot.anchor_after(selection_head);
 5482                        self.autoclose_regions.push(AutocloseRegion {
 5483                            selection_id: selection.id,
 5484                            range: start..end,
 5485                            pair,
 5486                        });
 5487                    }
 5488                }
 5489            }
 5490        }
 5491        Ok(())
 5492    }
 5493
 5494    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5495        self.move_to_snippet_tabstop(Bias::Right, cx)
 5496    }
 5497
 5498    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5499        self.move_to_snippet_tabstop(Bias::Left, cx)
 5500    }
 5501
 5502    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5503        if let Some(mut snippet) = self.snippet_stack.pop() {
 5504            match bias {
 5505                Bias::Left => {
 5506                    if snippet.active_index > 0 {
 5507                        snippet.active_index -= 1;
 5508                    } else {
 5509                        self.snippet_stack.push(snippet);
 5510                        return false;
 5511                    }
 5512                }
 5513                Bias::Right => {
 5514                    if snippet.active_index + 1 < snippet.ranges.len() {
 5515                        snippet.active_index += 1;
 5516                    } else {
 5517                        self.snippet_stack.push(snippet);
 5518                        return false;
 5519                    }
 5520                }
 5521            }
 5522            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5523                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5524                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5525                });
 5526                // If snippet state is not at the last tabstop, push it back on the stack
 5527                if snippet.active_index + 1 < snippet.ranges.len() {
 5528                    self.snippet_stack.push(snippet);
 5529                }
 5530                return true;
 5531            }
 5532        }
 5533
 5534        false
 5535    }
 5536
 5537    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5538        self.transact(cx, |this, cx| {
 5539            this.select_all(&SelectAll, cx);
 5540            this.insert("", cx);
 5541        });
 5542    }
 5543
 5544    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5545        self.transact(cx, |this, cx| {
 5546            this.select_autoclose_pair(cx);
 5547            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5548            if !this.linked_edit_ranges.is_empty() {
 5549                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5550                let snapshot = this.buffer.read(cx).snapshot(cx);
 5551
 5552                for selection in selections.iter() {
 5553                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5554                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5555                    if selection_start.buffer_id != selection_end.buffer_id {
 5556                        continue;
 5557                    }
 5558                    if let Some(ranges) =
 5559                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5560                    {
 5561                        for (buffer, entries) in ranges {
 5562                            linked_ranges.entry(buffer).or_default().extend(entries);
 5563                        }
 5564                    }
 5565                }
 5566            }
 5567
 5568            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5569            if !this.selections.line_mode {
 5570                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5571                for selection in &mut selections {
 5572                    if selection.is_empty() {
 5573                        let old_head = selection.head();
 5574                        let mut new_head =
 5575                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5576                                .to_point(&display_map);
 5577                        if let Some((buffer, line_buffer_range)) = display_map
 5578                            .buffer_snapshot
 5579                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5580                        {
 5581                            let indent_size =
 5582                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5583                            let indent_len = match indent_size.kind {
 5584                                IndentKind::Space => {
 5585                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5586                                }
 5587                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5588                            };
 5589                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5590                                let indent_len = indent_len.get();
 5591                                new_head = cmp::min(
 5592                                    new_head,
 5593                                    MultiBufferPoint::new(
 5594                                        old_head.row,
 5595                                        ((old_head.column - 1) / indent_len) * indent_len,
 5596                                    ),
 5597                                );
 5598                            }
 5599                        }
 5600
 5601                        selection.set_head(new_head, SelectionGoal::None);
 5602                    }
 5603                }
 5604            }
 5605
 5606            this.signature_help_state.set_backspace_pressed(true);
 5607            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5608            this.insert("", cx);
 5609            let empty_str: Arc<str> = Arc::from("");
 5610            for (buffer, edits) in linked_ranges {
 5611                let snapshot = buffer.read(cx).snapshot();
 5612                use text::ToPoint as TP;
 5613
 5614                let edits = edits
 5615                    .into_iter()
 5616                    .map(|range| {
 5617                        let end_point = TP::to_point(&range.end, &snapshot);
 5618                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5619
 5620                        if end_point == start_point {
 5621                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5622                                .saturating_sub(1);
 5623                            start_point = TP::to_point(&offset, &snapshot);
 5624                        };
 5625
 5626                        (start_point..end_point, empty_str.clone())
 5627                    })
 5628                    .sorted_by_key(|(range, _)| range.start)
 5629                    .collect::<Vec<_>>();
 5630                buffer.update(cx, |this, cx| {
 5631                    this.edit(edits, None, cx);
 5632                })
 5633            }
 5634            this.refresh_inline_completion(true, false, cx);
 5635            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5636        });
 5637    }
 5638
 5639    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5640        self.transact(cx, |this, cx| {
 5641            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5642                let line_mode = s.line_mode;
 5643                s.move_with(|map, selection| {
 5644                    if selection.is_empty() && !line_mode {
 5645                        let cursor = movement::right(map, selection.head());
 5646                        selection.end = cursor;
 5647                        selection.reversed = true;
 5648                        selection.goal = SelectionGoal::None;
 5649                    }
 5650                })
 5651            });
 5652            this.insert("", cx);
 5653            this.refresh_inline_completion(true, false, cx);
 5654        });
 5655    }
 5656
 5657    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5658        if self.move_to_prev_snippet_tabstop(cx) {
 5659            return;
 5660        }
 5661
 5662        self.outdent(&Outdent, cx);
 5663    }
 5664
 5665    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5666        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5667            return;
 5668        }
 5669
 5670        let mut selections = self.selections.all_adjusted(cx);
 5671        let buffer = self.buffer.read(cx);
 5672        let snapshot = buffer.snapshot(cx);
 5673        let rows_iter = selections.iter().map(|s| s.head().row);
 5674        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5675
 5676        let mut edits = Vec::new();
 5677        let mut prev_edited_row = 0;
 5678        let mut row_delta = 0;
 5679        for selection in &mut selections {
 5680            if selection.start.row != prev_edited_row {
 5681                row_delta = 0;
 5682            }
 5683            prev_edited_row = selection.end.row;
 5684
 5685            // If the selection is non-empty, then increase the indentation of the selected lines.
 5686            if !selection.is_empty() {
 5687                row_delta =
 5688                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5689                continue;
 5690            }
 5691
 5692            // If the selection is empty and the cursor is in the leading whitespace before the
 5693            // suggested indentation, then auto-indent the line.
 5694            let cursor = selection.head();
 5695            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5696            if let Some(suggested_indent) =
 5697                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5698            {
 5699                if cursor.column < suggested_indent.len
 5700                    && cursor.column <= current_indent.len
 5701                    && current_indent.len <= suggested_indent.len
 5702                {
 5703                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5704                    selection.end = selection.start;
 5705                    if row_delta == 0 {
 5706                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5707                            cursor.row,
 5708                            current_indent,
 5709                            suggested_indent,
 5710                        ));
 5711                        row_delta = suggested_indent.len - current_indent.len;
 5712                    }
 5713                    continue;
 5714                }
 5715            }
 5716
 5717            // Otherwise, insert a hard or soft tab.
 5718            let settings = buffer.settings_at(cursor, cx);
 5719            let tab_size = if settings.hard_tabs {
 5720                IndentSize::tab()
 5721            } else {
 5722                let tab_size = settings.tab_size.get();
 5723                let char_column = snapshot
 5724                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5725                    .flat_map(str::chars)
 5726                    .count()
 5727                    + row_delta as usize;
 5728                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5729                IndentSize::spaces(chars_to_next_tab_stop)
 5730            };
 5731            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5732            selection.end = selection.start;
 5733            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5734            row_delta += tab_size.len;
 5735        }
 5736
 5737        self.transact(cx, |this, cx| {
 5738            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5739            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5740            this.refresh_inline_completion(true, false, cx);
 5741        });
 5742    }
 5743
 5744    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5745        if self.read_only(cx) {
 5746            return;
 5747        }
 5748        let mut selections = self.selections.all::<Point>(cx);
 5749        let mut prev_edited_row = 0;
 5750        let mut row_delta = 0;
 5751        let mut edits = Vec::new();
 5752        let buffer = self.buffer.read(cx);
 5753        let snapshot = buffer.snapshot(cx);
 5754        for selection in &mut selections {
 5755            if selection.start.row != prev_edited_row {
 5756                row_delta = 0;
 5757            }
 5758            prev_edited_row = selection.end.row;
 5759
 5760            row_delta =
 5761                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5762        }
 5763
 5764        self.transact(cx, |this, cx| {
 5765            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5766            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5767        });
 5768    }
 5769
 5770    fn indent_selection(
 5771        buffer: &MultiBuffer,
 5772        snapshot: &MultiBufferSnapshot,
 5773        selection: &mut Selection<Point>,
 5774        edits: &mut Vec<(Range<Point>, String)>,
 5775        delta_for_start_row: u32,
 5776        cx: &AppContext,
 5777    ) -> u32 {
 5778        let settings = buffer.settings_at(selection.start, cx);
 5779        let tab_size = settings.tab_size.get();
 5780        let indent_kind = if settings.hard_tabs {
 5781            IndentKind::Tab
 5782        } else {
 5783            IndentKind::Space
 5784        };
 5785        let mut start_row = selection.start.row;
 5786        let mut end_row = selection.end.row + 1;
 5787
 5788        // If a selection ends at the beginning of a line, don't indent
 5789        // that last line.
 5790        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5791            end_row -= 1;
 5792        }
 5793
 5794        // Avoid re-indenting a row that has already been indented by a
 5795        // previous selection, but still update this selection's column
 5796        // to reflect that indentation.
 5797        if delta_for_start_row > 0 {
 5798            start_row += 1;
 5799            selection.start.column += delta_for_start_row;
 5800            if selection.end.row == selection.start.row {
 5801                selection.end.column += delta_for_start_row;
 5802            }
 5803        }
 5804
 5805        let mut delta_for_end_row = 0;
 5806        let has_multiple_rows = start_row + 1 != end_row;
 5807        for row in start_row..end_row {
 5808            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5809            let indent_delta = match (current_indent.kind, indent_kind) {
 5810                (IndentKind::Space, IndentKind::Space) => {
 5811                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5812                    IndentSize::spaces(columns_to_next_tab_stop)
 5813                }
 5814                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5815                (_, IndentKind::Tab) => IndentSize::tab(),
 5816            };
 5817
 5818            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5819                0
 5820            } else {
 5821                selection.start.column
 5822            };
 5823            let row_start = Point::new(row, start);
 5824            edits.push((
 5825                row_start..row_start,
 5826                indent_delta.chars().collect::<String>(),
 5827            ));
 5828
 5829            // Update this selection's endpoints to reflect the indentation.
 5830            if row == selection.start.row {
 5831                selection.start.column += indent_delta.len;
 5832            }
 5833            if row == selection.end.row {
 5834                selection.end.column += indent_delta.len;
 5835                delta_for_end_row = indent_delta.len;
 5836            }
 5837        }
 5838
 5839        if selection.start.row == selection.end.row {
 5840            delta_for_start_row + delta_for_end_row
 5841        } else {
 5842            delta_for_end_row
 5843        }
 5844    }
 5845
 5846    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5847        if self.read_only(cx) {
 5848            return;
 5849        }
 5850        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5851        let selections = self.selections.all::<Point>(cx);
 5852        let mut deletion_ranges = Vec::new();
 5853        let mut last_outdent = None;
 5854        {
 5855            let buffer = self.buffer.read(cx);
 5856            let snapshot = buffer.snapshot(cx);
 5857            for selection in &selections {
 5858                let settings = buffer.settings_at(selection.start, cx);
 5859                let tab_size = settings.tab_size.get();
 5860                let mut rows = selection.spanned_rows(false, &display_map);
 5861
 5862                // Avoid re-outdenting a row that has already been outdented by a
 5863                // previous selection.
 5864                if let Some(last_row) = last_outdent {
 5865                    if last_row == rows.start {
 5866                        rows.start = rows.start.next_row();
 5867                    }
 5868                }
 5869                let has_multiple_rows = rows.len() > 1;
 5870                for row in rows.iter_rows() {
 5871                    let indent_size = snapshot.indent_size_for_line(row);
 5872                    if indent_size.len > 0 {
 5873                        let deletion_len = match indent_size.kind {
 5874                            IndentKind::Space => {
 5875                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5876                                if columns_to_prev_tab_stop == 0 {
 5877                                    tab_size
 5878                                } else {
 5879                                    columns_to_prev_tab_stop
 5880                                }
 5881                            }
 5882                            IndentKind::Tab => 1,
 5883                        };
 5884                        let start = if has_multiple_rows
 5885                            || deletion_len > selection.start.column
 5886                            || indent_size.len < selection.start.column
 5887                        {
 5888                            0
 5889                        } else {
 5890                            selection.start.column - deletion_len
 5891                        };
 5892                        deletion_ranges.push(
 5893                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5894                        );
 5895                        last_outdent = Some(row);
 5896                    }
 5897                }
 5898            }
 5899        }
 5900
 5901        self.transact(cx, |this, cx| {
 5902            this.buffer.update(cx, |buffer, cx| {
 5903                let empty_str: Arc<str> = Arc::default();
 5904                buffer.edit(
 5905                    deletion_ranges
 5906                        .into_iter()
 5907                        .map(|range| (range, empty_str.clone())),
 5908                    None,
 5909                    cx,
 5910                );
 5911            });
 5912            let selections = this.selections.all::<usize>(cx);
 5913            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5914        });
 5915    }
 5916
 5917    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5918        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5919        let selections = self.selections.all::<Point>(cx);
 5920
 5921        let mut new_cursors = Vec::new();
 5922        let mut edit_ranges = Vec::new();
 5923        let mut selections = selections.iter().peekable();
 5924        while let Some(selection) = selections.next() {
 5925            let mut rows = selection.spanned_rows(false, &display_map);
 5926            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5927
 5928            // Accumulate contiguous regions of rows that we want to delete.
 5929            while let Some(next_selection) = selections.peek() {
 5930                let next_rows = next_selection.spanned_rows(false, &display_map);
 5931                if next_rows.start <= rows.end {
 5932                    rows.end = next_rows.end;
 5933                    selections.next().unwrap();
 5934                } else {
 5935                    break;
 5936                }
 5937            }
 5938
 5939            let buffer = &display_map.buffer_snapshot;
 5940            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5941            let edit_end;
 5942            let cursor_buffer_row;
 5943            if buffer.max_point().row >= rows.end.0 {
 5944                // If there's a line after the range, delete the \n from the end of the row range
 5945                // and position the cursor on the next line.
 5946                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5947                cursor_buffer_row = rows.end;
 5948            } else {
 5949                // If there isn't a line after the range, delete the \n from the line before the
 5950                // start of the row range and position the cursor there.
 5951                edit_start = edit_start.saturating_sub(1);
 5952                edit_end = buffer.len();
 5953                cursor_buffer_row = rows.start.previous_row();
 5954            }
 5955
 5956            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5957            *cursor.column_mut() =
 5958                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5959
 5960            new_cursors.push((
 5961                selection.id,
 5962                buffer.anchor_after(cursor.to_point(&display_map)),
 5963            ));
 5964            edit_ranges.push(edit_start..edit_end);
 5965        }
 5966
 5967        self.transact(cx, |this, cx| {
 5968            let buffer = this.buffer.update(cx, |buffer, cx| {
 5969                let empty_str: Arc<str> = Arc::default();
 5970                buffer.edit(
 5971                    edit_ranges
 5972                        .into_iter()
 5973                        .map(|range| (range, empty_str.clone())),
 5974                    None,
 5975                    cx,
 5976                );
 5977                buffer.snapshot(cx)
 5978            });
 5979            let new_selections = new_cursors
 5980                .into_iter()
 5981                .map(|(id, cursor)| {
 5982                    let cursor = cursor.to_point(&buffer);
 5983                    Selection {
 5984                        id,
 5985                        start: cursor,
 5986                        end: cursor,
 5987                        reversed: false,
 5988                        goal: SelectionGoal::None,
 5989                    }
 5990                })
 5991                .collect();
 5992
 5993            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5994                s.select(new_selections);
 5995            });
 5996        });
 5997    }
 5998
 5999    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6000        if self.read_only(cx) {
 6001            return;
 6002        }
 6003        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6004        for selection in self.selections.all::<Point>(cx) {
 6005            let start = MultiBufferRow(selection.start.row);
 6006            let end = if selection.start.row == selection.end.row {
 6007                MultiBufferRow(selection.start.row + 1)
 6008            } else {
 6009                MultiBufferRow(selection.end.row)
 6010            };
 6011
 6012            if let Some(last_row_range) = row_ranges.last_mut() {
 6013                if start <= last_row_range.end {
 6014                    last_row_range.end = end;
 6015                    continue;
 6016                }
 6017            }
 6018            row_ranges.push(start..end);
 6019        }
 6020
 6021        let snapshot = self.buffer.read(cx).snapshot(cx);
 6022        let mut cursor_positions = Vec::new();
 6023        for row_range in &row_ranges {
 6024            let anchor = snapshot.anchor_before(Point::new(
 6025                row_range.end.previous_row().0,
 6026                snapshot.line_len(row_range.end.previous_row()),
 6027            ));
 6028            cursor_positions.push(anchor..anchor);
 6029        }
 6030
 6031        self.transact(cx, |this, cx| {
 6032            for row_range in row_ranges.into_iter().rev() {
 6033                for row in row_range.iter_rows().rev() {
 6034                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6035                    let next_line_row = row.next_row();
 6036                    let indent = snapshot.indent_size_for_line(next_line_row);
 6037                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6038
 6039                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6040                        " "
 6041                    } else {
 6042                        ""
 6043                    };
 6044
 6045                    this.buffer.update(cx, |buffer, cx| {
 6046                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6047                    });
 6048                }
 6049            }
 6050
 6051            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6052                s.select_anchor_ranges(cursor_positions)
 6053            });
 6054        });
 6055    }
 6056
 6057    pub fn sort_lines_case_sensitive(
 6058        &mut self,
 6059        _: &SortLinesCaseSensitive,
 6060        cx: &mut ViewContext<Self>,
 6061    ) {
 6062        self.manipulate_lines(cx, |lines| lines.sort())
 6063    }
 6064
 6065    pub fn sort_lines_case_insensitive(
 6066        &mut self,
 6067        _: &SortLinesCaseInsensitive,
 6068        cx: &mut ViewContext<Self>,
 6069    ) {
 6070        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6071    }
 6072
 6073    pub fn unique_lines_case_insensitive(
 6074        &mut self,
 6075        _: &UniqueLinesCaseInsensitive,
 6076        cx: &mut ViewContext<Self>,
 6077    ) {
 6078        self.manipulate_lines(cx, |lines| {
 6079            let mut seen = HashSet::default();
 6080            lines.retain(|line| seen.insert(line.to_lowercase()));
 6081        })
 6082    }
 6083
 6084    pub fn unique_lines_case_sensitive(
 6085        &mut self,
 6086        _: &UniqueLinesCaseSensitive,
 6087        cx: &mut ViewContext<Self>,
 6088    ) {
 6089        self.manipulate_lines(cx, |lines| {
 6090            let mut seen = HashSet::default();
 6091            lines.retain(|line| seen.insert(*line));
 6092        })
 6093    }
 6094
 6095    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6096        let mut revert_changes = HashMap::default();
 6097        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6098        for hunk in hunks_for_rows(
 6099            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6100            &multi_buffer_snapshot,
 6101        ) {
 6102            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6103        }
 6104        if !revert_changes.is_empty() {
 6105            self.transact(cx, |editor, cx| {
 6106                editor.revert(revert_changes, cx);
 6107            });
 6108        }
 6109    }
 6110
 6111    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6112        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6113        if !revert_changes.is_empty() {
 6114            self.transact(cx, |editor, cx| {
 6115                editor.revert(revert_changes, cx);
 6116            });
 6117        }
 6118    }
 6119
 6120    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6121        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6122            let project_path = buffer.read(cx).project_path(cx)?;
 6123            let project = self.project.as_ref()?.read(cx);
 6124            let entry = project.entry_for_path(&project_path, cx)?;
 6125            let abs_path = project.absolute_path(&project_path, cx)?;
 6126            let parent = if entry.is_symlink {
 6127                abs_path.canonicalize().ok()?
 6128            } else {
 6129                abs_path
 6130            }
 6131            .parent()?
 6132            .to_path_buf();
 6133            Some(parent)
 6134        }) {
 6135            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6136        }
 6137    }
 6138
 6139    fn gather_revert_changes(
 6140        &mut self,
 6141        selections: &[Selection<Anchor>],
 6142        cx: &mut ViewContext<'_, Editor>,
 6143    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6144        let mut revert_changes = HashMap::default();
 6145        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6146        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6147            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6148        }
 6149        revert_changes
 6150    }
 6151
 6152    pub fn prepare_revert_change(
 6153        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6154        multi_buffer: &Model<MultiBuffer>,
 6155        hunk: &DiffHunk<MultiBufferRow>,
 6156        cx: &AppContext,
 6157    ) -> Option<()> {
 6158        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6159        let buffer = buffer.read(cx);
 6160        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6161        let buffer_snapshot = buffer.snapshot();
 6162        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6163        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6164            probe
 6165                .0
 6166                .start
 6167                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6168                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6169        }) {
 6170            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6171            Some(())
 6172        } else {
 6173            None
 6174        }
 6175    }
 6176
 6177    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6178        self.manipulate_lines(cx, |lines| lines.reverse())
 6179    }
 6180
 6181    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6182        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6183    }
 6184
 6185    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6186    where
 6187        Fn: FnMut(&mut Vec<&str>),
 6188    {
 6189        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6190        let buffer = self.buffer.read(cx).snapshot(cx);
 6191
 6192        let mut edits = Vec::new();
 6193
 6194        let selections = self.selections.all::<Point>(cx);
 6195        let mut selections = selections.iter().peekable();
 6196        let mut contiguous_row_selections = Vec::new();
 6197        let mut new_selections = Vec::new();
 6198        let mut added_lines = 0;
 6199        let mut removed_lines = 0;
 6200
 6201        while let Some(selection) = selections.next() {
 6202            let (start_row, end_row) = consume_contiguous_rows(
 6203                &mut contiguous_row_selections,
 6204                selection,
 6205                &display_map,
 6206                &mut selections,
 6207            );
 6208
 6209            let start_point = Point::new(start_row.0, 0);
 6210            let end_point = Point::new(
 6211                end_row.previous_row().0,
 6212                buffer.line_len(end_row.previous_row()),
 6213            );
 6214            let text = buffer
 6215                .text_for_range(start_point..end_point)
 6216                .collect::<String>();
 6217
 6218            let mut lines = text.split('\n').collect_vec();
 6219
 6220            let lines_before = lines.len();
 6221            callback(&mut lines);
 6222            let lines_after = lines.len();
 6223
 6224            edits.push((start_point..end_point, lines.join("\n")));
 6225
 6226            // Selections must change based on added and removed line count
 6227            let start_row =
 6228                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6229            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6230            new_selections.push(Selection {
 6231                id: selection.id,
 6232                start: start_row,
 6233                end: end_row,
 6234                goal: SelectionGoal::None,
 6235                reversed: selection.reversed,
 6236            });
 6237
 6238            if lines_after > lines_before {
 6239                added_lines += lines_after - lines_before;
 6240            } else if lines_before > lines_after {
 6241                removed_lines += lines_before - lines_after;
 6242            }
 6243        }
 6244
 6245        self.transact(cx, |this, cx| {
 6246            let buffer = this.buffer.update(cx, |buffer, cx| {
 6247                buffer.edit(edits, None, cx);
 6248                buffer.snapshot(cx)
 6249            });
 6250
 6251            // Recalculate offsets on newly edited buffer
 6252            let new_selections = new_selections
 6253                .iter()
 6254                .map(|s| {
 6255                    let start_point = Point::new(s.start.0, 0);
 6256                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6257                    Selection {
 6258                        id: s.id,
 6259                        start: buffer.point_to_offset(start_point),
 6260                        end: buffer.point_to_offset(end_point),
 6261                        goal: s.goal,
 6262                        reversed: s.reversed,
 6263                    }
 6264                })
 6265                .collect();
 6266
 6267            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6268                s.select(new_selections);
 6269            });
 6270
 6271            this.request_autoscroll(Autoscroll::fit(), cx);
 6272        });
 6273    }
 6274
 6275    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6276        self.manipulate_text(cx, |text| text.to_uppercase())
 6277    }
 6278
 6279    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6280        self.manipulate_text(cx, |text| text.to_lowercase())
 6281    }
 6282
 6283    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6284        self.manipulate_text(cx, |text| {
 6285            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6286            // https://github.com/rutrum/convert-case/issues/16
 6287            text.split('\n')
 6288                .map(|line| line.to_case(Case::Title))
 6289                .join("\n")
 6290        })
 6291    }
 6292
 6293    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6294        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6295    }
 6296
 6297    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6298        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6299    }
 6300
 6301    pub fn convert_to_upper_camel_case(
 6302        &mut self,
 6303        _: &ConvertToUpperCamelCase,
 6304        cx: &mut ViewContext<Self>,
 6305    ) {
 6306        self.manipulate_text(cx, |text| {
 6307            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6308            // https://github.com/rutrum/convert-case/issues/16
 6309            text.split('\n')
 6310                .map(|line| line.to_case(Case::UpperCamel))
 6311                .join("\n")
 6312        })
 6313    }
 6314
 6315    pub fn convert_to_lower_camel_case(
 6316        &mut self,
 6317        _: &ConvertToLowerCamelCase,
 6318        cx: &mut ViewContext<Self>,
 6319    ) {
 6320        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6321    }
 6322
 6323    pub fn convert_to_opposite_case(
 6324        &mut self,
 6325        _: &ConvertToOppositeCase,
 6326        cx: &mut ViewContext<Self>,
 6327    ) {
 6328        self.manipulate_text(cx, |text| {
 6329            text.chars()
 6330                .fold(String::with_capacity(text.len()), |mut t, c| {
 6331                    if c.is_uppercase() {
 6332                        t.extend(c.to_lowercase());
 6333                    } else {
 6334                        t.extend(c.to_uppercase());
 6335                    }
 6336                    t
 6337                })
 6338        })
 6339    }
 6340
 6341    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6342    where
 6343        Fn: FnMut(&str) -> String,
 6344    {
 6345        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6346        let buffer = self.buffer.read(cx).snapshot(cx);
 6347
 6348        let mut new_selections = Vec::new();
 6349        let mut edits = Vec::new();
 6350        let mut selection_adjustment = 0i32;
 6351
 6352        for selection in self.selections.all::<usize>(cx) {
 6353            let selection_is_empty = selection.is_empty();
 6354
 6355            let (start, end) = if selection_is_empty {
 6356                let word_range = movement::surrounding_word(
 6357                    &display_map,
 6358                    selection.start.to_display_point(&display_map),
 6359                );
 6360                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6361                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6362                (start, end)
 6363            } else {
 6364                (selection.start, selection.end)
 6365            };
 6366
 6367            let text = buffer.text_for_range(start..end).collect::<String>();
 6368            let old_length = text.len() as i32;
 6369            let text = callback(&text);
 6370
 6371            new_selections.push(Selection {
 6372                start: (start as i32 - selection_adjustment) as usize,
 6373                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6374                goal: SelectionGoal::None,
 6375                ..selection
 6376            });
 6377
 6378            selection_adjustment += old_length - text.len() as i32;
 6379
 6380            edits.push((start..end, text));
 6381        }
 6382
 6383        self.transact(cx, |this, cx| {
 6384            this.buffer.update(cx, |buffer, cx| {
 6385                buffer.edit(edits, None, cx);
 6386            });
 6387
 6388            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6389                s.select(new_selections);
 6390            });
 6391
 6392            this.request_autoscroll(Autoscroll::fit(), cx);
 6393        });
 6394    }
 6395
 6396    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6397        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6398        let buffer = &display_map.buffer_snapshot;
 6399        let selections = self.selections.all::<Point>(cx);
 6400
 6401        let mut edits = Vec::new();
 6402        let mut selections_iter = selections.iter().peekable();
 6403        while let Some(selection) = selections_iter.next() {
 6404            // Avoid duplicating the same lines twice.
 6405            let mut rows = selection.spanned_rows(false, &display_map);
 6406
 6407            while let Some(next_selection) = selections_iter.peek() {
 6408                let next_rows = next_selection.spanned_rows(false, &display_map);
 6409                if next_rows.start < rows.end {
 6410                    rows.end = next_rows.end;
 6411                    selections_iter.next().unwrap();
 6412                } else {
 6413                    break;
 6414                }
 6415            }
 6416
 6417            // Copy the text from the selected row region and splice it either at the start
 6418            // or end of the region.
 6419            let start = Point::new(rows.start.0, 0);
 6420            let end = Point::new(
 6421                rows.end.previous_row().0,
 6422                buffer.line_len(rows.end.previous_row()),
 6423            );
 6424            let text = buffer
 6425                .text_for_range(start..end)
 6426                .chain(Some("\n"))
 6427                .collect::<String>();
 6428            let insert_location = if upwards {
 6429                Point::new(rows.end.0, 0)
 6430            } else {
 6431                start
 6432            };
 6433            edits.push((insert_location..insert_location, text));
 6434        }
 6435
 6436        self.transact(cx, |this, cx| {
 6437            this.buffer.update(cx, |buffer, cx| {
 6438                buffer.edit(edits, None, cx);
 6439            });
 6440
 6441            this.request_autoscroll(Autoscroll::fit(), cx);
 6442        });
 6443    }
 6444
 6445    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6446        self.duplicate_line(true, cx);
 6447    }
 6448
 6449    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6450        self.duplicate_line(false, cx);
 6451    }
 6452
 6453    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6454        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6455        let buffer = self.buffer.read(cx).snapshot(cx);
 6456
 6457        let mut edits = Vec::new();
 6458        let mut unfold_ranges = Vec::new();
 6459        let mut refold_ranges = Vec::new();
 6460
 6461        let selections = self.selections.all::<Point>(cx);
 6462        let mut selections = selections.iter().peekable();
 6463        let mut contiguous_row_selections = Vec::new();
 6464        let mut new_selections = Vec::new();
 6465
 6466        while let Some(selection) = selections.next() {
 6467            // Find all the selections that span a contiguous row range
 6468            let (start_row, end_row) = consume_contiguous_rows(
 6469                &mut contiguous_row_selections,
 6470                selection,
 6471                &display_map,
 6472                &mut selections,
 6473            );
 6474
 6475            // Move the text spanned by the row range to be before the line preceding the row range
 6476            if start_row.0 > 0 {
 6477                let range_to_move = Point::new(
 6478                    start_row.previous_row().0,
 6479                    buffer.line_len(start_row.previous_row()),
 6480                )
 6481                    ..Point::new(
 6482                        end_row.previous_row().0,
 6483                        buffer.line_len(end_row.previous_row()),
 6484                    );
 6485                let insertion_point = display_map
 6486                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6487                    .0;
 6488
 6489                // Don't move lines across excerpts
 6490                if buffer
 6491                    .excerpt_boundaries_in_range((
 6492                        Bound::Excluded(insertion_point),
 6493                        Bound::Included(range_to_move.end),
 6494                    ))
 6495                    .next()
 6496                    .is_none()
 6497                {
 6498                    let text = buffer
 6499                        .text_for_range(range_to_move.clone())
 6500                        .flat_map(|s| s.chars())
 6501                        .skip(1)
 6502                        .chain(['\n'])
 6503                        .collect::<String>();
 6504
 6505                    edits.push((
 6506                        buffer.anchor_after(range_to_move.start)
 6507                            ..buffer.anchor_before(range_to_move.end),
 6508                        String::new(),
 6509                    ));
 6510                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6511                    edits.push((insertion_anchor..insertion_anchor, text));
 6512
 6513                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6514
 6515                    // Move selections up
 6516                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6517                        |mut selection| {
 6518                            selection.start.row -= row_delta;
 6519                            selection.end.row -= row_delta;
 6520                            selection
 6521                        },
 6522                    ));
 6523
 6524                    // Move folds up
 6525                    unfold_ranges.push(range_to_move.clone());
 6526                    for fold in display_map.folds_in_range(
 6527                        buffer.anchor_before(range_to_move.start)
 6528                            ..buffer.anchor_after(range_to_move.end),
 6529                    ) {
 6530                        let mut start = fold.range.start.to_point(&buffer);
 6531                        let mut end = fold.range.end.to_point(&buffer);
 6532                        start.row -= row_delta;
 6533                        end.row -= row_delta;
 6534                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6535                    }
 6536                }
 6537            }
 6538
 6539            // If we didn't move line(s), preserve the existing selections
 6540            new_selections.append(&mut contiguous_row_selections);
 6541        }
 6542
 6543        self.transact(cx, |this, cx| {
 6544            this.unfold_ranges(unfold_ranges, true, true, cx);
 6545            this.buffer.update(cx, |buffer, cx| {
 6546                for (range, text) in edits {
 6547                    buffer.edit([(range, text)], None, cx);
 6548                }
 6549            });
 6550            this.fold_ranges(refold_ranges, true, cx);
 6551            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6552                s.select(new_selections);
 6553            })
 6554        });
 6555    }
 6556
 6557    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6558        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6559        let buffer = self.buffer.read(cx).snapshot(cx);
 6560
 6561        let mut edits = Vec::new();
 6562        let mut unfold_ranges = Vec::new();
 6563        let mut refold_ranges = Vec::new();
 6564
 6565        let selections = self.selections.all::<Point>(cx);
 6566        let mut selections = selections.iter().peekable();
 6567        let mut contiguous_row_selections = Vec::new();
 6568        let mut new_selections = Vec::new();
 6569
 6570        while let Some(selection) = selections.next() {
 6571            // Find all the selections that span a contiguous row range
 6572            let (start_row, end_row) = consume_contiguous_rows(
 6573                &mut contiguous_row_selections,
 6574                selection,
 6575                &display_map,
 6576                &mut selections,
 6577            );
 6578
 6579            // Move the text spanned by the row range to be after the last line of the row range
 6580            if end_row.0 <= buffer.max_point().row {
 6581                let range_to_move =
 6582                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6583                let insertion_point = display_map
 6584                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6585                    .0;
 6586
 6587                // Don't move lines across excerpt boundaries
 6588                if buffer
 6589                    .excerpt_boundaries_in_range((
 6590                        Bound::Excluded(range_to_move.start),
 6591                        Bound::Included(insertion_point),
 6592                    ))
 6593                    .next()
 6594                    .is_none()
 6595                {
 6596                    let mut text = String::from("\n");
 6597                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6598                    text.pop(); // Drop trailing newline
 6599                    edits.push((
 6600                        buffer.anchor_after(range_to_move.start)
 6601                            ..buffer.anchor_before(range_to_move.end),
 6602                        String::new(),
 6603                    ));
 6604                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6605                    edits.push((insertion_anchor..insertion_anchor, text));
 6606
 6607                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6608
 6609                    // Move selections down
 6610                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6611                        |mut selection| {
 6612                            selection.start.row += row_delta;
 6613                            selection.end.row += row_delta;
 6614                            selection
 6615                        },
 6616                    ));
 6617
 6618                    // Move folds down
 6619                    unfold_ranges.push(range_to_move.clone());
 6620                    for fold in display_map.folds_in_range(
 6621                        buffer.anchor_before(range_to_move.start)
 6622                            ..buffer.anchor_after(range_to_move.end),
 6623                    ) {
 6624                        let mut start = fold.range.start.to_point(&buffer);
 6625                        let mut end = fold.range.end.to_point(&buffer);
 6626                        start.row += row_delta;
 6627                        end.row += row_delta;
 6628                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6629                    }
 6630                }
 6631            }
 6632
 6633            // If we didn't move line(s), preserve the existing selections
 6634            new_selections.append(&mut contiguous_row_selections);
 6635        }
 6636
 6637        self.transact(cx, |this, cx| {
 6638            this.unfold_ranges(unfold_ranges, true, true, cx);
 6639            this.buffer.update(cx, |buffer, cx| {
 6640                for (range, text) in edits {
 6641                    buffer.edit([(range, text)], None, cx);
 6642                }
 6643            });
 6644            this.fold_ranges(refold_ranges, true, cx);
 6645            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6646        });
 6647    }
 6648
 6649    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6650        let text_layout_details = &self.text_layout_details(cx);
 6651        self.transact(cx, |this, cx| {
 6652            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6653                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6654                let line_mode = s.line_mode;
 6655                s.move_with(|display_map, selection| {
 6656                    if !selection.is_empty() || line_mode {
 6657                        return;
 6658                    }
 6659
 6660                    let mut head = selection.head();
 6661                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6662                    if head.column() == display_map.line_len(head.row()) {
 6663                        transpose_offset = display_map
 6664                            .buffer_snapshot
 6665                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6666                    }
 6667
 6668                    if transpose_offset == 0 {
 6669                        return;
 6670                    }
 6671
 6672                    *head.column_mut() += 1;
 6673                    head = display_map.clip_point(head, Bias::Right);
 6674                    let goal = SelectionGoal::HorizontalPosition(
 6675                        display_map
 6676                            .x_for_display_point(head, text_layout_details)
 6677                            .into(),
 6678                    );
 6679                    selection.collapse_to(head, goal);
 6680
 6681                    let transpose_start = display_map
 6682                        .buffer_snapshot
 6683                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6684                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6685                        let transpose_end = display_map
 6686                            .buffer_snapshot
 6687                            .clip_offset(transpose_offset + 1, Bias::Right);
 6688                        if let Some(ch) =
 6689                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6690                        {
 6691                            edits.push((transpose_start..transpose_offset, String::new()));
 6692                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6693                        }
 6694                    }
 6695                });
 6696                edits
 6697            });
 6698            this.buffer
 6699                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6700            let selections = this.selections.all::<usize>(cx);
 6701            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6702                s.select(selections);
 6703            });
 6704        });
 6705    }
 6706
 6707    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6708        let buffer = self.buffer.read(cx).snapshot(cx);
 6709        let selections = self.selections.all::<Point>(cx);
 6710        let mut selections = selections.iter().peekable();
 6711
 6712        let mut edits = Vec::new();
 6713        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6714
 6715        while let Some(selection) = selections.next() {
 6716            let mut start_row = selection.start.row;
 6717            let mut end_row = selection.end.row;
 6718
 6719            // Skip selections that overlap with a range that has already been rewrapped.
 6720            let selection_range = start_row..end_row;
 6721            if rewrapped_row_ranges
 6722                .iter()
 6723                .any(|range| range.overlaps(&selection_range))
 6724            {
 6725                continue;
 6726            }
 6727
 6728            let mut should_rewrap = false;
 6729
 6730            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6731                match language_scope.language_name().0.as_ref() {
 6732                    "Markdown" | "Plain Text" => {
 6733                        should_rewrap = true;
 6734                    }
 6735                    _ => {}
 6736                }
 6737            }
 6738
 6739            let row = selection.head().row;
 6740            let indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
 6741            let indent_end = Point::new(row, indent_size.len);
 6742
 6743            let mut line_prefix = indent_size.chars().collect::<String>();
 6744
 6745            if let Some(comment_prefix) =
 6746                buffer
 6747                    .language_scope_at(selection.head())
 6748                    .and_then(|language| {
 6749                        language
 6750                            .line_comment_prefixes()
 6751                            .iter()
 6752                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6753                            .cloned()
 6754                    })
 6755            {
 6756                line_prefix.push_str(&comment_prefix);
 6757                should_rewrap = true;
 6758            }
 6759
 6760            if selection.is_empty() {
 6761                'expand_upwards: while start_row > 0 {
 6762                    let prev_row = start_row - 1;
 6763                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6764                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6765                    {
 6766                        start_row = prev_row;
 6767                    } else {
 6768                        break 'expand_upwards;
 6769                    }
 6770                }
 6771
 6772                'expand_downwards: while end_row < buffer.max_point().row {
 6773                    let next_row = end_row + 1;
 6774                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6775                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6776                    {
 6777                        end_row = next_row;
 6778                    } else {
 6779                        break 'expand_downwards;
 6780                    }
 6781                }
 6782            }
 6783
 6784            if !should_rewrap {
 6785                continue;
 6786            }
 6787
 6788            let start = Point::new(start_row, 0);
 6789            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6790            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6791            let unwrapped_text = selection_text
 6792                .lines()
 6793                .map(|line| line.strip_prefix(&line_prefix).unwrap())
 6794                .join(" ");
 6795            let wrap_column = buffer
 6796                .settings_at(Point::new(start_row, 0), cx)
 6797                .preferred_line_length as usize;
 6798            let mut wrapped_text = String::new();
 6799            let mut current_line = line_prefix.clone();
 6800            for word in unwrapped_text.split_whitespace() {
 6801                if current_line.len() + word.len() >= wrap_column {
 6802                    wrapped_text.push_str(&current_line);
 6803                    wrapped_text.push('\n');
 6804                    current_line.truncate(line_prefix.len());
 6805                }
 6806
 6807                if current_line.len() > line_prefix.len() {
 6808                    current_line.push(' ');
 6809                }
 6810
 6811                current_line.push_str(word);
 6812            }
 6813
 6814            if !current_line.is_empty() {
 6815                wrapped_text.push_str(&current_line);
 6816            }
 6817
 6818            let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
 6819            let mut offset = start.to_offset(&buffer);
 6820            let mut moved_since_edit = true;
 6821
 6822            for change in diff.iter_all_changes() {
 6823                let value = change.value();
 6824                match change.tag() {
 6825                    ChangeTag::Equal => {
 6826                        offset += value.len();
 6827                        moved_since_edit = true;
 6828                    }
 6829                    ChangeTag::Delete => {
 6830                        let start = buffer.anchor_after(offset);
 6831                        let end = buffer.anchor_before(offset + value.len());
 6832
 6833                        if moved_since_edit {
 6834                            edits.push((start..end, String::new()));
 6835                        } else {
 6836                            edits.last_mut().unwrap().0.end = end;
 6837                        }
 6838
 6839                        offset += value.len();
 6840                        moved_since_edit = false;
 6841                    }
 6842                    ChangeTag::Insert => {
 6843                        if moved_since_edit {
 6844                            let anchor = buffer.anchor_after(offset);
 6845                            edits.push((anchor..anchor, value.to_string()));
 6846                        } else {
 6847                            edits.last_mut().unwrap().1.push_str(value);
 6848                        }
 6849
 6850                        moved_since_edit = false;
 6851                    }
 6852                }
 6853            }
 6854
 6855            rewrapped_row_ranges.push(start_row..=end_row);
 6856        }
 6857
 6858        self.buffer
 6859            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6860    }
 6861
 6862    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6863        let mut text = String::new();
 6864        let buffer = self.buffer.read(cx).snapshot(cx);
 6865        let mut selections = self.selections.all::<Point>(cx);
 6866        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6867        {
 6868            let max_point = buffer.max_point();
 6869            let mut is_first = true;
 6870            for selection in &mut selections {
 6871                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6872                if is_entire_line {
 6873                    selection.start = Point::new(selection.start.row, 0);
 6874                    if !selection.is_empty() && selection.end.column == 0 {
 6875                        selection.end = cmp::min(max_point, selection.end);
 6876                    } else {
 6877                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6878                    }
 6879                    selection.goal = SelectionGoal::None;
 6880                }
 6881                if is_first {
 6882                    is_first = false;
 6883                } else {
 6884                    text += "\n";
 6885                }
 6886                let mut len = 0;
 6887                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6888                    text.push_str(chunk);
 6889                    len += chunk.len();
 6890                }
 6891                clipboard_selections.push(ClipboardSelection {
 6892                    len,
 6893                    is_entire_line,
 6894                    first_line_indent: buffer
 6895                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6896                        .len,
 6897                });
 6898            }
 6899        }
 6900
 6901        self.transact(cx, |this, cx| {
 6902            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6903                s.select(selections);
 6904            });
 6905            this.insert("", cx);
 6906            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6907                text,
 6908                clipboard_selections,
 6909            ));
 6910        });
 6911    }
 6912
 6913    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6914        let selections = self.selections.all::<Point>(cx);
 6915        let buffer = self.buffer.read(cx).read(cx);
 6916        let mut text = String::new();
 6917
 6918        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6919        {
 6920            let max_point = buffer.max_point();
 6921            let mut is_first = true;
 6922            for selection in selections.iter() {
 6923                let mut start = selection.start;
 6924                let mut end = selection.end;
 6925                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6926                if is_entire_line {
 6927                    start = Point::new(start.row, 0);
 6928                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6929                }
 6930                if is_first {
 6931                    is_first = false;
 6932                } else {
 6933                    text += "\n";
 6934                }
 6935                let mut len = 0;
 6936                for chunk in buffer.text_for_range(start..end) {
 6937                    text.push_str(chunk);
 6938                    len += chunk.len();
 6939                }
 6940                clipboard_selections.push(ClipboardSelection {
 6941                    len,
 6942                    is_entire_line,
 6943                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6944                });
 6945            }
 6946        }
 6947
 6948        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6949            text,
 6950            clipboard_selections,
 6951        ));
 6952    }
 6953
 6954    pub fn do_paste(
 6955        &mut self,
 6956        text: &String,
 6957        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6958        handle_entire_lines: bool,
 6959        cx: &mut ViewContext<Self>,
 6960    ) {
 6961        if self.read_only(cx) {
 6962            return;
 6963        }
 6964
 6965        let clipboard_text = Cow::Borrowed(text);
 6966
 6967        self.transact(cx, |this, cx| {
 6968            if let Some(mut clipboard_selections) = clipboard_selections {
 6969                let old_selections = this.selections.all::<usize>(cx);
 6970                let all_selections_were_entire_line =
 6971                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6972                let first_selection_indent_column =
 6973                    clipboard_selections.first().map(|s| s.first_line_indent);
 6974                if clipboard_selections.len() != old_selections.len() {
 6975                    clipboard_selections.drain(..);
 6976                }
 6977
 6978                this.buffer.update(cx, |buffer, cx| {
 6979                    let snapshot = buffer.read(cx);
 6980                    let mut start_offset = 0;
 6981                    let mut edits = Vec::new();
 6982                    let mut original_indent_columns = Vec::new();
 6983                    for (ix, selection) in old_selections.iter().enumerate() {
 6984                        let to_insert;
 6985                        let entire_line;
 6986                        let original_indent_column;
 6987                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6988                            let end_offset = start_offset + clipboard_selection.len;
 6989                            to_insert = &clipboard_text[start_offset..end_offset];
 6990                            entire_line = clipboard_selection.is_entire_line;
 6991                            start_offset = end_offset + 1;
 6992                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6993                        } else {
 6994                            to_insert = clipboard_text.as_str();
 6995                            entire_line = all_selections_were_entire_line;
 6996                            original_indent_column = first_selection_indent_column
 6997                        }
 6998
 6999                        // If the corresponding selection was empty when this slice of the
 7000                        // clipboard text was written, then the entire line containing the
 7001                        // selection was copied. If this selection is also currently empty,
 7002                        // then paste the line before the current line of the buffer.
 7003                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7004                            let column = selection.start.to_point(&snapshot).column as usize;
 7005                            let line_start = selection.start - column;
 7006                            line_start..line_start
 7007                        } else {
 7008                            selection.range()
 7009                        };
 7010
 7011                        edits.push((range, to_insert));
 7012                        original_indent_columns.extend(original_indent_column);
 7013                    }
 7014                    drop(snapshot);
 7015
 7016                    buffer.edit(
 7017                        edits,
 7018                        Some(AutoindentMode::Block {
 7019                            original_indent_columns,
 7020                        }),
 7021                        cx,
 7022                    );
 7023                });
 7024
 7025                let selections = this.selections.all::<usize>(cx);
 7026                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7027            } else {
 7028                this.insert(&clipboard_text, cx);
 7029            }
 7030        });
 7031    }
 7032
 7033    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7034        if let Some(item) = cx.read_from_clipboard() {
 7035            let entries = item.entries();
 7036
 7037            match entries.first() {
 7038                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7039                // of all the pasted entries.
 7040                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7041                    .do_paste(
 7042                        clipboard_string.text(),
 7043                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7044                        true,
 7045                        cx,
 7046                    ),
 7047                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7048            }
 7049        }
 7050    }
 7051
 7052    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7053        if self.read_only(cx) {
 7054            return;
 7055        }
 7056
 7057        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7058            if let Some((selections, _)) =
 7059                self.selection_history.transaction(transaction_id).cloned()
 7060            {
 7061                self.change_selections(None, cx, |s| {
 7062                    s.select_anchors(selections.to_vec());
 7063                });
 7064            }
 7065            self.request_autoscroll(Autoscroll::fit(), cx);
 7066            self.unmark_text(cx);
 7067            self.refresh_inline_completion(true, false, cx);
 7068            cx.emit(EditorEvent::Edited { transaction_id });
 7069            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7070        }
 7071    }
 7072
 7073    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7074        if self.read_only(cx) {
 7075            return;
 7076        }
 7077
 7078        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7079            if let Some((_, Some(selections))) =
 7080                self.selection_history.transaction(transaction_id).cloned()
 7081            {
 7082                self.change_selections(None, cx, |s| {
 7083                    s.select_anchors(selections.to_vec());
 7084                });
 7085            }
 7086            self.request_autoscroll(Autoscroll::fit(), cx);
 7087            self.unmark_text(cx);
 7088            self.refresh_inline_completion(true, false, cx);
 7089            cx.emit(EditorEvent::Edited { transaction_id });
 7090        }
 7091    }
 7092
 7093    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7094        self.buffer
 7095            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7096    }
 7097
 7098    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7099        self.buffer
 7100            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7101    }
 7102
 7103    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7104        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7105            let line_mode = s.line_mode;
 7106            s.move_with(|map, selection| {
 7107                let cursor = if selection.is_empty() && !line_mode {
 7108                    movement::left(map, selection.start)
 7109                } else {
 7110                    selection.start
 7111                };
 7112                selection.collapse_to(cursor, SelectionGoal::None);
 7113            });
 7114        })
 7115    }
 7116
 7117    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7118        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7119            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7120        })
 7121    }
 7122
 7123    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7124        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7125            let line_mode = s.line_mode;
 7126            s.move_with(|map, selection| {
 7127                let cursor = if selection.is_empty() && !line_mode {
 7128                    movement::right(map, selection.end)
 7129                } else {
 7130                    selection.end
 7131                };
 7132                selection.collapse_to(cursor, SelectionGoal::None)
 7133            });
 7134        })
 7135    }
 7136
 7137    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7138        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7139            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7140        })
 7141    }
 7142
 7143    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7144        if self.take_rename(true, cx).is_some() {
 7145            return;
 7146        }
 7147
 7148        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7149            cx.propagate();
 7150            return;
 7151        }
 7152
 7153        let text_layout_details = &self.text_layout_details(cx);
 7154        let selection_count = self.selections.count();
 7155        let first_selection = self.selections.first_anchor();
 7156
 7157        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7158            let line_mode = s.line_mode;
 7159            s.move_with(|map, selection| {
 7160                if !selection.is_empty() && !line_mode {
 7161                    selection.goal = SelectionGoal::None;
 7162                }
 7163                let (cursor, goal) = movement::up(
 7164                    map,
 7165                    selection.start,
 7166                    selection.goal,
 7167                    false,
 7168                    text_layout_details,
 7169                );
 7170                selection.collapse_to(cursor, goal);
 7171            });
 7172        });
 7173
 7174        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7175        {
 7176            cx.propagate();
 7177        }
 7178    }
 7179
 7180    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7181        if self.take_rename(true, cx).is_some() {
 7182            return;
 7183        }
 7184
 7185        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7186            cx.propagate();
 7187            return;
 7188        }
 7189
 7190        let text_layout_details = &self.text_layout_details(cx);
 7191
 7192        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7193            let line_mode = s.line_mode;
 7194            s.move_with(|map, selection| {
 7195                if !selection.is_empty() && !line_mode {
 7196                    selection.goal = SelectionGoal::None;
 7197                }
 7198                let (cursor, goal) = movement::up_by_rows(
 7199                    map,
 7200                    selection.start,
 7201                    action.lines,
 7202                    selection.goal,
 7203                    false,
 7204                    text_layout_details,
 7205                );
 7206                selection.collapse_to(cursor, goal);
 7207            });
 7208        })
 7209    }
 7210
 7211    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7212        if self.take_rename(true, cx).is_some() {
 7213            return;
 7214        }
 7215
 7216        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7217            cx.propagate();
 7218            return;
 7219        }
 7220
 7221        let text_layout_details = &self.text_layout_details(cx);
 7222
 7223        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7224            let line_mode = s.line_mode;
 7225            s.move_with(|map, selection| {
 7226                if !selection.is_empty() && !line_mode {
 7227                    selection.goal = SelectionGoal::None;
 7228                }
 7229                let (cursor, goal) = movement::down_by_rows(
 7230                    map,
 7231                    selection.start,
 7232                    action.lines,
 7233                    selection.goal,
 7234                    false,
 7235                    text_layout_details,
 7236                );
 7237                selection.collapse_to(cursor, goal);
 7238            });
 7239        })
 7240    }
 7241
 7242    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7243        let text_layout_details = &self.text_layout_details(cx);
 7244        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7245            s.move_heads_with(|map, head, goal| {
 7246                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7247            })
 7248        })
 7249    }
 7250
 7251    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7252        let text_layout_details = &self.text_layout_details(cx);
 7253        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7254            s.move_heads_with(|map, head, goal| {
 7255                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7256            })
 7257        })
 7258    }
 7259
 7260    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7261        let Some(row_count) = self.visible_row_count() else {
 7262            return;
 7263        };
 7264
 7265        let text_layout_details = &self.text_layout_details(cx);
 7266
 7267        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7268            s.move_heads_with(|map, head, goal| {
 7269                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7270            })
 7271        })
 7272    }
 7273
 7274    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7275        if self.take_rename(true, cx).is_some() {
 7276            return;
 7277        }
 7278
 7279        if self
 7280            .context_menu
 7281            .write()
 7282            .as_mut()
 7283            .map(|menu| menu.select_first(self.project.as_ref(), cx))
 7284            .unwrap_or(false)
 7285        {
 7286            return;
 7287        }
 7288
 7289        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7290            cx.propagate();
 7291            return;
 7292        }
 7293
 7294        let Some(row_count) = self.visible_row_count() else {
 7295            return;
 7296        };
 7297
 7298        let autoscroll = if action.center_cursor {
 7299            Autoscroll::center()
 7300        } else {
 7301            Autoscroll::fit()
 7302        };
 7303
 7304        let text_layout_details = &self.text_layout_details(cx);
 7305
 7306        self.change_selections(Some(autoscroll), cx, |s| {
 7307            let line_mode = s.line_mode;
 7308            s.move_with(|map, selection| {
 7309                if !selection.is_empty() && !line_mode {
 7310                    selection.goal = SelectionGoal::None;
 7311                }
 7312                let (cursor, goal) = movement::up_by_rows(
 7313                    map,
 7314                    selection.end,
 7315                    row_count,
 7316                    selection.goal,
 7317                    false,
 7318                    text_layout_details,
 7319                );
 7320                selection.collapse_to(cursor, goal);
 7321            });
 7322        });
 7323    }
 7324
 7325    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7326        let text_layout_details = &self.text_layout_details(cx);
 7327        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7328            s.move_heads_with(|map, head, goal| {
 7329                movement::up(map, head, goal, false, text_layout_details)
 7330            })
 7331        })
 7332    }
 7333
 7334    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7335        self.take_rename(true, cx);
 7336
 7337        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7338            cx.propagate();
 7339            return;
 7340        }
 7341
 7342        let text_layout_details = &self.text_layout_details(cx);
 7343        let selection_count = self.selections.count();
 7344        let first_selection = self.selections.first_anchor();
 7345
 7346        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7347            let line_mode = s.line_mode;
 7348            s.move_with(|map, selection| {
 7349                if !selection.is_empty() && !line_mode {
 7350                    selection.goal = SelectionGoal::None;
 7351                }
 7352                let (cursor, goal) = movement::down(
 7353                    map,
 7354                    selection.end,
 7355                    selection.goal,
 7356                    false,
 7357                    text_layout_details,
 7358                );
 7359                selection.collapse_to(cursor, goal);
 7360            });
 7361        });
 7362
 7363        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7364        {
 7365            cx.propagate();
 7366        }
 7367    }
 7368
 7369    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7370        let Some(row_count) = self.visible_row_count() else {
 7371            return;
 7372        };
 7373
 7374        let text_layout_details = &self.text_layout_details(cx);
 7375
 7376        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7377            s.move_heads_with(|map, head, goal| {
 7378                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7379            })
 7380        })
 7381    }
 7382
 7383    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7384        if self.take_rename(true, cx).is_some() {
 7385            return;
 7386        }
 7387
 7388        if self
 7389            .context_menu
 7390            .write()
 7391            .as_mut()
 7392            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 7393            .unwrap_or(false)
 7394        {
 7395            return;
 7396        }
 7397
 7398        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7399            cx.propagate();
 7400            return;
 7401        }
 7402
 7403        let Some(row_count) = self.visible_row_count() else {
 7404            return;
 7405        };
 7406
 7407        let autoscroll = if action.center_cursor {
 7408            Autoscroll::center()
 7409        } else {
 7410            Autoscroll::fit()
 7411        };
 7412
 7413        let text_layout_details = &self.text_layout_details(cx);
 7414        self.change_selections(Some(autoscroll), cx, |s| {
 7415            let line_mode = s.line_mode;
 7416            s.move_with(|map, selection| {
 7417                if !selection.is_empty() && !line_mode {
 7418                    selection.goal = SelectionGoal::None;
 7419                }
 7420                let (cursor, goal) = movement::down_by_rows(
 7421                    map,
 7422                    selection.end,
 7423                    row_count,
 7424                    selection.goal,
 7425                    false,
 7426                    text_layout_details,
 7427                );
 7428                selection.collapse_to(cursor, goal);
 7429            });
 7430        });
 7431    }
 7432
 7433    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7434        let text_layout_details = &self.text_layout_details(cx);
 7435        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7436            s.move_heads_with(|map, head, goal| {
 7437                movement::down(map, head, goal, false, text_layout_details)
 7438            })
 7439        });
 7440    }
 7441
 7442    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7443        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7444            context_menu.select_first(self.project.as_ref(), cx);
 7445        }
 7446    }
 7447
 7448    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7449        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7450            context_menu.select_prev(self.project.as_ref(), cx);
 7451        }
 7452    }
 7453
 7454    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7455        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7456            context_menu.select_next(self.project.as_ref(), cx);
 7457        }
 7458    }
 7459
 7460    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7461        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7462            context_menu.select_last(self.project.as_ref(), cx);
 7463        }
 7464    }
 7465
 7466    pub fn move_to_previous_word_start(
 7467        &mut self,
 7468        _: &MoveToPreviousWordStart,
 7469        cx: &mut ViewContext<Self>,
 7470    ) {
 7471        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7472            s.move_cursors_with(|map, head, _| {
 7473                (
 7474                    movement::previous_word_start(map, head),
 7475                    SelectionGoal::None,
 7476                )
 7477            });
 7478        })
 7479    }
 7480
 7481    pub fn move_to_previous_subword_start(
 7482        &mut self,
 7483        _: &MoveToPreviousSubwordStart,
 7484        cx: &mut ViewContext<Self>,
 7485    ) {
 7486        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7487            s.move_cursors_with(|map, head, _| {
 7488                (
 7489                    movement::previous_subword_start(map, head),
 7490                    SelectionGoal::None,
 7491                )
 7492            });
 7493        })
 7494    }
 7495
 7496    pub fn select_to_previous_word_start(
 7497        &mut self,
 7498        _: &SelectToPreviousWordStart,
 7499        cx: &mut ViewContext<Self>,
 7500    ) {
 7501        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7502            s.move_heads_with(|map, head, _| {
 7503                (
 7504                    movement::previous_word_start(map, head),
 7505                    SelectionGoal::None,
 7506                )
 7507            });
 7508        })
 7509    }
 7510
 7511    pub fn select_to_previous_subword_start(
 7512        &mut self,
 7513        _: &SelectToPreviousSubwordStart,
 7514        cx: &mut ViewContext<Self>,
 7515    ) {
 7516        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7517            s.move_heads_with(|map, head, _| {
 7518                (
 7519                    movement::previous_subword_start(map, head),
 7520                    SelectionGoal::None,
 7521                )
 7522            });
 7523        })
 7524    }
 7525
 7526    pub fn delete_to_previous_word_start(
 7527        &mut self,
 7528        action: &DeleteToPreviousWordStart,
 7529        cx: &mut ViewContext<Self>,
 7530    ) {
 7531        self.transact(cx, |this, cx| {
 7532            this.select_autoclose_pair(cx);
 7533            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7534                let line_mode = s.line_mode;
 7535                s.move_with(|map, selection| {
 7536                    if selection.is_empty() && !line_mode {
 7537                        let cursor = if action.ignore_newlines {
 7538                            movement::previous_word_start(map, selection.head())
 7539                        } else {
 7540                            movement::previous_word_start_or_newline(map, selection.head())
 7541                        };
 7542                        selection.set_head(cursor, SelectionGoal::None);
 7543                    }
 7544                });
 7545            });
 7546            this.insert("", cx);
 7547        });
 7548    }
 7549
 7550    pub fn delete_to_previous_subword_start(
 7551        &mut self,
 7552        _: &DeleteToPreviousSubwordStart,
 7553        cx: &mut ViewContext<Self>,
 7554    ) {
 7555        self.transact(cx, |this, cx| {
 7556            this.select_autoclose_pair(cx);
 7557            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7558                let line_mode = s.line_mode;
 7559                s.move_with(|map, selection| {
 7560                    if selection.is_empty() && !line_mode {
 7561                        let cursor = movement::previous_subword_start(map, selection.head());
 7562                        selection.set_head(cursor, SelectionGoal::None);
 7563                    }
 7564                });
 7565            });
 7566            this.insert("", cx);
 7567        });
 7568    }
 7569
 7570    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7571        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7572            s.move_cursors_with(|map, head, _| {
 7573                (movement::next_word_end(map, head), SelectionGoal::None)
 7574            });
 7575        })
 7576    }
 7577
 7578    pub fn move_to_next_subword_end(
 7579        &mut self,
 7580        _: &MoveToNextSubwordEnd,
 7581        cx: &mut ViewContext<Self>,
 7582    ) {
 7583        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7584            s.move_cursors_with(|map, head, _| {
 7585                (movement::next_subword_end(map, head), SelectionGoal::None)
 7586            });
 7587        })
 7588    }
 7589
 7590    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7591        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7592            s.move_heads_with(|map, head, _| {
 7593                (movement::next_word_end(map, head), SelectionGoal::None)
 7594            });
 7595        })
 7596    }
 7597
 7598    pub fn select_to_next_subword_end(
 7599        &mut self,
 7600        _: &SelectToNextSubwordEnd,
 7601        cx: &mut ViewContext<Self>,
 7602    ) {
 7603        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7604            s.move_heads_with(|map, head, _| {
 7605                (movement::next_subword_end(map, head), SelectionGoal::None)
 7606            });
 7607        })
 7608    }
 7609
 7610    pub fn delete_to_next_word_end(
 7611        &mut self,
 7612        action: &DeleteToNextWordEnd,
 7613        cx: &mut ViewContext<Self>,
 7614    ) {
 7615        self.transact(cx, |this, cx| {
 7616            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7617                let line_mode = s.line_mode;
 7618                s.move_with(|map, selection| {
 7619                    if selection.is_empty() && !line_mode {
 7620                        let cursor = if action.ignore_newlines {
 7621                            movement::next_word_end(map, selection.head())
 7622                        } else {
 7623                            movement::next_word_end_or_newline(map, selection.head())
 7624                        };
 7625                        selection.set_head(cursor, SelectionGoal::None);
 7626                    }
 7627                });
 7628            });
 7629            this.insert("", cx);
 7630        });
 7631    }
 7632
 7633    pub fn delete_to_next_subword_end(
 7634        &mut self,
 7635        _: &DeleteToNextSubwordEnd,
 7636        cx: &mut ViewContext<Self>,
 7637    ) {
 7638        self.transact(cx, |this, cx| {
 7639            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7640                s.move_with(|map, selection| {
 7641                    if selection.is_empty() {
 7642                        let cursor = movement::next_subword_end(map, selection.head());
 7643                        selection.set_head(cursor, SelectionGoal::None);
 7644                    }
 7645                });
 7646            });
 7647            this.insert("", cx);
 7648        });
 7649    }
 7650
 7651    pub fn move_to_beginning_of_line(
 7652        &mut self,
 7653        action: &MoveToBeginningOfLine,
 7654        cx: &mut ViewContext<Self>,
 7655    ) {
 7656        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7657            s.move_cursors_with(|map, head, _| {
 7658                (
 7659                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7660                    SelectionGoal::None,
 7661                )
 7662            });
 7663        })
 7664    }
 7665
 7666    pub fn select_to_beginning_of_line(
 7667        &mut self,
 7668        action: &SelectToBeginningOfLine,
 7669        cx: &mut ViewContext<Self>,
 7670    ) {
 7671        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7672            s.move_heads_with(|map, head, _| {
 7673                (
 7674                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7675                    SelectionGoal::None,
 7676                )
 7677            });
 7678        });
 7679    }
 7680
 7681    pub fn delete_to_beginning_of_line(
 7682        &mut self,
 7683        _: &DeleteToBeginningOfLine,
 7684        cx: &mut ViewContext<Self>,
 7685    ) {
 7686        self.transact(cx, |this, cx| {
 7687            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7688                s.move_with(|_, selection| {
 7689                    selection.reversed = true;
 7690                });
 7691            });
 7692
 7693            this.select_to_beginning_of_line(
 7694                &SelectToBeginningOfLine {
 7695                    stop_at_soft_wraps: false,
 7696                },
 7697                cx,
 7698            );
 7699            this.backspace(&Backspace, cx);
 7700        });
 7701    }
 7702
 7703    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7704        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7705            s.move_cursors_with(|map, head, _| {
 7706                (
 7707                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7708                    SelectionGoal::None,
 7709                )
 7710            });
 7711        })
 7712    }
 7713
 7714    pub fn select_to_end_of_line(
 7715        &mut self,
 7716        action: &SelectToEndOfLine,
 7717        cx: &mut ViewContext<Self>,
 7718    ) {
 7719        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7720            s.move_heads_with(|map, head, _| {
 7721                (
 7722                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7723                    SelectionGoal::None,
 7724                )
 7725            });
 7726        })
 7727    }
 7728
 7729    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7730        self.transact(cx, |this, cx| {
 7731            this.select_to_end_of_line(
 7732                &SelectToEndOfLine {
 7733                    stop_at_soft_wraps: false,
 7734                },
 7735                cx,
 7736            );
 7737            this.delete(&Delete, cx);
 7738        });
 7739    }
 7740
 7741    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7742        self.transact(cx, |this, cx| {
 7743            this.select_to_end_of_line(
 7744                &SelectToEndOfLine {
 7745                    stop_at_soft_wraps: false,
 7746                },
 7747                cx,
 7748            );
 7749            this.cut(&Cut, cx);
 7750        });
 7751    }
 7752
 7753    pub fn move_to_start_of_paragraph(
 7754        &mut self,
 7755        _: &MoveToStartOfParagraph,
 7756        cx: &mut ViewContext<Self>,
 7757    ) {
 7758        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7759            cx.propagate();
 7760            return;
 7761        }
 7762
 7763        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7764            s.move_with(|map, selection| {
 7765                selection.collapse_to(
 7766                    movement::start_of_paragraph(map, selection.head(), 1),
 7767                    SelectionGoal::None,
 7768                )
 7769            });
 7770        })
 7771    }
 7772
 7773    pub fn move_to_end_of_paragraph(
 7774        &mut self,
 7775        _: &MoveToEndOfParagraph,
 7776        cx: &mut ViewContext<Self>,
 7777    ) {
 7778        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7779            cx.propagate();
 7780            return;
 7781        }
 7782
 7783        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7784            s.move_with(|map, selection| {
 7785                selection.collapse_to(
 7786                    movement::end_of_paragraph(map, selection.head(), 1),
 7787                    SelectionGoal::None,
 7788                )
 7789            });
 7790        })
 7791    }
 7792
 7793    pub fn select_to_start_of_paragraph(
 7794        &mut self,
 7795        _: &SelectToStartOfParagraph,
 7796        cx: &mut ViewContext<Self>,
 7797    ) {
 7798        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7799            cx.propagate();
 7800            return;
 7801        }
 7802
 7803        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7804            s.move_heads_with(|map, head, _| {
 7805                (
 7806                    movement::start_of_paragraph(map, head, 1),
 7807                    SelectionGoal::None,
 7808                )
 7809            });
 7810        })
 7811    }
 7812
 7813    pub fn select_to_end_of_paragraph(
 7814        &mut self,
 7815        _: &SelectToEndOfParagraph,
 7816        cx: &mut ViewContext<Self>,
 7817    ) {
 7818        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7819            cx.propagate();
 7820            return;
 7821        }
 7822
 7823        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7824            s.move_heads_with(|map, head, _| {
 7825                (
 7826                    movement::end_of_paragraph(map, head, 1),
 7827                    SelectionGoal::None,
 7828                )
 7829            });
 7830        })
 7831    }
 7832
 7833    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7834        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7835            cx.propagate();
 7836            return;
 7837        }
 7838
 7839        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7840            s.select_ranges(vec![0..0]);
 7841        });
 7842    }
 7843
 7844    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7845        let mut selection = self.selections.last::<Point>(cx);
 7846        selection.set_head(Point::zero(), SelectionGoal::None);
 7847
 7848        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7849            s.select(vec![selection]);
 7850        });
 7851    }
 7852
 7853    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7854        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7855            cx.propagate();
 7856            return;
 7857        }
 7858
 7859        let cursor = self.buffer.read(cx).read(cx).len();
 7860        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7861            s.select_ranges(vec![cursor..cursor])
 7862        });
 7863    }
 7864
 7865    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7866        self.nav_history = nav_history;
 7867    }
 7868
 7869    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7870        self.nav_history.as_ref()
 7871    }
 7872
 7873    fn push_to_nav_history(
 7874        &mut self,
 7875        cursor_anchor: Anchor,
 7876        new_position: Option<Point>,
 7877        cx: &mut ViewContext<Self>,
 7878    ) {
 7879        if let Some(nav_history) = self.nav_history.as_mut() {
 7880            let buffer = self.buffer.read(cx).read(cx);
 7881            let cursor_position = cursor_anchor.to_point(&buffer);
 7882            let scroll_state = self.scroll_manager.anchor();
 7883            let scroll_top_row = scroll_state.top_row(&buffer);
 7884            drop(buffer);
 7885
 7886            if let Some(new_position) = new_position {
 7887                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7888                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7889                    return;
 7890                }
 7891            }
 7892
 7893            nav_history.push(
 7894                Some(NavigationData {
 7895                    cursor_anchor,
 7896                    cursor_position,
 7897                    scroll_anchor: scroll_state,
 7898                    scroll_top_row,
 7899                }),
 7900                cx,
 7901            );
 7902        }
 7903    }
 7904
 7905    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7906        let buffer = self.buffer.read(cx).snapshot(cx);
 7907        let mut selection = self.selections.first::<usize>(cx);
 7908        selection.set_head(buffer.len(), SelectionGoal::None);
 7909        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7910            s.select(vec![selection]);
 7911        });
 7912    }
 7913
 7914    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7915        let end = self.buffer.read(cx).read(cx).len();
 7916        self.change_selections(None, cx, |s| {
 7917            s.select_ranges(vec![0..end]);
 7918        });
 7919    }
 7920
 7921    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7922        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7923        let mut selections = self.selections.all::<Point>(cx);
 7924        let max_point = display_map.buffer_snapshot.max_point();
 7925        for selection in &mut selections {
 7926            let rows = selection.spanned_rows(true, &display_map);
 7927            selection.start = Point::new(rows.start.0, 0);
 7928            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7929            selection.reversed = false;
 7930        }
 7931        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7932            s.select(selections);
 7933        });
 7934    }
 7935
 7936    pub fn split_selection_into_lines(
 7937        &mut self,
 7938        _: &SplitSelectionIntoLines,
 7939        cx: &mut ViewContext<Self>,
 7940    ) {
 7941        let mut to_unfold = Vec::new();
 7942        let mut new_selection_ranges = Vec::new();
 7943        {
 7944            let selections = self.selections.all::<Point>(cx);
 7945            let buffer = self.buffer.read(cx).read(cx);
 7946            for selection in selections {
 7947                for row in selection.start.row..selection.end.row {
 7948                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7949                    new_selection_ranges.push(cursor..cursor);
 7950                }
 7951                new_selection_ranges.push(selection.end..selection.end);
 7952                to_unfold.push(selection.start..selection.end);
 7953            }
 7954        }
 7955        self.unfold_ranges(to_unfold, true, true, cx);
 7956        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7957            s.select_ranges(new_selection_ranges);
 7958        });
 7959    }
 7960
 7961    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7962        self.add_selection(true, cx);
 7963    }
 7964
 7965    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7966        self.add_selection(false, cx);
 7967    }
 7968
 7969    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7970        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7971        let mut selections = self.selections.all::<Point>(cx);
 7972        let text_layout_details = self.text_layout_details(cx);
 7973        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7974            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7975            let range = oldest_selection.display_range(&display_map).sorted();
 7976
 7977            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7978            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7979            let positions = start_x.min(end_x)..start_x.max(end_x);
 7980
 7981            selections.clear();
 7982            let mut stack = Vec::new();
 7983            for row in range.start.row().0..=range.end.row().0 {
 7984                if let Some(selection) = self.selections.build_columnar_selection(
 7985                    &display_map,
 7986                    DisplayRow(row),
 7987                    &positions,
 7988                    oldest_selection.reversed,
 7989                    &text_layout_details,
 7990                ) {
 7991                    stack.push(selection.id);
 7992                    selections.push(selection);
 7993                }
 7994            }
 7995
 7996            if above {
 7997                stack.reverse();
 7998            }
 7999
 8000            AddSelectionsState { above, stack }
 8001        });
 8002
 8003        let last_added_selection = *state.stack.last().unwrap();
 8004        let mut new_selections = Vec::new();
 8005        if above == state.above {
 8006            let end_row = if above {
 8007                DisplayRow(0)
 8008            } else {
 8009                display_map.max_point().row()
 8010            };
 8011
 8012            'outer: for selection in selections {
 8013                if selection.id == last_added_selection {
 8014                    let range = selection.display_range(&display_map).sorted();
 8015                    debug_assert_eq!(range.start.row(), range.end.row());
 8016                    let mut row = range.start.row();
 8017                    let positions =
 8018                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8019                            px(start)..px(end)
 8020                        } else {
 8021                            let start_x =
 8022                                display_map.x_for_display_point(range.start, &text_layout_details);
 8023                            let end_x =
 8024                                display_map.x_for_display_point(range.end, &text_layout_details);
 8025                            start_x.min(end_x)..start_x.max(end_x)
 8026                        };
 8027
 8028                    while row != end_row {
 8029                        if above {
 8030                            row.0 -= 1;
 8031                        } else {
 8032                            row.0 += 1;
 8033                        }
 8034
 8035                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8036                            &display_map,
 8037                            row,
 8038                            &positions,
 8039                            selection.reversed,
 8040                            &text_layout_details,
 8041                        ) {
 8042                            state.stack.push(new_selection.id);
 8043                            if above {
 8044                                new_selections.push(new_selection);
 8045                                new_selections.push(selection);
 8046                            } else {
 8047                                new_selections.push(selection);
 8048                                new_selections.push(new_selection);
 8049                            }
 8050
 8051                            continue 'outer;
 8052                        }
 8053                    }
 8054                }
 8055
 8056                new_selections.push(selection);
 8057            }
 8058        } else {
 8059            new_selections = selections;
 8060            new_selections.retain(|s| s.id != last_added_selection);
 8061            state.stack.pop();
 8062        }
 8063
 8064        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8065            s.select(new_selections);
 8066        });
 8067        if state.stack.len() > 1 {
 8068            self.add_selections_state = Some(state);
 8069        }
 8070    }
 8071
 8072    pub fn select_next_match_internal(
 8073        &mut self,
 8074        display_map: &DisplaySnapshot,
 8075        replace_newest: bool,
 8076        autoscroll: Option<Autoscroll>,
 8077        cx: &mut ViewContext<Self>,
 8078    ) -> Result<()> {
 8079        fn select_next_match_ranges(
 8080            this: &mut Editor,
 8081            range: Range<usize>,
 8082            replace_newest: bool,
 8083            auto_scroll: Option<Autoscroll>,
 8084            cx: &mut ViewContext<Editor>,
 8085        ) {
 8086            this.unfold_ranges([range.clone()], false, true, cx);
 8087            this.change_selections(auto_scroll, cx, |s| {
 8088                if replace_newest {
 8089                    s.delete(s.newest_anchor().id);
 8090                }
 8091                s.insert_range(range.clone());
 8092            });
 8093        }
 8094
 8095        let buffer = &display_map.buffer_snapshot;
 8096        let mut selections = self.selections.all::<usize>(cx);
 8097        if let Some(mut select_next_state) = self.select_next_state.take() {
 8098            let query = &select_next_state.query;
 8099            if !select_next_state.done {
 8100                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8101                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8102                let mut next_selected_range = None;
 8103
 8104                let bytes_after_last_selection =
 8105                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8106                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8107                let query_matches = query
 8108                    .stream_find_iter(bytes_after_last_selection)
 8109                    .map(|result| (last_selection.end, result))
 8110                    .chain(
 8111                        query
 8112                            .stream_find_iter(bytes_before_first_selection)
 8113                            .map(|result| (0, result)),
 8114                    );
 8115
 8116                for (start_offset, query_match) in query_matches {
 8117                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8118                    let offset_range =
 8119                        start_offset + query_match.start()..start_offset + query_match.end();
 8120                    let display_range = offset_range.start.to_display_point(display_map)
 8121                        ..offset_range.end.to_display_point(display_map);
 8122
 8123                    if !select_next_state.wordwise
 8124                        || (!movement::is_inside_word(display_map, display_range.start)
 8125                            && !movement::is_inside_word(display_map, display_range.end))
 8126                    {
 8127                        // TODO: This is n^2, because we might check all the selections
 8128                        if !selections
 8129                            .iter()
 8130                            .any(|selection| selection.range().overlaps(&offset_range))
 8131                        {
 8132                            next_selected_range = Some(offset_range);
 8133                            break;
 8134                        }
 8135                    }
 8136                }
 8137
 8138                if let Some(next_selected_range) = next_selected_range {
 8139                    select_next_match_ranges(
 8140                        self,
 8141                        next_selected_range,
 8142                        replace_newest,
 8143                        autoscroll,
 8144                        cx,
 8145                    );
 8146                } else {
 8147                    select_next_state.done = true;
 8148                }
 8149            }
 8150
 8151            self.select_next_state = Some(select_next_state);
 8152        } else {
 8153            let mut only_carets = true;
 8154            let mut same_text_selected = true;
 8155            let mut selected_text = None;
 8156
 8157            let mut selections_iter = selections.iter().peekable();
 8158            while let Some(selection) = selections_iter.next() {
 8159                if selection.start != selection.end {
 8160                    only_carets = false;
 8161                }
 8162
 8163                if same_text_selected {
 8164                    if selected_text.is_none() {
 8165                        selected_text =
 8166                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8167                    }
 8168
 8169                    if let Some(next_selection) = selections_iter.peek() {
 8170                        if next_selection.range().len() == selection.range().len() {
 8171                            let next_selected_text = buffer
 8172                                .text_for_range(next_selection.range())
 8173                                .collect::<String>();
 8174                            if Some(next_selected_text) != selected_text {
 8175                                same_text_selected = false;
 8176                                selected_text = None;
 8177                            }
 8178                        } else {
 8179                            same_text_selected = false;
 8180                            selected_text = None;
 8181                        }
 8182                    }
 8183                }
 8184            }
 8185
 8186            if only_carets {
 8187                for selection in &mut selections {
 8188                    let word_range = movement::surrounding_word(
 8189                        display_map,
 8190                        selection.start.to_display_point(display_map),
 8191                    );
 8192                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8193                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8194                    selection.goal = SelectionGoal::None;
 8195                    selection.reversed = false;
 8196                    select_next_match_ranges(
 8197                        self,
 8198                        selection.start..selection.end,
 8199                        replace_newest,
 8200                        autoscroll,
 8201                        cx,
 8202                    );
 8203                }
 8204
 8205                if selections.len() == 1 {
 8206                    let selection = selections
 8207                        .last()
 8208                        .expect("ensured that there's only one selection");
 8209                    let query = buffer
 8210                        .text_for_range(selection.start..selection.end)
 8211                        .collect::<String>();
 8212                    let is_empty = query.is_empty();
 8213                    let select_state = SelectNextState {
 8214                        query: AhoCorasick::new(&[query])?,
 8215                        wordwise: true,
 8216                        done: is_empty,
 8217                    };
 8218                    self.select_next_state = Some(select_state);
 8219                } else {
 8220                    self.select_next_state = None;
 8221                }
 8222            } else if let Some(selected_text) = selected_text {
 8223                self.select_next_state = Some(SelectNextState {
 8224                    query: AhoCorasick::new(&[selected_text])?,
 8225                    wordwise: false,
 8226                    done: false,
 8227                });
 8228                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8229            }
 8230        }
 8231        Ok(())
 8232    }
 8233
 8234    pub fn select_all_matches(
 8235        &mut self,
 8236        _action: &SelectAllMatches,
 8237        cx: &mut ViewContext<Self>,
 8238    ) -> Result<()> {
 8239        self.push_to_selection_history();
 8240        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8241
 8242        self.select_next_match_internal(&display_map, false, None, cx)?;
 8243        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8244            return Ok(());
 8245        };
 8246        if select_next_state.done {
 8247            return Ok(());
 8248        }
 8249
 8250        let mut new_selections = self.selections.all::<usize>(cx);
 8251
 8252        let buffer = &display_map.buffer_snapshot;
 8253        let query_matches = select_next_state
 8254            .query
 8255            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8256
 8257        for query_match in query_matches {
 8258            let query_match = query_match.unwrap(); // can only fail due to I/O
 8259            let offset_range = query_match.start()..query_match.end();
 8260            let display_range = offset_range.start.to_display_point(&display_map)
 8261                ..offset_range.end.to_display_point(&display_map);
 8262
 8263            if !select_next_state.wordwise
 8264                || (!movement::is_inside_word(&display_map, display_range.start)
 8265                    && !movement::is_inside_word(&display_map, display_range.end))
 8266            {
 8267                self.selections.change_with(cx, |selections| {
 8268                    new_selections.push(Selection {
 8269                        id: selections.new_selection_id(),
 8270                        start: offset_range.start,
 8271                        end: offset_range.end,
 8272                        reversed: false,
 8273                        goal: SelectionGoal::None,
 8274                    });
 8275                });
 8276            }
 8277        }
 8278
 8279        new_selections.sort_by_key(|selection| selection.start);
 8280        let mut ix = 0;
 8281        while ix + 1 < new_selections.len() {
 8282            let current_selection = &new_selections[ix];
 8283            let next_selection = &new_selections[ix + 1];
 8284            if current_selection.range().overlaps(&next_selection.range()) {
 8285                if current_selection.id < next_selection.id {
 8286                    new_selections.remove(ix + 1);
 8287                } else {
 8288                    new_selections.remove(ix);
 8289                }
 8290            } else {
 8291                ix += 1;
 8292            }
 8293        }
 8294
 8295        select_next_state.done = true;
 8296        self.unfold_ranges(
 8297            new_selections.iter().map(|selection| selection.range()),
 8298            false,
 8299            false,
 8300            cx,
 8301        );
 8302        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8303            selections.select(new_selections)
 8304        });
 8305
 8306        Ok(())
 8307    }
 8308
 8309    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8310        self.push_to_selection_history();
 8311        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8312        self.select_next_match_internal(
 8313            &display_map,
 8314            action.replace_newest,
 8315            Some(Autoscroll::newest()),
 8316            cx,
 8317        )?;
 8318        Ok(())
 8319    }
 8320
 8321    pub fn select_previous(
 8322        &mut self,
 8323        action: &SelectPrevious,
 8324        cx: &mut ViewContext<Self>,
 8325    ) -> Result<()> {
 8326        self.push_to_selection_history();
 8327        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8328        let buffer = &display_map.buffer_snapshot;
 8329        let mut selections = self.selections.all::<usize>(cx);
 8330        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8331            let query = &select_prev_state.query;
 8332            if !select_prev_state.done {
 8333                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8334                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8335                let mut next_selected_range = None;
 8336                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8337                let bytes_before_last_selection =
 8338                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8339                let bytes_after_first_selection =
 8340                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8341                let query_matches = query
 8342                    .stream_find_iter(bytes_before_last_selection)
 8343                    .map(|result| (last_selection.start, result))
 8344                    .chain(
 8345                        query
 8346                            .stream_find_iter(bytes_after_first_selection)
 8347                            .map(|result| (buffer.len(), result)),
 8348                    );
 8349                for (end_offset, query_match) in query_matches {
 8350                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8351                    let offset_range =
 8352                        end_offset - query_match.end()..end_offset - query_match.start();
 8353                    let display_range = offset_range.start.to_display_point(&display_map)
 8354                        ..offset_range.end.to_display_point(&display_map);
 8355
 8356                    if !select_prev_state.wordwise
 8357                        || (!movement::is_inside_word(&display_map, display_range.start)
 8358                            && !movement::is_inside_word(&display_map, display_range.end))
 8359                    {
 8360                        next_selected_range = Some(offset_range);
 8361                        break;
 8362                    }
 8363                }
 8364
 8365                if let Some(next_selected_range) = next_selected_range {
 8366                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 8367                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8368                        if action.replace_newest {
 8369                            s.delete(s.newest_anchor().id);
 8370                        }
 8371                        s.insert_range(next_selected_range);
 8372                    });
 8373                } else {
 8374                    select_prev_state.done = true;
 8375                }
 8376            }
 8377
 8378            self.select_prev_state = Some(select_prev_state);
 8379        } else {
 8380            let mut only_carets = true;
 8381            let mut same_text_selected = true;
 8382            let mut selected_text = None;
 8383
 8384            let mut selections_iter = selections.iter().peekable();
 8385            while let Some(selection) = selections_iter.next() {
 8386                if selection.start != selection.end {
 8387                    only_carets = false;
 8388                }
 8389
 8390                if same_text_selected {
 8391                    if selected_text.is_none() {
 8392                        selected_text =
 8393                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8394                    }
 8395
 8396                    if let Some(next_selection) = selections_iter.peek() {
 8397                        if next_selection.range().len() == selection.range().len() {
 8398                            let next_selected_text = buffer
 8399                                .text_for_range(next_selection.range())
 8400                                .collect::<String>();
 8401                            if Some(next_selected_text) != selected_text {
 8402                                same_text_selected = false;
 8403                                selected_text = None;
 8404                            }
 8405                        } else {
 8406                            same_text_selected = false;
 8407                            selected_text = None;
 8408                        }
 8409                    }
 8410                }
 8411            }
 8412
 8413            if only_carets {
 8414                for selection in &mut selections {
 8415                    let word_range = movement::surrounding_word(
 8416                        &display_map,
 8417                        selection.start.to_display_point(&display_map),
 8418                    );
 8419                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8420                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8421                    selection.goal = SelectionGoal::None;
 8422                    selection.reversed = false;
 8423                }
 8424                if selections.len() == 1 {
 8425                    let selection = selections
 8426                        .last()
 8427                        .expect("ensured that there's only one selection");
 8428                    let query = buffer
 8429                        .text_for_range(selection.start..selection.end)
 8430                        .collect::<String>();
 8431                    let is_empty = query.is_empty();
 8432                    let select_state = SelectNextState {
 8433                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8434                        wordwise: true,
 8435                        done: is_empty,
 8436                    };
 8437                    self.select_prev_state = Some(select_state);
 8438                } else {
 8439                    self.select_prev_state = None;
 8440                }
 8441
 8442                self.unfold_ranges(
 8443                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8444                    false,
 8445                    true,
 8446                    cx,
 8447                );
 8448                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8449                    s.select(selections);
 8450                });
 8451            } else if let Some(selected_text) = selected_text {
 8452                self.select_prev_state = Some(SelectNextState {
 8453                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8454                    wordwise: false,
 8455                    done: false,
 8456                });
 8457                self.select_previous(action, cx)?;
 8458            }
 8459        }
 8460        Ok(())
 8461    }
 8462
 8463    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8464        let text_layout_details = &self.text_layout_details(cx);
 8465        self.transact(cx, |this, cx| {
 8466            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8467            let mut edits = Vec::new();
 8468            let mut selection_edit_ranges = Vec::new();
 8469            let mut last_toggled_row = None;
 8470            let snapshot = this.buffer.read(cx).read(cx);
 8471            let empty_str: Arc<str> = Arc::default();
 8472            let mut suffixes_inserted = Vec::new();
 8473
 8474            fn comment_prefix_range(
 8475                snapshot: &MultiBufferSnapshot,
 8476                row: MultiBufferRow,
 8477                comment_prefix: &str,
 8478                comment_prefix_whitespace: &str,
 8479            ) -> Range<Point> {
 8480                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8481
 8482                let mut line_bytes = snapshot
 8483                    .bytes_in_range(start..snapshot.max_point())
 8484                    .flatten()
 8485                    .copied();
 8486
 8487                // If this line currently begins with the line comment prefix, then record
 8488                // the range containing the prefix.
 8489                if line_bytes
 8490                    .by_ref()
 8491                    .take(comment_prefix.len())
 8492                    .eq(comment_prefix.bytes())
 8493                {
 8494                    // Include any whitespace that matches the comment prefix.
 8495                    let matching_whitespace_len = line_bytes
 8496                        .zip(comment_prefix_whitespace.bytes())
 8497                        .take_while(|(a, b)| a == b)
 8498                        .count() as u32;
 8499                    let end = Point::new(
 8500                        start.row,
 8501                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8502                    );
 8503                    start..end
 8504                } else {
 8505                    start..start
 8506                }
 8507            }
 8508
 8509            fn comment_suffix_range(
 8510                snapshot: &MultiBufferSnapshot,
 8511                row: MultiBufferRow,
 8512                comment_suffix: &str,
 8513                comment_suffix_has_leading_space: bool,
 8514            ) -> Range<Point> {
 8515                let end = Point::new(row.0, snapshot.line_len(row));
 8516                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8517
 8518                let mut line_end_bytes = snapshot
 8519                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8520                    .flatten()
 8521                    .copied();
 8522
 8523                let leading_space_len = if suffix_start_column > 0
 8524                    && line_end_bytes.next() == Some(b' ')
 8525                    && comment_suffix_has_leading_space
 8526                {
 8527                    1
 8528                } else {
 8529                    0
 8530                };
 8531
 8532                // If this line currently begins with the line comment prefix, then record
 8533                // the range containing the prefix.
 8534                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8535                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8536                    start..end
 8537                } else {
 8538                    end..end
 8539                }
 8540            }
 8541
 8542            // TODO: Handle selections that cross excerpts
 8543            for selection in &mut selections {
 8544                let start_column = snapshot
 8545                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8546                    .len;
 8547                let language = if let Some(language) =
 8548                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8549                {
 8550                    language
 8551                } else {
 8552                    continue;
 8553                };
 8554
 8555                selection_edit_ranges.clear();
 8556
 8557                // If multiple selections contain a given row, avoid processing that
 8558                // row more than once.
 8559                let mut start_row = MultiBufferRow(selection.start.row);
 8560                if last_toggled_row == Some(start_row) {
 8561                    start_row = start_row.next_row();
 8562                }
 8563                let end_row =
 8564                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8565                        MultiBufferRow(selection.end.row - 1)
 8566                    } else {
 8567                        MultiBufferRow(selection.end.row)
 8568                    };
 8569                last_toggled_row = Some(end_row);
 8570
 8571                if start_row > end_row {
 8572                    continue;
 8573                }
 8574
 8575                // If the language has line comments, toggle those.
 8576                let full_comment_prefixes = language.line_comment_prefixes();
 8577                if !full_comment_prefixes.is_empty() {
 8578                    let first_prefix = full_comment_prefixes
 8579                        .first()
 8580                        .expect("prefixes is non-empty");
 8581                    let prefix_trimmed_lengths = full_comment_prefixes
 8582                        .iter()
 8583                        .map(|p| p.trim_end_matches(' ').len())
 8584                        .collect::<SmallVec<[usize; 4]>>();
 8585
 8586                    let mut all_selection_lines_are_comments = true;
 8587
 8588                    for row in start_row.0..=end_row.0 {
 8589                        let row = MultiBufferRow(row);
 8590                        if start_row < end_row && snapshot.is_line_blank(row) {
 8591                            continue;
 8592                        }
 8593
 8594                        let prefix_range = full_comment_prefixes
 8595                            .iter()
 8596                            .zip(prefix_trimmed_lengths.iter().copied())
 8597                            .map(|(prefix, trimmed_prefix_len)| {
 8598                                comment_prefix_range(
 8599                                    snapshot.deref(),
 8600                                    row,
 8601                                    &prefix[..trimmed_prefix_len],
 8602                                    &prefix[trimmed_prefix_len..],
 8603                                )
 8604                            })
 8605                            .max_by_key(|range| range.end.column - range.start.column)
 8606                            .expect("prefixes is non-empty");
 8607
 8608                        if prefix_range.is_empty() {
 8609                            all_selection_lines_are_comments = false;
 8610                        }
 8611
 8612                        selection_edit_ranges.push(prefix_range);
 8613                    }
 8614
 8615                    if all_selection_lines_are_comments {
 8616                        edits.extend(
 8617                            selection_edit_ranges
 8618                                .iter()
 8619                                .cloned()
 8620                                .map(|range| (range, empty_str.clone())),
 8621                        );
 8622                    } else {
 8623                        let min_column = selection_edit_ranges
 8624                            .iter()
 8625                            .map(|range| range.start.column)
 8626                            .min()
 8627                            .unwrap_or(0);
 8628                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8629                            let position = Point::new(range.start.row, min_column);
 8630                            (position..position, first_prefix.clone())
 8631                        }));
 8632                    }
 8633                } else if let Some((full_comment_prefix, comment_suffix)) =
 8634                    language.block_comment_delimiters()
 8635                {
 8636                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8637                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8638                    let prefix_range = comment_prefix_range(
 8639                        snapshot.deref(),
 8640                        start_row,
 8641                        comment_prefix,
 8642                        comment_prefix_whitespace,
 8643                    );
 8644                    let suffix_range = comment_suffix_range(
 8645                        snapshot.deref(),
 8646                        end_row,
 8647                        comment_suffix.trim_start_matches(' '),
 8648                        comment_suffix.starts_with(' '),
 8649                    );
 8650
 8651                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8652                        edits.push((
 8653                            prefix_range.start..prefix_range.start,
 8654                            full_comment_prefix.clone(),
 8655                        ));
 8656                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8657                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8658                    } else {
 8659                        edits.push((prefix_range, empty_str.clone()));
 8660                        edits.push((suffix_range, empty_str.clone()));
 8661                    }
 8662                } else {
 8663                    continue;
 8664                }
 8665            }
 8666
 8667            drop(snapshot);
 8668            this.buffer.update(cx, |buffer, cx| {
 8669                buffer.edit(edits, None, cx);
 8670            });
 8671
 8672            // Adjust selections so that they end before any comment suffixes that
 8673            // were inserted.
 8674            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8675            let mut selections = this.selections.all::<Point>(cx);
 8676            let snapshot = this.buffer.read(cx).read(cx);
 8677            for selection in &mut selections {
 8678                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8679                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8680                        Ordering::Less => {
 8681                            suffixes_inserted.next();
 8682                            continue;
 8683                        }
 8684                        Ordering::Greater => break,
 8685                        Ordering::Equal => {
 8686                            if selection.end.column == snapshot.line_len(row) {
 8687                                if selection.is_empty() {
 8688                                    selection.start.column -= suffix_len as u32;
 8689                                }
 8690                                selection.end.column -= suffix_len as u32;
 8691                            }
 8692                            break;
 8693                        }
 8694                    }
 8695                }
 8696            }
 8697
 8698            drop(snapshot);
 8699            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8700
 8701            let selections = this.selections.all::<Point>(cx);
 8702            let selections_on_single_row = selections.windows(2).all(|selections| {
 8703                selections[0].start.row == selections[1].start.row
 8704                    && selections[0].end.row == selections[1].end.row
 8705                    && selections[0].start.row == selections[0].end.row
 8706            });
 8707            let selections_selecting = selections
 8708                .iter()
 8709                .any(|selection| selection.start != selection.end);
 8710            let advance_downwards = action.advance_downwards
 8711                && selections_on_single_row
 8712                && !selections_selecting
 8713                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8714
 8715            if advance_downwards {
 8716                let snapshot = this.buffer.read(cx).snapshot(cx);
 8717
 8718                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8719                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8720                        let mut point = display_point.to_point(display_snapshot);
 8721                        point.row += 1;
 8722                        point = snapshot.clip_point(point, Bias::Left);
 8723                        let display_point = point.to_display_point(display_snapshot);
 8724                        let goal = SelectionGoal::HorizontalPosition(
 8725                            display_snapshot
 8726                                .x_for_display_point(display_point, text_layout_details)
 8727                                .into(),
 8728                        );
 8729                        (display_point, goal)
 8730                    })
 8731                });
 8732            }
 8733        });
 8734    }
 8735
 8736    pub fn select_enclosing_symbol(
 8737        &mut self,
 8738        _: &SelectEnclosingSymbol,
 8739        cx: &mut ViewContext<Self>,
 8740    ) {
 8741        let buffer = self.buffer.read(cx).snapshot(cx);
 8742        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8743
 8744        fn update_selection(
 8745            selection: &Selection<usize>,
 8746            buffer_snap: &MultiBufferSnapshot,
 8747        ) -> Option<Selection<usize>> {
 8748            let cursor = selection.head();
 8749            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8750            for symbol in symbols.iter().rev() {
 8751                let start = symbol.range.start.to_offset(buffer_snap);
 8752                let end = symbol.range.end.to_offset(buffer_snap);
 8753                let new_range = start..end;
 8754                if start < selection.start || end > selection.end {
 8755                    return Some(Selection {
 8756                        id: selection.id,
 8757                        start: new_range.start,
 8758                        end: new_range.end,
 8759                        goal: SelectionGoal::None,
 8760                        reversed: selection.reversed,
 8761                    });
 8762                }
 8763            }
 8764            None
 8765        }
 8766
 8767        let mut selected_larger_symbol = false;
 8768        let new_selections = old_selections
 8769            .iter()
 8770            .map(|selection| match update_selection(selection, &buffer) {
 8771                Some(new_selection) => {
 8772                    if new_selection.range() != selection.range() {
 8773                        selected_larger_symbol = true;
 8774                    }
 8775                    new_selection
 8776                }
 8777                None => selection.clone(),
 8778            })
 8779            .collect::<Vec<_>>();
 8780
 8781        if selected_larger_symbol {
 8782            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8783                s.select(new_selections);
 8784            });
 8785        }
 8786    }
 8787
 8788    pub fn select_larger_syntax_node(
 8789        &mut self,
 8790        _: &SelectLargerSyntaxNode,
 8791        cx: &mut ViewContext<Self>,
 8792    ) {
 8793        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8794        let buffer = self.buffer.read(cx).snapshot(cx);
 8795        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8796
 8797        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8798        let mut selected_larger_node = false;
 8799        let new_selections = old_selections
 8800            .iter()
 8801            .map(|selection| {
 8802                let old_range = selection.start..selection.end;
 8803                let mut new_range = old_range.clone();
 8804                while let Some(containing_range) =
 8805                    buffer.range_for_syntax_ancestor(new_range.clone())
 8806                {
 8807                    new_range = containing_range;
 8808                    if !display_map.intersects_fold(new_range.start)
 8809                        && !display_map.intersects_fold(new_range.end)
 8810                    {
 8811                        break;
 8812                    }
 8813                }
 8814
 8815                selected_larger_node |= new_range != old_range;
 8816                Selection {
 8817                    id: selection.id,
 8818                    start: new_range.start,
 8819                    end: new_range.end,
 8820                    goal: SelectionGoal::None,
 8821                    reversed: selection.reversed,
 8822                }
 8823            })
 8824            .collect::<Vec<_>>();
 8825
 8826        if selected_larger_node {
 8827            stack.push(old_selections);
 8828            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8829                s.select(new_selections);
 8830            });
 8831        }
 8832        self.select_larger_syntax_node_stack = stack;
 8833    }
 8834
 8835    pub fn select_smaller_syntax_node(
 8836        &mut self,
 8837        _: &SelectSmallerSyntaxNode,
 8838        cx: &mut ViewContext<Self>,
 8839    ) {
 8840        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8841        if let Some(selections) = stack.pop() {
 8842            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8843                s.select(selections.to_vec());
 8844            });
 8845        }
 8846        self.select_larger_syntax_node_stack = stack;
 8847    }
 8848
 8849    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8850        if !EditorSettings::get_global(cx).gutter.runnables {
 8851            self.clear_tasks();
 8852            return Task::ready(());
 8853        }
 8854        let project = self.project.clone();
 8855        cx.spawn(|this, mut cx| async move {
 8856            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8857                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8858            }) else {
 8859                return;
 8860            };
 8861
 8862            let Some(project) = project else {
 8863                return;
 8864            };
 8865
 8866            let hide_runnables = project
 8867                .update(&mut cx, |project, cx| {
 8868                    // Do not display any test indicators in non-dev server remote projects.
 8869                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8870                })
 8871                .unwrap_or(true);
 8872            if hide_runnables {
 8873                return;
 8874            }
 8875            let new_rows =
 8876                cx.background_executor()
 8877                    .spawn({
 8878                        let snapshot = display_snapshot.clone();
 8879                        async move {
 8880                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8881                        }
 8882                    })
 8883                    .await;
 8884            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8885
 8886            this.update(&mut cx, |this, _| {
 8887                this.clear_tasks();
 8888                for (key, value) in rows {
 8889                    this.insert_tasks(key, value);
 8890                }
 8891            })
 8892            .ok();
 8893        })
 8894    }
 8895    fn fetch_runnable_ranges(
 8896        snapshot: &DisplaySnapshot,
 8897        range: Range<Anchor>,
 8898    ) -> Vec<language::RunnableRange> {
 8899        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8900    }
 8901
 8902    fn runnable_rows(
 8903        project: Model<Project>,
 8904        snapshot: DisplaySnapshot,
 8905        runnable_ranges: Vec<RunnableRange>,
 8906        mut cx: AsyncWindowContext,
 8907    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8908        runnable_ranges
 8909            .into_iter()
 8910            .filter_map(|mut runnable| {
 8911                let tasks = cx
 8912                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8913                    .ok()?;
 8914                if tasks.is_empty() {
 8915                    return None;
 8916                }
 8917
 8918                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8919
 8920                let row = snapshot
 8921                    .buffer_snapshot
 8922                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8923                    .1
 8924                    .start
 8925                    .row;
 8926
 8927                let context_range =
 8928                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8929                Some((
 8930                    (runnable.buffer_id, row),
 8931                    RunnableTasks {
 8932                        templates: tasks,
 8933                        offset: MultiBufferOffset(runnable.run_range.start),
 8934                        context_range,
 8935                        column: point.column,
 8936                        extra_variables: runnable.extra_captures,
 8937                    },
 8938                ))
 8939            })
 8940            .collect()
 8941    }
 8942
 8943    fn templates_with_tags(
 8944        project: &Model<Project>,
 8945        runnable: &mut Runnable,
 8946        cx: &WindowContext<'_>,
 8947    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8948        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8949            let (worktree_id, file) = project
 8950                .buffer_for_id(runnable.buffer, cx)
 8951                .and_then(|buffer| buffer.read(cx).file())
 8952                .map(|file| (file.worktree_id(cx), file.clone()))
 8953                .unzip();
 8954
 8955            (project.task_inventory().clone(), worktree_id, file)
 8956        });
 8957
 8958        let inventory = inventory.read(cx);
 8959        let tags = mem::take(&mut runnable.tags);
 8960        let mut tags: Vec<_> = tags
 8961            .into_iter()
 8962            .flat_map(|tag| {
 8963                let tag = tag.0.clone();
 8964                inventory
 8965                    .list_tasks(
 8966                        file.clone(),
 8967                        Some(runnable.language.clone()),
 8968                        worktree_id,
 8969                        cx,
 8970                    )
 8971                    .into_iter()
 8972                    .filter(move |(_, template)| {
 8973                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8974                    })
 8975            })
 8976            .sorted_by_key(|(kind, _)| kind.to_owned())
 8977            .collect();
 8978        if let Some((leading_tag_source, _)) = tags.first() {
 8979            // Strongest source wins; if we have worktree tag binding, prefer that to
 8980            // global and language bindings;
 8981            // if we have a global binding, prefer that to language binding.
 8982            let first_mismatch = tags
 8983                .iter()
 8984                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8985            if let Some(index) = first_mismatch {
 8986                tags.truncate(index);
 8987            }
 8988        }
 8989
 8990        tags
 8991    }
 8992
 8993    pub fn move_to_enclosing_bracket(
 8994        &mut self,
 8995        _: &MoveToEnclosingBracket,
 8996        cx: &mut ViewContext<Self>,
 8997    ) {
 8998        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8999            s.move_offsets_with(|snapshot, selection| {
 9000                let Some(enclosing_bracket_ranges) =
 9001                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9002                else {
 9003                    return;
 9004                };
 9005
 9006                let mut best_length = usize::MAX;
 9007                let mut best_inside = false;
 9008                let mut best_in_bracket_range = false;
 9009                let mut best_destination = None;
 9010                for (open, close) in enclosing_bracket_ranges {
 9011                    let close = close.to_inclusive();
 9012                    let length = close.end() - open.start;
 9013                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9014                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9015                        || close.contains(&selection.head());
 9016
 9017                    // If best is next to a bracket and current isn't, skip
 9018                    if !in_bracket_range && best_in_bracket_range {
 9019                        continue;
 9020                    }
 9021
 9022                    // Prefer smaller lengths unless best is inside and current isn't
 9023                    if length > best_length && (best_inside || !inside) {
 9024                        continue;
 9025                    }
 9026
 9027                    best_length = length;
 9028                    best_inside = inside;
 9029                    best_in_bracket_range = in_bracket_range;
 9030                    best_destination = Some(
 9031                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9032                            if inside {
 9033                                open.end
 9034                            } else {
 9035                                open.start
 9036                            }
 9037                        } else if inside {
 9038                            *close.start()
 9039                        } else {
 9040                            *close.end()
 9041                        },
 9042                    );
 9043                }
 9044
 9045                if let Some(destination) = best_destination {
 9046                    selection.collapse_to(destination, SelectionGoal::None);
 9047                }
 9048            })
 9049        });
 9050    }
 9051
 9052    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9053        self.end_selection(cx);
 9054        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9055        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9056            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9057            self.select_next_state = entry.select_next_state;
 9058            self.select_prev_state = entry.select_prev_state;
 9059            self.add_selections_state = entry.add_selections_state;
 9060            self.request_autoscroll(Autoscroll::newest(), cx);
 9061        }
 9062        self.selection_history.mode = SelectionHistoryMode::Normal;
 9063    }
 9064
 9065    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9066        self.end_selection(cx);
 9067        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9068        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9069            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9070            self.select_next_state = entry.select_next_state;
 9071            self.select_prev_state = entry.select_prev_state;
 9072            self.add_selections_state = entry.add_selections_state;
 9073            self.request_autoscroll(Autoscroll::newest(), cx);
 9074        }
 9075        self.selection_history.mode = SelectionHistoryMode::Normal;
 9076    }
 9077
 9078    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9079        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9080    }
 9081
 9082    pub fn expand_excerpts_down(
 9083        &mut self,
 9084        action: &ExpandExcerptsDown,
 9085        cx: &mut ViewContext<Self>,
 9086    ) {
 9087        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9088    }
 9089
 9090    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9091        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9092    }
 9093
 9094    pub fn expand_excerpts_for_direction(
 9095        &mut self,
 9096        lines: u32,
 9097        direction: ExpandExcerptDirection,
 9098        cx: &mut ViewContext<Self>,
 9099    ) {
 9100        let selections = self.selections.disjoint_anchors();
 9101
 9102        let lines = if lines == 0 {
 9103            EditorSettings::get_global(cx).expand_excerpt_lines
 9104        } else {
 9105            lines
 9106        };
 9107
 9108        self.buffer.update(cx, |buffer, cx| {
 9109            buffer.expand_excerpts(
 9110                selections
 9111                    .iter()
 9112                    .map(|selection| selection.head().excerpt_id)
 9113                    .dedup(),
 9114                lines,
 9115                direction,
 9116                cx,
 9117            )
 9118        })
 9119    }
 9120
 9121    pub fn expand_excerpt(
 9122        &mut self,
 9123        excerpt: ExcerptId,
 9124        direction: ExpandExcerptDirection,
 9125        cx: &mut ViewContext<Self>,
 9126    ) {
 9127        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9128        self.buffer.update(cx, |buffer, cx| {
 9129            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9130        })
 9131    }
 9132
 9133    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9134        self.go_to_diagnostic_impl(Direction::Next, cx)
 9135    }
 9136
 9137    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9138        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9139    }
 9140
 9141    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9142        let buffer = self.buffer.read(cx).snapshot(cx);
 9143        let selection = self.selections.newest::<usize>(cx);
 9144
 9145        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9146        if direction == Direction::Next {
 9147            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9148                let (group_id, jump_to) = popover.activation_info();
 9149                if self.activate_diagnostics(group_id, cx) {
 9150                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9151                        let mut new_selection = s.newest_anchor().clone();
 9152                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9153                        s.select_anchors(vec![new_selection.clone()]);
 9154                    });
 9155                }
 9156                return;
 9157            }
 9158        }
 9159
 9160        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9161            active_diagnostics
 9162                .primary_range
 9163                .to_offset(&buffer)
 9164                .to_inclusive()
 9165        });
 9166        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9167            if active_primary_range.contains(&selection.head()) {
 9168                *active_primary_range.start()
 9169            } else {
 9170                selection.head()
 9171            }
 9172        } else {
 9173            selection.head()
 9174        };
 9175        let snapshot = self.snapshot(cx);
 9176        loop {
 9177            let diagnostics = if direction == Direction::Prev {
 9178                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9179            } else {
 9180                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9181            }
 9182            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9183            let group = diagnostics
 9184                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9185                // be sorted in a stable way
 9186                // skip until we are at current active diagnostic, if it exists
 9187                .skip_while(|entry| {
 9188                    (match direction {
 9189                        Direction::Prev => entry.range.start >= search_start,
 9190                        Direction::Next => entry.range.start <= search_start,
 9191                    }) && self
 9192                        .active_diagnostics
 9193                        .as_ref()
 9194                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9195                })
 9196                .find_map(|entry| {
 9197                    if entry.diagnostic.is_primary
 9198                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9199                        && !entry.range.is_empty()
 9200                        // if we match with the active diagnostic, skip it
 9201                        && Some(entry.diagnostic.group_id)
 9202                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9203                    {
 9204                        Some((entry.range, entry.diagnostic.group_id))
 9205                    } else {
 9206                        None
 9207                    }
 9208                });
 9209
 9210            if let Some((primary_range, group_id)) = group {
 9211                if self.activate_diagnostics(group_id, cx) {
 9212                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9213                        s.select(vec![Selection {
 9214                            id: selection.id,
 9215                            start: primary_range.start,
 9216                            end: primary_range.start,
 9217                            reversed: false,
 9218                            goal: SelectionGoal::None,
 9219                        }]);
 9220                    });
 9221                }
 9222                break;
 9223            } else {
 9224                // Cycle around to the start of the buffer, potentially moving back to the start of
 9225                // the currently active diagnostic.
 9226                active_primary_range.take();
 9227                if direction == Direction::Prev {
 9228                    if search_start == buffer.len() {
 9229                        break;
 9230                    } else {
 9231                        search_start = buffer.len();
 9232                    }
 9233                } else if search_start == 0 {
 9234                    break;
 9235                } else {
 9236                    search_start = 0;
 9237                }
 9238            }
 9239        }
 9240    }
 9241
 9242    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9243        let snapshot = self
 9244            .display_map
 9245            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9246        let selection = self.selections.newest::<Point>(cx);
 9247
 9248        if !self.seek_in_direction(
 9249            &snapshot,
 9250            selection.head(),
 9251            false,
 9252            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9253                MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
 9254            ),
 9255            cx,
 9256        ) {
 9257            let wrapped_point = Point::zero();
 9258            self.seek_in_direction(
 9259                &snapshot,
 9260                wrapped_point,
 9261                true,
 9262                snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9263                    MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9264                ),
 9265                cx,
 9266            );
 9267        }
 9268    }
 9269
 9270    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9271        let snapshot = self
 9272            .display_map
 9273            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9274        let selection = self.selections.newest::<Point>(cx);
 9275
 9276        if !self.seek_in_direction(
 9277            &snapshot,
 9278            selection.head(),
 9279            false,
 9280            snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 9281                MultiBufferRow(0)..MultiBufferRow(selection.head().row),
 9282            ),
 9283            cx,
 9284        ) {
 9285            let wrapped_point = snapshot.buffer_snapshot.max_point();
 9286            self.seek_in_direction(
 9287                &snapshot,
 9288                wrapped_point,
 9289                true,
 9290                snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 9291                    MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
 9292                ),
 9293                cx,
 9294            );
 9295        }
 9296    }
 9297
 9298    fn seek_in_direction(
 9299        &mut self,
 9300        snapshot: &DisplaySnapshot,
 9301        initial_point: Point,
 9302        is_wrapped: bool,
 9303        hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
 9304        cx: &mut ViewContext<Editor>,
 9305    ) -> bool {
 9306        let display_point = initial_point.to_display_point(snapshot);
 9307        let mut hunks = hunks
 9308            .map(|hunk| diff_hunk_to_display(&hunk, snapshot))
 9309            .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
 9310            .dedup();
 9311
 9312        if let Some(hunk) = hunks.next() {
 9313            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9314                let row = hunk.start_display_row();
 9315                let point = DisplayPoint::new(row, 0);
 9316                s.select_display_ranges([point..point]);
 9317            });
 9318
 9319            true
 9320        } else {
 9321            false
 9322        }
 9323    }
 9324
 9325    pub fn go_to_definition(
 9326        &mut self,
 9327        _: &GoToDefinition,
 9328        cx: &mut ViewContext<Self>,
 9329    ) -> Task<Result<Navigated>> {
 9330        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9331        cx.spawn(|editor, mut cx| async move {
 9332            if definition.await? == Navigated::Yes {
 9333                return Ok(Navigated::Yes);
 9334            }
 9335            match editor.update(&mut cx, |editor, cx| {
 9336                editor.find_all_references(&FindAllReferences, cx)
 9337            })? {
 9338                Some(references) => references.await,
 9339                None => Ok(Navigated::No),
 9340            }
 9341        })
 9342    }
 9343
 9344    pub fn go_to_declaration(
 9345        &mut self,
 9346        _: &GoToDeclaration,
 9347        cx: &mut ViewContext<Self>,
 9348    ) -> Task<Result<Navigated>> {
 9349        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9350    }
 9351
 9352    pub fn go_to_declaration_split(
 9353        &mut self,
 9354        _: &GoToDeclaration,
 9355        cx: &mut ViewContext<Self>,
 9356    ) -> Task<Result<Navigated>> {
 9357        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9358    }
 9359
 9360    pub fn go_to_implementation(
 9361        &mut self,
 9362        _: &GoToImplementation,
 9363        cx: &mut ViewContext<Self>,
 9364    ) -> Task<Result<Navigated>> {
 9365        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9366    }
 9367
 9368    pub fn go_to_implementation_split(
 9369        &mut self,
 9370        _: &GoToImplementationSplit,
 9371        cx: &mut ViewContext<Self>,
 9372    ) -> Task<Result<Navigated>> {
 9373        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9374    }
 9375
 9376    pub fn go_to_type_definition(
 9377        &mut self,
 9378        _: &GoToTypeDefinition,
 9379        cx: &mut ViewContext<Self>,
 9380    ) -> Task<Result<Navigated>> {
 9381        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9382    }
 9383
 9384    pub fn go_to_definition_split(
 9385        &mut self,
 9386        _: &GoToDefinitionSplit,
 9387        cx: &mut ViewContext<Self>,
 9388    ) -> Task<Result<Navigated>> {
 9389        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9390    }
 9391
 9392    pub fn go_to_type_definition_split(
 9393        &mut self,
 9394        _: &GoToTypeDefinitionSplit,
 9395        cx: &mut ViewContext<Self>,
 9396    ) -> Task<Result<Navigated>> {
 9397        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9398    }
 9399
 9400    fn go_to_definition_of_kind(
 9401        &mut self,
 9402        kind: GotoDefinitionKind,
 9403        split: bool,
 9404        cx: &mut ViewContext<Self>,
 9405    ) -> Task<Result<Navigated>> {
 9406        let Some(workspace) = self.workspace() else {
 9407            return Task::ready(Ok(Navigated::No));
 9408        };
 9409        let buffer = self.buffer.read(cx);
 9410        let head = self.selections.newest::<usize>(cx).head();
 9411        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9412            text_anchor
 9413        } else {
 9414            return Task::ready(Ok(Navigated::No));
 9415        };
 9416
 9417        let project = workspace.read(cx).project().clone();
 9418        let definitions = project.update(cx, |project, cx| match kind {
 9419            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 9420            GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
 9421            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 9422            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 9423        });
 9424
 9425        cx.spawn(|editor, mut cx| async move {
 9426            let definitions = definitions.await?;
 9427            let navigated = editor
 9428                .update(&mut cx, |editor, cx| {
 9429                    editor.navigate_to_hover_links(
 9430                        Some(kind),
 9431                        definitions
 9432                            .into_iter()
 9433                            .filter(|location| {
 9434                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9435                            })
 9436                            .map(HoverLink::Text)
 9437                            .collect::<Vec<_>>(),
 9438                        split,
 9439                        cx,
 9440                    )
 9441                })?
 9442                .await?;
 9443            anyhow::Ok(navigated)
 9444        })
 9445    }
 9446
 9447    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9448        let position = self.selections.newest_anchor().head();
 9449        let Some((buffer, buffer_position)) =
 9450            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9451        else {
 9452            return;
 9453        };
 9454
 9455        cx.spawn(|editor, mut cx| async move {
 9456            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9457                editor.update(&mut cx, |_, cx| {
 9458                    cx.open_url(&url);
 9459                })
 9460            } else {
 9461                Ok(())
 9462            }
 9463        })
 9464        .detach();
 9465    }
 9466
 9467    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9468        let Some(workspace) = self.workspace() else {
 9469            return;
 9470        };
 9471
 9472        let position = self.selections.newest_anchor().head();
 9473
 9474        let Some((buffer, buffer_position)) =
 9475            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9476        else {
 9477            return;
 9478        };
 9479
 9480        let Some(project) = self.project.clone() else {
 9481            return;
 9482        };
 9483
 9484        cx.spawn(|_, mut cx| async move {
 9485            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9486
 9487            if let Some((_, path)) = result {
 9488                workspace
 9489                    .update(&mut cx, |workspace, cx| {
 9490                        workspace.open_resolved_path(path, cx)
 9491                    })?
 9492                    .await?;
 9493            }
 9494            anyhow::Ok(())
 9495        })
 9496        .detach();
 9497    }
 9498
 9499    pub(crate) fn navigate_to_hover_links(
 9500        &mut self,
 9501        kind: Option<GotoDefinitionKind>,
 9502        mut definitions: Vec<HoverLink>,
 9503        split: bool,
 9504        cx: &mut ViewContext<Editor>,
 9505    ) -> Task<Result<Navigated>> {
 9506        // If there is one definition, just open it directly
 9507        if definitions.len() == 1 {
 9508            let definition = definitions.pop().unwrap();
 9509
 9510            enum TargetTaskResult {
 9511                Location(Option<Location>),
 9512                AlreadyNavigated,
 9513            }
 9514
 9515            let target_task = match definition {
 9516                HoverLink::Text(link) => {
 9517                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9518                }
 9519                HoverLink::InlayHint(lsp_location, server_id) => {
 9520                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9521                    cx.background_executor().spawn(async move {
 9522                        let location = computation.await?;
 9523                        Ok(TargetTaskResult::Location(location))
 9524                    })
 9525                }
 9526                HoverLink::Url(url) => {
 9527                    cx.open_url(&url);
 9528                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9529                }
 9530                HoverLink::File(path) => {
 9531                    if let Some(workspace) = self.workspace() {
 9532                        cx.spawn(|_, mut cx| async move {
 9533                            workspace
 9534                                .update(&mut cx, |workspace, cx| {
 9535                                    workspace.open_resolved_path(path, cx)
 9536                                })?
 9537                                .await
 9538                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9539                        })
 9540                    } else {
 9541                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9542                    }
 9543                }
 9544            };
 9545            cx.spawn(|editor, mut cx| async move {
 9546                let target = match target_task.await.context("target resolution task")? {
 9547                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9548                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9549                    TargetTaskResult::Location(Some(target)) => target,
 9550                };
 9551
 9552                editor.update(&mut cx, |editor, cx| {
 9553                    let Some(workspace) = editor.workspace() else {
 9554                        return Navigated::No;
 9555                    };
 9556                    let pane = workspace.read(cx).active_pane().clone();
 9557
 9558                    let range = target.range.to_offset(target.buffer.read(cx));
 9559                    let range = editor.range_for_match(&range);
 9560
 9561                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9562                        let buffer = target.buffer.read(cx);
 9563                        let range = check_multiline_range(buffer, range);
 9564                        editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
 9565                            s.select_ranges([range]);
 9566                        });
 9567                    } else {
 9568                        cx.window_context().defer(move |cx| {
 9569                            let target_editor: View<Self> =
 9570                                workspace.update(cx, |workspace, cx| {
 9571                                    let pane = if split {
 9572                                        workspace.adjacent_pane(cx)
 9573                                    } else {
 9574                                        workspace.active_pane().clone()
 9575                                    };
 9576
 9577                                    workspace.open_project_item(
 9578                                        pane,
 9579                                        target.buffer.clone(),
 9580                                        true,
 9581                                        true,
 9582                                        cx,
 9583                                    )
 9584                                });
 9585                            target_editor.update(cx, |target_editor, cx| {
 9586                                // When selecting a definition in a different buffer, disable the nav history
 9587                                // to avoid creating a history entry at the previous cursor location.
 9588                                pane.update(cx, |pane, _| pane.disable_history());
 9589                                let buffer = target.buffer.read(cx);
 9590                                let range = check_multiline_range(buffer, range);
 9591                                target_editor.change_selections(
 9592                                    Some(Autoscroll::focused()),
 9593                                    cx,
 9594                                    |s| {
 9595                                        s.select_ranges([range]);
 9596                                    },
 9597                                );
 9598                                pane.update(cx, |pane, _| pane.enable_history());
 9599                            });
 9600                        });
 9601                    }
 9602                    Navigated::Yes
 9603                })
 9604            })
 9605        } else if !definitions.is_empty() {
 9606            cx.spawn(|editor, mut cx| async move {
 9607                let (title, location_tasks, workspace) = editor
 9608                    .update(&mut cx, |editor, cx| {
 9609                        let tab_kind = match kind {
 9610                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9611                            _ => "Definitions",
 9612                        };
 9613                        let title = definitions
 9614                            .iter()
 9615                            .find_map(|definition| match definition {
 9616                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9617                                    let buffer = origin.buffer.read(cx);
 9618                                    format!(
 9619                                        "{} for {}",
 9620                                        tab_kind,
 9621                                        buffer
 9622                                            .text_for_range(origin.range.clone())
 9623                                            .collect::<String>()
 9624                                    )
 9625                                }),
 9626                                HoverLink::InlayHint(_, _) => None,
 9627                                HoverLink::Url(_) => None,
 9628                                HoverLink::File(_) => None,
 9629                            })
 9630                            .unwrap_or(tab_kind.to_string());
 9631                        let location_tasks = definitions
 9632                            .into_iter()
 9633                            .map(|definition| match definition {
 9634                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9635                                HoverLink::InlayHint(lsp_location, server_id) => {
 9636                                    editor.compute_target_location(lsp_location, server_id, cx)
 9637                                }
 9638                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9639                                HoverLink::File(_) => Task::ready(Ok(None)),
 9640                            })
 9641                            .collect::<Vec<_>>();
 9642                        (title, location_tasks, editor.workspace().clone())
 9643                    })
 9644                    .context("location tasks preparation")?;
 9645
 9646                let locations = futures::future::join_all(location_tasks)
 9647                    .await
 9648                    .into_iter()
 9649                    .filter_map(|location| location.transpose())
 9650                    .collect::<Result<_>>()
 9651                    .context("location tasks")?;
 9652
 9653                let Some(workspace) = workspace else {
 9654                    return Ok(Navigated::No);
 9655                };
 9656                let opened = workspace
 9657                    .update(&mut cx, |workspace, cx| {
 9658                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9659                    })
 9660                    .ok();
 9661
 9662                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9663            })
 9664        } else {
 9665            Task::ready(Ok(Navigated::No))
 9666        }
 9667    }
 9668
 9669    fn compute_target_location(
 9670        &self,
 9671        lsp_location: lsp::Location,
 9672        server_id: LanguageServerId,
 9673        cx: &mut ViewContext<Editor>,
 9674    ) -> Task<anyhow::Result<Option<Location>>> {
 9675        let Some(project) = self.project.clone() else {
 9676            return Task::Ready(Some(Ok(None)));
 9677        };
 9678
 9679        cx.spawn(move |editor, mut cx| async move {
 9680            let location_task = editor.update(&mut cx, |editor, cx| {
 9681                project.update(cx, |project, cx| {
 9682                    let language_server_name =
 9683                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 9684                            project
 9685                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 9686                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 9687                        });
 9688                    language_server_name.map(|language_server_name| {
 9689                        project.open_local_buffer_via_lsp(
 9690                            lsp_location.uri.clone(),
 9691                            server_id,
 9692                            language_server_name,
 9693                            cx,
 9694                        )
 9695                    })
 9696                })
 9697            })?;
 9698            let location = match location_task {
 9699                Some(task) => Some({
 9700                    let target_buffer_handle = task.await.context("open local buffer")?;
 9701                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9702                        let target_start = target_buffer
 9703                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9704                        let target_end = target_buffer
 9705                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9706                        target_buffer.anchor_after(target_start)
 9707                            ..target_buffer.anchor_before(target_end)
 9708                    })?;
 9709                    Location {
 9710                        buffer: target_buffer_handle,
 9711                        range,
 9712                    }
 9713                }),
 9714                None => None,
 9715            };
 9716            Ok(location)
 9717        })
 9718    }
 9719
 9720    pub fn find_all_references(
 9721        &mut self,
 9722        _: &FindAllReferences,
 9723        cx: &mut ViewContext<Self>,
 9724    ) -> Option<Task<Result<Navigated>>> {
 9725        let multi_buffer = self.buffer.read(cx);
 9726        let selection = self.selections.newest::<usize>(cx);
 9727        let head = selection.head();
 9728
 9729        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9730        let head_anchor = multi_buffer_snapshot.anchor_at(
 9731            head,
 9732            if head < selection.tail() {
 9733                Bias::Right
 9734            } else {
 9735                Bias::Left
 9736            },
 9737        );
 9738
 9739        match self
 9740            .find_all_references_task_sources
 9741            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9742        {
 9743            Ok(_) => {
 9744                log::info!(
 9745                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9746                );
 9747                return None;
 9748            }
 9749            Err(i) => {
 9750                self.find_all_references_task_sources.insert(i, head_anchor);
 9751            }
 9752        }
 9753
 9754        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9755        let workspace = self.workspace()?;
 9756        let project = workspace.read(cx).project().clone();
 9757        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9758        Some(cx.spawn(|editor, mut cx| async move {
 9759            let _cleanup = defer({
 9760                let mut cx = cx.clone();
 9761                move || {
 9762                    let _ = editor.update(&mut cx, |editor, _| {
 9763                        if let Ok(i) =
 9764                            editor
 9765                                .find_all_references_task_sources
 9766                                .binary_search_by(|anchor| {
 9767                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9768                                })
 9769                        {
 9770                            editor.find_all_references_task_sources.remove(i);
 9771                        }
 9772                    });
 9773                }
 9774            });
 9775
 9776            let locations = references.await?;
 9777            if locations.is_empty() {
 9778                return anyhow::Ok(Navigated::No);
 9779            }
 9780
 9781            workspace.update(&mut cx, |workspace, cx| {
 9782                let title = locations
 9783                    .first()
 9784                    .as_ref()
 9785                    .map(|location| {
 9786                        let buffer = location.buffer.read(cx);
 9787                        format!(
 9788                            "References to `{}`",
 9789                            buffer
 9790                                .text_for_range(location.range.clone())
 9791                                .collect::<String>()
 9792                        )
 9793                    })
 9794                    .unwrap();
 9795                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9796                Navigated::Yes
 9797            })
 9798        }))
 9799    }
 9800
 9801    /// Opens a multibuffer with the given project locations in it
 9802    pub fn open_locations_in_multibuffer(
 9803        workspace: &mut Workspace,
 9804        mut locations: Vec<Location>,
 9805        title: String,
 9806        split: bool,
 9807        cx: &mut ViewContext<Workspace>,
 9808    ) {
 9809        // If there are multiple definitions, open them in a multibuffer
 9810        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9811        let mut locations = locations.into_iter().peekable();
 9812        let mut ranges_to_highlight = Vec::new();
 9813        let capability = workspace.project().read(cx).capability();
 9814
 9815        let excerpt_buffer = cx.new_model(|cx| {
 9816            let mut multibuffer = MultiBuffer::new(capability);
 9817            while let Some(location) = locations.next() {
 9818                let buffer = location.buffer.read(cx);
 9819                let mut ranges_for_buffer = Vec::new();
 9820                let range = location.range.to_offset(buffer);
 9821                ranges_for_buffer.push(range.clone());
 9822
 9823                while let Some(next_location) = locations.peek() {
 9824                    if next_location.buffer == location.buffer {
 9825                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9826                        locations.next();
 9827                    } else {
 9828                        break;
 9829                    }
 9830                }
 9831
 9832                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9833                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9834                    location.buffer.clone(),
 9835                    ranges_for_buffer,
 9836                    DEFAULT_MULTIBUFFER_CONTEXT,
 9837                    cx,
 9838                ))
 9839            }
 9840
 9841            multibuffer.with_title(title)
 9842        });
 9843
 9844        let editor = cx.new_view(|cx| {
 9845            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9846        });
 9847        editor.update(cx, |editor, cx| {
 9848            if let Some(first_range) = ranges_to_highlight.first() {
 9849                editor.change_selections(None, cx, |selections| {
 9850                    selections.clear_disjoint();
 9851                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9852                });
 9853            }
 9854            editor.highlight_background::<Self>(
 9855                &ranges_to_highlight,
 9856                |theme| theme.editor_highlighted_line_background,
 9857                cx,
 9858            );
 9859        });
 9860
 9861        let item = Box::new(editor);
 9862        let item_id = item.item_id();
 9863
 9864        if split {
 9865            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9866        } else {
 9867            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9868                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9869                    pane.close_current_preview_item(cx)
 9870                } else {
 9871                    None
 9872                }
 9873            });
 9874            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9875        }
 9876        workspace.active_pane().update(cx, |pane, cx| {
 9877            pane.set_preview_item_id(Some(item_id), cx);
 9878        });
 9879    }
 9880
 9881    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9882        use language::ToOffset as _;
 9883
 9884        let project = self.project.clone()?;
 9885        let selection = self.selections.newest_anchor().clone();
 9886        let (cursor_buffer, cursor_buffer_position) = self
 9887            .buffer
 9888            .read(cx)
 9889            .text_anchor_for_position(selection.head(), cx)?;
 9890        let (tail_buffer, cursor_buffer_position_end) = self
 9891            .buffer
 9892            .read(cx)
 9893            .text_anchor_for_position(selection.tail(), cx)?;
 9894        if tail_buffer != cursor_buffer {
 9895            return None;
 9896        }
 9897
 9898        let snapshot = cursor_buffer.read(cx).snapshot();
 9899        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9900        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9901        let prepare_rename = project.update(cx, |project, cx| {
 9902            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
 9903        });
 9904        drop(snapshot);
 9905
 9906        Some(cx.spawn(|this, mut cx| async move {
 9907            let rename_range = if let Some(range) = prepare_rename.await? {
 9908                Some(range)
 9909            } else {
 9910                this.update(&mut cx, |this, cx| {
 9911                    let buffer = this.buffer.read(cx).snapshot(cx);
 9912                    let mut buffer_highlights = this
 9913                        .document_highlights_for_position(selection.head(), &buffer)
 9914                        .filter(|highlight| {
 9915                            highlight.start.excerpt_id == selection.head().excerpt_id
 9916                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9917                        });
 9918                    buffer_highlights
 9919                        .next()
 9920                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9921                })?
 9922            };
 9923            if let Some(rename_range) = rename_range {
 9924                this.update(&mut cx, |this, cx| {
 9925                    let snapshot = cursor_buffer.read(cx).snapshot();
 9926                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9927                    let cursor_offset_in_rename_range =
 9928                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9929                    let cursor_offset_in_rename_range_end =
 9930                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9931
 9932                    this.take_rename(false, cx);
 9933                    let buffer = this.buffer.read(cx).read(cx);
 9934                    let cursor_offset = selection.head().to_offset(&buffer);
 9935                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9936                    let rename_end = rename_start + rename_buffer_range.len();
 9937                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9938                    let mut old_highlight_id = None;
 9939                    let old_name: Arc<str> = buffer
 9940                        .chunks(rename_start..rename_end, true)
 9941                        .map(|chunk| {
 9942                            if old_highlight_id.is_none() {
 9943                                old_highlight_id = chunk.syntax_highlight_id;
 9944                            }
 9945                            chunk.text
 9946                        })
 9947                        .collect::<String>()
 9948                        .into();
 9949
 9950                    drop(buffer);
 9951
 9952                    // Position the selection in the rename editor so that it matches the current selection.
 9953                    this.show_local_selections = false;
 9954                    let rename_editor = cx.new_view(|cx| {
 9955                        let mut editor = Editor::single_line(cx);
 9956                        editor.buffer.update(cx, |buffer, cx| {
 9957                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9958                        });
 9959                        let rename_selection_range = match cursor_offset_in_rename_range
 9960                            .cmp(&cursor_offset_in_rename_range_end)
 9961                        {
 9962                            Ordering::Equal => {
 9963                                editor.select_all(&SelectAll, cx);
 9964                                return editor;
 9965                            }
 9966                            Ordering::Less => {
 9967                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9968                            }
 9969                            Ordering::Greater => {
 9970                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9971                            }
 9972                        };
 9973                        if rename_selection_range.end > old_name.len() {
 9974                            editor.select_all(&SelectAll, cx);
 9975                        } else {
 9976                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9977                                s.select_ranges([rename_selection_range]);
 9978                            });
 9979                        }
 9980                        editor
 9981                    });
 9982                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
 9983                        if e == &EditorEvent::Focused {
 9984                            cx.emit(EditorEvent::FocusedIn)
 9985                        }
 9986                    })
 9987                    .detach();
 9988
 9989                    let write_highlights =
 9990                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9991                    let read_highlights =
 9992                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9993                    let ranges = write_highlights
 9994                        .iter()
 9995                        .flat_map(|(_, ranges)| ranges.iter())
 9996                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9997                        .cloned()
 9998                        .collect();
 9999
10000                    this.highlight_text::<Rename>(
10001                        ranges,
10002                        HighlightStyle {
10003                            fade_out: Some(0.6),
10004                            ..Default::default()
10005                        },
10006                        cx,
10007                    );
10008                    let rename_focus_handle = rename_editor.focus_handle(cx);
10009                    cx.focus(&rename_focus_handle);
10010                    let block_id = this.insert_blocks(
10011                        [BlockProperties {
10012                            style: BlockStyle::Flex,
10013                            position: range.start,
10014                            height: 1,
10015                            render: Box::new({
10016                                let rename_editor = rename_editor.clone();
10017                                move |cx: &mut BlockContext| {
10018                                    let mut text_style = cx.editor_style.text.clone();
10019                                    if let Some(highlight_style) = old_highlight_id
10020                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10021                                    {
10022                                        text_style = text_style.highlight(highlight_style);
10023                                    }
10024                                    div()
10025                                        .pl(cx.anchor_x)
10026                                        .child(EditorElement::new(
10027                                            &rename_editor,
10028                                            EditorStyle {
10029                                                background: cx.theme().system().transparent,
10030                                                local_player: cx.editor_style.local_player,
10031                                                text: text_style,
10032                                                scrollbar_width: cx.editor_style.scrollbar_width,
10033                                                syntax: cx.editor_style.syntax.clone(),
10034                                                status: cx.editor_style.status.clone(),
10035                                                inlay_hints_style: HighlightStyle {
10036                                                    font_weight: Some(FontWeight::BOLD),
10037                                                    ..make_inlay_hints_style(cx)
10038                                                },
10039                                                suggestions_style: HighlightStyle {
10040                                                    color: Some(cx.theme().status().predictive),
10041                                                    ..HighlightStyle::default()
10042                                                },
10043                                                ..EditorStyle::default()
10044                                            },
10045                                        ))
10046                                        .into_any_element()
10047                                }
10048                            }),
10049                            disposition: BlockDisposition::Below,
10050                            priority: 0,
10051                        }],
10052                        Some(Autoscroll::fit()),
10053                        cx,
10054                    )[0];
10055                    this.pending_rename = Some(RenameState {
10056                        range,
10057                        old_name,
10058                        editor: rename_editor,
10059                        block_id,
10060                    });
10061                })?;
10062            }
10063
10064            Ok(())
10065        }))
10066    }
10067
10068    pub fn confirm_rename(
10069        &mut self,
10070        _: &ConfirmRename,
10071        cx: &mut ViewContext<Self>,
10072    ) -> Option<Task<Result<()>>> {
10073        let rename = self.take_rename(false, cx)?;
10074        let workspace = self.workspace()?;
10075        let (start_buffer, start) = self
10076            .buffer
10077            .read(cx)
10078            .text_anchor_for_position(rename.range.start, cx)?;
10079        let (end_buffer, end) = self
10080            .buffer
10081            .read(cx)
10082            .text_anchor_for_position(rename.range.end, cx)?;
10083        if start_buffer != end_buffer {
10084            return None;
10085        }
10086
10087        let buffer = start_buffer;
10088        let range = start..end;
10089        let old_name = rename.old_name;
10090        let new_name = rename.editor.read(cx).text(cx);
10091
10092        let rename = workspace
10093            .read(cx)
10094            .project()
10095            .clone()
10096            .update(cx, |project, cx| {
10097                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
10098            });
10099        let workspace = workspace.downgrade();
10100
10101        Some(cx.spawn(|editor, mut cx| async move {
10102            let project_transaction = rename.await?;
10103            Self::open_project_transaction(
10104                &editor,
10105                workspace,
10106                project_transaction,
10107                format!("Rename: {}{}", old_name, new_name),
10108                cx.clone(),
10109            )
10110            .await?;
10111
10112            editor.update(&mut cx, |editor, cx| {
10113                editor.refresh_document_highlights(cx);
10114            })?;
10115            Ok(())
10116        }))
10117    }
10118
10119    fn take_rename(
10120        &mut self,
10121        moving_cursor: bool,
10122        cx: &mut ViewContext<Self>,
10123    ) -> Option<RenameState> {
10124        let rename = self.pending_rename.take()?;
10125        if rename.editor.focus_handle(cx).is_focused(cx) {
10126            cx.focus(&self.focus_handle);
10127        }
10128
10129        self.remove_blocks(
10130            [rename.block_id].into_iter().collect(),
10131            Some(Autoscroll::fit()),
10132            cx,
10133        );
10134        self.clear_highlights::<Rename>(cx);
10135        self.show_local_selections = true;
10136
10137        if moving_cursor {
10138            let rename_editor = rename.editor.read(cx);
10139            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10140
10141            // Update the selection to match the position of the selection inside
10142            // the rename editor.
10143            let snapshot = self.buffer.read(cx).read(cx);
10144            let rename_range = rename.range.to_offset(&snapshot);
10145            let cursor_in_editor = snapshot
10146                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10147                .min(rename_range.end);
10148            drop(snapshot);
10149
10150            self.change_selections(None, cx, |s| {
10151                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10152            });
10153        } else {
10154            self.refresh_document_highlights(cx);
10155        }
10156
10157        Some(rename)
10158    }
10159
10160    pub fn pending_rename(&self) -> Option<&RenameState> {
10161        self.pending_rename.as_ref()
10162    }
10163
10164    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10165        let project = match &self.project {
10166            Some(project) => project.clone(),
10167            None => return None,
10168        };
10169
10170        Some(self.perform_format(project, FormatTrigger::Manual, cx))
10171    }
10172
10173    fn perform_format(
10174        &mut self,
10175        project: Model<Project>,
10176        trigger: FormatTrigger,
10177        cx: &mut ViewContext<Self>,
10178    ) -> Task<Result<()>> {
10179        let buffer = self.buffer().clone();
10180        let mut buffers = buffer.read(cx).all_buffers();
10181        if trigger == FormatTrigger::Save {
10182            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10183        }
10184
10185        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10186        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
10187
10188        cx.spawn(|_, mut cx| async move {
10189            let transaction = futures::select_biased! {
10190                () = timeout => {
10191                    log::warn!("timed out waiting for formatting");
10192                    None
10193                }
10194                transaction = format.log_err().fuse() => transaction,
10195            };
10196
10197            buffer
10198                .update(&mut cx, |buffer, cx| {
10199                    if let Some(transaction) = transaction {
10200                        if !buffer.is_singleton() {
10201                            buffer.push_transaction(&transaction.0, cx);
10202                        }
10203                    }
10204
10205                    cx.notify();
10206                })
10207                .ok();
10208
10209            Ok(())
10210        })
10211    }
10212
10213    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10214        if let Some(project) = self.project.clone() {
10215            self.buffer.update(cx, |multi_buffer, cx| {
10216                project.update(cx, |project, cx| {
10217                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10218                });
10219            })
10220        }
10221    }
10222
10223    fn cancel_language_server_work(
10224        &mut self,
10225        _: &CancelLanguageServerWork,
10226        cx: &mut ViewContext<Self>,
10227    ) {
10228        if let Some(project) = self.project.clone() {
10229            self.buffer.update(cx, |multi_buffer, cx| {
10230                project.update(cx, |project, cx| {
10231                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10232                });
10233            })
10234        }
10235    }
10236
10237    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10238        cx.show_character_palette();
10239    }
10240
10241    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10242        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10243            let buffer = self.buffer.read(cx).snapshot(cx);
10244            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10245            let is_valid = buffer
10246                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10247                .any(|entry| {
10248                    entry.diagnostic.is_primary
10249                        && !entry.range.is_empty()
10250                        && entry.range.start == primary_range_start
10251                        && entry.diagnostic.message == active_diagnostics.primary_message
10252                });
10253
10254            if is_valid != active_diagnostics.is_valid {
10255                active_diagnostics.is_valid = is_valid;
10256                let mut new_styles = HashMap::default();
10257                for (block_id, diagnostic) in &active_diagnostics.blocks {
10258                    new_styles.insert(
10259                        *block_id,
10260                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10261                    );
10262                }
10263                self.display_map.update(cx, |display_map, _cx| {
10264                    display_map.replace_blocks(new_styles)
10265                });
10266            }
10267        }
10268    }
10269
10270    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10271        self.dismiss_diagnostics(cx);
10272        let snapshot = self.snapshot(cx);
10273        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10274            let buffer = self.buffer.read(cx).snapshot(cx);
10275
10276            let mut primary_range = None;
10277            let mut primary_message = None;
10278            let mut group_end = Point::zero();
10279            let diagnostic_group = buffer
10280                .diagnostic_group::<MultiBufferPoint>(group_id)
10281                .filter_map(|entry| {
10282                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10283                        && (entry.range.start.row == entry.range.end.row
10284                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10285                    {
10286                        return None;
10287                    }
10288                    if entry.range.end > group_end {
10289                        group_end = entry.range.end;
10290                    }
10291                    if entry.diagnostic.is_primary {
10292                        primary_range = Some(entry.range.clone());
10293                        primary_message = Some(entry.diagnostic.message.clone());
10294                    }
10295                    Some(entry)
10296                })
10297                .collect::<Vec<_>>();
10298            let primary_range = primary_range?;
10299            let primary_message = primary_message?;
10300            let primary_range =
10301                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10302
10303            let blocks = display_map
10304                .insert_blocks(
10305                    diagnostic_group.iter().map(|entry| {
10306                        let diagnostic = entry.diagnostic.clone();
10307                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10308                        BlockProperties {
10309                            style: BlockStyle::Fixed,
10310                            position: buffer.anchor_after(entry.range.start),
10311                            height: message_height,
10312                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10313                            disposition: BlockDisposition::Below,
10314                            priority: 0,
10315                        }
10316                    }),
10317                    cx,
10318                )
10319                .into_iter()
10320                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10321                .collect();
10322
10323            Some(ActiveDiagnosticGroup {
10324                primary_range,
10325                primary_message,
10326                group_id,
10327                blocks,
10328                is_valid: true,
10329            })
10330        });
10331        self.active_diagnostics.is_some()
10332    }
10333
10334    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10335        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10336            self.display_map.update(cx, |display_map, cx| {
10337                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10338            });
10339            cx.notify();
10340        }
10341    }
10342
10343    pub fn set_selections_from_remote(
10344        &mut self,
10345        selections: Vec<Selection<Anchor>>,
10346        pending_selection: Option<Selection<Anchor>>,
10347        cx: &mut ViewContext<Self>,
10348    ) {
10349        let old_cursor_position = self.selections.newest_anchor().head();
10350        self.selections.change_with(cx, |s| {
10351            s.select_anchors(selections);
10352            if let Some(pending_selection) = pending_selection {
10353                s.set_pending(pending_selection, SelectMode::Character);
10354            } else {
10355                s.clear_pending();
10356            }
10357        });
10358        self.selections_did_change(false, &old_cursor_position, true, cx);
10359    }
10360
10361    fn push_to_selection_history(&mut self) {
10362        self.selection_history.push(SelectionHistoryEntry {
10363            selections: self.selections.disjoint_anchors(),
10364            select_next_state: self.select_next_state.clone(),
10365            select_prev_state: self.select_prev_state.clone(),
10366            add_selections_state: self.add_selections_state.clone(),
10367        });
10368    }
10369
10370    pub fn transact(
10371        &mut self,
10372        cx: &mut ViewContext<Self>,
10373        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10374    ) -> Option<TransactionId> {
10375        self.start_transaction_at(Instant::now(), cx);
10376        update(self, cx);
10377        self.end_transaction_at(Instant::now(), cx)
10378    }
10379
10380    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10381        self.end_selection(cx);
10382        if let Some(tx_id) = self
10383            .buffer
10384            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10385        {
10386            self.selection_history
10387                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10388            cx.emit(EditorEvent::TransactionBegun {
10389                transaction_id: tx_id,
10390            })
10391        }
10392    }
10393
10394    fn end_transaction_at(
10395        &mut self,
10396        now: Instant,
10397        cx: &mut ViewContext<Self>,
10398    ) -> Option<TransactionId> {
10399        if let Some(transaction_id) = self
10400            .buffer
10401            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10402        {
10403            if let Some((_, end_selections)) =
10404                self.selection_history.transaction_mut(transaction_id)
10405            {
10406                *end_selections = Some(self.selections.disjoint_anchors());
10407            } else {
10408                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10409            }
10410
10411            cx.emit(EditorEvent::Edited { transaction_id });
10412            Some(transaction_id)
10413        } else {
10414            None
10415        }
10416    }
10417
10418    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10419        let mut fold_ranges = Vec::new();
10420
10421        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10422
10423        let selections = self.selections.all_adjusted(cx);
10424        for selection in selections {
10425            let range = selection.range().sorted();
10426            let buffer_start_row = range.start.row;
10427
10428            for row in (0..=range.end.row).rev() {
10429                if let Some((foldable_range, fold_text)) =
10430                    display_map.foldable_range(MultiBufferRow(row))
10431                {
10432                    if foldable_range.end.row >= buffer_start_row {
10433                        fold_ranges.push((foldable_range, fold_text));
10434                        if row <= range.start.row {
10435                            break;
10436                        }
10437                    }
10438                }
10439            }
10440        }
10441
10442        self.fold_ranges(fold_ranges, true, cx);
10443    }
10444
10445    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10446        let buffer_row = fold_at.buffer_row;
10447        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10448
10449        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10450            let autoscroll = self
10451                .selections
10452                .all::<Point>(cx)
10453                .iter()
10454                .any(|selection| fold_range.overlaps(&selection.range()));
10455
10456            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10457        }
10458    }
10459
10460    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10461        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10462        let buffer = &display_map.buffer_snapshot;
10463        let selections = self.selections.all::<Point>(cx);
10464        let ranges = selections
10465            .iter()
10466            .map(|s| {
10467                let range = s.display_range(&display_map).sorted();
10468                let mut start = range.start.to_point(&display_map);
10469                let mut end = range.end.to_point(&display_map);
10470                start.column = 0;
10471                end.column = buffer.line_len(MultiBufferRow(end.row));
10472                start..end
10473            })
10474            .collect::<Vec<_>>();
10475
10476        self.unfold_ranges(ranges, true, true, cx);
10477    }
10478
10479    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10480        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10481
10482        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10483            ..Point::new(
10484                unfold_at.buffer_row.0,
10485                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10486            );
10487
10488        let autoscroll = self
10489            .selections
10490            .all::<Point>(cx)
10491            .iter()
10492            .any(|selection| selection.range().overlaps(&intersection_range));
10493
10494        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10495    }
10496
10497    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10498        let selections = self.selections.all::<Point>(cx);
10499        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10500        let line_mode = self.selections.line_mode;
10501        let ranges = selections.into_iter().map(|s| {
10502            if line_mode {
10503                let start = Point::new(s.start.row, 0);
10504                let end = Point::new(
10505                    s.end.row,
10506                    display_map
10507                        .buffer_snapshot
10508                        .line_len(MultiBufferRow(s.end.row)),
10509                );
10510                (start..end, display_map.fold_placeholder.clone())
10511            } else {
10512                (s.start..s.end, display_map.fold_placeholder.clone())
10513            }
10514        });
10515        self.fold_ranges(ranges, true, cx);
10516    }
10517
10518    pub fn fold_ranges<T: ToOffset + Clone>(
10519        &mut self,
10520        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10521        auto_scroll: bool,
10522        cx: &mut ViewContext<Self>,
10523    ) {
10524        let mut fold_ranges = Vec::new();
10525        let mut buffers_affected = HashMap::default();
10526        let multi_buffer = self.buffer().read(cx);
10527        for (fold_range, fold_text) in ranges {
10528            if let Some((_, buffer, _)) =
10529                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10530            {
10531                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10532            };
10533            fold_ranges.push((fold_range, fold_text));
10534        }
10535
10536        let mut ranges = fold_ranges.into_iter().peekable();
10537        if ranges.peek().is_some() {
10538            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10539
10540            if auto_scroll {
10541                self.request_autoscroll(Autoscroll::fit(), cx);
10542            }
10543
10544            for buffer in buffers_affected.into_values() {
10545                self.sync_expanded_diff_hunks(buffer, cx);
10546            }
10547
10548            cx.notify();
10549
10550            if let Some(active_diagnostics) = self.active_diagnostics.take() {
10551                // Clear diagnostics block when folding a range that contains it.
10552                let snapshot = self.snapshot(cx);
10553                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10554                    drop(snapshot);
10555                    self.active_diagnostics = Some(active_diagnostics);
10556                    self.dismiss_diagnostics(cx);
10557                } else {
10558                    self.active_diagnostics = Some(active_diagnostics);
10559                }
10560            }
10561
10562            self.scrollbar_marker_state.dirty = true;
10563        }
10564    }
10565
10566    pub fn unfold_ranges<T: ToOffset + Clone>(
10567        &mut self,
10568        ranges: impl IntoIterator<Item = Range<T>>,
10569        inclusive: bool,
10570        auto_scroll: bool,
10571        cx: &mut ViewContext<Self>,
10572    ) {
10573        let mut unfold_ranges = Vec::new();
10574        let mut buffers_affected = HashMap::default();
10575        let multi_buffer = self.buffer().read(cx);
10576        for range in ranges {
10577            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10578                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10579            };
10580            unfold_ranges.push(range);
10581        }
10582
10583        let mut ranges = unfold_ranges.into_iter().peekable();
10584        if ranges.peek().is_some() {
10585            self.display_map
10586                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10587            if auto_scroll {
10588                self.request_autoscroll(Autoscroll::fit(), cx);
10589            }
10590
10591            for buffer in buffers_affected.into_values() {
10592                self.sync_expanded_diff_hunks(buffer, cx);
10593            }
10594
10595            cx.notify();
10596            self.scrollbar_marker_state.dirty = true;
10597            self.active_indent_guides_state.dirty = true;
10598        }
10599    }
10600
10601    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10602        self.display_map.read(cx).fold_placeholder.clone()
10603    }
10604
10605    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10606        if hovered != self.gutter_hovered {
10607            self.gutter_hovered = hovered;
10608            cx.notify();
10609        }
10610    }
10611
10612    pub fn insert_blocks(
10613        &mut self,
10614        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10615        autoscroll: Option<Autoscroll>,
10616        cx: &mut ViewContext<Self>,
10617    ) -> Vec<CustomBlockId> {
10618        let blocks = self
10619            .display_map
10620            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10621        if let Some(autoscroll) = autoscroll {
10622            self.request_autoscroll(autoscroll, cx);
10623        }
10624        cx.notify();
10625        blocks
10626    }
10627
10628    pub fn resize_blocks(
10629        &mut self,
10630        heights: HashMap<CustomBlockId, u32>,
10631        autoscroll: Option<Autoscroll>,
10632        cx: &mut ViewContext<Self>,
10633    ) {
10634        self.display_map
10635            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10636        if let Some(autoscroll) = autoscroll {
10637            self.request_autoscroll(autoscroll, cx);
10638        }
10639        cx.notify();
10640    }
10641
10642    pub fn replace_blocks(
10643        &mut self,
10644        renderers: HashMap<CustomBlockId, RenderBlock>,
10645        autoscroll: Option<Autoscroll>,
10646        cx: &mut ViewContext<Self>,
10647    ) {
10648        self.display_map
10649            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10650        if let Some(autoscroll) = autoscroll {
10651            self.request_autoscroll(autoscroll, cx);
10652        }
10653        cx.notify();
10654    }
10655
10656    pub fn remove_blocks(
10657        &mut self,
10658        block_ids: HashSet<CustomBlockId>,
10659        autoscroll: Option<Autoscroll>,
10660        cx: &mut ViewContext<Self>,
10661    ) {
10662        self.display_map.update(cx, |display_map, cx| {
10663            display_map.remove_blocks(block_ids, cx)
10664        });
10665        if let Some(autoscroll) = autoscroll {
10666            self.request_autoscroll(autoscroll, cx);
10667        }
10668        cx.notify();
10669    }
10670
10671    pub fn row_for_block(
10672        &self,
10673        block_id: CustomBlockId,
10674        cx: &mut ViewContext<Self>,
10675    ) -> Option<DisplayRow> {
10676        self.display_map
10677            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10678    }
10679
10680    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10681        self.focused_block = Some(focused_block);
10682    }
10683
10684    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10685        self.focused_block.take()
10686    }
10687
10688    pub fn insert_creases(
10689        &mut self,
10690        creases: impl IntoIterator<Item = Crease>,
10691        cx: &mut ViewContext<Self>,
10692    ) -> Vec<CreaseId> {
10693        self.display_map
10694            .update(cx, |map, cx| map.insert_creases(creases, cx))
10695    }
10696
10697    pub fn remove_creases(
10698        &mut self,
10699        ids: impl IntoIterator<Item = CreaseId>,
10700        cx: &mut ViewContext<Self>,
10701    ) {
10702        self.display_map
10703            .update(cx, |map, cx| map.remove_creases(ids, cx));
10704    }
10705
10706    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10707        self.display_map
10708            .update(cx, |map, cx| map.snapshot(cx))
10709            .longest_row()
10710    }
10711
10712    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10713        self.display_map
10714            .update(cx, |map, cx| map.snapshot(cx))
10715            .max_point()
10716    }
10717
10718    pub fn text(&self, cx: &AppContext) -> String {
10719        self.buffer.read(cx).read(cx).text()
10720    }
10721
10722    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10723        let text = self.text(cx);
10724        let text = text.trim();
10725
10726        if text.is_empty() {
10727            return None;
10728        }
10729
10730        Some(text.to_string())
10731    }
10732
10733    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10734        self.transact(cx, |this, cx| {
10735            this.buffer
10736                .read(cx)
10737                .as_singleton()
10738                .expect("you can only call set_text on editors for singleton buffers")
10739                .update(cx, |buffer, cx| buffer.set_text(text, cx));
10740        });
10741    }
10742
10743    pub fn display_text(&self, cx: &mut AppContext) -> String {
10744        self.display_map
10745            .update(cx, |map, cx| map.snapshot(cx))
10746            .text()
10747    }
10748
10749    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10750        let mut wrap_guides = smallvec::smallvec![];
10751
10752        if self.show_wrap_guides == Some(false) {
10753            return wrap_guides;
10754        }
10755
10756        let settings = self.buffer.read(cx).settings_at(0, cx);
10757        if settings.show_wrap_guides {
10758            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10759                wrap_guides.push((soft_wrap as usize, true));
10760            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10761                wrap_guides.push((soft_wrap as usize, true));
10762            }
10763            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10764        }
10765
10766        wrap_guides
10767    }
10768
10769    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10770        let settings = self.buffer.read(cx).settings_at(0, cx);
10771        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
10772        match mode {
10773            language_settings::SoftWrap::None => SoftWrap::None,
10774            language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10775            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10776            language_settings::SoftWrap::PreferredLineLength => {
10777                SoftWrap::Column(settings.preferred_line_length)
10778            }
10779            language_settings::SoftWrap::Bounded => {
10780                SoftWrap::Bounded(settings.preferred_line_length)
10781            }
10782        }
10783    }
10784
10785    pub fn set_soft_wrap_mode(
10786        &mut self,
10787        mode: language_settings::SoftWrap,
10788        cx: &mut ViewContext<Self>,
10789    ) {
10790        self.soft_wrap_mode_override = Some(mode);
10791        cx.notify();
10792    }
10793
10794    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10795        let rem_size = cx.rem_size();
10796        self.display_map.update(cx, |map, cx| {
10797            map.set_font(
10798                style.text.font(),
10799                style.text.font_size.to_pixels(rem_size),
10800                cx,
10801            )
10802        });
10803        self.style = Some(style);
10804    }
10805
10806    pub fn style(&self) -> Option<&EditorStyle> {
10807        self.style.as_ref()
10808    }
10809
10810    // Called by the element. This method is not designed to be called outside of the editor
10811    // element's layout code because it does not notify when rewrapping is computed synchronously.
10812    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10813        self.display_map
10814            .update(cx, |map, cx| map.set_wrap_width(width, cx))
10815    }
10816
10817    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10818        if self.soft_wrap_mode_override.is_some() {
10819            self.soft_wrap_mode_override.take();
10820        } else {
10821            let soft_wrap = match self.soft_wrap_mode(cx) {
10822                SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10823                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10824                    language_settings::SoftWrap::PreferLine
10825                }
10826            };
10827            self.soft_wrap_mode_override = Some(soft_wrap);
10828        }
10829        cx.notify();
10830    }
10831
10832    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10833        let Some(workspace) = self.workspace() else {
10834            return;
10835        };
10836        let fs = workspace.read(cx).app_state().fs.clone();
10837        let current_show = TabBarSettings::get_global(cx).show;
10838        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10839            setting.show = Some(!current_show);
10840        });
10841    }
10842
10843    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10844        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10845            self.buffer
10846                .read(cx)
10847                .settings_at(0, cx)
10848                .indent_guides
10849                .enabled
10850        });
10851        self.show_indent_guides = Some(!currently_enabled);
10852        cx.notify();
10853    }
10854
10855    fn should_show_indent_guides(&self) -> Option<bool> {
10856        self.show_indent_guides
10857    }
10858
10859    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10860        let mut editor_settings = EditorSettings::get_global(cx).clone();
10861        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10862        EditorSettings::override_global(editor_settings, cx);
10863    }
10864
10865    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10866        self.use_relative_line_numbers
10867            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10868    }
10869
10870    pub fn toggle_relative_line_numbers(
10871        &mut self,
10872        _: &ToggleRelativeLineNumbers,
10873        cx: &mut ViewContext<Self>,
10874    ) {
10875        let is_relative = self.should_use_relative_line_numbers(cx);
10876        self.set_relative_line_number(Some(!is_relative), cx)
10877    }
10878
10879    pub fn set_relative_line_number(
10880        &mut self,
10881        is_relative: Option<bool>,
10882        cx: &mut ViewContext<Self>,
10883    ) {
10884        self.use_relative_line_numbers = is_relative;
10885        cx.notify();
10886    }
10887
10888    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10889        self.show_gutter = show_gutter;
10890        cx.notify();
10891    }
10892
10893    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10894        self.show_line_numbers = Some(show_line_numbers);
10895        cx.notify();
10896    }
10897
10898    pub fn set_show_git_diff_gutter(
10899        &mut self,
10900        show_git_diff_gutter: bool,
10901        cx: &mut ViewContext<Self>,
10902    ) {
10903        self.show_git_diff_gutter = Some(show_git_diff_gutter);
10904        cx.notify();
10905    }
10906
10907    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10908        self.show_code_actions = Some(show_code_actions);
10909        cx.notify();
10910    }
10911
10912    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10913        self.show_runnables = Some(show_runnables);
10914        cx.notify();
10915    }
10916
10917    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10918        if self.display_map.read(cx).masked != masked {
10919            self.display_map.update(cx, |map, _| map.masked = masked);
10920        }
10921        cx.notify()
10922    }
10923
10924    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10925        self.show_wrap_guides = Some(show_wrap_guides);
10926        cx.notify();
10927    }
10928
10929    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10930        self.show_indent_guides = Some(show_indent_guides);
10931        cx.notify();
10932    }
10933
10934    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10935        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10936            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10937                if let Some(dir) = file.abs_path(cx).parent() {
10938                    return Some(dir.to_owned());
10939                }
10940            }
10941
10942            if let Some(project_path) = buffer.read(cx).project_path(cx) {
10943                return Some(project_path.path.to_path_buf());
10944            }
10945        }
10946
10947        None
10948    }
10949
10950    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10951        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10952            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10953                cx.reveal_path(&file.abs_path(cx));
10954            }
10955        }
10956    }
10957
10958    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10959        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10960            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10961                if let Some(path) = file.abs_path(cx).to_str() {
10962                    cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10963                }
10964            }
10965        }
10966    }
10967
10968    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10969        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10970            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10971                if let Some(path) = file.path().to_str() {
10972                    cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10973                }
10974            }
10975        }
10976    }
10977
10978    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10979        self.show_git_blame_gutter = !self.show_git_blame_gutter;
10980
10981        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10982            self.start_git_blame(true, cx);
10983        }
10984
10985        cx.notify();
10986    }
10987
10988    pub fn toggle_git_blame_inline(
10989        &mut self,
10990        _: &ToggleGitBlameInline,
10991        cx: &mut ViewContext<Self>,
10992    ) {
10993        self.toggle_git_blame_inline_internal(true, cx);
10994        cx.notify();
10995    }
10996
10997    pub fn git_blame_inline_enabled(&self) -> bool {
10998        self.git_blame_inline_enabled
10999    }
11000
11001    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11002        self.show_selection_menu = self
11003            .show_selection_menu
11004            .map(|show_selections_menu| !show_selections_menu)
11005            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11006
11007        cx.notify();
11008    }
11009
11010    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11011        self.show_selection_menu
11012            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11013    }
11014
11015    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11016        if let Some(project) = self.project.as_ref() {
11017            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11018                return;
11019            };
11020
11021            if buffer.read(cx).file().is_none() {
11022                return;
11023            }
11024
11025            let focused = self.focus_handle(cx).contains_focused(cx);
11026
11027            let project = project.clone();
11028            let blame =
11029                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11030            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11031            self.blame = Some(blame);
11032        }
11033    }
11034
11035    fn toggle_git_blame_inline_internal(
11036        &mut self,
11037        user_triggered: bool,
11038        cx: &mut ViewContext<Self>,
11039    ) {
11040        if self.git_blame_inline_enabled {
11041            self.git_blame_inline_enabled = false;
11042            self.show_git_blame_inline = false;
11043            self.show_git_blame_inline_delay_task.take();
11044        } else {
11045            self.git_blame_inline_enabled = true;
11046            self.start_git_blame_inline(user_triggered, cx);
11047        }
11048
11049        cx.notify();
11050    }
11051
11052    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11053        self.start_git_blame(user_triggered, cx);
11054
11055        if ProjectSettings::get_global(cx)
11056            .git
11057            .inline_blame_delay()
11058            .is_some()
11059        {
11060            self.start_inline_blame_timer(cx);
11061        } else {
11062            self.show_git_blame_inline = true
11063        }
11064    }
11065
11066    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11067        self.blame.as_ref()
11068    }
11069
11070    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11071        self.show_git_blame_gutter && self.has_blame_entries(cx)
11072    }
11073
11074    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11075        self.show_git_blame_inline
11076            && self.focus_handle.is_focused(cx)
11077            && !self.newest_selection_head_on_empty_line(cx)
11078            && self.has_blame_entries(cx)
11079    }
11080
11081    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11082        self.blame()
11083            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11084    }
11085
11086    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11087        let cursor_anchor = self.selections.newest_anchor().head();
11088
11089        let snapshot = self.buffer.read(cx).snapshot(cx);
11090        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11091
11092        snapshot.line_len(buffer_row) == 0
11093    }
11094
11095    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
11096        let (path, selection, repo) = maybe!({
11097            let project_handle = self.project.as_ref()?.clone();
11098            let project = project_handle.read(cx);
11099
11100            let selection = self.selections.newest::<Point>(cx);
11101            let selection_range = selection.range();
11102
11103            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11104                (buffer, selection_range.start.row..selection_range.end.row)
11105            } else {
11106                let buffer_ranges = self
11107                    .buffer()
11108                    .read(cx)
11109                    .range_to_buffer_ranges(selection_range, cx);
11110
11111                let (buffer, range, _) = if selection.reversed {
11112                    buffer_ranges.first()
11113                } else {
11114                    buffer_ranges.last()
11115                }?;
11116
11117                let snapshot = buffer.read(cx).snapshot();
11118                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11119                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11120                (buffer.clone(), selection)
11121            };
11122
11123            let path = buffer
11124                .read(cx)
11125                .file()?
11126                .as_local()?
11127                .path()
11128                .to_str()?
11129                .to_string();
11130            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
11131            Some((path, selection, repo))
11132        })
11133        .ok_or_else(|| anyhow!("unable to open git repository"))?;
11134
11135        const REMOTE_NAME: &str = "origin";
11136        let origin_url = repo
11137            .remote_url(REMOTE_NAME)
11138            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
11139        let sha = repo
11140            .head_sha()
11141            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
11142
11143        let (provider, remote) =
11144            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
11145                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
11146
11147        Ok(provider.build_permalink(
11148            remote,
11149            BuildPermalinkParams {
11150                sha: &sha,
11151                path: &path,
11152                selection: Some(selection),
11153            },
11154        ))
11155    }
11156
11157    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11158        let permalink = self.get_permalink_to_line(cx);
11159
11160        match permalink {
11161            Ok(permalink) => {
11162                cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11163            }
11164            Err(err) => {
11165                let message = format!("Failed to copy permalink: {err}");
11166
11167                Err::<(), anyhow::Error>(err).log_err();
11168
11169                if let Some(workspace) = self.workspace() {
11170                    workspace.update(cx, |workspace, cx| {
11171                        struct CopyPermalinkToLine;
11172
11173                        workspace.show_toast(
11174                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
11175                            cx,
11176                        )
11177                    })
11178                }
11179            }
11180        }
11181    }
11182
11183    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11184        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11185            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11186                if let Some(path) = file.path().to_str() {
11187                    let selection = self.selections.newest::<Point>(cx).start.row + 1;
11188                    cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11189                }
11190            }
11191        }
11192    }
11193
11194    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11195        let permalink = self.get_permalink_to_line(cx);
11196
11197        match permalink {
11198            Ok(permalink) => {
11199                cx.open_url(permalink.as_ref());
11200            }
11201            Err(err) => {
11202                let message = format!("Failed to open permalink: {err}");
11203
11204                Err::<(), anyhow::Error>(err).log_err();
11205
11206                if let Some(workspace) = self.workspace() {
11207                    workspace.update(cx, |workspace, cx| {
11208                        struct OpenPermalinkToLine;
11209
11210                        workspace.show_toast(
11211                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11212                            cx,
11213                        )
11214                    })
11215                }
11216            }
11217        }
11218    }
11219
11220    /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
11221    /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
11222    /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
11223    pub fn highlight_rows<T: 'static>(
11224        &mut self,
11225        rows: RangeInclusive<Anchor>,
11226        color: Option<Hsla>,
11227        should_autoscroll: bool,
11228        cx: &mut ViewContext<Self>,
11229    ) {
11230        let snapshot = self.buffer().read(cx).snapshot(cx);
11231        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11232        let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
11233            highlight
11234                .range
11235                .start()
11236                .cmp(rows.start(), &snapshot)
11237                .then(highlight.range.end().cmp(rows.end(), &snapshot))
11238        });
11239        match (color, existing_highlight_index) {
11240            (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
11241                ix,
11242                RowHighlight {
11243                    index: post_inc(&mut self.highlight_order),
11244                    range: rows,
11245                    should_autoscroll,
11246                    color,
11247                },
11248            ),
11249            (None, Ok(i)) => {
11250                row_highlights.remove(i);
11251            }
11252        }
11253    }
11254
11255    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11256    pub fn clear_row_highlights<T: 'static>(&mut self) {
11257        self.highlighted_rows.remove(&TypeId::of::<T>());
11258    }
11259
11260    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11261    pub fn highlighted_rows<T: 'static>(
11262        &self,
11263    ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
11264        Some(
11265            self.highlighted_rows
11266                .get(&TypeId::of::<T>())?
11267                .iter()
11268                .map(|highlight| (&highlight.range, highlight.color.as_ref())),
11269        )
11270    }
11271
11272    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11273    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11274    /// Allows to ignore certain kinds of highlights.
11275    pub fn highlighted_display_rows(
11276        &mut self,
11277        cx: &mut WindowContext,
11278    ) -> BTreeMap<DisplayRow, Hsla> {
11279        let snapshot = self.snapshot(cx);
11280        let mut used_highlight_orders = HashMap::default();
11281        self.highlighted_rows
11282            .iter()
11283            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11284            .fold(
11285                BTreeMap::<DisplayRow, Hsla>::new(),
11286                |mut unique_rows, highlight| {
11287                    let start_row = highlight.range.start().to_display_point(&snapshot).row();
11288                    let end_row = highlight.range.end().to_display_point(&snapshot).row();
11289                    for row in start_row.0..=end_row.0 {
11290                        let used_index =
11291                            used_highlight_orders.entry(row).or_insert(highlight.index);
11292                        if highlight.index >= *used_index {
11293                            *used_index = highlight.index;
11294                            match highlight.color {
11295                                Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
11296                                None => unique_rows.remove(&DisplayRow(row)),
11297                            };
11298                        }
11299                    }
11300                    unique_rows
11301                },
11302            )
11303    }
11304
11305    pub fn highlighted_display_row_for_autoscroll(
11306        &self,
11307        snapshot: &DisplaySnapshot,
11308    ) -> Option<DisplayRow> {
11309        self.highlighted_rows
11310            .values()
11311            .flat_map(|highlighted_rows| highlighted_rows.iter())
11312            .filter_map(|highlight| {
11313                if highlight.color.is_none() || !highlight.should_autoscroll {
11314                    return None;
11315                }
11316                Some(highlight.range.start().to_display_point(snapshot).row())
11317            })
11318            .min()
11319    }
11320
11321    pub fn set_search_within_ranges(
11322        &mut self,
11323        ranges: &[Range<Anchor>],
11324        cx: &mut ViewContext<Self>,
11325    ) {
11326        self.highlight_background::<SearchWithinRange>(
11327            ranges,
11328            |colors| colors.editor_document_highlight_read_background,
11329            cx,
11330        )
11331    }
11332
11333    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11334        self.breadcrumb_header = Some(new_header);
11335    }
11336
11337    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11338        self.clear_background_highlights::<SearchWithinRange>(cx);
11339    }
11340
11341    pub fn highlight_background<T: 'static>(
11342        &mut self,
11343        ranges: &[Range<Anchor>],
11344        color_fetcher: fn(&ThemeColors) -> Hsla,
11345        cx: &mut ViewContext<Self>,
11346    ) {
11347        self.background_highlights
11348            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11349        self.scrollbar_marker_state.dirty = true;
11350        cx.notify();
11351    }
11352
11353    pub fn clear_background_highlights<T: 'static>(
11354        &mut self,
11355        cx: &mut ViewContext<Self>,
11356    ) -> Option<BackgroundHighlight> {
11357        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11358        if !text_highlights.1.is_empty() {
11359            self.scrollbar_marker_state.dirty = true;
11360            cx.notify();
11361        }
11362        Some(text_highlights)
11363    }
11364
11365    pub fn highlight_gutter<T: 'static>(
11366        &mut self,
11367        ranges: &[Range<Anchor>],
11368        color_fetcher: fn(&AppContext) -> Hsla,
11369        cx: &mut ViewContext<Self>,
11370    ) {
11371        self.gutter_highlights
11372            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11373        cx.notify();
11374    }
11375
11376    pub fn clear_gutter_highlights<T: 'static>(
11377        &mut self,
11378        cx: &mut ViewContext<Self>,
11379    ) -> Option<GutterHighlight> {
11380        cx.notify();
11381        self.gutter_highlights.remove(&TypeId::of::<T>())
11382    }
11383
11384    #[cfg(feature = "test-support")]
11385    pub fn all_text_background_highlights(
11386        &mut self,
11387        cx: &mut ViewContext<Self>,
11388    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11389        let snapshot = self.snapshot(cx);
11390        let buffer = &snapshot.buffer_snapshot;
11391        let start = buffer.anchor_before(0);
11392        let end = buffer.anchor_after(buffer.len());
11393        let theme = cx.theme().colors();
11394        self.background_highlights_in_range(start..end, &snapshot, theme)
11395    }
11396
11397    #[cfg(feature = "test-support")]
11398    pub fn search_background_highlights(
11399        &mut self,
11400        cx: &mut ViewContext<Self>,
11401    ) -> Vec<Range<Point>> {
11402        let snapshot = self.buffer().read(cx).snapshot(cx);
11403
11404        let highlights = self
11405            .background_highlights
11406            .get(&TypeId::of::<items::BufferSearchHighlights>());
11407
11408        if let Some((_color, ranges)) = highlights {
11409            ranges
11410                .iter()
11411                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11412                .collect_vec()
11413        } else {
11414            vec![]
11415        }
11416    }
11417
11418    fn document_highlights_for_position<'a>(
11419        &'a self,
11420        position: Anchor,
11421        buffer: &'a MultiBufferSnapshot,
11422    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
11423        let read_highlights = self
11424            .background_highlights
11425            .get(&TypeId::of::<DocumentHighlightRead>())
11426            .map(|h| &h.1);
11427        let write_highlights = self
11428            .background_highlights
11429            .get(&TypeId::of::<DocumentHighlightWrite>())
11430            .map(|h| &h.1);
11431        let left_position = position.bias_left(buffer);
11432        let right_position = position.bias_right(buffer);
11433        read_highlights
11434            .into_iter()
11435            .chain(write_highlights)
11436            .flat_map(move |ranges| {
11437                let start_ix = match ranges.binary_search_by(|probe| {
11438                    let cmp = probe.end.cmp(&left_position, buffer);
11439                    if cmp.is_ge() {
11440                        Ordering::Greater
11441                    } else {
11442                        Ordering::Less
11443                    }
11444                }) {
11445                    Ok(i) | Err(i) => i,
11446                };
11447
11448                ranges[start_ix..]
11449                    .iter()
11450                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11451            })
11452    }
11453
11454    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11455        self.background_highlights
11456            .get(&TypeId::of::<T>())
11457            .map_or(false, |(_, highlights)| !highlights.is_empty())
11458    }
11459
11460    pub fn background_highlights_in_range(
11461        &self,
11462        search_range: Range<Anchor>,
11463        display_snapshot: &DisplaySnapshot,
11464        theme: &ThemeColors,
11465    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11466        let mut results = Vec::new();
11467        for (color_fetcher, ranges) in self.background_highlights.values() {
11468            let color = color_fetcher(theme);
11469            let start_ix = match ranges.binary_search_by(|probe| {
11470                let cmp = probe
11471                    .end
11472                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11473                if cmp.is_gt() {
11474                    Ordering::Greater
11475                } else {
11476                    Ordering::Less
11477                }
11478            }) {
11479                Ok(i) | Err(i) => i,
11480            };
11481            for range in &ranges[start_ix..] {
11482                if range
11483                    .start
11484                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11485                    .is_ge()
11486                {
11487                    break;
11488                }
11489
11490                let start = range.start.to_display_point(display_snapshot);
11491                let end = range.end.to_display_point(display_snapshot);
11492                results.push((start..end, color))
11493            }
11494        }
11495        results
11496    }
11497
11498    pub fn background_highlight_row_ranges<T: 'static>(
11499        &self,
11500        search_range: Range<Anchor>,
11501        display_snapshot: &DisplaySnapshot,
11502        count: usize,
11503    ) -> Vec<RangeInclusive<DisplayPoint>> {
11504        let mut results = Vec::new();
11505        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11506            return vec![];
11507        };
11508
11509        let start_ix = match ranges.binary_search_by(|probe| {
11510            let cmp = probe
11511                .end
11512                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11513            if cmp.is_gt() {
11514                Ordering::Greater
11515            } else {
11516                Ordering::Less
11517            }
11518        }) {
11519            Ok(i) | Err(i) => i,
11520        };
11521        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11522            if let (Some(start_display), Some(end_display)) = (start, end) {
11523                results.push(
11524                    start_display.to_display_point(display_snapshot)
11525                        ..=end_display.to_display_point(display_snapshot),
11526                );
11527            }
11528        };
11529        let mut start_row: Option<Point> = None;
11530        let mut end_row: Option<Point> = None;
11531        if ranges.len() > count {
11532            return Vec::new();
11533        }
11534        for range in &ranges[start_ix..] {
11535            if range
11536                .start
11537                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11538                .is_ge()
11539            {
11540                break;
11541            }
11542            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11543            if let Some(current_row) = &end_row {
11544                if end.row == current_row.row {
11545                    continue;
11546                }
11547            }
11548            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11549            if start_row.is_none() {
11550                assert_eq!(end_row, None);
11551                start_row = Some(start);
11552                end_row = Some(end);
11553                continue;
11554            }
11555            if let Some(current_end) = end_row.as_mut() {
11556                if start.row > current_end.row + 1 {
11557                    push_region(start_row, end_row);
11558                    start_row = Some(start);
11559                    end_row = Some(end);
11560                } else {
11561                    // Merge two hunks.
11562                    *current_end = end;
11563                }
11564            } else {
11565                unreachable!();
11566            }
11567        }
11568        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11569        push_region(start_row, end_row);
11570        results
11571    }
11572
11573    pub fn gutter_highlights_in_range(
11574        &self,
11575        search_range: Range<Anchor>,
11576        display_snapshot: &DisplaySnapshot,
11577        cx: &AppContext,
11578    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11579        let mut results = Vec::new();
11580        for (color_fetcher, ranges) in self.gutter_highlights.values() {
11581            let color = color_fetcher(cx);
11582            let start_ix = match ranges.binary_search_by(|probe| {
11583                let cmp = probe
11584                    .end
11585                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11586                if cmp.is_gt() {
11587                    Ordering::Greater
11588                } else {
11589                    Ordering::Less
11590                }
11591            }) {
11592                Ok(i) | Err(i) => i,
11593            };
11594            for range in &ranges[start_ix..] {
11595                if range
11596                    .start
11597                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11598                    .is_ge()
11599                {
11600                    break;
11601                }
11602
11603                let start = range.start.to_display_point(display_snapshot);
11604                let end = range.end.to_display_point(display_snapshot);
11605                results.push((start..end, color))
11606            }
11607        }
11608        results
11609    }
11610
11611    /// Get the text ranges corresponding to the redaction query
11612    pub fn redacted_ranges(
11613        &self,
11614        search_range: Range<Anchor>,
11615        display_snapshot: &DisplaySnapshot,
11616        cx: &WindowContext,
11617    ) -> Vec<Range<DisplayPoint>> {
11618        display_snapshot
11619            .buffer_snapshot
11620            .redacted_ranges(search_range, |file| {
11621                if let Some(file) = file {
11622                    file.is_private()
11623                        && EditorSettings::get(
11624                            Some(SettingsLocation {
11625                                worktree_id: file.worktree_id(cx),
11626                                path: file.path().as_ref(),
11627                            }),
11628                            cx,
11629                        )
11630                        .redact_private_values
11631                } else {
11632                    false
11633                }
11634            })
11635            .map(|range| {
11636                range.start.to_display_point(display_snapshot)
11637                    ..range.end.to_display_point(display_snapshot)
11638            })
11639            .collect()
11640    }
11641
11642    pub fn highlight_text<T: 'static>(
11643        &mut self,
11644        ranges: Vec<Range<Anchor>>,
11645        style: HighlightStyle,
11646        cx: &mut ViewContext<Self>,
11647    ) {
11648        self.display_map.update(cx, |map, _| {
11649            map.highlight_text(TypeId::of::<T>(), ranges, style)
11650        });
11651        cx.notify();
11652    }
11653
11654    pub(crate) fn highlight_inlays<T: 'static>(
11655        &mut self,
11656        highlights: Vec<InlayHighlight>,
11657        style: HighlightStyle,
11658        cx: &mut ViewContext<Self>,
11659    ) {
11660        self.display_map.update(cx, |map, _| {
11661            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11662        });
11663        cx.notify();
11664    }
11665
11666    pub fn text_highlights<'a, T: 'static>(
11667        &'a self,
11668        cx: &'a AppContext,
11669    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11670        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11671    }
11672
11673    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11674        let cleared = self
11675            .display_map
11676            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11677        if cleared {
11678            cx.notify();
11679        }
11680    }
11681
11682    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11683        (self.read_only(cx) || self.blink_manager.read(cx).visible())
11684            && self.focus_handle.is_focused(cx)
11685    }
11686
11687    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11688        self.show_cursor_when_unfocused = is_enabled;
11689        cx.notify();
11690    }
11691
11692    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11693        cx.notify();
11694    }
11695
11696    fn on_buffer_event(
11697        &mut self,
11698        multibuffer: Model<MultiBuffer>,
11699        event: &multi_buffer::Event,
11700        cx: &mut ViewContext<Self>,
11701    ) {
11702        match event {
11703            multi_buffer::Event::Edited {
11704                singleton_buffer_edited,
11705            } => {
11706                self.scrollbar_marker_state.dirty = true;
11707                self.active_indent_guides_state.dirty = true;
11708                self.refresh_active_diagnostics(cx);
11709                self.refresh_code_actions(cx);
11710                if self.has_active_inline_completion(cx) {
11711                    self.update_visible_inline_completion(cx);
11712                }
11713                cx.emit(EditorEvent::BufferEdited);
11714                cx.emit(SearchEvent::MatchesInvalidated);
11715                if *singleton_buffer_edited {
11716                    if let Some(project) = &self.project {
11717                        let project = project.read(cx);
11718                        #[allow(clippy::mutable_key_type)]
11719                        let languages_affected = multibuffer
11720                            .read(cx)
11721                            .all_buffers()
11722                            .into_iter()
11723                            .filter_map(|buffer| {
11724                                let buffer = buffer.read(cx);
11725                                let language = buffer.language()?;
11726                                if project.is_local_or_ssh()
11727                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
11728                                {
11729                                    None
11730                                } else {
11731                                    Some(language)
11732                                }
11733                            })
11734                            .cloned()
11735                            .collect::<HashSet<_>>();
11736                        if !languages_affected.is_empty() {
11737                            self.refresh_inlay_hints(
11738                                InlayHintRefreshReason::BufferEdited(languages_affected),
11739                                cx,
11740                            );
11741                        }
11742                    }
11743                }
11744
11745                let Some(project) = &self.project else { return };
11746                let telemetry = project.read(cx).client().telemetry().clone();
11747                refresh_linked_ranges(self, cx);
11748                telemetry.log_edit_event("editor");
11749            }
11750            multi_buffer::Event::ExcerptsAdded {
11751                buffer,
11752                predecessor,
11753                excerpts,
11754            } => {
11755                self.tasks_update_task = Some(self.refresh_runnables(cx));
11756                cx.emit(EditorEvent::ExcerptsAdded {
11757                    buffer: buffer.clone(),
11758                    predecessor: *predecessor,
11759                    excerpts: excerpts.clone(),
11760                });
11761                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11762            }
11763            multi_buffer::Event::ExcerptsRemoved { ids } => {
11764                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11765                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11766            }
11767            multi_buffer::Event::ExcerptsEdited { ids } => {
11768                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11769            }
11770            multi_buffer::Event::ExcerptsExpanded { ids } => {
11771                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11772            }
11773            multi_buffer::Event::Reparsed(buffer_id) => {
11774                self.tasks_update_task = Some(self.refresh_runnables(cx));
11775
11776                cx.emit(EditorEvent::Reparsed(*buffer_id));
11777            }
11778            multi_buffer::Event::LanguageChanged(buffer_id) => {
11779                linked_editing_ranges::refresh_linked_ranges(self, cx);
11780                cx.emit(EditorEvent::Reparsed(*buffer_id));
11781                cx.notify();
11782            }
11783            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11784            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11785            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11786                cx.emit(EditorEvent::TitleChanged)
11787            }
11788            multi_buffer::Event::DiffBaseChanged => {
11789                self.scrollbar_marker_state.dirty = true;
11790                cx.emit(EditorEvent::DiffBaseChanged);
11791                cx.notify();
11792            }
11793            multi_buffer::Event::DiffUpdated { buffer } => {
11794                self.sync_expanded_diff_hunks(buffer.clone(), cx);
11795                cx.notify();
11796            }
11797            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11798            multi_buffer::Event::DiagnosticsUpdated => {
11799                self.refresh_active_diagnostics(cx);
11800                self.scrollbar_marker_state.dirty = true;
11801                cx.notify();
11802            }
11803            _ => {}
11804        };
11805    }
11806
11807    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11808        cx.notify();
11809    }
11810
11811    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11812        self.tasks_update_task = Some(self.refresh_runnables(cx));
11813        self.refresh_inline_completion(true, false, cx);
11814        self.refresh_inlay_hints(
11815            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11816                self.selections.newest_anchor().head(),
11817                &self.buffer.read(cx).snapshot(cx),
11818                cx,
11819            )),
11820            cx,
11821        );
11822        let editor_settings = EditorSettings::get_global(cx);
11823        if let Some(cursor_shape) = editor_settings.cursor_shape {
11824            self.cursor_shape = cursor_shape;
11825        }
11826        self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11827        self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11828
11829        let project_settings = ProjectSettings::get_global(cx);
11830        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11831
11832        if self.mode == EditorMode::Full {
11833            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11834            if self.git_blame_inline_enabled != inline_blame_enabled {
11835                self.toggle_git_blame_inline_internal(false, cx);
11836            }
11837        }
11838
11839        cx.notify();
11840    }
11841
11842    pub fn set_searchable(&mut self, searchable: bool) {
11843        self.searchable = searchable;
11844    }
11845
11846    pub fn searchable(&self) -> bool {
11847        self.searchable
11848    }
11849
11850    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11851        self.open_excerpts_common(true, cx)
11852    }
11853
11854    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11855        self.open_excerpts_common(false, cx)
11856    }
11857
11858    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11859        let buffer = self.buffer.read(cx);
11860        if buffer.is_singleton() {
11861            cx.propagate();
11862            return;
11863        }
11864
11865        let Some(workspace) = self.workspace() else {
11866            cx.propagate();
11867            return;
11868        };
11869
11870        let mut new_selections_by_buffer = HashMap::default();
11871        for selection in self.selections.all::<usize>(cx) {
11872            for (buffer, mut range, _) in
11873                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11874            {
11875                if selection.reversed {
11876                    mem::swap(&mut range.start, &mut range.end);
11877                }
11878                new_selections_by_buffer
11879                    .entry(buffer)
11880                    .or_insert(Vec::new())
11881                    .push(range)
11882            }
11883        }
11884
11885        // We defer the pane interaction because we ourselves are a workspace item
11886        // and activating a new item causes the pane to call a method on us reentrantly,
11887        // which panics if we're on the stack.
11888        cx.window_context().defer(move |cx| {
11889            workspace.update(cx, |workspace, cx| {
11890                let pane = if split {
11891                    workspace.adjacent_pane(cx)
11892                } else {
11893                    workspace.active_pane().clone()
11894                };
11895
11896                for (buffer, ranges) in new_selections_by_buffer {
11897                    let editor =
11898                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11899                    editor.update(cx, |editor, cx| {
11900                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11901                            s.select_ranges(ranges);
11902                        });
11903                    });
11904                }
11905            })
11906        });
11907    }
11908
11909    fn jump(
11910        &mut self,
11911        path: ProjectPath,
11912        position: Point,
11913        anchor: language::Anchor,
11914        offset_from_top: u32,
11915        cx: &mut ViewContext<Self>,
11916    ) {
11917        let workspace = self.workspace();
11918        cx.spawn(|_, mut cx| async move {
11919            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11920            let editor = workspace.update(&mut cx, |workspace, cx| {
11921                // Reset the preview item id before opening the new item
11922                workspace.active_pane().update(cx, |pane, cx| {
11923                    pane.set_preview_item_id(None, cx);
11924                });
11925                workspace.open_path_preview(path, None, true, true, cx)
11926            })?;
11927            let editor = editor
11928                .await?
11929                .downcast::<Editor>()
11930                .ok_or_else(|| anyhow!("opened item was not an editor"))?
11931                .downgrade();
11932            editor.update(&mut cx, |editor, cx| {
11933                let buffer = editor
11934                    .buffer()
11935                    .read(cx)
11936                    .as_singleton()
11937                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11938                let buffer = buffer.read(cx);
11939                let cursor = if buffer.can_resolve(&anchor) {
11940                    language::ToPoint::to_point(&anchor, buffer)
11941                } else {
11942                    buffer.clip_point(position, Bias::Left)
11943                };
11944
11945                let nav_history = editor.nav_history.take();
11946                editor.change_selections(
11947                    Some(Autoscroll::top_relative(offset_from_top as usize)),
11948                    cx,
11949                    |s| {
11950                        s.select_ranges([cursor..cursor]);
11951                    },
11952                );
11953                editor.nav_history = nav_history;
11954
11955                anyhow::Ok(())
11956            })??;
11957
11958            anyhow::Ok(())
11959        })
11960        .detach_and_log_err(cx);
11961    }
11962
11963    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11964        let snapshot = self.buffer.read(cx).read(cx);
11965        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11966        Some(
11967            ranges
11968                .iter()
11969                .map(move |range| {
11970                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11971                })
11972                .collect(),
11973        )
11974    }
11975
11976    fn selection_replacement_ranges(
11977        &self,
11978        range: Range<OffsetUtf16>,
11979        cx: &AppContext,
11980    ) -> Vec<Range<OffsetUtf16>> {
11981        let selections = self.selections.all::<OffsetUtf16>(cx);
11982        let newest_selection = selections
11983            .iter()
11984            .max_by_key(|selection| selection.id)
11985            .unwrap();
11986        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11987        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11988        let snapshot = self.buffer.read(cx).read(cx);
11989        selections
11990            .into_iter()
11991            .map(|mut selection| {
11992                selection.start.0 =
11993                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
11994                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11995                snapshot.clip_offset_utf16(selection.start, Bias::Left)
11996                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11997            })
11998            .collect()
11999    }
12000
12001    fn report_editor_event(
12002        &self,
12003        operation: &'static str,
12004        file_extension: Option<String>,
12005        cx: &AppContext,
12006    ) {
12007        if cfg!(any(test, feature = "test-support")) {
12008            return;
12009        }
12010
12011        let Some(project) = &self.project else { return };
12012
12013        // If None, we are in a file without an extension
12014        let file = self
12015            .buffer
12016            .read(cx)
12017            .as_singleton()
12018            .and_then(|b| b.read(cx).file());
12019        let file_extension = file_extension.or(file
12020            .as_ref()
12021            .and_then(|file| Path::new(file.file_name(cx)).extension())
12022            .and_then(|e| e.to_str())
12023            .map(|a| a.to_string()));
12024
12025        let vim_mode = cx
12026            .global::<SettingsStore>()
12027            .raw_user_settings()
12028            .get("vim_mode")
12029            == Some(&serde_json::Value::Bool(true));
12030
12031        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12032            == language::language_settings::InlineCompletionProvider::Copilot;
12033        let copilot_enabled_for_language = self
12034            .buffer
12035            .read(cx)
12036            .settings_at(0, cx)
12037            .show_inline_completions;
12038
12039        let telemetry = project.read(cx).client().telemetry().clone();
12040        telemetry.report_editor_event(
12041            file_extension,
12042            vim_mode,
12043            operation,
12044            copilot_enabled,
12045            copilot_enabled_for_language,
12046        )
12047    }
12048
12049    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12050    /// with each line being an array of {text, highlight} objects.
12051    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12052        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12053            return;
12054        };
12055
12056        #[derive(Serialize)]
12057        struct Chunk<'a> {
12058            text: String,
12059            highlight: Option<&'a str>,
12060        }
12061
12062        let snapshot = buffer.read(cx).snapshot();
12063        let range = self
12064            .selected_text_range(false, cx)
12065            .and_then(|selection| {
12066                if selection.range.is_empty() {
12067                    None
12068                } else {
12069                    Some(selection.range)
12070                }
12071            })
12072            .unwrap_or_else(|| 0..snapshot.len());
12073
12074        let chunks = snapshot.chunks(range, true);
12075        let mut lines = Vec::new();
12076        let mut line: VecDeque<Chunk> = VecDeque::new();
12077
12078        let Some(style) = self.style.as_ref() else {
12079            return;
12080        };
12081
12082        for chunk in chunks {
12083            let highlight = chunk
12084                .syntax_highlight_id
12085                .and_then(|id| id.name(&style.syntax));
12086            let mut chunk_lines = chunk.text.split('\n').peekable();
12087            while let Some(text) = chunk_lines.next() {
12088                let mut merged_with_last_token = false;
12089                if let Some(last_token) = line.back_mut() {
12090                    if last_token.highlight == highlight {
12091                        last_token.text.push_str(text);
12092                        merged_with_last_token = true;
12093                    }
12094                }
12095
12096                if !merged_with_last_token {
12097                    line.push_back(Chunk {
12098                        text: text.into(),
12099                        highlight,
12100                    });
12101                }
12102
12103                if chunk_lines.peek().is_some() {
12104                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12105                        line.pop_front();
12106                    }
12107                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12108                        line.pop_back();
12109                    }
12110
12111                    lines.push(mem::take(&mut line));
12112                }
12113            }
12114        }
12115
12116        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12117            return;
12118        };
12119        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12120    }
12121
12122    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12123        &self.inlay_hint_cache
12124    }
12125
12126    pub fn replay_insert_event(
12127        &mut self,
12128        text: &str,
12129        relative_utf16_range: Option<Range<isize>>,
12130        cx: &mut ViewContext<Self>,
12131    ) {
12132        if !self.input_enabled {
12133            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12134            return;
12135        }
12136        if let Some(relative_utf16_range) = relative_utf16_range {
12137            let selections = self.selections.all::<OffsetUtf16>(cx);
12138            self.change_selections(None, cx, |s| {
12139                let new_ranges = selections.into_iter().map(|range| {
12140                    let start = OffsetUtf16(
12141                        range
12142                            .head()
12143                            .0
12144                            .saturating_add_signed(relative_utf16_range.start),
12145                    );
12146                    let end = OffsetUtf16(
12147                        range
12148                            .head()
12149                            .0
12150                            .saturating_add_signed(relative_utf16_range.end),
12151                    );
12152                    start..end
12153                });
12154                s.select_ranges(new_ranges);
12155            });
12156        }
12157
12158        self.handle_input(text, cx);
12159    }
12160
12161    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12162        let Some(project) = self.project.as_ref() else {
12163            return false;
12164        };
12165        let project = project.read(cx);
12166
12167        let mut supports = false;
12168        self.buffer().read(cx).for_each_buffer(|buffer| {
12169            if !supports {
12170                supports = project
12171                    .language_servers_for_buffer(buffer.read(cx), cx)
12172                    .any(
12173                        |(_, server)| match server.capabilities().inlay_hint_provider {
12174                            Some(lsp::OneOf::Left(enabled)) => enabled,
12175                            Some(lsp::OneOf::Right(_)) => true,
12176                            None => false,
12177                        },
12178                    )
12179            }
12180        });
12181        supports
12182    }
12183
12184    pub fn focus(&self, cx: &mut WindowContext) {
12185        cx.focus(&self.focus_handle)
12186    }
12187
12188    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12189        self.focus_handle.is_focused(cx)
12190    }
12191
12192    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12193        cx.emit(EditorEvent::Focused);
12194
12195        if let Some(descendant) = self
12196            .last_focused_descendant
12197            .take()
12198            .and_then(|descendant| descendant.upgrade())
12199        {
12200            cx.focus(&descendant);
12201        } else {
12202            if let Some(blame) = self.blame.as_ref() {
12203                blame.update(cx, GitBlame::focus)
12204            }
12205
12206            self.blink_manager.update(cx, BlinkManager::enable);
12207            self.show_cursor_names(cx);
12208            self.buffer.update(cx, |buffer, cx| {
12209                buffer.finalize_last_transaction(cx);
12210                if self.leader_peer_id.is_none() {
12211                    buffer.set_active_selections(
12212                        &self.selections.disjoint_anchors(),
12213                        self.selections.line_mode,
12214                        self.cursor_shape,
12215                        cx,
12216                    );
12217                }
12218            });
12219        }
12220    }
12221
12222    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12223        cx.emit(EditorEvent::FocusedIn)
12224    }
12225
12226    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12227        if event.blurred != self.focus_handle {
12228            self.last_focused_descendant = Some(event.blurred);
12229        }
12230    }
12231
12232    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12233        self.blink_manager.update(cx, BlinkManager::disable);
12234        self.buffer
12235            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12236
12237        if let Some(blame) = self.blame.as_ref() {
12238            blame.update(cx, GitBlame::blur)
12239        }
12240        if !self.hover_state.focused(cx) {
12241            hide_hover(self, cx);
12242        }
12243
12244        self.hide_context_menu(cx);
12245        cx.emit(EditorEvent::Blurred);
12246        cx.notify();
12247    }
12248
12249    pub fn register_action<A: Action>(
12250        &mut self,
12251        listener: impl Fn(&A, &mut WindowContext) + 'static,
12252    ) -> Subscription {
12253        let id = self.next_editor_action_id.post_inc();
12254        let listener = Arc::new(listener);
12255        self.editor_actions.borrow_mut().insert(
12256            id,
12257            Box::new(move |cx| {
12258                let cx = cx.window_context();
12259                let listener = listener.clone();
12260                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12261                    let action = action.downcast_ref().unwrap();
12262                    if phase == DispatchPhase::Bubble {
12263                        listener(action, cx)
12264                    }
12265                })
12266            }),
12267        );
12268
12269        let editor_actions = self.editor_actions.clone();
12270        Subscription::new(move || {
12271            editor_actions.borrow_mut().remove(&id);
12272        })
12273    }
12274
12275    pub fn file_header_size(&self) -> u32 {
12276        self.file_header_size
12277    }
12278
12279    pub fn revert(
12280        &mut self,
12281        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12282        cx: &mut ViewContext<Self>,
12283    ) {
12284        self.buffer().update(cx, |multi_buffer, cx| {
12285            for (buffer_id, changes) in revert_changes {
12286                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12287                    buffer.update(cx, |buffer, cx| {
12288                        buffer.edit(
12289                            changes.into_iter().map(|(range, text)| {
12290                                (range, text.to_string().map(Arc::<str>::from))
12291                            }),
12292                            None,
12293                            cx,
12294                        );
12295                    });
12296                }
12297            }
12298        });
12299        self.change_selections(None, cx, |selections| selections.refresh());
12300    }
12301
12302    pub fn to_pixel_point(
12303        &mut self,
12304        source: multi_buffer::Anchor,
12305        editor_snapshot: &EditorSnapshot,
12306        cx: &mut ViewContext<Self>,
12307    ) -> Option<gpui::Point<Pixels>> {
12308        let source_point = source.to_display_point(editor_snapshot);
12309        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12310    }
12311
12312    pub fn display_to_pixel_point(
12313        &mut self,
12314        source: DisplayPoint,
12315        editor_snapshot: &EditorSnapshot,
12316        cx: &mut ViewContext<Self>,
12317    ) -> Option<gpui::Point<Pixels>> {
12318        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12319        let text_layout_details = self.text_layout_details(cx);
12320        let scroll_top = text_layout_details
12321            .scroll_anchor
12322            .scroll_position(editor_snapshot)
12323            .y;
12324
12325        if source.row().as_f32() < scroll_top.floor() {
12326            return None;
12327        }
12328        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12329        let source_y = line_height * (source.row().as_f32() - scroll_top);
12330        Some(gpui::Point::new(source_x, source_y))
12331    }
12332
12333    fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
12334        let bounds = self.last_bounds?;
12335        Some(element::gutter_bounds(bounds, self.gutter_dimensions))
12336    }
12337
12338    pub fn has_active_completions_menu(&self) -> bool {
12339        self.context_menu.read().as_ref().map_or(false, |menu| {
12340            menu.visible() && matches!(menu, ContextMenu::Completions(_))
12341        })
12342    }
12343
12344    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12345        self.addons
12346            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12347    }
12348
12349    pub fn unregister_addon<T: Addon>(&mut self) {
12350        self.addons.remove(&std::any::TypeId::of::<T>());
12351    }
12352
12353    pub fn addon<T: Addon>(&self) -> Option<&T> {
12354        let type_id = std::any::TypeId::of::<T>();
12355        self.addons
12356            .get(&type_id)
12357            .and_then(|item| item.to_any().downcast_ref::<T>())
12358    }
12359}
12360
12361fn hunks_for_selections(
12362    multi_buffer_snapshot: &MultiBufferSnapshot,
12363    selections: &[Selection<Anchor>],
12364) -> Vec<DiffHunk<MultiBufferRow>> {
12365    let buffer_rows_for_selections = selections.iter().map(|selection| {
12366        let head = selection.head();
12367        let tail = selection.tail();
12368        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12369        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12370        if start > end {
12371            end..start
12372        } else {
12373            start..end
12374        }
12375    });
12376
12377    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12378}
12379
12380pub fn hunks_for_rows(
12381    rows: impl Iterator<Item = Range<MultiBufferRow>>,
12382    multi_buffer_snapshot: &MultiBufferSnapshot,
12383) -> Vec<DiffHunk<MultiBufferRow>> {
12384    let mut hunks = Vec::new();
12385    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12386        HashMap::default();
12387    for selected_multi_buffer_rows in rows {
12388        let query_rows =
12389            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12390        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12391            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12392            // when the caret is just above or just below the deleted hunk.
12393            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12394            let related_to_selection = if allow_adjacent {
12395                hunk.associated_range.overlaps(&query_rows)
12396                    || hunk.associated_range.start == query_rows.end
12397                    || hunk.associated_range.end == query_rows.start
12398            } else {
12399                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12400                // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12401                hunk.associated_range.overlaps(&selected_multi_buffer_rows)
12402                    || selected_multi_buffer_rows.end == hunk.associated_range.start
12403            };
12404            if related_to_selection {
12405                if !processed_buffer_rows
12406                    .entry(hunk.buffer_id)
12407                    .or_default()
12408                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12409                {
12410                    continue;
12411                }
12412                hunks.push(hunk);
12413            }
12414        }
12415    }
12416
12417    hunks
12418}
12419
12420pub trait CollaborationHub {
12421    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12422    fn user_participant_indices<'a>(
12423        &self,
12424        cx: &'a AppContext,
12425    ) -> &'a HashMap<u64, ParticipantIndex>;
12426    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12427}
12428
12429impl CollaborationHub for Model<Project> {
12430    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12431        self.read(cx).collaborators()
12432    }
12433
12434    fn user_participant_indices<'a>(
12435        &self,
12436        cx: &'a AppContext,
12437    ) -> &'a HashMap<u64, ParticipantIndex> {
12438        self.read(cx).user_store().read(cx).participant_indices()
12439    }
12440
12441    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12442        let this = self.read(cx);
12443        let user_ids = this.collaborators().values().map(|c| c.user_id);
12444        this.user_store().read_with(cx, |user_store, cx| {
12445            user_store.participant_names(user_ids, cx)
12446        })
12447    }
12448}
12449
12450pub trait CompletionProvider {
12451    fn completions(
12452        &self,
12453        buffer: &Model<Buffer>,
12454        buffer_position: text::Anchor,
12455        trigger: CompletionContext,
12456        cx: &mut ViewContext<Editor>,
12457    ) -> Task<Result<Vec<Completion>>>;
12458
12459    fn resolve_completions(
12460        &self,
12461        buffer: Model<Buffer>,
12462        completion_indices: Vec<usize>,
12463        completions: Arc<RwLock<Box<[Completion]>>>,
12464        cx: &mut ViewContext<Editor>,
12465    ) -> Task<Result<bool>>;
12466
12467    fn apply_additional_edits_for_completion(
12468        &self,
12469        buffer: Model<Buffer>,
12470        completion: Completion,
12471        push_to_history: bool,
12472        cx: &mut ViewContext<Editor>,
12473    ) -> Task<Result<Option<language::Transaction>>>;
12474
12475    fn is_completion_trigger(
12476        &self,
12477        buffer: &Model<Buffer>,
12478        position: language::Anchor,
12479        text: &str,
12480        trigger_in_words: bool,
12481        cx: &mut ViewContext<Editor>,
12482    ) -> bool;
12483
12484    fn sort_completions(&self) -> bool {
12485        true
12486    }
12487}
12488
12489fn snippet_completions(
12490    project: &Project,
12491    buffer: &Model<Buffer>,
12492    buffer_position: text::Anchor,
12493    cx: &mut AppContext,
12494) -> Vec<Completion> {
12495    let language = buffer.read(cx).language_at(buffer_position);
12496    let language_name = language.as_ref().map(|language| language.lsp_id());
12497    let snippet_store = project.snippets().read(cx);
12498    let snippets = snippet_store.snippets_for(language_name, cx);
12499
12500    if snippets.is_empty() {
12501        return vec![];
12502    }
12503    let snapshot = buffer.read(cx).text_snapshot();
12504    let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12505
12506    let mut lines = chunks.lines();
12507    let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12508        return vec![];
12509    };
12510
12511    let scope = language.map(|language| language.default_scope());
12512    let classifier = CharClassifier::new(scope).for_completion(true);
12513    let mut last_word = line_at
12514        .chars()
12515        .rev()
12516        .take_while(|c| classifier.is_word(*c))
12517        .collect::<String>();
12518    last_word = last_word.chars().rev().collect();
12519    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12520    let to_lsp = |point: &text::Anchor| {
12521        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12522        point_to_lsp(end)
12523    };
12524    let lsp_end = to_lsp(&buffer_position);
12525    snippets
12526        .into_iter()
12527        .filter_map(|snippet| {
12528            let matching_prefix = snippet
12529                .prefix
12530                .iter()
12531                .find(|prefix| prefix.starts_with(&last_word))?;
12532            let start = as_offset - last_word.len();
12533            let start = snapshot.anchor_before(start);
12534            let range = start..buffer_position;
12535            let lsp_start = to_lsp(&start);
12536            let lsp_range = lsp::Range {
12537                start: lsp_start,
12538                end: lsp_end,
12539            };
12540            Some(Completion {
12541                old_range: range,
12542                new_text: snippet.body.clone(),
12543                label: CodeLabel {
12544                    text: matching_prefix.clone(),
12545                    runs: vec![],
12546                    filter_range: 0..matching_prefix.len(),
12547                },
12548                server_id: LanguageServerId(usize::MAX),
12549                documentation: snippet.description.clone().map(Documentation::SingleLine),
12550                lsp_completion: lsp::CompletionItem {
12551                    label: snippet.prefix.first().unwrap().clone(),
12552                    kind: Some(CompletionItemKind::SNIPPET),
12553                    label_details: snippet.description.as_ref().map(|description| {
12554                        lsp::CompletionItemLabelDetails {
12555                            detail: Some(description.clone()),
12556                            description: None,
12557                        }
12558                    }),
12559                    insert_text_format: Some(InsertTextFormat::SNIPPET),
12560                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12561                        lsp::InsertReplaceEdit {
12562                            new_text: snippet.body.clone(),
12563                            insert: lsp_range,
12564                            replace: lsp_range,
12565                        },
12566                    )),
12567                    filter_text: Some(snippet.body.clone()),
12568                    sort_text: Some(char::MAX.to_string()),
12569                    ..Default::default()
12570                },
12571                confirm: None,
12572            })
12573        })
12574        .collect()
12575}
12576
12577impl CompletionProvider for Model<Project> {
12578    fn completions(
12579        &self,
12580        buffer: &Model<Buffer>,
12581        buffer_position: text::Anchor,
12582        options: CompletionContext,
12583        cx: &mut ViewContext<Editor>,
12584    ) -> Task<Result<Vec<Completion>>> {
12585        self.update(cx, |project, cx| {
12586            let snippets = snippet_completions(project, buffer, buffer_position, cx);
12587            let project_completions = project.completions(buffer, buffer_position, options, cx);
12588            cx.background_executor().spawn(async move {
12589                let mut completions = project_completions.await?;
12590                //let snippets = snippets.into_iter().;
12591                completions.extend(snippets);
12592                Ok(completions)
12593            })
12594        })
12595    }
12596
12597    fn resolve_completions(
12598        &self,
12599        buffer: Model<Buffer>,
12600        completion_indices: Vec<usize>,
12601        completions: Arc<RwLock<Box<[Completion]>>>,
12602        cx: &mut ViewContext<Editor>,
12603    ) -> Task<Result<bool>> {
12604        self.update(cx, |project, cx| {
12605            project.resolve_completions(buffer, completion_indices, completions, cx)
12606        })
12607    }
12608
12609    fn apply_additional_edits_for_completion(
12610        &self,
12611        buffer: Model<Buffer>,
12612        completion: Completion,
12613        push_to_history: bool,
12614        cx: &mut ViewContext<Editor>,
12615    ) -> Task<Result<Option<language::Transaction>>> {
12616        self.update(cx, |project, cx| {
12617            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12618        })
12619    }
12620
12621    fn is_completion_trigger(
12622        &self,
12623        buffer: &Model<Buffer>,
12624        position: language::Anchor,
12625        text: &str,
12626        trigger_in_words: bool,
12627        cx: &mut ViewContext<Editor>,
12628    ) -> bool {
12629        if !EditorSettings::get_global(cx).show_completions_on_input {
12630            return false;
12631        }
12632
12633        let mut chars = text.chars();
12634        let char = if let Some(char) = chars.next() {
12635            char
12636        } else {
12637            return false;
12638        };
12639        if chars.next().is_some() {
12640            return false;
12641        }
12642
12643        let buffer = buffer.read(cx);
12644        let classifier = buffer
12645            .snapshot()
12646            .char_classifier_at(position)
12647            .for_completion(true);
12648        if trigger_in_words && classifier.is_word(char) {
12649            return true;
12650        }
12651
12652        buffer
12653            .completion_triggers()
12654            .iter()
12655            .any(|string| string == text)
12656    }
12657}
12658
12659fn inlay_hint_settings(
12660    location: Anchor,
12661    snapshot: &MultiBufferSnapshot,
12662    cx: &mut ViewContext<'_, Editor>,
12663) -> InlayHintSettings {
12664    let file = snapshot.file_at(location);
12665    let language = snapshot.language_at(location);
12666    let settings = all_language_settings(file, cx);
12667    settings
12668        .language(language.map(|l| l.name()).as_ref())
12669        .inlay_hints
12670}
12671
12672fn consume_contiguous_rows(
12673    contiguous_row_selections: &mut Vec<Selection<Point>>,
12674    selection: &Selection<Point>,
12675    display_map: &DisplaySnapshot,
12676    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12677) -> (MultiBufferRow, MultiBufferRow) {
12678    contiguous_row_selections.push(selection.clone());
12679    let start_row = MultiBufferRow(selection.start.row);
12680    let mut end_row = ending_row(selection, display_map);
12681
12682    while let Some(next_selection) = selections.peek() {
12683        if next_selection.start.row <= end_row.0 {
12684            end_row = ending_row(next_selection, display_map);
12685            contiguous_row_selections.push(selections.next().unwrap().clone());
12686        } else {
12687            break;
12688        }
12689    }
12690    (start_row, end_row)
12691}
12692
12693fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12694    if next_selection.end.column > 0 || next_selection.is_empty() {
12695        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12696    } else {
12697        MultiBufferRow(next_selection.end.row)
12698    }
12699}
12700
12701impl EditorSnapshot {
12702    pub fn remote_selections_in_range<'a>(
12703        &'a self,
12704        range: &'a Range<Anchor>,
12705        collaboration_hub: &dyn CollaborationHub,
12706        cx: &'a AppContext,
12707    ) -> impl 'a + Iterator<Item = RemoteSelection> {
12708        let participant_names = collaboration_hub.user_names(cx);
12709        let participant_indices = collaboration_hub.user_participant_indices(cx);
12710        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12711        let collaborators_by_replica_id = collaborators_by_peer_id
12712            .iter()
12713            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12714            .collect::<HashMap<_, _>>();
12715        self.buffer_snapshot
12716            .selections_in_range(range, false)
12717            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12718                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12719                let participant_index = participant_indices.get(&collaborator.user_id).copied();
12720                let user_name = participant_names.get(&collaborator.user_id).cloned();
12721                Some(RemoteSelection {
12722                    replica_id,
12723                    selection,
12724                    cursor_shape,
12725                    line_mode,
12726                    participant_index,
12727                    peer_id: collaborator.peer_id,
12728                    user_name,
12729                })
12730            })
12731    }
12732
12733    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12734        self.display_snapshot.buffer_snapshot.language_at(position)
12735    }
12736
12737    pub fn is_focused(&self) -> bool {
12738        self.is_focused
12739    }
12740
12741    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12742        self.placeholder_text.as_ref()
12743    }
12744
12745    pub fn scroll_position(&self) -> gpui::Point<f32> {
12746        self.scroll_anchor.scroll_position(&self.display_snapshot)
12747    }
12748
12749    fn gutter_dimensions(
12750        &self,
12751        font_id: FontId,
12752        font_size: Pixels,
12753        em_width: Pixels,
12754        max_line_number_width: Pixels,
12755        cx: &AppContext,
12756    ) -> GutterDimensions {
12757        if !self.show_gutter {
12758            return GutterDimensions::default();
12759        }
12760        let descent = cx.text_system().descent(font_id, font_size);
12761
12762        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12763            matches!(
12764                ProjectSettings::get_global(cx).git.git_gutter,
12765                Some(GitGutterSetting::TrackedFiles)
12766            )
12767        });
12768        let gutter_settings = EditorSettings::get_global(cx).gutter;
12769        let show_line_numbers = self
12770            .show_line_numbers
12771            .unwrap_or(gutter_settings.line_numbers);
12772        let line_gutter_width = if show_line_numbers {
12773            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12774            let min_width_for_number_on_gutter = em_width * 4.0;
12775            max_line_number_width.max(min_width_for_number_on_gutter)
12776        } else {
12777            0.0.into()
12778        };
12779
12780        let show_code_actions = self
12781            .show_code_actions
12782            .unwrap_or(gutter_settings.code_actions);
12783
12784        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12785
12786        let git_blame_entries_width = self
12787            .render_git_blame_gutter
12788            .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12789
12790        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12791        left_padding += if show_code_actions || show_runnables {
12792            em_width * 3.0
12793        } else if show_git_gutter && show_line_numbers {
12794            em_width * 2.0
12795        } else if show_git_gutter || show_line_numbers {
12796            em_width
12797        } else {
12798            px(0.)
12799        };
12800
12801        let right_padding = if gutter_settings.folds && show_line_numbers {
12802            em_width * 4.0
12803        } else if gutter_settings.folds {
12804            em_width * 3.0
12805        } else if show_line_numbers {
12806            em_width
12807        } else {
12808            px(0.)
12809        };
12810
12811        GutterDimensions {
12812            left_padding,
12813            right_padding,
12814            width: line_gutter_width + left_padding + right_padding,
12815            margin: -descent,
12816            git_blame_entries_width,
12817        }
12818    }
12819
12820    pub fn render_fold_toggle(
12821        &self,
12822        buffer_row: MultiBufferRow,
12823        row_contains_cursor: bool,
12824        editor: View<Editor>,
12825        cx: &mut WindowContext,
12826    ) -> Option<AnyElement> {
12827        let folded = self.is_line_folded(buffer_row);
12828
12829        if let Some(crease) = self
12830            .crease_snapshot
12831            .query_row(buffer_row, &self.buffer_snapshot)
12832        {
12833            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12834                if folded {
12835                    editor.update(cx, |editor, cx| {
12836                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12837                    });
12838                } else {
12839                    editor.update(cx, |editor, cx| {
12840                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12841                    });
12842                }
12843            });
12844
12845            Some((crease.render_toggle)(
12846                buffer_row,
12847                folded,
12848                toggle_callback,
12849                cx,
12850            ))
12851        } else if folded
12852            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12853        {
12854            Some(
12855                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12856                    .selected(folded)
12857                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12858                        if folded {
12859                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
12860                        } else {
12861                            this.fold_at(&FoldAt { buffer_row }, cx);
12862                        }
12863                    }))
12864                    .into_any_element(),
12865            )
12866        } else {
12867            None
12868        }
12869    }
12870
12871    pub fn render_crease_trailer(
12872        &self,
12873        buffer_row: MultiBufferRow,
12874        cx: &mut WindowContext,
12875    ) -> Option<AnyElement> {
12876        let folded = self.is_line_folded(buffer_row);
12877        let crease = self
12878            .crease_snapshot
12879            .query_row(buffer_row, &self.buffer_snapshot)?;
12880        Some((crease.render_trailer)(buffer_row, folded, cx))
12881    }
12882}
12883
12884impl Deref for EditorSnapshot {
12885    type Target = DisplaySnapshot;
12886
12887    fn deref(&self) -> &Self::Target {
12888        &self.display_snapshot
12889    }
12890}
12891
12892#[derive(Clone, Debug, PartialEq, Eq)]
12893pub enum EditorEvent {
12894    InputIgnored {
12895        text: Arc<str>,
12896    },
12897    InputHandled {
12898        utf16_range_to_replace: Option<Range<isize>>,
12899        text: Arc<str>,
12900    },
12901    ExcerptsAdded {
12902        buffer: Model<Buffer>,
12903        predecessor: ExcerptId,
12904        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12905    },
12906    ExcerptsRemoved {
12907        ids: Vec<ExcerptId>,
12908    },
12909    ExcerptsEdited {
12910        ids: Vec<ExcerptId>,
12911    },
12912    ExcerptsExpanded {
12913        ids: Vec<ExcerptId>,
12914    },
12915    BufferEdited,
12916    Edited {
12917        transaction_id: clock::Lamport,
12918    },
12919    Reparsed(BufferId),
12920    Focused,
12921    FocusedIn,
12922    Blurred,
12923    DirtyChanged,
12924    Saved,
12925    TitleChanged,
12926    DiffBaseChanged,
12927    SelectionsChanged {
12928        local: bool,
12929    },
12930    ScrollPositionChanged {
12931        local: bool,
12932        autoscroll: bool,
12933    },
12934    Closed,
12935    TransactionUndone {
12936        transaction_id: clock::Lamport,
12937    },
12938    TransactionBegun {
12939        transaction_id: clock::Lamport,
12940    },
12941}
12942
12943impl EventEmitter<EditorEvent> for Editor {}
12944
12945impl FocusableView for Editor {
12946    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12947        self.focus_handle.clone()
12948    }
12949}
12950
12951impl Render for Editor {
12952    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12953        let settings = ThemeSettings::get_global(cx);
12954
12955        let text_style = match self.mode {
12956            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12957                color: cx.theme().colors().editor_foreground,
12958                font_family: settings.ui_font.family.clone(),
12959                font_features: settings.ui_font.features.clone(),
12960                font_fallbacks: settings.ui_font.fallbacks.clone(),
12961                font_size: rems(0.875).into(),
12962                font_weight: settings.ui_font.weight,
12963                line_height: relative(settings.buffer_line_height.value()),
12964                ..Default::default()
12965            },
12966            EditorMode::Full => TextStyle {
12967                color: cx.theme().colors().editor_foreground,
12968                font_family: settings.buffer_font.family.clone(),
12969                font_features: settings.buffer_font.features.clone(),
12970                font_fallbacks: settings.buffer_font.fallbacks.clone(),
12971                font_size: settings.buffer_font_size(cx).into(),
12972                font_weight: settings.buffer_font.weight,
12973                line_height: relative(settings.buffer_line_height.value()),
12974                ..Default::default()
12975            },
12976        };
12977
12978        let background = match self.mode {
12979            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12980            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12981            EditorMode::Full => cx.theme().colors().editor_background,
12982        };
12983
12984        EditorElement::new(
12985            cx.view(),
12986            EditorStyle {
12987                background,
12988                local_player: cx.theme().players().local(),
12989                text: text_style,
12990                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12991                syntax: cx.theme().syntax().clone(),
12992                status: cx.theme().status().clone(),
12993                inlay_hints_style: make_inlay_hints_style(cx),
12994                suggestions_style: HighlightStyle {
12995                    color: Some(cx.theme().status().predictive),
12996                    ..HighlightStyle::default()
12997                },
12998                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
12999            },
13000        )
13001    }
13002}
13003
13004impl ViewInputHandler for Editor {
13005    fn text_for_range(
13006        &mut self,
13007        range_utf16: Range<usize>,
13008        cx: &mut ViewContext<Self>,
13009    ) -> Option<String> {
13010        Some(
13011            self.buffer
13012                .read(cx)
13013                .read(cx)
13014                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13015                .collect(),
13016        )
13017    }
13018
13019    fn selected_text_range(
13020        &mut self,
13021        ignore_disabled_input: bool,
13022        cx: &mut ViewContext<Self>,
13023    ) -> Option<UTF16Selection> {
13024        // Prevent the IME menu from appearing when holding down an alphabetic key
13025        // while input is disabled.
13026        if !ignore_disabled_input && !self.input_enabled {
13027            return None;
13028        }
13029
13030        let selection = self.selections.newest::<OffsetUtf16>(cx);
13031        let range = selection.range();
13032
13033        Some(UTF16Selection {
13034            range: range.start.0..range.end.0,
13035            reversed: selection.reversed,
13036        })
13037    }
13038
13039    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13040        let snapshot = self.buffer.read(cx).read(cx);
13041        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13042        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13043    }
13044
13045    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13046        self.clear_highlights::<InputComposition>(cx);
13047        self.ime_transaction.take();
13048    }
13049
13050    fn replace_text_in_range(
13051        &mut self,
13052        range_utf16: Option<Range<usize>>,
13053        text: &str,
13054        cx: &mut ViewContext<Self>,
13055    ) {
13056        if !self.input_enabled {
13057            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13058            return;
13059        }
13060
13061        self.transact(cx, |this, cx| {
13062            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13063                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13064                Some(this.selection_replacement_ranges(range_utf16, cx))
13065            } else {
13066                this.marked_text_ranges(cx)
13067            };
13068
13069            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13070                let newest_selection_id = this.selections.newest_anchor().id;
13071                this.selections
13072                    .all::<OffsetUtf16>(cx)
13073                    .iter()
13074                    .zip(ranges_to_replace.iter())
13075                    .find_map(|(selection, range)| {
13076                        if selection.id == newest_selection_id {
13077                            Some(
13078                                (range.start.0 as isize - selection.head().0 as isize)
13079                                    ..(range.end.0 as isize - selection.head().0 as isize),
13080                            )
13081                        } else {
13082                            None
13083                        }
13084                    })
13085            });
13086
13087            cx.emit(EditorEvent::InputHandled {
13088                utf16_range_to_replace: range_to_replace,
13089                text: text.into(),
13090            });
13091
13092            if let Some(new_selected_ranges) = new_selected_ranges {
13093                this.change_selections(None, cx, |selections| {
13094                    selections.select_ranges(new_selected_ranges)
13095                });
13096                this.backspace(&Default::default(), cx);
13097            }
13098
13099            this.handle_input(text, cx);
13100        });
13101
13102        if let Some(transaction) = self.ime_transaction {
13103            self.buffer.update(cx, |buffer, cx| {
13104                buffer.group_until_transaction(transaction, cx);
13105            });
13106        }
13107
13108        self.unmark_text(cx);
13109    }
13110
13111    fn replace_and_mark_text_in_range(
13112        &mut self,
13113        range_utf16: Option<Range<usize>>,
13114        text: &str,
13115        new_selected_range_utf16: Option<Range<usize>>,
13116        cx: &mut ViewContext<Self>,
13117    ) {
13118        if !self.input_enabled {
13119            return;
13120        }
13121
13122        let transaction = self.transact(cx, |this, cx| {
13123            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13124                let snapshot = this.buffer.read(cx).read(cx);
13125                if let Some(relative_range_utf16) = range_utf16.as_ref() {
13126                    for marked_range in &mut marked_ranges {
13127                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13128                        marked_range.start.0 += relative_range_utf16.start;
13129                        marked_range.start =
13130                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13131                        marked_range.end =
13132                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13133                    }
13134                }
13135                Some(marked_ranges)
13136            } else if let Some(range_utf16) = range_utf16 {
13137                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13138                Some(this.selection_replacement_ranges(range_utf16, cx))
13139            } else {
13140                None
13141            };
13142
13143            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13144                let newest_selection_id = this.selections.newest_anchor().id;
13145                this.selections
13146                    .all::<OffsetUtf16>(cx)
13147                    .iter()
13148                    .zip(ranges_to_replace.iter())
13149                    .find_map(|(selection, range)| {
13150                        if selection.id == newest_selection_id {
13151                            Some(
13152                                (range.start.0 as isize - selection.head().0 as isize)
13153                                    ..(range.end.0 as isize - selection.head().0 as isize),
13154                            )
13155                        } else {
13156                            None
13157                        }
13158                    })
13159            });
13160
13161            cx.emit(EditorEvent::InputHandled {
13162                utf16_range_to_replace: range_to_replace,
13163                text: text.into(),
13164            });
13165
13166            if let Some(ranges) = ranges_to_replace {
13167                this.change_selections(None, cx, |s| s.select_ranges(ranges));
13168            }
13169
13170            let marked_ranges = {
13171                let snapshot = this.buffer.read(cx).read(cx);
13172                this.selections
13173                    .disjoint_anchors()
13174                    .iter()
13175                    .map(|selection| {
13176                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13177                    })
13178                    .collect::<Vec<_>>()
13179            };
13180
13181            if text.is_empty() {
13182                this.unmark_text(cx);
13183            } else {
13184                this.highlight_text::<InputComposition>(
13185                    marked_ranges.clone(),
13186                    HighlightStyle {
13187                        underline: Some(UnderlineStyle {
13188                            thickness: px(1.),
13189                            color: None,
13190                            wavy: false,
13191                        }),
13192                        ..Default::default()
13193                    },
13194                    cx,
13195                );
13196            }
13197
13198            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13199            let use_autoclose = this.use_autoclose;
13200            let use_auto_surround = this.use_auto_surround;
13201            this.set_use_autoclose(false);
13202            this.set_use_auto_surround(false);
13203            this.handle_input(text, cx);
13204            this.set_use_autoclose(use_autoclose);
13205            this.set_use_auto_surround(use_auto_surround);
13206
13207            if let Some(new_selected_range) = new_selected_range_utf16 {
13208                let snapshot = this.buffer.read(cx).read(cx);
13209                let new_selected_ranges = marked_ranges
13210                    .into_iter()
13211                    .map(|marked_range| {
13212                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13213                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13214                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13215                        snapshot.clip_offset_utf16(new_start, Bias::Left)
13216                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13217                    })
13218                    .collect::<Vec<_>>();
13219
13220                drop(snapshot);
13221                this.change_selections(None, cx, |selections| {
13222                    selections.select_ranges(new_selected_ranges)
13223                });
13224            }
13225        });
13226
13227        self.ime_transaction = self.ime_transaction.or(transaction);
13228        if let Some(transaction) = self.ime_transaction {
13229            self.buffer.update(cx, |buffer, cx| {
13230                buffer.group_until_transaction(transaction, cx);
13231            });
13232        }
13233
13234        if self.text_highlights::<InputComposition>(cx).is_none() {
13235            self.ime_transaction.take();
13236        }
13237    }
13238
13239    fn bounds_for_range(
13240        &mut self,
13241        range_utf16: Range<usize>,
13242        element_bounds: gpui::Bounds<Pixels>,
13243        cx: &mut ViewContext<Self>,
13244    ) -> Option<gpui::Bounds<Pixels>> {
13245        let text_layout_details = self.text_layout_details(cx);
13246        let style = &text_layout_details.editor_style;
13247        let font_id = cx.text_system().resolve_font(&style.text.font());
13248        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13249        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13250
13251        let em_width = cx
13252            .text_system()
13253            .typographic_bounds(font_id, font_size, 'm')
13254            .unwrap()
13255            .size
13256            .width;
13257
13258        let snapshot = self.snapshot(cx);
13259        let scroll_position = snapshot.scroll_position();
13260        let scroll_left = scroll_position.x * em_width;
13261
13262        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13263        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13264            + self.gutter_dimensions.width;
13265        let y = line_height * (start.row().as_f32() - scroll_position.y);
13266
13267        Some(Bounds {
13268            origin: element_bounds.origin + point(x, y),
13269            size: size(em_width, line_height),
13270        })
13271    }
13272}
13273
13274trait SelectionExt {
13275    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13276    fn spanned_rows(
13277        &self,
13278        include_end_if_at_line_start: bool,
13279        map: &DisplaySnapshot,
13280    ) -> Range<MultiBufferRow>;
13281}
13282
13283impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13284    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13285        let start = self
13286            .start
13287            .to_point(&map.buffer_snapshot)
13288            .to_display_point(map);
13289        let end = self
13290            .end
13291            .to_point(&map.buffer_snapshot)
13292            .to_display_point(map);
13293        if self.reversed {
13294            end..start
13295        } else {
13296            start..end
13297        }
13298    }
13299
13300    fn spanned_rows(
13301        &self,
13302        include_end_if_at_line_start: bool,
13303        map: &DisplaySnapshot,
13304    ) -> Range<MultiBufferRow> {
13305        let start = self.start.to_point(&map.buffer_snapshot);
13306        let mut end = self.end.to_point(&map.buffer_snapshot);
13307        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13308            end.row -= 1;
13309        }
13310
13311        let buffer_start = map.prev_line_boundary(start).0;
13312        let buffer_end = map.next_line_boundary(end).0;
13313        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13314    }
13315}
13316
13317impl<T: InvalidationRegion> InvalidationStack<T> {
13318    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13319    where
13320        S: Clone + ToOffset,
13321    {
13322        while let Some(region) = self.last() {
13323            let all_selections_inside_invalidation_ranges =
13324                if selections.len() == region.ranges().len() {
13325                    selections
13326                        .iter()
13327                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13328                        .all(|(selection, invalidation_range)| {
13329                            let head = selection.head().to_offset(buffer);
13330                            invalidation_range.start <= head && invalidation_range.end >= head
13331                        })
13332                } else {
13333                    false
13334                };
13335
13336            if all_selections_inside_invalidation_ranges {
13337                break;
13338            } else {
13339                self.pop();
13340            }
13341        }
13342    }
13343}
13344
13345impl<T> Default for InvalidationStack<T> {
13346    fn default() -> Self {
13347        Self(Default::default())
13348    }
13349}
13350
13351impl<T> Deref for InvalidationStack<T> {
13352    type Target = Vec<T>;
13353
13354    fn deref(&self) -> &Self::Target {
13355        &self.0
13356    }
13357}
13358
13359impl<T> DerefMut for InvalidationStack<T> {
13360    fn deref_mut(&mut self) -> &mut Self::Target {
13361        &mut self.0
13362    }
13363}
13364
13365impl InvalidationRegion for SnippetState {
13366    fn ranges(&self) -> &[Range<Anchor>] {
13367        &self.ranges[self.active_index]
13368    }
13369}
13370
13371pub fn diagnostic_block_renderer(
13372    diagnostic: Diagnostic,
13373    max_message_rows: Option<u8>,
13374    allow_closing: bool,
13375    _is_valid: bool,
13376) -> RenderBlock {
13377    let (text_without_backticks, code_ranges) =
13378        highlight_diagnostic_message(&diagnostic, max_message_rows);
13379
13380    Box::new(move |cx: &mut BlockContext| {
13381        let group_id: SharedString = cx.block_id.to_string().into();
13382
13383        let mut text_style = cx.text_style().clone();
13384        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13385        let theme_settings = ThemeSettings::get_global(cx);
13386        text_style.font_family = theme_settings.buffer_font.family.clone();
13387        text_style.font_style = theme_settings.buffer_font.style;
13388        text_style.font_features = theme_settings.buffer_font.features.clone();
13389        text_style.font_weight = theme_settings.buffer_font.weight;
13390
13391        let multi_line_diagnostic = diagnostic.message.contains('\n');
13392
13393        let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13394            if multi_line_diagnostic {
13395                v_flex()
13396            } else {
13397                h_flex()
13398            }
13399            .when(allow_closing, |div| {
13400                div.children(diagnostic.is_primary.then(|| {
13401                    IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13402                        .icon_color(Color::Muted)
13403                        .size(ButtonSize::Compact)
13404                        .style(ButtonStyle::Transparent)
13405                        .visible_on_hover(group_id.clone())
13406                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13407                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13408                }))
13409            })
13410            .child(
13411                IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13412                    .icon_color(Color::Muted)
13413                    .size(ButtonSize::Compact)
13414                    .style(ButtonStyle::Transparent)
13415                    .visible_on_hover(group_id.clone())
13416                    .on_click({
13417                        let message = diagnostic.message.clone();
13418                        move |_click, cx| {
13419                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13420                        }
13421                    })
13422                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13423            )
13424        };
13425
13426        let icon_size = buttons(&diagnostic, cx.block_id)
13427            .into_any_element()
13428            .layout_as_root(AvailableSpace::min_size(), cx);
13429
13430        h_flex()
13431            .id(cx.block_id)
13432            .group(group_id.clone())
13433            .relative()
13434            .size_full()
13435            .pl(cx.gutter_dimensions.width)
13436            .w(cx.max_width + cx.gutter_dimensions.width)
13437            .child(
13438                div()
13439                    .flex()
13440                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13441                    .flex_shrink(),
13442            )
13443            .child(buttons(&diagnostic, cx.block_id))
13444            .child(div().flex().flex_shrink_0().child(
13445                StyledText::new(text_without_backticks.clone()).with_highlights(
13446                    &text_style,
13447                    code_ranges.iter().map(|range| {
13448                        (
13449                            range.clone(),
13450                            HighlightStyle {
13451                                font_weight: Some(FontWeight::BOLD),
13452                                ..Default::default()
13453                            },
13454                        )
13455                    }),
13456                ),
13457            ))
13458            .into_any_element()
13459    })
13460}
13461
13462pub fn highlight_diagnostic_message(
13463    diagnostic: &Diagnostic,
13464    mut max_message_rows: Option<u8>,
13465) -> (SharedString, Vec<Range<usize>>) {
13466    let mut text_without_backticks = String::new();
13467    let mut code_ranges = Vec::new();
13468
13469    if let Some(source) = &diagnostic.source {
13470        text_without_backticks.push_str(source);
13471        code_ranges.push(0..source.len());
13472        text_without_backticks.push_str(": ");
13473    }
13474
13475    let mut prev_offset = 0;
13476    let mut in_code_block = false;
13477    let has_row_limit = max_message_rows.is_some();
13478    let mut newline_indices = diagnostic
13479        .message
13480        .match_indices('\n')
13481        .filter(|_| has_row_limit)
13482        .map(|(ix, _)| ix)
13483        .fuse()
13484        .peekable();
13485
13486    for (quote_ix, _) in diagnostic
13487        .message
13488        .match_indices('`')
13489        .chain([(diagnostic.message.len(), "")])
13490    {
13491        let mut first_newline_ix = None;
13492        let mut last_newline_ix = None;
13493        while let Some(newline_ix) = newline_indices.peek() {
13494            if *newline_ix < quote_ix {
13495                if first_newline_ix.is_none() {
13496                    first_newline_ix = Some(*newline_ix);
13497                }
13498                last_newline_ix = Some(*newline_ix);
13499
13500                if let Some(rows_left) = &mut max_message_rows {
13501                    if *rows_left == 0 {
13502                        break;
13503                    } else {
13504                        *rows_left -= 1;
13505                    }
13506                }
13507                let _ = newline_indices.next();
13508            } else {
13509                break;
13510            }
13511        }
13512        let prev_len = text_without_backticks.len();
13513        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13514        text_without_backticks.push_str(new_text);
13515        if in_code_block {
13516            code_ranges.push(prev_len..text_without_backticks.len());
13517        }
13518        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13519        in_code_block = !in_code_block;
13520        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13521            text_without_backticks.push_str("...");
13522            break;
13523        }
13524    }
13525
13526    (text_without_backticks.into(), code_ranges)
13527}
13528
13529fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13530    match severity {
13531        DiagnosticSeverity::ERROR => colors.error,
13532        DiagnosticSeverity::WARNING => colors.warning,
13533        DiagnosticSeverity::INFORMATION => colors.info,
13534        DiagnosticSeverity::HINT => colors.info,
13535        _ => colors.ignored,
13536    }
13537}
13538
13539pub fn styled_runs_for_code_label<'a>(
13540    label: &'a CodeLabel,
13541    syntax_theme: &'a theme::SyntaxTheme,
13542) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13543    let fade_out = HighlightStyle {
13544        fade_out: Some(0.35),
13545        ..Default::default()
13546    };
13547
13548    let mut prev_end = label.filter_range.end;
13549    label
13550        .runs
13551        .iter()
13552        .enumerate()
13553        .flat_map(move |(ix, (range, highlight_id))| {
13554            let style = if let Some(style) = highlight_id.style(syntax_theme) {
13555                style
13556            } else {
13557                return Default::default();
13558            };
13559            let mut muted_style = style;
13560            muted_style.highlight(fade_out);
13561
13562            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13563            if range.start >= label.filter_range.end {
13564                if range.start > prev_end {
13565                    runs.push((prev_end..range.start, fade_out));
13566                }
13567                runs.push((range.clone(), muted_style));
13568            } else if range.end <= label.filter_range.end {
13569                runs.push((range.clone(), style));
13570            } else {
13571                runs.push((range.start..label.filter_range.end, style));
13572                runs.push((label.filter_range.end..range.end, muted_style));
13573            }
13574            prev_end = cmp::max(prev_end, range.end);
13575
13576            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13577                runs.push((prev_end..label.text.len(), fade_out));
13578            }
13579
13580            runs
13581        })
13582}
13583
13584pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13585    let mut prev_index = 0;
13586    let mut prev_codepoint: Option<char> = None;
13587    text.char_indices()
13588        .chain([(text.len(), '\0')])
13589        .filter_map(move |(index, codepoint)| {
13590            let prev_codepoint = prev_codepoint.replace(codepoint)?;
13591            let is_boundary = index == text.len()
13592                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13593                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13594            if is_boundary {
13595                let chunk = &text[prev_index..index];
13596                prev_index = index;
13597                Some(chunk)
13598            } else {
13599                None
13600            }
13601        })
13602}
13603
13604pub trait RangeToAnchorExt: Sized {
13605    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13606
13607    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13608        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13609        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
13610    }
13611}
13612
13613impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13614    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13615        let start_offset = self.start.to_offset(snapshot);
13616        let end_offset = self.end.to_offset(snapshot);
13617        if start_offset == end_offset {
13618            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13619        } else {
13620            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13621        }
13622    }
13623}
13624
13625pub trait RowExt {
13626    fn as_f32(&self) -> f32;
13627
13628    fn next_row(&self) -> Self;
13629
13630    fn previous_row(&self) -> Self;
13631
13632    fn minus(&self, other: Self) -> u32;
13633}
13634
13635impl RowExt for DisplayRow {
13636    fn as_f32(&self) -> f32 {
13637        self.0 as f32
13638    }
13639
13640    fn next_row(&self) -> Self {
13641        Self(self.0 + 1)
13642    }
13643
13644    fn previous_row(&self) -> Self {
13645        Self(self.0.saturating_sub(1))
13646    }
13647
13648    fn minus(&self, other: Self) -> u32 {
13649        self.0 - other.0
13650    }
13651}
13652
13653impl RowExt for MultiBufferRow {
13654    fn as_f32(&self) -> f32 {
13655        self.0 as f32
13656    }
13657
13658    fn next_row(&self) -> Self {
13659        Self(self.0 + 1)
13660    }
13661
13662    fn previous_row(&self) -> Self {
13663        Self(self.0.saturating_sub(1))
13664    }
13665
13666    fn minus(&self, other: Self) -> u32 {
13667        self.0 - other.0
13668    }
13669}
13670
13671trait RowRangeExt {
13672    type Row;
13673
13674    fn len(&self) -> usize;
13675
13676    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13677}
13678
13679impl RowRangeExt for Range<MultiBufferRow> {
13680    type Row = MultiBufferRow;
13681
13682    fn len(&self) -> usize {
13683        (self.end.0 - self.start.0) as usize
13684    }
13685
13686    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13687        (self.start.0..self.end.0).map(MultiBufferRow)
13688    }
13689}
13690
13691impl RowRangeExt for Range<DisplayRow> {
13692    type Row = DisplayRow;
13693
13694    fn len(&self) -> usize {
13695        (self.end.0 - self.start.0) as usize
13696    }
13697
13698    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13699        (self.start.0..self.end.0).map(DisplayRow)
13700    }
13701}
13702
13703fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13704    if hunk.diff_base_byte_range.is_empty() {
13705        DiffHunkStatus::Added
13706    } else if hunk.associated_range.is_empty() {
13707        DiffHunkStatus::Removed
13708    } else {
13709        DiffHunkStatus::Modified
13710    }
13711}
13712
13713/// If select range has more than one line, we
13714/// just point the cursor to range.start.
13715fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13716    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13717        range
13718    } else {
13719        range.start..range.start
13720    }
13721}