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 behaviour.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18pub mod display_map;
   19mod editor_settings;
   20mod element;
   21mod hunk_diff;
   22mod inlay_hint_cache;
   23
   24mod debounced_delay;
   25mod git;
   26mod highlight_matching_bracket;
   27mod hover_links;
   28mod hover_popover;
   29mod indent_guides;
   30mod inline_completion_provider;
   31pub mod items;
   32mod mouse_context_menu;
   33pub mod movement;
   34mod persistence;
   35mod rust_analyzer_ext;
   36pub mod scroll;
   37mod selections_collection;
   38pub mod tasks;
   39
   40#[cfg(test)]
   41mod editor_tests;
   42#[cfg(any(test, feature = "test-support"))]
   43pub mod test;
   44use ::git::diff::{DiffHunk, DiffHunkStatus};
   45use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
   46pub(crate) use actions::*;
   47use aho_corasick::AhoCorasick;
   48use anyhow::{anyhow, Context as _, Result};
   49use blink_manager::BlinkManager;
   50use client::{Collaborator, ParticipantIndex};
   51use clock::ReplicaId;
   52use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   53use convert_case::{Case, Casing};
   54use debounced_delay::DebouncedDelay;
   55use display_map::*;
   56pub use display_map::{DisplayPoint, FoldPlaceholder};
   57use editor_settings::CurrentLineHighlight;
   58pub use editor_settings::EditorSettings;
   59use element::LineWithInvisibles;
   60pub use element::{
   61    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   62};
   63use futures::FutureExt;
   64use fuzzy::{StringMatch, StringMatchCandidate};
   65use git::blame::GitBlame;
   66use git::diff_hunk_to_display;
   67use gpui::{
   68    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   69    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardItem,
   70    Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusableView, FontId, FontStyle,
   71    FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, MouseButton, PaintQuad,
   72    ParentElement, Pixels, Render, SharedString, Size, StrikethroughStyle, Styled, StyledText,
   73    Subscription, Task, TextStyle, UnderlineStyle, UniformListScrollHandle, View, ViewContext,
   74    ViewInputHandler, VisualContext, WeakView, WhiteSpace, WindowContext,
   75};
   76use highlight_matching_bracket::refresh_matching_bracket_highlights;
   77use hover_popover::{hide_hover, HoverState};
   78use hunk_diff::ExpandedHunks;
   79pub(crate) use hunk_diff::HunkToExpand;
   80use indent_guides::ActiveIndentGuidesState;
   81use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   82pub use inline_completion_provider::*;
   83pub use items::MAX_TAB_TITLE_LEN;
   84use itertools::Itertools;
   85use language::{
   86    char_kind,
   87    language_settings::{self, all_language_settings, InlayHintSettings},
   88    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   89    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   90    Point, Selection, SelectionGoal, TransactionId,
   91};
   92use language::{BufferRow, Runnable, RunnableRange};
   93use task::{ResolvedTask, TaskTemplate, TaskVariables};
   94
   95use hover_links::{HoverLink, HoveredLinkState, InlayHighlight};
   96use lsp::{DiagnosticSeverity, LanguageServerId};
   97use mouse_context_menu::MouseContextMenu;
   98use movement::TextLayoutDetails;
   99pub use multi_buffer::{
  100    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  101    ToPoint,
  102};
  103use multi_buffer::{MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
  104use ordered_float::OrderedFloat;
  105use parking_lot::{Mutex, RwLock};
  106use project::project_settings::{GitGutterSetting, ProjectSettings};
  107use project::{
  108    CodeAction, Completion, FormatTrigger, Item, Location, Project, ProjectPath,
  109    ProjectTransaction, TaskSourceKind, WorktreeId,
  110};
  111use rand::prelude::*;
  112use rpc::{proto::*, ErrorExt};
  113use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  114use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  115use serde::{Deserialize, Serialize};
  116use settings::{Settings, SettingsStore};
  117use smallvec::SmallVec;
  118use snippet::Snippet;
  119use std::ops::Not as _;
  120use std::{
  121    any::TypeId,
  122    borrow::Cow,
  123    cmp::{self, Ordering, Reverse},
  124    mem,
  125    num::NonZeroU32,
  126    ops::{ControlFlow, Deref, DerefMut, Range, RangeInclusive},
  127    path::Path,
  128    sync::Arc,
  129    time::{Duration, Instant},
  130};
  131pub use sum_tree::Bias;
  132use sum_tree::TreeMap;
  133use text::{BufferId, OffsetUtf16, Rope};
  134use theme::{
  135    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  136    ThemeColors, ThemeSettings,
  137};
  138use ui::{
  139    h_flex, prelude::*, ButtonSize, ButtonStyle, IconButton, IconName, IconSize, ListItem, Popover,
  140    Tooltip,
  141};
  142use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  143use workspace::item::{ItemHandle, PreviewTabsSettings};
  144use workspace::notifications::{DetachAndPromptErr, NotificationId};
  145use workspace::{
  146    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  147};
  148use workspace::{OpenInTerminal, OpenTerminal, Toast};
  149
  150use crate::hover_links::find_url;
  151
  152pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  153const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  154const MAX_LINE_LEN: usize = 1024;
  155const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  156const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  157pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  158#[doc(hidden)]
  159pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  160#[doc(hidden)]
  161pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  162
  163pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  164
  165pub fn render_parsed_markdown(
  166    element_id: impl Into<ElementId>,
  167    parsed: &language::ParsedMarkdown,
  168    editor_style: &EditorStyle,
  169    workspace: Option<WeakView<Workspace>>,
  170    cx: &mut WindowContext,
  171) -> InteractiveText {
  172    let code_span_background_color = cx
  173        .theme()
  174        .colors()
  175        .editor_document_highlight_read_background;
  176
  177    let highlights = gpui::combine_highlights(
  178        parsed.highlights.iter().filter_map(|(range, highlight)| {
  179            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  180            Some((range.clone(), highlight))
  181        }),
  182        parsed
  183            .regions
  184            .iter()
  185            .zip(&parsed.region_ranges)
  186            .filter_map(|(region, range)| {
  187                if region.code {
  188                    Some((
  189                        range.clone(),
  190                        HighlightStyle {
  191                            background_color: Some(code_span_background_color),
  192                            ..Default::default()
  193                        },
  194                    ))
  195                } else {
  196                    None
  197                }
  198            }),
  199    );
  200
  201    let mut links = Vec::new();
  202    let mut link_ranges = Vec::new();
  203    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  204        if let Some(link) = region.link.clone() {
  205            links.push(link);
  206            link_ranges.push(range.clone());
  207        }
  208    }
  209
  210    InteractiveText::new(
  211        element_id,
  212        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  213    )
  214    .on_click(link_ranges, move |clicked_range_ix, cx| {
  215        match &links[clicked_range_ix] {
  216            markdown::Link::Web { url } => cx.open_url(url),
  217            markdown::Link::Path { path } => {
  218                if let Some(workspace) = &workspace {
  219                    _ = workspace.update(cx, |workspace, cx| {
  220                        workspace.open_abs_path(path.clone(), false, cx).detach();
  221                    });
  222                }
  223            }
  224        }
  225    })
  226}
  227
  228#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  229pub(crate) enum InlayId {
  230    Suggestion(usize),
  231    Hint(usize),
  232}
  233
  234impl InlayId {
  235    fn id(&self) -> usize {
  236        match self {
  237            Self::Suggestion(id) => *id,
  238            Self::Hint(id) => *id,
  239        }
  240    }
  241}
  242
  243enum DiffRowHighlight {}
  244enum DocumentHighlightRead {}
  245enum DocumentHighlightWrite {}
  246enum InputComposition {}
  247
  248#[derive(Copy, Clone, PartialEq, Eq)]
  249pub enum Direction {
  250    Prev,
  251    Next,
  252}
  253
  254pub fn init_settings(cx: &mut AppContext) {
  255    EditorSettings::register(cx);
  256}
  257
  258pub fn init(cx: &mut AppContext) {
  259    init_settings(cx);
  260
  261    workspace::register_project_item::<Editor>(cx);
  262    workspace::register_followable_item::<Editor>(cx);
  263    workspace::register_deserializable_item::<Editor>(cx);
  264    cx.observe_new_views(
  265        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  266            workspace.register_action(Editor::new_file);
  267            workspace.register_action(Editor::new_file_in_direction);
  268        },
  269    )
  270    .detach();
  271
  272    cx.on_action(move |_: &workspace::NewFile, cx| {
  273        let app_state = workspace::AppState::global(cx);
  274        if let Some(app_state) = app_state.upgrade() {
  275            workspace::open_new(app_state, cx, |workspace, cx| {
  276                Editor::new_file(workspace, &Default::default(), cx)
  277            })
  278            .detach();
  279        }
  280    });
  281    cx.on_action(move |_: &workspace::NewWindow, cx| {
  282        let app_state = workspace::AppState::global(cx);
  283        if let Some(app_state) = app_state.upgrade() {
  284            workspace::open_new(app_state, cx, |workspace, cx| {
  285                Editor::new_file(workspace, &Default::default(), cx)
  286            })
  287            .detach();
  288        }
  289    });
  290}
  291
  292pub struct SearchWithinRange;
  293
  294trait InvalidationRegion {
  295    fn ranges(&self) -> &[Range<Anchor>];
  296}
  297
  298#[derive(Clone, Debug, PartialEq)]
  299pub enum SelectPhase {
  300    Begin {
  301        position: DisplayPoint,
  302        add: bool,
  303        click_count: usize,
  304    },
  305    BeginColumnar {
  306        position: DisplayPoint,
  307        reset: bool,
  308        goal_column: u32,
  309    },
  310    Extend {
  311        position: DisplayPoint,
  312        click_count: usize,
  313    },
  314    Update {
  315        position: DisplayPoint,
  316        goal_column: u32,
  317        scroll_delta: gpui::Point<f32>,
  318    },
  319    End,
  320}
  321
  322#[derive(Clone, Debug)]
  323pub enum SelectMode {
  324    Character,
  325    Word(Range<Anchor>),
  326    Line(Range<Anchor>),
  327    All,
  328}
  329
  330#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  331pub enum EditorMode {
  332    SingleLine,
  333    AutoHeight { max_lines: usize },
  334    Full,
  335}
  336
  337#[derive(Clone, Debug)]
  338pub enum SoftWrap {
  339    None,
  340    PreferLine,
  341    EditorWidth,
  342    Column(u32),
  343}
  344
  345#[derive(Clone)]
  346pub struct EditorStyle {
  347    pub background: Hsla,
  348    pub local_player: PlayerColor,
  349    pub text: TextStyle,
  350    pub scrollbar_width: Pixels,
  351    pub syntax: Arc<SyntaxTheme>,
  352    pub status: StatusColors,
  353    pub inlay_hints_style: HighlightStyle,
  354    pub suggestions_style: HighlightStyle,
  355}
  356
  357impl Default for EditorStyle {
  358    fn default() -> Self {
  359        Self {
  360            background: Hsla::default(),
  361            local_player: PlayerColor::default(),
  362            text: TextStyle::default(),
  363            scrollbar_width: Pixels::default(),
  364            syntax: Default::default(),
  365            // HACK: Status colors don't have a real default.
  366            // We should look into removing the status colors from the editor
  367            // style and retrieve them directly from the theme.
  368            status: StatusColors::dark(),
  369            inlay_hints_style: HighlightStyle::default(),
  370            suggestions_style: HighlightStyle::default(),
  371        }
  372    }
  373}
  374
  375type CompletionId = usize;
  376
  377// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  378// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  379
  380type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  381
  382struct ScrollbarMarkerState {
  383    scrollbar_size: Size<Pixels>,
  384    dirty: bool,
  385    markers: Arc<[PaintQuad]>,
  386    pending_refresh: Option<Task<Result<()>>>,
  387}
  388
  389impl ScrollbarMarkerState {
  390    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  391        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  392    }
  393}
  394
  395impl Default for ScrollbarMarkerState {
  396    fn default() -> Self {
  397        Self {
  398            scrollbar_size: Size::default(),
  399            dirty: false,
  400            markers: Arc::from([]),
  401            pending_refresh: None,
  402        }
  403    }
  404}
  405
  406#[derive(Clone, Debug)]
  407struct RunnableTasks {
  408    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  409    offset: MultiBufferOffset,
  410    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  411    column: u32,
  412    // Values of all named captures, including those starting with '_'
  413    extra_variables: HashMap<String, String>,
  414    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  415    context_range: Range<BufferOffset>,
  416}
  417
  418#[derive(Clone)]
  419struct ResolvedTasks {
  420    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  421    position: Anchor,
  422}
  423#[derive(Copy, Clone, Debug)]
  424struct MultiBufferOffset(usize);
  425#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  426struct BufferOffset(usize);
  427/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  428///
  429/// See the [module level documentation](self) for more information.
  430pub struct Editor {
  431    focus_handle: FocusHandle,
  432    /// The text buffer being edited
  433    buffer: Model<MultiBuffer>,
  434    /// Map of how text in the buffer should be displayed.
  435    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  436    pub display_map: Model<DisplayMap>,
  437    pub selections: SelectionsCollection,
  438    pub scroll_manager: ScrollManager,
  439    columnar_selection_tail: Option<Anchor>,
  440    add_selections_state: Option<AddSelectionsState>,
  441    select_next_state: Option<SelectNextState>,
  442    select_prev_state: Option<SelectNextState>,
  443    selection_history: SelectionHistory,
  444    autoclose_regions: Vec<AutocloseRegion>,
  445    snippet_stack: InvalidationStack<SnippetState>,
  446    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  447    ime_transaction: Option<TransactionId>,
  448    active_diagnostics: Option<ActiveDiagnosticGroup>,
  449    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  450    project: Option<Model<Project>>,
  451    completion_provider: Option<Box<dyn CompletionProvider>>,
  452    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  453    blink_manager: Model<BlinkManager>,
  454    show_cursor_names: bool,
  455    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  456    pub show_local_selections: bool,
  457    mode: EditorMode,
  458    show_breadcrumbs: bool,
  459    show_gutter: bool,
  460    show_line_numbers: Option<bool>,
  461    show_git_diff_gutter: Option<bool>,
  462    show_code_actions: Option<bool>,
  463    show_wrap_guides: Option<bool>,
  464    show_indent_guides: Option<bool>,
  465    placeholder_text: Option<Arc<str>>,
  466    highlight_order: usize,
  467    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  468    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  469    scrollbar_marker_state: ScrollbarMarkerState,
  470    active_indent_guides_state: ActiveIndentGuidesState,
  471    nav_history: Option<ItemNavHistory>,
  472    context_menu: RwLock<Option<ContextMenu>>,
  473    mouse_context_menu: Option<MouseContextMenu>,
  474    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  475    find_all_references_task_sources: Vec<Anchor>,
  476    next_completion_id: CompletionId,
  477    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  478    available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
  479    code_actions_task: Option<Task<()>>,
  480    document_highlights_task: Option<Task<()>>,
  481    pending_rename: Option<RenameState>,
  482    searchable: bool,
  483    cursor_shape: CursorShape,
  484    current_line_highlight: CurrentLineHighlight,
  485    collapse_matches: bool,
  486    autoindent_mode: Option<AutoindentMode>,
  487    workspace: Option<(WeakView<Workspace>, WorkspaceId)>,
  488    keymap_context_layers: BTreeMap<TypeId, KeyContext>,
  489    input_enabled: bool,
  490    use_modal_editing: bool,
  491    read_only: bool,
  492    leader_peer_id: Option<PeerId>,
  493    remote_id: Option<ViewId>,
  494    hover_state: HoverState,
  495    gutter_hovered: bool,
  496    hovered_link_state: Option<HoveredLinkState>,
  497    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  498    active_inline_completion: Option<Inlay>,
  499    show_inline_completions: bool,
  500    inlay_hint_cache: InlayHintCache,
  501    expanded_hunks: ExpandedHunks,
  502    next_inlay_id: usize,
  503    _subscriptions: Vec<Subscription>,
  504    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  505    gutter_dimensions: GutterDimensions,
  506    pub vim_replace_map: HashMap<Range<usize>, String>,
  507    style: Option<EditorStyle>,
  508    editor_actions: Vec<Box<dyn Fn(&mut ViewContext<Self>)>>,
  509    use_autoclose: bool,
  510    auto_replace_emoji_shortcode: bool,
  511    show_git_blame_gutter: bool,
  512    show_git_blame_inline: bool,
  513    show_git_blame_inline_delay_task: Option<Task<()>>,
  514    git_blame_inline_enabled: bool,
  515    blame: Option<Model<GitBlame>>,
  516    blame_subscription: Option<Subscription>,
  517    custom_context_menu: Option<
  518        Box<
  519            dyn 'static
  520                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  521        >,
  522    >,
  523    last_bounds: Option<Bounds<Pixels>>,
  524    expect_bounds_change: Option<Bounds<Pixels>>,
  525    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  526    tasks_update_task: Option<Task<()>>,
  527}
  528
  529#[derive(Clone)]
  530pub struct EditorSnapshot {
  531    pub mode: EditorMode,
  532    show_gutter: bool,
  533    show_line_numbers: Option<bool>,
  534    show_git_diff_gutter: Option<bool>,
  535    show_code_actions: Option<bool>,
  536    render_git_blame_gutter: bool,
  537    pub display_snapshot: DisplaySnapshot,
  538    pub placeholder_text: Option<Arc<str>>,
  539    is_focused: bool,
  540    scroll_anchor: ScrollAnchor,
  541    ongoing_scroll: OngoingScroll,
  542    current_line_highlight: CurrentLineHighlight,
  543    gutter_hovered: bool,
  544}
  545
  546const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
  547
  548#[derive(Debug, Clone, Copy)]
  549pub struct GutterDimensions {
  550    pub left_padding: Pixels,
  551    pub right_padding: Pixels,
  552    pub width: Pixels,
  553    pub margin: Pixels,
  554    pub git_blame_entries_width: Option<Pixels>,
  555}
  556
  557impl Default for GutterDimensions {
  558    fn default() -> Self {
  559        Self {
  560            left_padding: Pixels::ZERO,
  561            right_padding: Pixels::ZERO,
  562            width: Pixels::ZERO,
  563            margin: Pixels::ZERO,
  564            git_blame_entries_width: None,
  565        }
  566    }
  567}
  568
  569#[derive(Debug)]
  570pub struct RemoteSelection {
  571    pub replica_id: ReplicaId,
  572    pub selection: Selection<Anchor>,
  573    pub cursor_shape: CursorShape,
  574    pub peer_id: PeerId,
  575    pub line_mode: bool,
  576    pub participant_index: Option<ParticipantIndex>,
  577    pub user_name: Option<SharedString>,
  578}
  579
  580#[derive(Clone, Debug)]
  581struct SelectionHistoryEntry {
  582    selections: Arc<[Selection<Anchor>]>,
  583    select_next_state: Option<SelectNextState>,
  584    select_prev_state: Option<SelectNextState>,
  585    add_selections_state: Option<AddSelectionsState>,
  586}
  587
  588enum SelectionHistoryMode {
  589    Normal,
  590    Undoing,
  591    Redoing,
  592}
  593
  594#[derive(Clone, PartialEq, Eq, Hash)]
  595struct HoveredCursor {
  596    replica_id: u16,
  597    selection_id: usize,
  598}
  599
  600impl Default for SelectionHistoryMode {
  601    fn default() -> Self {
  602        Self::Normal
  603    }
  604}
  605
  606#[derive(Default)]
  607struct SelectionHistory {
  608    #[allow(clippy::type_complexity)]
  609    selections_by_transaction:
  610        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  611    mode: SelectionHistoryMode,
  612    undo_stack: VecDeque<SelectionHistoryEntry>,
  613    redo_stack: VecDeque<SelectionHistoryEntry>,
  614}
  615
  616impl SelectionHistory {
  617    fn insert_transaction(
  618        &mut self,
  619        transaction_id: TransactionId,
  620        selections: Arc<[Selection<Anchor>]>,
  621    ) {
  622        self.selections_by_transaction
  623            .insert(transaction_id, (selections, None));
  624    }
  625
  626    #[allow(clippy::type_complexity)]
  627    fn transaction(
  628        &self,
  629        transaction_id: TransactionId,
  630    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  631        self.selections_by_transaction.get(&transaction_id)
  632    }
  633
  634    #[allow(clippy::type_complexity)]
  635    fn transaction_mut(
  636        &mut self,
  637        transaction_id: TransactionId,
  638    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  639        self.selections_by_transaction.get_mut(&transaction_id)
  640    }
  641
  642    fn push(&mut self, entry: SelectionHistoryEntry) {
  643        if !entry.selections.is_empty() {
  644            match self.mode {
  645                SelectionHistoryMode::Normal => {
  646                    self.push_undo(entry);
  647                    self.redo_stack.clear();
  648                }
  649                SelectionHistoryMode::Undoing => self.push_redo(entry),
  650                SelectionHistoryMode::Redoing => self.push_undo(entry),
  651            }
  652        }
  653    }
  654
  655    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  656        if self
  657            .undo_stack
  658            .back()
  659            .map_or(true, |e| e.selections != entry.selections)
  660        {
  661            self.undo_stack.push_back(entry);
  662            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  663                self.undo_stack.pop_front();
  664            }
  665        }
  666    }
  667
  668    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  669        if self
  670            .redo_stack
  671            .back()
  672            .map_or(true, |e| e.selections != entry.selections)
  673        {
  674            self.redo_stack.push_back(entry);
  675            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  676                self.redo_stack.pop_front();
  677            }
  678        }
  679    }
  680}
  681
  682struct RowHighlight {
  683    index: usize,
  684    range: RangeInclusive<Anchor>,
  685    color: Option<Hsla>,
  686    should_autoscroll: bool,
  687}
  688
  689#[derive(Clone, Debug)]
  690struct AddSelectionsState {
  691    above: bool,
  692    stack: Vec<usize>,
  693}
  694
  695#[derive(Clone)]
  696struct SelectNextState {
  697    query: AhoCorasick,
  698    wordwise: bool,
  699    done: bool,
  700}
  701
  702impl std::fmt::Debug for SelectNextState {
  703    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  704        f.debug_struct(std::any::type_name::<Self>())
  705            .field("wordwise", &self.wordwise)
  706            .field("done", &self.done)
  707            .finish()
  708    }
  709}
  710
  711#[derive(Debug)]
  712struct AutocloseRegion {
  713    selection_id: usize,
  714    range: Range<Anchor>,
  715    pair: BracketPair,
  716}
  717
  718#[derive(Debug)]
  719struct SnippetState {
  720    ranges: Vec<Vec<Range<Anchor>>>,
  721    active_index: usize,
  722}
  723
  724#[doc(hidden)]
  725pub struct RenameState {
  726    pub range: Range<Anchor>,
  727    pub old_name: Arc<str>,
  728    pub editor: View<Editor>,
  729    block_id: BlockId,
  730}
  731
  732struct InvalidationStack<T>(Vec<T>);
  733
  734struct RegisteredInlineCompletionProvider {
  735    provider: Arc<dyn InlineCompletionProviderHandle>,
  736    _subscription: Subscription,
  737}
  738
  739enum ContextMenu {
  740    Completions(CompletionsMenu),
  741    CodeActions(CodeActionsMenu),
  742}
  743
  744impl ContextMenu {
  745    fn select_first(
  746        &mut self,
  747        project: Option<&Model<Project>>,
  748        cx: &mut ViewContext<Editor>,
  749    ) -> bool {
  750        if self.visible() {
  751            match self {
  752                ContextMenu::Completions(menu) => menu.select_first(project, cx),
  753                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  754            }
  755            true
  756        } else {
  757            false
  758        }
  759    }
  760
  761    fn select_prev(
  762        &mut self,
  763        project: Option<&Model<Project>>,
  764        cx: &mut ViewContext<Editor>,
  765    ) -> bool {
  766        if self.visible() {
  767            match self {
  768                ContextMenu::Completions(menu) => menu.select_prev(project, cx),
  769                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  770            }
  771            true
  772        } else {
  773            false
  774        }
  775    }
  776
  777    fn select_next(
  778        &mut self,
  779        project: Option<&Model<Project>>,
  780        cx: &mut ViewContext<Editor>,
  781    ) -> bool {
  782        if self.visible() {
  783            match self {
  784                ContextMenu::Completions(menu) => menu.select_next(project, cx),
  785                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  786            }
  787            true
  788        } else {
  789            false
  790        }
  791    }
  792
  793    fn select_last(
  794        &mut self,
  795        project: Option<&Model<Project>>,
  796        cx: &mut ViewContext<Editor>,
  797    ) -> bool {
  798        if self.visible() {
  799            match self {
  800                ContextMenu::Completions(menu) => menu.select_last(project, cx),
  801                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  802            }
  803            true
  804        } else {
  805            false
  806        }
  807    }
  808
  809    fn visible(&self) -> bool {
  810        match self {
  811            ContextMenu::Completions(menu) => menu.visible(),
  812            ContextMenu::CodeActions(menu) => menu.visible(),
  813        }
  814    }
  815
  816    fn render(
  817        &self,
  818        cursor_position: DisplayPoint,
  819        style: &EditorStyle,
  820        max_height: Pixels,
  821        workspace: Option<WeakView<Workspace>>,
  822        cx: &mut ViewContext<Editor>,
  823    ) -> (ContextMenuOrigin, AnyElement) {
  824        match self {
  825            ContextMenu::Completions(menu) => (
  826                ContextMenuOrigin::EditorPoint(cursor_position),
  827                menu.render(style, max_height, workspace, cx),
  828            ),
  829            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  830        }
  831    }
  832}
  833
  834enum ContextMenuOrigin {
  835    EditorPoint(DisplayPoint),
  836    GutterIndicator(DisplayRow),
  837}
  838
  839#[derive(Clone)]
  840struct CompletionsMenu {
  841    id: CompletionId,
  842    initial_position: Anchor,
  843    buffer: Model<Buffer>,
  844    completions: Arc<RwLock<Box<[Completion]>>>,
  845    match_candidates: Arc<[StringMatchCandidate]>,
  846    matches: Arc<[StringMatch]>,
  847    selected_item: usize,
  848    scroll_handle: UniformListScrollHandle,
  849    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  850}
  851
  852impl CompletionsMenu {
  853    fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  854        self.selected_item = 0;
  855        self.scroll_handle.scroll_to_item(self.selected_item);
  856        self.attempt_resolve_selected_completion_documentation(project, cx);
  857        cx.notify();
  858    }
  859
  860    fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  861        if self.selected_item > 0 {
  862            self.selected_item -= 1;
  863        } else {
  864            self.selected_item = self.matches.len() - 1;
  865        }
  866        self.scroll_handle.scroll_to_item(self.selected_item);
  867        self.attempt_resolve_selected_completion_documentation(project, cx);
  868        cx.notify();
  869    }
  870
  871    fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  872        if self.selected_item + 1 < self.matches.len() {
  873            self.selected_item += 1;
  874        } else {
  875            self.selected_item = 0;
  876        }
  877        self.scroll_handle.scroll_to_item(self.selected_item);
  878        self.attempt_resolve_selected_completion_documentation(project, cx);
  879        cx.notify();
  880    }
  881
  882    fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  883        self.selected_item = self.matches.len() - 1;
  884        self.scroll_handle.scroll_to_item(self.selected_item);
  885        self.attempt_resolve_selected_completion_documentation(project, cx);
  886        cx.notify();
  887    }
  888
  889    fn pre_resolve_completion_documentation(
  890        buffer: Model<Buffer>,
  891        completions: Arc<RwLock<Box<[Completion]>>>,
  892        matches: Arc<[StringMatch]>,
  893        editor: &Editor,
  894        cx: &mut ViewContext<Editor>,
  895    ) -> Task<()> {
  896        let settings = EditorSettings::get_global(cx);
  897        if !settings.show_completion_documentation {
  898            return Task::ready(());
  899        }
  900
  901        let Some(provider) = editor.completion_provider.as_ref() else {
  902            return Task::ready(());
  903        };
  904
  905        let resolve_task = provider.resolve_completions(
  906            buffer,
  907            matches.iter().map(|m| m.candidate_id).collect(),
  908            completions.clone(),
  909            cx,
  910        );
  911
  912        return cx.spawn(move |this, mut cx| async move {
  913            if let Some(true) = resolve_task.await.log_err() {
  914                this.update(&mut cx, |_, cx| cx.notify()).ok();
  915            }
  916        });
  917    }
  918
  919    fn attempt_resolve_selected_completion_documentation(
  920        &mut self,
  921        project: Option<&Model<Project>>,
  922        cx: &mut ViewContext<Editor>,
  923    ) {
  924        let settings = EditorSettings::get_global(cx);
  925        if !settings.show_completion_documentation {
  926            return;
  927        }
  928
  929        let completion_index = self.matches[self.selected_item].candidate_id;
  930        let Some(project) = project else {
  931            return;
  932        };
  933
  934        let resolve_task = project.update(cx, |project, cx| {
  935            project.resolve_completions(
  936                self.buffer.clone(),
  937                vec![completion_index],
  938                self.completions.clone(),
  939                cx,
  940            )
  941        });
  942
  943        let delay_ms =
  944            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
  945        let delay = Duration::from_millis(delay_ms);
  946
  947        self.selected_completion_documentation_resolve_debounce
  948            .lock()
  949            .fire_new(delay, cx, |_, cx| {
  950                cx.spawn(move |this, mut cx| async move {
  951                    if let Some(true) = resolve_task.await.log_err() {
  952                        this.update(&mut cx, |_, cx| cx.notify()).ok();
  953                    }
  954                })
  955            });
  956    }
  957
  958    fn visible(&self) -> bool {
  959        !self.matches.is_empty()
  960    }
  961
  962    fn render(
  963        &self,
  964        style: &EditorStyle,
  965        max_height: Pixels,
  966        workspace: Option<WeakView<Workspace>>,
  967        cx: &mut ViewContext<Editor>,
  968    ) -> AnyElement {
  969        let settings = EditorSettings::get_global(cx);
  970        let show_completion_documentation = settings.show_completion_documentation;
  971
  972        let widest_completion_ix = self
  973            .matches
  974            .iter()
  975            .enumerate()
  976            .max_by_key(|(_, mat)| {
  977                let completions = self.completions.read();
  978                let completion = &completions[mat.candidate_id];
  979                let documentation = &completion.documentation;
  980
  981                let mut len = completion.label.text.chars().count();
  982                if let Some(Documentation::SingleLine(text)) = documentation {
  983                    if show_completion_documentation {
  984                        len += text.chars().count();
  985                    }
  986                }
  987
  988                len
  989            })
  990            .map(|(ix, _)| ix);
  991
  992        let completions = self.completions.clone();
  993        let matches = self.matches.clone();
  994        let selected_item = self.selected_item;
  995        let style = style.clone();
  996
  997        let multiline_docs = if show_completion_documentation {
  998            let mat = &self.matches[selected_item];
  999            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1000                Some(Documentation::MultiLinePlainText(text)) => {
 1001                    Some(div().child(SharedString::from(text.clone())))
 1002                }
 1003                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1004                    Some(div().child(render_parsed_markdown(
 1005                        "completions_markdown",
 1006                        parsed,
 1007                        &style,
 1008                        workspace,
 1009                        cx,
 1010                    )))
 1011                }
 1012                _ => None,
 1013            };
 1014            multiline_docs.map(|div| {
 1015                div.id("multiline_docs")
 1016                    .max_h(max_height)
 1017                    .flex_1()
 1018                    .px_1p5()
 1019                    .py_1()
 1020                    .min_w(px(260.))
 1021                    .max_w(px(640.))
 1022                    .w(px(500.))
 1023                    .overflow_y_scroll()
 1024                    .occlude()
 1025            })
 1026        } else {
 1027            None
 1028        };
 1029
 1030        let list = uniform_list(
 1031            cx.view().clone(),
 1032            "completions",
 1033            matches.len(),
 1034            move |_editor, range, cx| {
 1035                let start_ix = range.start;
 1036                let completions_guard = completions.read();
 1037
 1038                matches[range]
 1039                    .iter()
 1040                    .enumerate()
 1041                    .map(|(ix, mat)| {
 1042                        let item_ix = start_ix + ix;
 1043                        let candidate_id = mat.candidate_id;
 1044                        let completion = &completions_guard[candidate_id];
 1045
 1046                        let documentation = if show_completion_documentation {
 1047                            &completion.documentation
 1048                        } else {
 1049                            &None
 1050                        };
 1051
 1052                        let highlights = gpui::combine_highlights(
 1053                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1054                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1055                                |(range, mut highlight)| {
 1056                                    // Ignore font weight for syntax highlighting, as we'll use it
 1057                                    // for fuzzy matches.
 1058                                    highlight.font_weight = None;
 1059
 1060                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1061                                        highlight.strikethrough = Some(StrikethroughStyle {
 1062                                            thickness: 1.0.into(),
 1063                                            ..Default::default()
 1064                                        });
 1065                                        highlight.color = Some(cx.theme().colors().text_muted);
 1066                                    }
 1067
 1068                                    (range, highlight)
 1069                                },
 1070                            ),
 1071                        );
 1072                        let completion_label = StyledText::new(completion.label.text.clone())
 1073                            .with_highlights(&style.text, highlights);
 1074                        let documentation_label =
 1075                            if let Some(Documentation::SingleLine(text)) = documentation {
 1076                                if text.trim().is_empty() {
 1077                                    None
 1078                                } else {
 1079                                    Some(
 1080                                        h_flex().ml_4().child(
 1081                                            Label::new(text.clone())
 1082                                                .size(LabelSize::Small)
 1083                                                .color(Color::Muted),
 1084                                        ),
 1085                                    )
 1086                                }
 1087                            } else {
 1088                                None
 1089                            };
 1090
 1091                        div().min_w(px(220.)).max_w(px(540.)).child(
 1092                            ListItem::new(mat.candidate_id)
 1093                                .inset(true)
 1094                                .selected(item_ix == selected_item)
 1095                                .on_click(cx.listener(move |editor, _event, cx| {
 1096                                    cx.stop_propagation();
 1097                                    if let Some(task) = editor.confirm_completion(
 1098                                        &ConfirmCompletion {
 1099                                            item_ix: Some(item_ix),
 1100                                        },
 1101                                        cx,
 1102                                    ) {
 1103                                        task.detach_and_log_err(cx)
 1104                                    }
 1105                                }))
 1106                                .child(h_flex().overflow_hidden().child(completion_label))
 1107                                .end_slot::<Div>(documentation_label),
 1108                        )
 1109                    })
 1110                    .collect()
 1111            },
 1112        )
 1113        .occlude()
 1114        .max_h(max_height)
 1115        .track_scroll(self.scroll_handle.clone())
 1116        .with_width_from_item(widest_completion_ix);
 1117
 1118        Popover::new()
 1119            .child(list)
 1120            .when_some(multiline_docs, |popover, multiline_docs| {
 1121                popover.aside(multiline_docs)
 1122            })
 1123            .into_any_element()
 1124    }
 1125
 1126    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1127        let mut matches = if let Some(query) = query {
 1128            fuzzy::match_strings(
 1129                &self.match_candidates,
 1130                query,
 1131                query.chars().any(|c| c.is_uppercase()),
 1132                100,
 1133                &Default::default(),
 1134                executor,
 1135            )
 1136            .await
 1137        } else {
 1138            self.match_candidates
 1139                .iter()
 1140                .enumerate()
 1141                .map(|(candidate_id, candidate)| StringMatch {
 1142                    candidate_id,
 1143                    score: Default::default(),
 1144                    positions: Default::default(),
 1145                    string: candidate.string.clone(),
 1146                })
 1147                .collect()
 1148        };
 1149
 1150        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1151        if let Some(query) = query {
 1152            if let Some(query_start) = query.chars().next() {
 1153                matches.retain(|string_match| {
 1154                    split_words(&string_match.string).any(|word| {
 1155                        // Check that the first codepoint of the word as lowercase matches the first
 1156                        // codepoint of the query as lowercase
 1157                        word.chars()
 1158                            .flat_map(|codepoint| codepoint.to_lowercase())
 1159                            .zip(query_start.to_lowercase())
 1160                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1161                    })
 1162                });
 1163            }
 1164        }
 1165
 1166        let completions = self.completions.read();
 1167        matches.sort_unstable_by_key(|mat| {
 1168            // We do want to strike a balance here between what the language server tells us
 1169            // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1170            // `Creat` and there is a local variable called `CreateComponent`).
 1171            // So what we do is: we bucket all matches into two buckets
 1172            // - Strong matches
 1173            // - Weak matches
 1174            // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1175            // and the Weak matches are the rest.
 1176            //
 1177            // For the strong matches, we sort by the language-servers score first and for the weak
 1178            // matches, we prefer our fuzzy finder first.
 1179            //
 1180            // The thinking behind that: it's useless to take the sort_text the language-server gives
 1181            // us into account when it's obviously a bad match.
 1182
 1183            #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1184            enum MatchScore<'a> {
 1185                Strong {
 1186                    sort_text: Option<&'a str>,
 1187                    score: Reverse<OrderedFloat<f64>>,
 1188                    sort_key: (usize, &'a str),
 1189                },
 1190                Weak {
 1191                    score: Reverse<OrderedFloat<f64>>,
 1192                    sort_text: Option<&'a str>,
 1193                    sort_key: (usize, &'a str),
 1194                },
 1195            }
 1196
 1197            let completion = &completions[mat.candidate_id];
 1198            let sort_key = completion.sort_key();
 1199            let sort_text = completion.lsp_completion.sort_text.as_deref();
 1200            let score = Reverse(OrderedFloat(mat.score));
 1201
 1202            if mat.score >= 0.2 {
 1203                MatchScore::Strong {
 1204                    sort_text,
 1205                    score,
 1206                    sort_key,
 1207                }
 1208            } else {
 1209                MatchScore::Weak {
 1210                    score,
 1211                    sort_text,
 1212                    sort_key,
 1213                }
 1214            }
 1215        });
 1216
 1217        for mat in &mut matches {
 1218            let completion = &completions[mat.candidate_id];
 1219            mat.string.clone_from(&completion.label.text);
 1220            for position in &mut mat.positions {
 1221                *position += completion.label.filter_range.start;
 1222            }
 1223        }
 1224        drop(completions);
 1225
 1226        self.matches = matches.into();
 1227        self.selected_item = 0;
 1228    }
 1229}
 1230
 1231#[derive(Clone)]
 1232struct CodeActionContents {
 1233    tasks: Option<Arc<ResolvedTasks>>,
 1234    actions: Option<Arc<[CodeAction]>>,
 1235}
 1236
 1237impl CodeActionContents {
 1238    fn len(&self) -> usize {
 1239        match (&self.tasks, &self.actions) {
 1240            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1241            (Some(tasks), None) => tasks.templates.len(),
 1242            (None, Some(actions)) => actions.len(),
 1243            (None, None) => 0,
 1244        }
 1245    }
 1246
 1247    fn is_empty(&self) -> bool {
 1248        match (&self.tasks, &self.actions) {
 1249            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1250            (Some(tasks), None) => tasks.templates.is_empty(),
 1251            (None, Some(actions)) => actions.is_empty(),
 1252            (None, None) => true,
 1253        }
 1254    }
 1255
 1256    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1257        self.tasks
 1258            .iter()
 1259            .flat_map(|tasks| {
 1260                tasks
 1261                    .templates
 1262                    .iter()
 1263                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1264            })
 1265            .chain(self.actions.iter().flat_map(|actions| {
 1266                actions
 1267                    .iter()
 1268                    .map(|action| CodeActionsItem::CodeAction(action.clone()))
 1269            }))
 1270    }
 1271    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1272        match (&self.tasks, &self.actions) {
 1273            (Some(tasks), Some(actions)) => {
 1274                if index < tasks.templates.len() {
 1275                    tasks
 1276                        .templates
 1277                        .get(index)
 1278                        .cloned()
 1279                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1280                } else {
 1281                    actions
 1282                        .get(index - tasks.templates.len())
 1283                        .cloned()
 1284                        .map(CodeActionsItem::CodeAction)
 1285                }
 1286            }
 1287            (Some(tasks), None) => tasks
 1288                .templates
 1289                .get(index)
 1290                .cloned()
 1291                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1292            (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
 1293            (None, None) => None,
 1294        }
 1295    }
 1296}
 1297
 1298#[allow(clippy::large_enum_variant)]
 1299#[derive(Clone)]
 1300enum CodeActionsItem {
 1301    Task(TaskSourceKind, ResolvedTask),
 1302    CodeAction(CodeAction),
 1303}
 1304
 1305impl CodeActionsItem {
 1306    fn as_task(&self) -> Option<&ResolvedTask> {
 1307        let Self::Task(_, task) = self else {
 1308            return None;
 1309        };
 1310        Some(task)
 1311    }
 1312    fn as_code_action(&self) -> Option<&CodeAction> {
 1313        let Self::CodeAction(action) = self else {
 1314            return None;
 1315        };
 1316        Some(action)
 1317    }
 1318    fn label(&self) -> String {
 1319        match self {
 1320            Self::CodeAction(action) => action.lsp_action.title.clone(),
 1321            Self::Task(_, task) => task.resolved_label.clone(),
 1322        }
 1323    }
 1324}
 1325
 1326struct CodeActionsMenu {
 1327    actions: CodeActionContents,
 1328    buffer: Model<Buffer>,
 1329    selected_item: usize,
 1330    scroll_handle: UniformListScrollHandle,
 1331    deployed_from_indicator: Option<DisplayRow>,
 1332}
 1333
 1334impl CodeActionsMenu {
 1335    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1336        self.selected_item = 0;
 1337        self.scroll_handle.scroll_to_item(self.selected_item);
 1338        cx.notify()
 1339    }
 1340
 1341    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1342        if self.selected_item > 0 {
 1343            self.selected_item -= 1;
 1344        } else {
 1345            self.selected_item = self.actions.len() - 1;
 1346        }
 1347        self.scroll_handle.scroll_to_item(self.selected_item);
 1348        cx.notify();
 1349    }
 1350
 1351    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1352        if self.selected_item + 1 < self.actions.len() {
 1353            self.selected_item += 1;
 1354        } else {
 1355            self.selected_item = 0;
 1356        }
 1357        self.scroll_handle.scroll_to_item(self.selected_item);
 1358        cx.notify();
 1359    }
 1360
 1361    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1362        self.selected_item = self.actions.len() - 1;
 1363        self.scroll_handle.scroll_to_item(self.selected_item);
 1364        cx.notify()
 1365    }
 1366
 1367    fn visible(&self) -> bool {
 1368        !self.actions.is_empty()
 1369    }
 1370
 1371    fn render(
 1372        &self,
 1373        cursor_position: DisplayPoint,
 1374        _style: &EditorStyle,
 1375        max_height: Pixels,
 1376        cx: &mut ViewContext<Editor>,
 1377    ) -> (ContextMenuOrigin, AnyElement) {
 1378        let actions = self.actions.clone();
 1379        let selected_item = self.selected_item;
 1380        let element = uniform_list(
 1381            cx.view().clone(),
 1382            "code_actions_menu",
 1383            self.actions.len(),
 1384            move |_this, range, cx| {
 1385                actions
 1386                    .iter()
 1387                    .skip(range.start)
 1388                    .take(range.end - range.start)
 1389                    .enumerate()
 1390                    .map(|(ix, action)| {
 1391                        let item_ix = range.start + ix;
 1392                        let selected = selected_item == item_ix;
 1393                        let colors = cx.theme().colors();
 1394                        div()
 1395                            .px_2()
 1396                            .text_color(colors.text)
 1397                            .when(selected, |style| {
 1398                                style
 1399                                    .bg(colors.element_active)
 1400                                    .text_color(colors.text_accent)
 1401                            })
 1402                            .hover(|style| {
 1403                                style
 1404                                    .bg(colors.element_hover)
 1405                                    .text_color(colors.text_accent)
 1406                            })
 1407                            .whitespace_nowrap()
 1408                            .when_some(action.as_code_action(), |this, action| {
 1409                                this.on_mouse_down(
 1410                                    MouseButton::Left,
 1411                                    cx.listener(move |editor, _, cx| {
 1412                                        cx.stop_propagation();
 1413                                        if let Some(task) = editor.confirm_code_action(
 1414                                            &ConfirmCodeAction {
 1415                                                item_ix: Some(item_ix),
 1416                                            },
 1417                                            cx,
 1418                                        ) {
 1419                                            task.detach_and_log_err(cx)
 1420                                        }
 1421                                    }),
 1422                                )
 1423                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1424                                .child(SharedString::from(action.lsp_action.title.clone()))
 1425                            })
 1426                            .when_some(action.as_task(), |this, task| {
 1427                                this.on_mouse_down(
 1428                                    MouseButton::Left,
 1429                                    cx.listener(move |editor, _, cx| {
 1430                                        cx.stop_propagation();
 1431                                        if let Some(task) = editor.confirm_code_action(
 1432                                            &ConfirmCodeAction {
 1433                                                item_ix: Some(item_ix),
 1434                                            },
 1435                                            cx,
 1436                                        ) {
 1437                                            task.detach_and_log_err(cx)
 1438                                        }
 1439                                    }),
 1440                                )
 1441                                .child(SharedString::from(task.resolved_label.clone()))
 1442                            })
 1443                    })
 1444                    .collect()
 1445            },
 1446        )
 1447        .elevation_1(cx)
 1448        .px_2()
 1449        .py_1()
 1450        .max_h(max_height)
 1451        .occlude()
 1452        .track_scroll(self.scroll_handle.clone())
 1453        .with_width_from_item(
 1454            self.actions
 1455                .iter()
 1456                .enumerate()
 1457                .max_by_key(|(_, action)| match action {
 1458                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1459                    CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
 1460                })
 1461                .map(|(ix, _)| ix),
 1462        )
 1463        .into_any_element();
 1464
 1465        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1466            ContextMenuOrigin::GutterIndicator(row)
 1467        } else {
 1468            ContextMenuOrigin::EditorPoint(cursor_position)
 1469        };
 1470
 1471        (cursor_position, element)
 1472    }
 1473}
 1474
 1475#[derive(Debug)]
 1476struct ActiveDiagnosticGroup {
 1477    primary_range: Range<Anchor>,
 1478    primary_message: String,
 1479    group_id: usize,
 1480    blocks: HashMap<BlockId, Diagnostic>,
 1481    is_valid: bool,
 1482}
 1483
 1484#[derive(Serialize, Deserialize)]
 1485pub struct ClipboardSelection {
 1486    pub len: usize,
 1487    pub is_entire_line: bool,
 1488    pub first_line_indent: u32,
 1489}
 1490
 1491#[derive(Debug)]
 1492pub(crate) struct NavigationData {
 1493    cursor_anchor: Anchor,
 1494    cursor_position: Point,
 1495    scroll_anchor: ScrollAnchor,
 1496    scroll_top_row: u32,
 1497}
 1498
 1499enum GotoDefinitionKind {
 1500    Symbol,
 1501    Type,
 1502    Implementation,
 1503}
 1504
 1505#[derive(Debug, Clone)]
 1506enum InlayHintRefreshReason {
 1507    Toggle(bool),
 1508    SettingsChange(InlayHintSettings),
 1509    NewLinesShown,
 1510    BufferEdited(HashSet<Arc<Language>>),
 1511    RefreshRequested,
 1512    ExcerptsRemoved(Vec<ExcerptId>),
 1513}
 1514
 1515impl InlayHintRefreshReason {
 1516    fn description(&self) -> &'static str {
 1517        match self {
 1518            Self::Toggle(_) => "toggle",
 1519            Self::SettingsChange(_) => "settings change",
 1520            Self::NewLinesShown => "new lines shown",
 1521            Self::BufferEdited(_) => "buffer edited",
 1522            Self::RefreshRequested => "refresh requested",
 1523            Self::ExcerptsRemoved(_) => "excerpts removed",
 1524        }
 1525    }
 1526}
 1527
 1528impl Editor {
 1529    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1530        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1531        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1532        Self::new(EditorMode::SingleLine, buffer, None, cx)
 1533    }
 1534
 1535    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1536        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1537        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1538        Self::new(EditorMode::Full, buffer, None, cx)
 1539    }
 1540
 1541    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1542        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1543        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1544        Self::new(EditorMode::AutoHeight { max_lines }, buffer, None, cx)
 1545    }
 1546
 1547    pub fn for_buffer(
 1548        buffer: Model<Buffer>,
 1549        project: Option<Model<Project>>,
 1550        cx: &mut ViewContext<Self>,
 1551    ) -> Self {
 1552        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1553        Self::new(EditorMode::Full, buffer, project, cx)
 1554    }
 1555
 1556    pub fn for_multibuffer(
 1557        buffer: Model<MultiBuffer>,
 1558        project: Option<Model<Project>>,
 1559        cx: &mut ViewContext<Self>,
 1560    ) -> Self {
 1561        Self::new(EditorMode::Full, buffer, project, cx)
 1562    }
 1563
 1564    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1565        let mut clone = Self::new(self.mode, self.buffer.clone(), self.project.clone(), cx);
 1566        self.display_map.update(cx, |display_map, cx| {
 1567            let snapshot = display_map.snapshot(cx);
 1568            clone.display_map.update(cx, |display_map, cx| {
 1569                display_map.set_state(&snapshot, cx);
 1570            });
 1571        });
 1572        clone.selections.clone_state(&self.selections);
 1573        clone.scroll_manager.clone_state(&self.scroll_manager);
 1574        clone.searchable = self.searchable;
 1575        clone
 1576    }
 1577
 1578    fn new(
 1579        mode: EditorMode,
 1580        buffer: Model<MultiBuffer>,
 1581        project: Option<Model<Project>>,
 1582        cx: &mut ViewContext<Self>,
 1583    ) -> Self {
 1584        let style = cx.text_style();
 1585        let font_size = style.font_size.to_pixels(cx.rem_size());
 1586        let editor = cx.view().downgrade();
 1587        let fold_placeholder = FoldPlaceholder {
 1588            constrain_width: true,
 1589            render: Arc::new(move |fold_id, fold_range, cx| {
 1590                let editor = editor.clone();
 1591                div()
 1592                    .id(fold_id)
 1593                    .bg(cx.theme().colors().ghost_element_background)
 1594                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1595                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1596                    .rounded_sm()
 1597                    .size_full()
 1598                    .cursor_pointer()
 1599                    .child("")
 1600                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1601                    .on_click(move |_, cx| {
 1602                        editor
 1603                            .update(cx, |editor, cx| {
 1604                                editor.unfold_ranges(
 1605                                    [fold_range.start..fold_range.end],
 1606                                    true,
 1607                                    false,
 1608                                    cx,
 1609                                );
 1610                                cx.stop_propagation();
 1611                            })
 1612                            .ok();
 1613                    })
 1614                    .into_any()
 1615            }),
 1616        };
 1617        let display_map = cx.new_model(|cx| {
 1618            DisplayMap::new(
 1619                buffer.clone(),
 1620                style.font(),
 1621                font_size,
 1622                None,
 1623                2,
 1624                1,
 1625                fold_placeholder,
 1626                cx,
 1627            )
 1628        });
 1629
 1630        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1631
 1632        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1633
 1634        let soft_wrap_mode_override =
 1635            (mode == EditorMode::SingleLine).then(|| language_settings::SoftWrap::PreferLine);
 1636
 1637        let mut project_subscriptions = Vec::new();
 1638        if mode == EditorMode::Full {
 1639            if let Some(project) = project.as_ref() {
 1640                if buffer.read(cx).is_singleton() {
 1641                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1642                        cx.emit(EditorEvent::TitleChanged);
 1643                    }));
 1644                }
 1645                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1646                    if let project::Event::RefreshInlayHints = event {
 1647                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1648                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1649                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1650                            let focus_handle = editor.focus_handle(cx);
 1651                            if focus_handle.is_focused(cx) {
 1652                                let snapshot = buffer.read(cx).snapshot();
 1653                                for (range, snippet) in snippet_edits {
 1654                                    let editor_range =
 1655                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1656                                    editor
 1657                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1658                                        .ok();
 1659                                }
 1660                            }
 1661                        }
 1662                    }
 1663                }));
 1664                let task_inventory = project.read(cx).task_inventory().clone();
 1665                project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1666                    editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1667                }));
 1668            }
 1669        }
 1670
 1671        let inlay_hint_settings = inlay_hint_settings(
 1672            selections.newest_anchor().head(),
 1673            &buffer.read(cx).snapshot(cx),
 1674            cx,
 1675        );
 1676        let focus_handle = cx.focus_handle();
 1677        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1678        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1679
 1680        let mut this = Self {
 1681            focus_handle,
 1682            buffer: buffer.clone(),
 1683            display_map: display_map.clone(),
 1684            selections,
 1685            scroll_manager: ScrollManager::new(cx),
 1686            columnar_selection_tail: None,
 1687            add_selections_state: None,
 1688            select_next_state: None,
 1689            select_prev_state: None,
 1690            selection_history: Default::default(),
 1691            autoclose_regions: Default::default(),
 1692            snippet_stack: Default::default(),
 1693            select_larger_syntax_node_stack: Vec::new(),
 1694            ime_transaction: Default::default(),
 1695            active_diagnostics: None,
 1696            soft_wrap_mode_override,
 1697            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1698            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1699            project,
 1700            blink_manager: blink_manager.clone(),
 1701            show_local_selections: true,
 1702            mode,
 1703            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1704            show_gutter: mode == EditorMode::Full,
 1705            show_line_numbers: None,
 1706            show_git_diff_gutter: None,
 1707            show_code_actions: None,
 1708            show_wrap_guides: None,
 1709            show_indent_guides: None,
 1710            placeholder_text: None,
 1711            highlight_order: 0,
 1712            highlighted_rows: HashMap::default(),
 1713            background_highlights: Default::default(),
 1714            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1715            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1716            nav_history: None,
 1717            context_menu: RwLock::new(None),
 1718            mouse_context_menu: None,
 1719            completion_tasks: Default::default(),
 1720            find_all_references_task_sources: Vec::new(),
 1721            next_completion_id: 0,
 1722            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1723            next_inlay_id: 0,
 1724            available_code_actions: Default::default(),
 1725            code_actions_task: Default::default(),
 1726            document_highlights_task: Default::default(),
 1727            pending_rename: Default::default(),
 1728            searchable: true,
 1729            cursor_shape: Default::default(),
 1730            current_line_highlight: EditorSettings::get_global(cx).current_line_highlight,
 1731            autoindent_mode: Some(AutoindentMode::EachLine),
 1732            collapse_matches: false,
 1733            workspace: None,
 1734            keymap_context_layers: Default::default(),
 1735            input_enabled: true,
 1736            use_modal_editing: mode == EditorMode::Full,
 1737            read_only: false,
 1738            use_autoclose: true,
 1739            auto_replace_emoji_shortcode: false,
 1740            leader_peer_id: None,
 1741            remote_id: None,
 1742            hover_state: Default::default(),
 1743            hovered_link_state: Default::default(),
 1744            inline_completion_provider: None,
 1745            active_inline_completion: None,
 1746            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1747            expanded_hunks: ExpandedHunks::default(),
 1748            gutter_hovered: false,
 1749            pixel_position_of_newest_cursor: None,
 1750            last_bounds: None,
 1751            expect_bounds_change: None,
 1752            gutter_dimensions: GutterDimensions::default(),
 1753            style: None,
 1754            show_cursor_names: false,
 1755            hovered_cursors: Default::default(),
 1756            editor_actions: Default::default(),
 1757            vim_replace_map: Default::default(),
 1758            show_inline_completions: mode == EditorMode::Full,
 1759            custom_context_menu: None,
 1760            show_git_blame_gutter: false,
 1761            show_git_blame_inline: false,
 1762            show_git_blame_inline_delay_task: None,
 1763            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1764            blame: None,
 1765            blame_subscription: None,
 1766            tasks: Default::default(),
 1767            _subscriptions: vec![
 1768                cx.observe(&buffer, Self::on_buffer_changed),
 1769                cx.subscribe(&buffer, Self::on_buffer_event),
 1770                cx.observe(&display_map, Self::on_display_map_changed),
 1771                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1772                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1773                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1774                cx.observe_window_activation(|editor, cx| {
 1775                    let active = cx.is_window_active();
 1776                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1777                        if active {
 1778                            blink_manager.enable(cx);
 1779                        } else {
 1780                            blink_manager.show_cursor(cx);
 1781                            blink_manager.disable(cx);
 1782                        }
 1783                    });
 1784                }),
 1785            ],
 1786            tasks_update_task: None,
 1787        };
 1788        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1789        this._subscriptions.extend(project_subscriptions);
 1790
 1791        this.end_selection(cx);
 1792        this.scroll_manager.show_scrollbar(cx);
 1793
 1794        if mode == EditorMode::Full {
 1795            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1796            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1797
 1798            if this.git_blame_inline_enabled {
 1799                this.git_blame_inline_enabled = true;
 1800                this.start_git_blame_inline(false, cx);
 1801            }
 1802        }
 1803
 1804        this.report_editor_event("open", None, cx);
 1805        this
 1806    }
 1807
 1808    pub fn mouse_menu_is_focused(&self, cx: &mut WindowContext) -> bool {
 1809        self.mouse_context_menu
 1810            .as_ref()
 1811            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1812    }
 1813
 1814    fn key_context(&self, cx: &AppContext) -> KeyContext {
 1815        let mut key_context = KeyContext::new_with_defaults();
 1816        key_context.add("Editor");
 1817        let mode = match self.mode {
 1818            EditorMode::SingleLine => "single_line",
 1819            EditorMode::AutoHeight { .. } => "auto_height",
 1820            EditorMode::Full => "full",
 1821        };
 1822        key_context.set("mode", mode);
 1823        if self.pending_rename.is_some() {
 1824            key_context.add("renaming");
 1825        }
 1826        if self.context_menu_visible() {
 1827            match self.context_menu.read().as_ref() {
 1828                Some(ContextMenu::Completions(_)) => {
 1829                    key_context.add("menu");
 1830                    key_context.add("showing_completions")
 1831                }
 1832                Some(ContextMenu::CodeActions(_)) => {
 1833                    key_context.add("menu");
 1834                    key_context.add("showing_code_actions")
 1835                }
 1836                None => {}
 1837            }
 1838        }
 1839
 1840        for layer in self.keymap_context_layers.values() {
 1841            key_context.extend(layer);
 1842        }
 1843
 1844        if let Some(extension) = self
 1845            .buffer
 1846            .read(cx)
 1847            .as_singleton()
 1848            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1849        {
 1850            key_context.set("extension", extension.to_string());
 1851        }
 1852
 1853        if self.has_active_inline_completion(cx) {
 1854            key_context.add("copilot_suggestion");
 1855            key_context.add("inline_completion");
 1856        }
 1857
 1858        key_context
 1859    }
 1860
 1861    pub fn new_file(
 1862        workspace: &mut Workspace,
 1863        _: &workspace::NewFile,
 1864        cx: &mut ViewContext<Workspace>,
 1865    ) {
 1866        let project = workspace.project().clone();
 1867        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1868
 1869        cx.spawn(|workspace, mut cx| async move {
 1870            let buffer = create.await?;
 1871            workspace.update(&mut cx, |workspace, cx| {
 1872                workspace.add_item_to_active_pane(
 1873                    Box::new(
 1874                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1875                    ),
 1876                    None,
 1877                    cx,
 1878                )
 1879            })
 1880        })
 1881        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1882            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1883                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1884                e.error_tag("required").unwrap_or("the latest version")
 1885            )),
 1886            _ => None,
 1887        });
 1888    }
 1889
 1890    pub fn new_file_in_direction(
 1891        workspace: &mut Workspace,
 1892        action: &workspace::NewFileInDirection,
 1893        cx: &mut ViewContext<Workspace>,
 1894    ) {
 1895        let project = workspace.project().clone();
 1896        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1897        let direction = action.0;
 1898
 1899        cx.spawn(|workspace, mut cx| async move {
 1900            let buffer = create.await?;
 1901            workspace.update(&mut cx, move |workspace, cx| {
 1902                workspace.split_item(
 1903                    direction,
 1904                    Box::new(
 1905                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1906                    ),
 1907                    cx,
 1908                )
 1909            })?;
 1910            anyhow::Ok(())
 1911        })
 1912        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1913            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1914                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1915                e.error_tag("required").unwrap_or("the latest version")
 1916            )),
 1917            _ => None,
 1918        });
 1919    }
 1920
 1921    pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
 1922        self.buffer.read(cx).replica_id()
 1923    }
 1924
 1925    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1926        self.leader_peer_id
 1927    }
 1928
 1929    pub fn buffer(&self) -> &Model<MultiBuffer> {
 1930        &self.buffer
 1931    }
 1932
 1933    pub fn workspace(&self) -> Option<View<Workspace>> {
 1934        self.workspace.as_ref()?.0.upgrade()
 1935    }
 1936
 1937    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 1938        self.buffer().read(cx).title(cx)
 1939    }
 1940
 1941    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 1942        EditorSnapshot {
 1943            mode: self.mode,
 1944            show_gutter: self.show_gutter,
 1945            show_line_numbers: self.show_line_numbers,
 1946            show_git_diff_gutter: self.show_git_diff_gutter,
 1947            show_code_actions: self.show_code_actions,
 1948            render_git_blame_gutter: self.render_git_blame_gutter(cx),
 1949            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1950            scroll_anchor: self.scroll_manager.anchor(),
 1951            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1952            placeholder_text: self.placeholder_text.clone(),
 1953            is_focused: self.focus_handle.is_focused(cx),
 1954            current_line_highlight: self.current_line_highlight,
 1955            gutter_hovered: self.gutter_hovered,
 1956        }
 1957    }
 1958
 1959    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 1960        self.buffer.read(cx).language_at(point, cx)
 1961    }
 1962
 1963    pub fn file_at<T: ToOffset>(
 1964        &self,
 1965        point: T,
 1966        cx: &AppContext,
 1967    ) -> Option<Arc<dyn language::File>> {
 1968        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1969    }
 1970
 1971    pub fn active_excerpt(
 1972        &self,
 1973        cx: &AppContext,
 1974    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 1975        self.buffer
 1976            .read(cx)
 1977            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1978    }
 1979
 1980    pub fn mode(&self) -> EditorMode {
 1981        self.mode
 1982    }
 1983
 1984    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1985        self.collaboration_hub.as_deref()
 1986    }
 1987
 1988    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1989        self.collaboration_hub = Some(hub);
 1990    }
 1991
 1992    pub fn set_custom_context_menu(
 1993        &mut self,
 1994        f: impl 'static
 1995            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 1996    ) {
 1997        self.custom_context_menu = Some(Box::new(f))
 1998    }
 1999
 2000    pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
 2001        self.completion_provider = Some(provider);
 2002    }
 2003
 2004    pub fn set_inline_completion_provider<T>(
 2005        &mut self,
 2006        provider: Option<Model<T>>,
 2007        cx: &mut ViewContext<Self>,
 2008    ) where
 2009        T: InlineCompletionProvider,
 2010    {
 2011        self.inline_completion_provider =
 2012            provider.map(|provider| RegisteredInlineCompletionProvider {
 2013                _subscription: cx.observe(&provider, |this, _, cx| {
 2014                    if this.focus_handle.is_focused(cx) {
 2015                        this.update_visible_inline_completion(cx);
 2016                    }
 2017                }),
 2018                provider: Arc::new(provider),
 2019            });
 2020        self.refresh_inline_completion(false, cx);
 2021    }
 2022
 2023    pub fn placeholder_text(&self, _cx: &mut WindowContext) -> Option<&str> {
 2024        self.placeholder_text.as_deref()
 2025    }
 2026
 2027    pub fn set_placeholder_text(
 2028        &mut self,
 2029        placeholder_text: impl Into<Arc<str>>,
 2030        cx: &mut ViewContext<Self>,
 2031    ) {
 2032        let placeholder_text = Some(placeholder_text.into());
 2033        if self.placeholder_text != placeholder_text {
 2034            self.placeholder_text = placeholder_text;
 2035            cx.notify();
 2036        }
 2037    }
 2038
 2039    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2040        self.cursor_shape = cursor_shape;
 2041        cx.notify();
 2042    }
 2043
 2044    pub fn set_current_line_highlight(&mut self, current_line_highlight: CurrentLineHighlight) {
 2045        self.current_line_highlight = current_line_highlight;
 2046    }
 2047
 2048    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2049        self.collapse_matches = collapse_matches;
 2050    }
 2051
 2052    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2053        if self.collapse_matches {
 2054            return range.start..range.start;
 2055        }
 2056        range.clone()
 2057    }
 2058
 2059    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2060        if self.display_map.read(cx).clip_at_line_ends != clip {
 2061            self.display_map
 2062                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2063        }
 2064    }
 2065
 2066    pub fn set_keymap_context_layer<Tag: 'static>(
 2067        &mut self,
 2068        context: KeyContext,
 2069        cx: &mut ViewContext<Self>,
 2070    ) {
 2071        self.keymap_context_layers
 2072            .insert(TypeId::of::<Tag>(), context);
 2073        cx.notify();
 2074    }
 2075
 2076    pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
 2077        self.keymap_context_layers.remove(&TypeId::of::<Tag>());
 2078        cx.notify();
 2079    }
 2080
 2081    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2082        self.input_enabled = input_enabled;
 2083    }
 2084
 2085    pub fn set_autoindent(&mut self, autoindent: bool) {
 2086        if autoindent {
 2087            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2088        } else {
 2089            self.autoindent_mode = None;
 2090        }
 2091    }
 2092
 2093    pub fn read_only(&self, cx: &AppContext) -> bool {
 2094        self.read_only || self.buffer.read(cx).read_only()
 2095    }
 2096
 2097    pub fn set_read_only(&mut self, read_only: bool) {
 2098        self.read_only = read_only;
 2099    }
 2100
 2101    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2102        self.use_autoclose = autoclose;
 2103    }
 2104
 2105    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2106        self.auto_replace_emoji_shortcode = auto_replace;
 2107    }
 2108
 2109    pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
 2110        self.show_inline_completions = show_inline_completions;
 2111    }
 2112
 2113    pub fn set_use_modal_editing(&mut self, to: bool) {
 2114        self.use_modal_editing = to;
 2115    }
 2116
 2117    pub fn use_modal_editing(&self) -> bool {
 2118        self.use_modal_editing
 2119    }
 2120
 2121    fn selections_did_change(
 2122        &mut self,
 2123        local: bool,
 2124        old_cursor_position: &Anchor,
 2125        show_completions: bool,
 2126        cx: &mut ViewContext<Self>,
 2127    ) {
 2128        // Copy selections to primary selection buffer
 2129        #[cfg(target_os = "linux")]
 2130        if local {
 2131            let selections = self.selections.all::<usize>(cx);
 2132            let buffer_handle = self.buffer.read(cx).read(cx);
 2133
 2134            let mut text = String::new();
 2135            for (index, selection) in selections.iter().enumerate() {
 2136                let text_for_selection = buffer_handle
 2137                    .text_for_range(selection.start..selection.end)
 2138                    .collect::<String>();
 2139
 2140                text.push_str(&text_for_selection);
 2141                if index != selections.len() - 1 {
 2142                    text.push('\n');
 2143                }
 2144            }
 2145
 2146            if !text.is_empty() {
 2147                cx.write_to_primary(ClipboardItem::new(text));
 2148            }
 2149        }
 2150
 2151        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2152            self.buffer.update(cx, |buffer, cx| {
 2153                buffer.set_active_selections(
 2154                    &self.selections.disjoint_anchors(),
 2155                    self.selections.line_mode,
 2156                    self.cursor_shape,
 2157                    cx,
 2158                )
 2159            });
 2160        }
 2161
 2162        let display_map = self
 2163            .display_map
 2164            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2165        let buffer = &display_map.buffer_snapshot;
 2166        self.add_selections_state = None;
 2167        self.select_next_state = None;
 2168        self.select_prev_state = None;
 2169        self.select_larger_syntax_node_stack.clear();
 2170        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2171        self.snippet_stack
 2172            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2173        self.take_rename(false, cx);
 2174
 2175        let new_cursor_position = self.selections.newest_anchor().head();
 2176
 2177        self.push_to_nav_history(
 2178            *old_cursor_position,
 2179            Some(new_cursor_position.to_point(buffer)),
 2180            cx,
 2181        );
 2182
 2183        if local {
 2184            let new_cursor_position = self.selections.newest_anchor().head();
 2185            let mut context_menu = self.context_menu.write();
 2186            let completion_menu = match context_menu.as_ref() {
 2187                Some(ContextMenu::Completions(menu)) => Some(menu),
 2188
 2189                _ => {
 2190                    *context_menu = None;
 2191                    None
 2192                }
 2193            };
 2194
 2195            if let Some(completion_menu) = completion_menu {
 2196                let cursor_position = new_cursor_position.to_offset(buffer);
 2197                let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
 2198                if kind == Some(CharKind::Word)
 2199                    && word_range.to_inclusive().contains(&cursor_position)
 2200                {
 2201                    let mut completion_menu = completion_menu.clone();
 2202                    drop(context_menu);
 2203
 2204                    let query = Self::completion_query(buffer, cursor_position);
 2205                    cx.spawn(move |this, mut cx| async move {
 2206                        completion_menu
 2207                            .filter(query.as_deref(), cx.background_executor().clone())
 2208                            .await;
 2209
 2210                        this.update(&mut cx, |this, cx| {
 2211                            let mut context_menu = this.context_menu.write();
 2212                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2213                                return;
 2214                            };
 2215
 2216                            if menu.id > completion_menu.id {
 2217                                return;
 2218                            }
 2219
 2220                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2221                            drop(context_menu);
 2222                            cx.notify();
 2223                        })
 2224                    })
 2225                    .detach();
 2226
 2227                    if show_completions {
 2228                        self.show_completions(&ShowCompletions, cx);
 2229                    }
 2230                } else {
 2231                    drop(context_menu);
 2232                    self.hide_context_menu(cx);
 2233                }
 2234            } else {
 2235                drop(context_menu);
 2236            }
 2237
 2238            hide_hover(self, cx);
 2239
 2240            if old_cursor_position.to_display_point(&display_map).row()
 2241                != new_cursor_position.to_display_point(&display_map).row()
 2242            {
 2243                self.available_code_actions.take();
 2244            }
 2245            self.refresh_code_actions(cx);
 2246            self.refresh_document_highlights(cx);
 2247            refresh_matching_bracket_highlights(self, cx);
 2248            self.discard_inline_completion(false, cx);
 2249            if self.git_blame_inline_enabled {
 2250                self.start_inline_blame_timer(cx);
 2251            }
 2252        }
 2253
 2254        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2255        cx.emit(EditorEvent::SelectionsChanged { local });
 2256
 2257        if self.selections.disjoint_anchors().len() == 1 {
 2258            cx.emit(SearchEvent::ActiveMatchChanged)
 2259        }
 2260
 2261        cx.notify();
 2262    }
 2263
 2264    pub fn change_selections<R>(
 2265        &mut self,
 2266        autoscroll: Option<Autoscroll>,
 2267        cx: &mut ViewContext<Self>,
 2268        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2269    ) -> R {
 2270        self.change_selections_inner(autoscroll, true, cx, change)
 2271    }
 2272
 2273    pub fn change_selections_inner<R>(
 2274        &mut self,
 2275        autoscroll: Option<Autoscroll>,
 2276        request_completions: bool,
 2277        cx: &mut ViewContext<Self>,
 2278        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2279    ) -> R {
 2280        let old_cursor_position = self.selections.newest_anchor().head();
 2281        self.push_to_selection_history();
 2282
 2283        let (changed, result) = self.selections.change_with(cx, change);
 2284
 2285        if changed {
 2286            if let Some(autoscroll) = autoscroll {
 2287                self.request_autoscroll(autoscroll, cx);
 2288            }
 2289            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2290        }
 2291
 2292        result
 2293    }
 2294
 2295    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2296    where
 2297        I: IntoIterator<Item = (Range<S>, T)>,
 2298        S: ToOffset,
 2299        T: Into<Arc<str>>,
 2300    {
 2301        if self.read_only(cx) {
 2302            return;
 2303        }
 2304
 2305        self.buffer
 2306            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2307    }
 2308
 2309    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2310    where
 2311        I: IntoIterator<Item = (Range<S>, T)>,
 2312        S: ToOffset,
 2313        T: Into<Arc<str>>,
 2314    {
 2315        if self.read_only(cx) {
 2316            return;
 2317        }
 2318
 2319        self.buffer.update(cx, |buffer, cx| {
 2320            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2321        });
 2322    }
 2323
 2324    pub fn edit_with_block_indent<I, S, T>(
 2325        &mut self,
 2326        edits: I,
 2327        original_indent_columns: Vec<u32>,
 2328        cx: &mut ViewContext<Self>,
 2329    ) where
 2330        I: IntoIterator<Item = (Range<S>, T)>,
 2331        S: ToOffset,
 2332        T: Into<Arc<str>>,
 2333    {
 2334        if self.read_only(cx) {
 2335            return;
 2336        }
 2337
 2338        self.buffer.update(cx, |buffer, cx| {
 2339            buffer.edit(
 2340                edits,
 2341                Some(AutoindentMode::Block {
 2342                    original_indent_columns,
 2343                }),
 2344                cx,
 2345            )
 2346        });
 2347    }
 2348
 2349    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2350        self.hide_context_menu(cx);
 2351
 2352        match phase {
 2353            SelectPhase::Begin {
 2354                position,
 2355                add,
 2356                click_count,
 2357            } => self.begin_selection(position, add, click_count, cx),
 2358            SelectPhase::BeginColumnar {
 2359                position,
 2360                goal_column,
 2361                reset,
 2362            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2363            SelectPhase::Extend {
 2364                position,
 2365                click_count,
 2366            } => self.extend_selection(position, click_count, cx),
 2367            SelectPhase::Update {
 2368                position,
 2369                goal_column,
 2370                scroll_delta,
 2371            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2372            SelectPhase::End => self.end_selection(cx),
 2373        }
 2374    }
 2375
 2376    fn extend_selection(
 2377        &mut self,
 2378        position: DisplayPoint,
 2379        click_count: usize,
 2380        cx: &mut ViewContext<Self>,
 2381    ) {
 2382        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2383        let tail = self.selections.newest::<usize>(cx).tail();
 2384        self.begin_selection(position, false, click_count, cx);
 2385
 2386        let position = position.to_offset(&display_map, Bias::Left);
 2387        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2388
 2389        let mut pending_selection = self
 2390            .selections
 2391            .pending_anchor()
 2392            .expect("extend_selection not called with pending selection");
 2393        if position >= tail {
 2394            pending_selection.start = tail_anchor;
 2395        } else {
 2396            pending_selection.end = tail_anchor;
 2397            pending_selection.reversed = true;
 2398        }
 2399
 2400        let mut pending_mode = self.selections.pending_mode().unwrap();
 2401        match &mut pending_mode {
 2402            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2403            _ => {}
 2404        }
 2405
 2406        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2407            s.set_pending(pending_selection, pending_mode)
 2408        });
 2409    }
 2410
 2411    fn begin_selection(
 2412        &mut self,
 2413        position: DisplayPoint,
 2414        add: bool,
 2415        click_count: usize,
 2416        cx: &mut ViewContext<Self>,
 2417    ) {
 2418        if !self.focus_handle.is_focused(cx) {
 2419            cx.focus(&self.focus_handle);
 2420        }
 2421
 2422        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2423        let buffer = &display_map.buffer_snapshot;
 2424        let newest_selection = self.selections.newest_anchor().clone();
 2425        let position = display_map.clip_point(position, Bias::Left);
 2426
 2427        let start;
 2428        let end;
 2429        let mode;
 2430        let auto_scroll;
 2431        match click_count {
 2432            1 => {
 2433                start = buffer.anchor_before(position.to_point(&display_map));
 2434                end = start;
 2435                mode = SelectMode::Character;
 2436                auto_scroll = true;
 2437            }
 2438            2 => {
 2439                let range = movement::surrounding_word(&display_map, position);
 2440                start = buffer.anchor_before(range.start.to_point(&display_map));
 2441                end = buffer.anchor_before(range.end.to_point(&display_map));
 2442                mode = SelectMode::Word(start..end);
 2443                auto_scroll = true;
 2444            }
 2445            3 => {
 2446                let position = display_map
 2447                    .clip_point(position, Bias::Left)
 2448                    .to_point(&display_map);
 2449                let line_start = display_map.prev_line_boundary(position).0;
 2450                let next_line_start = buffer.clip_point(
 2451                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2452                    Bias::Left,
 2453                );
 2454                start = buffer.anchor_before(line_start);
 2455                end = buffer.anchor_before(next_line_start);
 2456                mode = SelectMode::Line(start..end);
 2457                auto_scroll = true;
 2458            }
 2459            _ => {
 2460                start = buffer.anchor_before(0);
 2461                end = buffer.anchor_before(buffer.len());
 2462                mode = SelectMode::All;
 2463                auto_scroll = false;
 2464            }
 2465        }
 2466
 2467        self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
 2468            if !add {
 2469                s.clear_disjoint();
 2470            } else if click_count > 1 {
 2471                s.delete(newest_selection.id)
 2472            }
 2473
 2474            s.set_pending_anchor_range(start..end, mode);
 2475        });
 2476    }
 2477
 2478    fn begin_columnar_selection(
 2479        &mut self,
 2480        position: DisplayPoint,
 2481        goal_column: u32,
 2482        reset: bool,
 2483        cx: &mut ViewContext<Self>,
 2484    ) {
 2485        if !self.focus_handle.is_focused(cx) {
 2486            cx.focus(&self.focus_handle);
 2487        }
 2488
 2489        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2490
 2491        if reset {
 2492            let pointer_position = display_map
 2493                .buffer_snapshot
 2494                .anchor_before(position.to_point(&display_map));
 2495
 2496            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2497                s.clear_disjoint();
 2498                s.set_pending_anchor_range(
 2499                    pointer_position..pointer_position,
 2500                    SelectMode::Character,
 2501                );
 2502            });
 2503        }
 2504
 2505        let tail = self.selections.newest::<Point>(cx).tail();
 2506        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2507
 2508        if !reset {
 2509            self.select_columns(
 2510                tail.to_display_point(&display_map),
 2511                position,
 2512                goal_column,
 2513                &display_map,
 2514                cx,
 2515            );
 2516        }
 2517    }
 2518
 2519    fn update_selection(
 2520        &mut self,
 2521        position: DisplayPoint,
 2522        goal_column: u32,
 2523        scroll_delta: gpui::Point<f32>,
 2524        cx: &mut ViewContext<Self>,
 2525    ) {
 2526        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2527
 2528        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2529            let tail = tail.to_display_point(&display_map);
 2530            self.select_columns(tail, position, goal_column, &display_map, cx);
 2531        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2532            let buffer = self.buffer.read(cx).snapshot(cx);
 2533            let head;
 2534            let tail;
 2535            let mode = self.selections.pending_mode().unwrap();
 2536            match &mode {
 2537                SelectMode::Character => {
 2538                    head = position.to_point(&display_map);
 2539                    tail = pending.tail().to_point(&buffer);
 2540                }
 2541                SelectMode::Word(original_range) => {
 2542                    let original_display_range = original_range.start.to_display_point(&display_map)
 2543                        ..original_range.end.to_display_point(&display_map);
 2544                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2545                        ..original_display_range.end.to_point(&display_map);
 2546                    if movement::is_inside_word(&display_map, position)
 2547                        || original_display_range.contains(&position)
 2548                    {
 2549                        let word_range = movement::surrounding_word(&display_map, position);
 2550                        if word_range.start < original_display_range.start {
 2551                            head = word_range.start.to_point(&display_map);
 2552                        } else {
 2553                            head = word_range.end.to_point(&display_map);
 2554                        }
 2555                    } else {
 2556                        head = position.to_point(&display_map);
 2557                    }
 2558
 2559                    if head <= original_buffer_range.start {
 2560                        tail = original_buffer_range.end;
 2561                    } else {
 2562                        tail = original_buffer_range.start;
 2563                    }
 2564                }
 2565                SelectMode::Line(original_range) => {
 2566                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2567
 2568                    let position = display_map
 2569                        .clip_point(position, Bias::Left)
 2570                        .to_point(&display_map);
 2571                    let line_start = display_map.prev_line_boundary(position).0;
 2572                    let next_line_start = buffer.clip_point(
 2573                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2574                        Bias::Left,
 2575                    );
 2576
 2577                    if line_start < original_range.start {
 2578                        head = line_start
 2579                    } else {
 2580                        head = next_line_start
 2581                    }
 2582
 2583                    if head <= original_range.start {
 2584                        tail = original_range.end;
 2585                    } else {
 2586                        tail = original_range.start;
 2587                    }
 2588                }
 2589                SelectMode::All => {
 2590                    return;
 2591                }
 2592            };
 2593
 2594            if head < tail {
 2595                pending.start = buffer.anchor_before(head);
 2596                pending.end = buffer.anchor_before(tail);
 2597                pending.reversed = true;
 2598            } else {
 2599                pending.start = buffer.anchor_before(tail);
 2600                pending.end = buffer.anchor_before(head);
 2601                pending.reversed = false;
 2602            }
 2603
 2604            self.change_selections(None, cx, |s| {
 2605                s.set_pending(pending, mode);
 2606            });
 2607        } else {
 2608            log::error!("update_selection dispatched with no pending selection");
 2609            return;
 2610        }
 2611
 2612        self.apply_scroll_delta(scroll_delta, cx);
 2613        cx.notify();
 2614    }
 2615
 2616    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2617        self.columnar_selection_tail.take();
 2618        if self.selections.pending_anchor().is_some() {
 2619            let selections = self.selections.all::<usize>(cx);
 2620            self.change_selections(None, cx, |s| {
 2621                s.select(selections);
 2622                s.clear_pending();
 2623            });
 2624        }
 2625    }
 2626
 2627    fn select_columns(
 2628        &mut self,
 2629        tail: DisplayPoint,
 2630        head: DisplayPoint,
 2631        goal_column: u32,
 2632        display_map: &DisplaySnapshot,
 2633        cx: &mut ViewContext<Self>,
 2634    ) {
 2635        let start_row = cmp::min(tail.row(), head.row());
 2636        let end_row = cmp::max(tail.row(), head.row());
 2637        let start_column = cmp::min(tail.column(), goal_column);
 2638        let end_column = cmp::max(tail.column(), goal_column);
 2639        let reversed = start_column < tail.column();
 2640
 2641        let selection_ranges = (start_row.0..=end_row.0)
 2642            .map(DisplayRow)
 2643            .filter_map(|row| {
 2644                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2645                    let start = display_map
 2646                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2647                        .to_point(display_map);
 2648                    let end = display_map
 2649                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2650                        .to_point(display_map);
 2651                    if reversed {
 2652                        Some(end..start)
 2653                    } else {
 2654                        Some(start..end)
 2655                    }
 2656                } else {
 2657                    None
 2658                }
 2659            })
 2660            .collect::<Vec<_>>();
 2661
 2662        self.change_selections(None, cx, |s| {
 2663            s.select_ranges(selection_ranges);
 2664        });
 2665        cx.notify();
 2666    }
 2667
 2668    pub fn has_pending_nonempty_selection(&self) -> bool {
 2669        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2670            Some(Selection { start, end, .. }) => start != end,
 2671            None => false,
 2672        };
 2673        pending_nonempty_selection || self.columnar_selection_tail.is_some()
 2674    }
 2675
 2676    pub fn has_pending_selection(&self) -> bool {
 2677        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2678    }
 2679
 2680    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2681        self.clear_expanded_diff_hunks(cx);
 2682        if self.dismiss_menus_and_popups(true, cx) {
 2683            return;
 2684        }
 2685
 2686        if self.mode == EditorMode::Full {
 2687            if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
 2688                return;
 2689            }
 2690        }
 2691
 2692        cx.propagate();
 2693    }
 2694
 2695    pub fn dismiss_menus_and_popups(
 2696        &mut self,
 2697        should_report_inline_completion_event: bool,
 2698        cx: &mut ViewContext<Self>,
 2699    ) -> bool {
 2700        if self.take_rename(false, cx).is_some() {
 2701            return true;
 2702        }
 2703
 2704        if hide_hover(self, cx) {
 2705            return true;
 2706        }
 2707
 2708        if self.hide_context_menu(cx).is_some() {
 2709            return true;
 2710        }
 2711
 2712        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2713            return true;
 2714        }
 2715
 2716        if self.snippet_stack.pop().is_some() {
 2717            return true;
 2718        }
 2719
 2720        if self.mode == EditorMode::Full {
 2721            if self.active_diagnostics.is_some() {
 2722                self.dismiss_diagnostics(cx);
 2723                return true;
 2724            }
 2725        }
 2726
 2727        false
 2728    }
 2729
 2730    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2731        let text: Arc<str> = text.into();
 2732
 2733        if self.read_only(cx) {
 2734            return;
 2735        }
 2736
 2737        let selections = self.selections.all_adjusted(cx);
 2738        let mut brace_inserted = false;
 2739        let mut edits = Vec::new();
 2740        let mut new_selections = Vec::with_capacity(selections.len());
 2741        let mut new_autoclose_regions = Vec::new();
 2742        let snapshot = self.buffer.read(cx).read(cx);
 2743
 2744        for (selection, autoclose_region) in
 2745            self.selections_with_autoclose_regions(selections, &snapshot)
 2746        {
 2747            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2748                // Determine if the inserted text matches the opening or closing
 2749                // bracket of any of this language's bracket pairs.
 2750                let mut bracket_pair = None;
 2751                let mut is_bracket_pair_start = false;
 2752                let mut is_bracket_pair_end = false;
 2753                if !text.is_empty() {
 2754                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2755                    //  and they are removing the character that triggered IME popup.
 2756                    for (pair, enabled) in scope.brackets() {
 2757                        if !pair.close {
 2758                            continue;
 2759                        }
 2760
 2761                        if enabled && pair.start.ends_with(text.as_ref()) {
 2762                            bracket_pair = Some(pair.clone());
 2763                            is_bracket_pair_start = true;
 2764                            break;
 2765                        }
 2766                        if pair.end.as_str() == text.as_ref() {
 2767                            bracket_pair = Some(pair.clone());
 2768                            is_bracket_pair_end = true;
 2769                            break;
 2770                        }
 2771                    }
 2772                }
 2773
 2774                if let Some(bracket_pair) = bracket_pair {
 2775                    if selection.is_empty() {
 2776                        if is_bracket_pair_start {
 2777                            let prefix_len = bracket_pair.start.len() - text.len();
 2778
 2779                            // If the inserted text is a suffix of an opening bracket and the
 2780                            // selection is preceded by the rest of the opening bracket, then
 2781                            // insert the closing bracket.
 2782                            let following_text_allows_autoclose = snapshot
 2783                                .chars_at(selection.start)
 2784                                .next()
 2785                                .map_or(true, |c| scope.should_autoclose_before(c));
 2786                            let preceding_text_matches_prefix = prefix_len == 0
 2787                                || (selection.start.column >= (prefix_len as u32)
 2788                                    && snapshot.contains_str_at(
 2789                                        Point::new(
 2790                                            selection.start.row,
 2791                                            selection.start.column - (prefix_len as u32),
 2792                                        ),
 2793                                        &bracket_pair.start[..prefix_len],
 2794                                    ));
 2795                            let autoclose = self.use_autoclose
 2796                                && snapshot.settings_at(selection.start, cx).use_autoclose;
 2797                            if autoclose
 2798                                && following_text_allows_autoclose
 2799                                && preceding_text_matches_prefix
 2800                            {
 2801                                let anchor = snapshot.anchor_before(selection.end);
 2802                                new_selections.push((selection.map(|_| anchor), text.len()));
 2803                                new_autoclose_regions.push((
 2804                                    anchor,
 2805                                    text.len(),
 2806                                    selection.id,
 2807                                    bracket_pair.clone(),
 2808                                ));
 2809                                edits.push((
 2810                                    selection.range(),
 2811                                    format!("{}{}", text, bracket_pair.end).into(),
 2812                                ));
 2813                                brace_inserted = true;
 2814                                continue;
 2815                            }
 2816                        }
 2817
 2818                        if let Some(region) = autoclose_region {
 2819                            // If the selection is followed by an auto-inserted closing bracket,
 2820                            // then don't insert that closing bracket again; just move the selection
 2821                            // past the closing bracket.
 2822                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2823                                && text.as_ref() == region.pair.end.as_str();
 2824                            if should_skip {
 2825                                let anchor = snapshot.anchor_after(selection.end);
 2826                                new_selections
 2827                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2828                                continue;
 2829                            }
 2830                        }
 2831
 2832                        let always_treat_brackets_as_autoclosed = snapshot
 2833                            .settings_at(selection.start, cx)
 2834                            .always_treat_brackets_as_autoclosed;
 2835                        if always_treat_brackets_as_autoclosed
 2836                            && is_bracket_pair_end
 2837                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2838                        {
 2839                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2840                            // and the inserted text is a closing bracket and the selection is followed
 2841                            // by the closing bracket then move the selection past the closing bracket.
 2842                            let anchor = snapshot.anchor_after(selection.end);
 2843                            new_selections.push((selection.map(|_| anchor), text.len()));
 2844                            continue;
 2845                        }
 2846                    }
 2847                    // If an opening bracket is 1 character long and is typed while
 2848                    // text is selected, then surround that text with the bracket pair.
 2849                    else if is_bracket_pair_start && bracket_pair.start.chars().count() == 1 {
 2850                        edits.push((selection.start..selection.start, text.clone()));
 2851                        edits.push((
 2852                            selection.end..selection.end,
 2853                            bracket_pair.end.as_str().into(),
 2854                        ));
 2855                        brace_inserted = true;
 2856                        new_selections.push((
 2857                            Selection {
 2858                                id: selection.id,
 2859                                start: snapshot.anchor_after(selection.start),
 2860                                end: snapshot.anchor_before(selection.end),
 2861                                reversed: selection.reversed,
 2862                                goal: selection.goal,
 2863                            },
 2864                            0,
 2865                        ));
 2866                        continue;
 2867                    }
 2868                }
 2869            }
 2870
 2871            if self.auto_replace_emoji_shortcode
 2872                && selection.is_empty()
 2873                && text.as_ref().ends_with(':')
 2874            {
 2875                if let Some(possible_emoji_short_code) =
 2876                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2877                {
 2878                    if !possible_emoji_short_code.is_empty() {
 2879                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2880                            let emoji_shortcode_start = Point::new(
 2881                                selection.start.row,
 2882                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2883                            );
 2884
 2885                            // Remove shortcode from buffer
 2886                            edits.push((
 2887                                emoji_shortcode_start..selection.start,
 2888                                "".to_string().into(),
 2889                            ));
 2890                            new_selections.push((
 2891                                Selection {
 2892                                    id: selection.id,
 2893                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2894                                    end: snapshot.anchor_before(selection.start),
 2895                                    reversed: selection.reversed,
 2896                                    goal: selection.goal,
 2897                                },
 2898                                0,
 2899                            ));
 2900
 2901                            // Insert emoji
 2902                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2903                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2904                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2905
 2906                            continue;
 2907                        }
 2908                    }
 2909                }
 2910            }
 2911
 2912            // If not handling any auto-close operation, then just replace the selected
 2913            // text with the given input and move the selection to the end of the
 2914            // newly inserted text.
 2915            let anchor = snapshot.anchor_after(selection.end);
 2916            new_selections.push((selection.map(|_| anchor), 0));
 2917            edits.push((selection.start..selection.end, text.clone()));
 2918        }
 2919
 2920        drop(snapshot);
 2921        self.transact(cx, |this, cx| {
 2922            this.buffer.update(cx, |buffer, cx| {
 2923                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2924            });
 2925
 2926            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2927            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2928            let snapshot = this.buffer.read(cx).read(cx);
 2929            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 2930                .zip(new_selection_deltas)
 2931                .map(|(selection, delta)| Selection {
 2932                    id: selection.id,
 2933                    start: selection.start + delta,
 2934                    end: selection.end + delta,
 2935                    reversed: selection.reversed,
 2936                    goal: SelectionGoal::None,
 2937                })
 2938                .collect::<Vec<_>>();
 2939
 2940            let mut i = 0;
 2941            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2942                let position = position.to_offset(&snapshot) + delta;
 2943                let start = snapshot.anchor_before(position);
 2944                let end = snapshot.anchor_after(position);
 2945                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2946                    match existing_state.range.start.cmp(&start, &snapshot) {
 2947                        Ordering::Less => i += 1,
 2948                        Ordering::Greater => break,
 2949                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 2950                            Ordering::Less => i += 1,
 2951                            Ordering::Equal => break,
 2952                            Ordering::Greater => break,
 2953                        },
 2954                    }
 2955                }
 2956                this.autoclose_regions.insert(
 2957                    i,
 2958                    AutocloseRegion {
 2959                        selection_id,
 2960                        range: start..end,
 2961                        pair,
 2962                    },
 2963                );
 2964            }
 2965
 2966            drop(snapshot);
 2967            let had_active_inline_completion = this.has_active_inline_completion(cx);
 2968            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 2969                s.select(new_selections)
 2970            });
 2971
 2972            if brace_inserted {
 2973                // If we inserted a brace while composing text (i.e. typing `"` on a
 2974                // Brazilian keyboard), exit the composing state because most likely
 2975                // the user wanted to surround the selection.
 2976                this.unmark_text(cx);
 2977            } else if EditorSettings::get_global(cx).use_on_type_format {
 2978                if let Some(on_type_format_task) =
 2979                    this.trigger_on_type_formatting(text.to_string(), cx)
 2980                {
 2981                    on_type_format_task.detach_and_log_err(cx);
 2982                }
 2983            }
 2984
 2985            let trigger_in_words = !had_active_inline_completion;
 2986            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 2987            this.refresh_inline_completion(true, cx);
 2988        });
 2989    }
 2990
 2991    fn find_possible_emoji_shortcode_at_position(
 2992        snapshot: &MultiBufferSnapshot,
 2993        position: Point,
 2994    ) -> Option<String> {
 2995        let mut chars = Vec::new();
 2996        let mut found_colon = false;
 2997        for char in snapshot.reversed_chars_at(position).take(100) {
 2998            // Found a possible emoji shortcode in the middle of the buffer
 2999            if found_colon {
 3000                if char.is_whitespace() {
 3001                    chars.reverse();
 3002                    return Some(chars.iter().collect());
 3003                }
 3004                // If the previous character is not a whitespace, we are in the middle of a word
 3005                // and we only want to complete the shortcode if the word is made up of other emojis
 3006                let mut containing_word = String::new();
 3007                for ch in snapshot
 3008                    .reversed_chars_at(position)
 3009                    .skip(chars.len() + 1)
 3010                    .take(100)
 3011                {
 3012                    if ch.is_whitespace() {
 3013                        break;
 3014                    }
 3015                    containing_word.push(ch);
 3016                }
 3017                let containing_word = containing_word.chars().rev().collect::<String>();
 3018                if util::word_consists_of_emojis(containing_word.as_str()) {
 3019                    chars.reverse();
 3020                    return Some(chars.iter().collect());
 3021                }
 3022            }
 3023
 3024            if char.is_whitespace() || !char.is_ascii() {
 3025                return None;
 3026            }
 3027            if char == ':' {
 3028                found_colon = true;
 3029            } else {
 3030                chars.push(char);
 3031            }
 3032        }
 3033        // Found a possible emoji shortcode at the beginning of the buffer
 3034        chars.reverse();
 3035        Some(chars.iter().collect())
 3036    }
 3037
 3038    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3039        self.transact(cx, |this, cx| {
 3040            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3041                let selections = this.selections.all::<usize>(cx);
 3042                let multi_buffer = this.buffer.read(cx);
 3043                let buffer = multi_buffer.snapshot(cx);
 3044                selections
 3045                    .iter()
 3046                    .map(|selection| {
 3047                        let start_point = selection.start.to_point(&buffer);
 3048                        let mut indent =
 3049                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3050                        indent.len = cmp::min(indent.len, start_point.column);
 3051                        let start = selection.start;
 3052                        let end = selection.end;
 3053                        let selection_is_empty = start == end;
 3054                        let language_scope = buffer.language_scope_at(start);
 3055                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3056                            &language_scope
 3057                        {
 3058                            let leading_whitespace_len = buffer
 3059                                .reversed_chars_at(start)
 3060                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3061                                .map(|c| c.len_utf8())
 3062                                .sum::<usize>();
 3063
 3064                            let trailing_whitespace_len = buffer
 3065                                .chars_at(end)
 3066                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3067                                .map(|c| c.len_utf8())
 3068                                .sum::<usize>();
 3069
 3070                            let insert_extra_newline =
 3071                                language.brackets().any(|(pair, enabled)| {
 3072                                    let pair_start = pair.start.trim_end();
 3073                                    let pair_end = pair.end.trim_start();
 3074
 3075                                    enabled
 3076                                        && pair.newline
 3077                                        && buffer.contains_str_at(
 3078                                            end + trailing_whitespace_len,
 3079                                            pair_end,
 3080                                        )
 3081                                        && buffer.contains_str_at(
 3082                                            (start - leading_whitespace_len)
 3083                                                .saturating_sub(pair_start.len()),
 3084                                            pair_start,
 3085                                        )
 3086                                });
 3087
 3088                            // Comment extension on newline is allowed only for cursor selections
 3089                            let comment_delimiter = maybe!({
 3090                                if !selection_is_empty {
 3091                                    return None;
 3092                                }
 3093
 3094                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3095                                    return None;
 3096                                }
 3097
 3098                                let delimiters = language.line_comment_prefixes();
 3099                                let max_len_of_delimiter =
 3100                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3101                                let (snapshot, range) =
 3102                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3103
 3104                                let mut index_of_first_non_whitespace = 0;
 3105                                let comment_candidate = snapshot
 3106                                    .chars_for_range(range)
 3107                                    .skip_while(|c| {
 3108                                        let should_skip = c.is_whitespace();
 3109                                        if should_skip {
 3110                                            index_of_first_non_whitespace += 1;
 3111                                        }
 3112                                        should_skip
 3113                                    })
 3114                                    .take(max_len_of_delimiter)
 3115                                    .collect::<String>();
 3116                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3117                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3118                                })?;
 3119                                let cursor_is_placed_after_comment_marker =
 3120                                    index_of_first_non_whitespace + comment_prefix.len()
 3121                                        <= start_point.column as usize;
 3122                                if cursor_is_placed_after_comment_marker {
 3123                                    Some(comment_prefix.clone())
 3124                                } else {
 3125                                    None
 3126                                }
 3127                            });
 3128                            (comment_delimiter, insert_extra_newline)
 3129                        } else {
 3130                            (None, false)
 3131                        };
 3132
 3133                        let capacity_for_delimiter = comment_delimiter
 3134                            .as_deref()
 3135                            .map(str::len)
 3136                            .unwrap_or_default();
 3137                        let mut new_text =
 3138                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3139                        new_text.push_str("\n");
 3140                        new_text.extend(indent.chars());
 3141                        if let Some(delimiter) = &comment_delimiter {
 3142                            new_text.push_str(&delimiter);
 3143                        }
 3144                        if insert_extra_newline {
 3145                            new_text = new_text.repeat(2);
 3146                        }
 3147
 3148                        let anchor = buffer.anchor_after(end);
 3149                        let new_selection = selection.map(|_| anchor);
 3150                        (
 3151                            (start..end, new_text),
 3152                            (insert_extra_newline, new_selection),
 3153                        )
 3154                    })
 3155                    .unzip()
 3156            };
 3157
 3158            this.edit_with_autoindent(edits, cx);
 3159            let buffer = this.buffer.read(cx).snapshot(cx);
 3160            let new_selections = selection_fixup_info
 3161                .into_iter()
 3162                .map(|(extra_newline_inserted, new_selection)| {
 3163                    let mut cursor = new_selection.end.to_point(&buffer);
 3164                    if extra_newline_inserted {
 3165                        cursor.row -= 1;
 3166                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3167                    }
 3168                    new_selection.map(|_| cursor)
 3169                })
 3170                .collect();
 3171
 3172            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3173            this.refresh_inline_completion(true, cx);
 3174        });
 3175    }
 3176
 3177    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3178        let buffer = self.buffer.read(cx);
 3179        let snapshot = buffer.snapshot(cx);
 3180
 3181        let mut edits = Vec::new();
 3182        let mut rows = Vec::new();
 3183
 3184        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3185            let cursor = selection.head();
 3186            let row = cursor.row;
 3187
 3188            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3189
 3190            let newline = "\n".to_string();
 3191            edits.push((start_of_line..start_of_line, newline));
 3192
 3193            rows.push(row + rows_inserted as u32);
 3194        }
 3195
 3196        self.transact(cx, |editor, cx| {
 3197            editor.edit(edits, cx);
 3198
 3199            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3200                let mut index = 0;
 3201                s.move_cursors_with(|map, _, _| {
 3202                    let row = rows[index];
 3203                    index += 1;
 3204
 3205                    let point = Point::new(row, 0);
 3206                    let boundary = map.next_line_boundary(point).1;
 3207                    let clipped = map.clip_point(boundary, Bias::Left);
 3208
 3209                    (clipped, SelectionGoal::None)
 3210                });
 3211            });
 3212
 3213            let mut indent_edits = Vec::new();
 3214            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3215            for row in rows {
 3216                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3217                for (row, indent) in indents {
 3218                    if indent.len == 0 {
 3219                        continue;
 3220                    }
 3221
 3222                    let text = match indent.kind {
 3223                        IndentKind::Space => " ".repeat(indent.len as usize),
 3224                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3225                    };
 3226                    let point = Point::new(row.0, 0);
 3227                    indent_edits.push((point..point, text));
 3228                }
 3229            }
 3230            editor.edit(indent_edits, cx);
 3231        });
 3232    }
 3233
 3234    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3235        let buffer = self.buffer.read(cx);
 3236        let snapshot = buffer.snapshot(cx);
 3237
 3238        let mut edits = Vec::new();
 3239        let mut rows = Vec::new();
 3240        let mut rows_inserted = 0;
 3241
 3242        for selection in self.selections.all_adjusted(cx) {
 3243            let cursor = selection.head();
 3244            let row = cursor.row;
 3245
 3246            let point = Point::new(row + 1, 0);
 3247            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3248
 3249            let newline = "\n".to_string();
 3250            edits.push((start_of_line..start_of_line, newline));
 3251
 3252            rows_inserted += 1;
 3253            rows.push(row + rows_inserted);
 3254        }
 3255
 3256        self.transact(cx, |editor, cx| {
 3257            editor.edit(edits, cx);
 3258
 3259            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3260                let mut index = 0;
 3261                s.move_cursors_with(|map, _, _| {
 3262                    let row = rows[index];
 3263                    index += 1;
 3264
 3265                    let point = Point::new(row, 0);
 3266                    let boundary = map.next_line_boundary(point).1;
 3267                    let clipped = map.clip_point(boundary, Bias::Left);
 3268
 3269                    (clipped, SelectionGoal::None)
 3270                });
 3271            });
 3272
 3273            let mut indent_edits = Vec::new();
 3274            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3275            for row in rows {
 3276                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3277                for (row, indent) in indents {
 3278                    if indent.len == 0 {
 3279                        continue;
 3280                    }
 3281
 3282                    let text = match indent.kind {
 3283                        IndentKind::Space => " ".repeat(indent.len as usize),
 3284                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3285                    };
 3286                    let point = Point::new(row.0, 0);
 3287                    indent_edits.push((point..point, text));
 3288                }
 3289            }
 3290            editor.edit(indent_edits, cx);
 3291        });
 3292    }
 3293
 3294    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3295        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3296            original_indent_columns: Vec::new(),
 3297        });
 3298        self.insert_with_autoindent_mode(text, autoindent, cx);
 3299    }
 3300
 3301    fn insert_with_autoindent_mode(
 3302        &mut self,
 3303        text: &str,
 3304        autoindent_mode: Option<AutoindentMode>,
 3305        cx: &mut ViewContext<Self>,
 3306    ) {
 3307        if self.read_only(cx) {
 3308            return;
 3309        }
 3310
 3311        let text: Arc<str> = text.into();
 3312        self.transact(cx, |this, cx| {
 3313            let old_selections = this.selections.all_adjusted(cx);
 3314            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3315                let anchors = {
 3316                    let snapshot = buffer.read(cx);
 3317                    old_selections
 3318                        .iter()
 3319                        .map(|s| {
 3320                            let anchor = snapshot.anchor_after(s.head());
 3321                            s.map(|_| anchor)
 3322                        })
 3323                        .collect::<Vec<_>>()
 3324                };
 3325                buffer.edit(
 3326                    old_selections
 3327                        .iter()
 3328                        .map(|s| (s.start..s.end, text.clone())),
 3329                    autoindent_mode,
 3330                    cx,
 3331                );
 3332                anchors
 3333            });
 3334
 3335            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3336                s.select_anchors(selection_anchors);
 3337            })
 3338        });
 3339    }
 3340
 3341    fn trigger_completion_on_input(
 3342        &mut self,
 3343        text: &str,
 3344        trigger_in_words: bool,
 3345        cx: &mut ViewContext<Self>,
 3346    ) {
 3347        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3348            self.show_completions(&ShowCompletions, cx);
 3349        } else {
 3350            self.hide_context_menu(cx);
 3351        }
 3352    }
 3353
 3354    fn is_completion_trigger(
 3355        &self,
 3356        text: &str,
 3357        trigger_in_words: bool,
 3358        cx: &mut ViewContext<Self>,
 3359    ) -> bool {
 3360        let position = self.selections.newest_anchor().head();
 3361        let multibuffer = self.buffer.read(cx);
 3362        let Some(buffer) = position
 3363            .buffer_id
 3364            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3365        else {
 3366            return false;
 3367        };
 3368
 3369        if let Some(completion_provider) = &self.completion_provider {
 3370            completion_provider.is_completion_trigger(
 3371                &buffer,
 3372                position.text_anchor,
 3373                text,
 3374                trigger_in_words,
 3375                cx,
 3376            )
 3377        } else {
 3378            false
 3379        }
 3380    }
 3381
 3382    /// If any empty selections is touching the start of its innermost containing autoclose
 3383    /// region, expand it to select the brackets.
 3384    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3385        let selections = self.selections.all::<usize>(cx);
 3386        let buffer = self.buffer.read(cx).read(cx);
 3387        let new_selections = self
 3388            .selections_with_autoclose_regions(selections, &buffer)
 3389            .map(|(mut selection, region)| {
 3390                if !selection.is_empty() {
 3391                    return selection;
 3392                }
 3393
 3394                if let Some(region) = region {
 3395                    let mut range = region.range.to_offset(&buffer);
 3396                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3397                        range.start -= region.pair.start.len();
 3398                        if buffer.contains_str_at(range.start, &region.pair.start)
 3399                            && buffer.contains_str_at(range.end, &region.pair.end)
 3400                        {
 3401                            range.end += region.pair.end.len();
 3402                            selection.start = range.start;
 3403                            selection.end = range.end;
 3404
 3405                            return selection;
 3406                        }
 3407                    }
 3408                }
 3409
 3410                let always_treat_brackets_as_autoclosed = buffer
 3411                    .settings_at(selection.start, cx)
 3412                    .always_treat_brackets_as_autoclosed;
 3413
 3414                if !always_treat_brackets_as_autoclosed {
 3415                    return selection;
 3416                }
 3417
 3418                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3419                    for (pair, enabled) in scope.brackets() {
 3420                        if !enabled || !pair.close {
 3421                            continue;
 3422                        }
 3423
 3424                        if buffer.contains_str_at(selection.start, &pair.end) {
 3425                            let pair_start_len = pair.start.len();
 3426                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3427                            {
 3428                                selection.start -= pair_start_len;
 3429                                selection.end += pair.end.len();
 3430
 3431                                return selection;
 3432                            }
 3433                        }
 3434                    }
 3435                }
 3436
 3437                selection
 3438            })
 3439            .collect();
 3440
 3441        drop(buffer);
 3442        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3443    }
 3444
 3445    /// Iterate the given selections, and for each one, find the smallest surrounding
 3446    /// autoclose region. This uses the ordering of the selections and the autoclose
 3447    /// regions to avoid repeated comparisons.
 3448    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3449        &'a self,
 3450        selections: impl IntoIterator<Item = Selection<D>>,
 3451        buffer: &'a MultiBufferSnapshot,
 3452    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3453        let mut i = 0;
 3454        let mut regions = self.autoclose_regions.as_slice();
 3455        selections.into_iter().map(move |selection| {
 3456            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3457
 3458            let mut enclosing = None;
 3459            while let Some(pair_state) = regions.get(i) {
 3460                if pair_state.range.end.to_offset(buffer) < range.start {
 3461                    regions = &regions[i + 1..];
 3462                    i = 0;
 3463                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3464                    break;
 3465                } else {
 3466                    if pair_state.selection_id == selection.id {
 3467                        enclosing = Some(pair_state);
 3468                    }
 3469                    i += 1;
 3470                }
 3471            }
 3472
 3473            (selection.clone(), enclosing)
 3474        })
 3475    }
 3476
 3477    /// Remove any autoclose regions that no longer contain their selection.
 3478    fn invalidate_autoclose_regions(
 3479        &mut self,
 3480        mut selections: &[Selection<Anchor>],
 3481        buffer: &MultiBufferSnapshot,
 3482    ) {
 3483        self.autoclose_regions.retain(|state| {
 3484            let mut i = 0;
 3485            while let Some(selection) = selections.get(i) {
 3486                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3487                    selections = &selections[1..];
 3488                    continue;
 3489                }
 3490                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3491                    break;
 3492                }
 3493                if selection.id == state.selection_id {
 3494                    return true;
 3495                } else {
 3496                    i += 1;
 3497                }
 3498            }
 3499            false
 3500        });
 3501    }
 3502
 3503    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3504        let offset = position.to_offset(buffer);
 3505        let (word_range, kind) = buffer.surrounding_word(offset);
 3506        if offset > word_range.start && kind == Some(CharKind::Word) {
 3507            Some(
 3508                buffer
 3509                    .text_for_range(word_range.start..offset)
 3510                    .collect::<String>(),
 3511            )
 3512        } else {
 3513            None
 3514        }
 3515    }
 3516
 3517    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3518        self.refresh_inlay_hints(
 3519            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3520            cx,
 3521        );
 3522    }
 3523
 3524    pub fn inlay_hints_enabled(&self) -> bool {
 3525        self.inlay_hint_cache.enabled
 3526    }
 3527
 3528    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3529        if self.project.is_none() || self.mode != EditorMode::Full {
 3530            return;
 3531        }
 3532
 3533        let reason_description = reason.description();
 3534        let ignore_debounce = matches!(
 3535            reason,
 3536            InlayHintRefreshReason::SettingsChange(_)
 3537                | InlayHintRefreshReason::Toggle(_)
 3538                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3539        );
 3540        let (invalidate_cache, required_languages) = match reason {
 3541            InlayHintRefreshReason::Toggle(enabled) => {
 3542                self.inlay_hint_cache.enabled = enabled;
 3543                if enabled {
 3544                    (InvalidationStrategy::RefreshRequested, None)
 3545                } else {
 3546                    self.inlay_hint_cache.clear();
 3547                    self.splice_inlays(
 3548                        self.visible_inlay_hints(cx)
 3549                            .iter()
 3550                            .map(|inlay| inlay.id)
 3551                            .collect(),
 3552                        Vec::new(),
 3553                        cx,
 3554                    );
 3555                    return;
 3556                }
 3557            }
 3558            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3559                match self.inlay_hint_cache.update_settings(
 3560                    &self.buffer,
 3561                    new_settings,
 3562                    self.visible_inlay_hints(cx),
 3563                    cx,
 3564                ) {
 3565                    ControlFlow::Break(Some(InlaySplice {
 3566                        to_remove,
 3567                        to_insert,
 3568                    })) => {
 3569                        self.splice_inlays(to_remove, to_insert, cx);
 3570                        return;
 3571                    }
 3572                    ControlFlow::Break(None) => return,
 3573                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3574                }
 3575            }
 3576            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3577                if let Some(InlaySplice {
 3578                    to_remove,
 3579                    to_insert,
 3580                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3581                {
 3582                    self.splice_inlays(to_remove, to_insert, cx);
 3583                }
 3584                return;
 3585            }
 3586            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3587            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3588                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3589            }
 3590            InlayHintRefreshReason::RefreshRequested => {
 3591                (InvalidationStrategy::RefreshRequested, None)
 3592            }
 3593        };
 3594
 3595        if let Some(InlaySplice {
 3596            to_remove,
 3597            to_insert,
 3598        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3599            reason_description,
 3600            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3601            invalidate_cache,
 3602            ignore_debounce,
 3603            cx,
 3604        ) {
 3605            self.splice_inlays(to_remove, to_insert, cx);
 3606        }
 3607    }
 3608
 3609    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 3610        self.display_map
 3611            .read(cx)
 3612            .current_inlays()
 3613            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3614            .cloned()
 3615            .collect()
 3616    }
 3617
 3618    pub fn excerpts_for_inlay_hints_query(
 3619        &self,
 3620        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3621        cx: &mut ViewContext<Editor>,
 3622    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3623        let Some(project) = self.project.as_ref() else {
 3624            return HashMap::default();
 3625        };
 3626        let project = project.read(cx);
 3627        let multi_buffer = self.buffer().read(cx);
 3628        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3629        let multi_buffer_visible_start = self
 3630            .scroll_manager
 3631            .anchor()
 3632            .anchor
 3633            .to_point(&multi_buffer_snapshot);
 3634        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3635            multi_buffer_visible_start
 3636                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3637            Bias::Left,
 3638        );
 3639        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3640        multi_buffer
 3641            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 3642            .into_iter()
 3643            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3644            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 3645                let buffer = buffer_handle.read(cx);
 3646                let buffer_file = project::File::from_dyn(buffer.file())?;
 3647                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3648                let worktree_entry = buffer_worktree
 3649                    .read(cx)
 3650                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3651                if worktree_entry.is_ignored {
 3652                    return None;
 3653                }
 3654
 3655                let language = buffer.language()?;
 3656                if let Some(restrict_to_languages) = restrict_to_languages {
 3657                    if !restrict_to_languages.contains(language) {
 3658                        return None;
 3659                    }
 3660                }
 3661                Some((
 3662                    excerpt_id,
 3663                    (
 3664                        buffer_handle,
 3665                        buffer.version().clone(),
 3666                        excerpt_visible_range,
 3667                    ),
 3668                ))
 3669            })
 3670            .collect()
 3671    }
 3672
 3673    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3674        TextLayoutDetails {
 3675            text_system: cx.text_system().clone(),
 3676            editor_style: self.style.clone().unwrap(),
 3677            rem_size: cx.rem_size(),
 3678            scroll_anchor: self.scroll_manager.anchor(),
 3679            visible_rows: self.visible_line_count(),
 3680            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3681        }
 3682    }
 3683
 3684    fn splice_inlays(
 3685        &self,
 3686        to_remove: Vec<InlayId>,
 3687        to_insert: Vec<Inlay>,
 3688        cx: &mut ViewContext<Self>,
 3689    ) {
 3690        self.display_map.update(cx, |display_map, cx| {
 3691            display_map.splice_inlays(to_remove, to_insert, cx);
 3692        });
 3693        cx.notify();
 3694    }
 3695
 3696    fn trigger_on_type_formatting(
 3697        &self,
 3698        input: String,
 3699        cx: &mut ViewContext<Self>,
 3700    ) -> Option<Task<Result<()>>> {
 3701        if input.len() != 1 {
 3702            return None;
 3703        }
 3704
 3705        let project = self.project.as_ref()?;
 3706        let position = self.selections.newest_anchor().head();
 3707        let (buffer, buffer_position) = self
 3708            .buffer
 3709            .read(cx)
 3710            .text_anchor_for_position(position, cx)?;
 3711
 3712        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3713        // hence we do LSP request & edit on host side only — add formats to host's history.
 3714        let push_to_lsp_host_history = true;
 3715        // If this is not the host, append its history with new edits.
 3716        let push_to_client_history = project.read(cx).is_remote();
 3717
 3718        let on_type_formatting = project.update(cx, |project, cx| {
 3719            project.on_type_format(
 3720                buffer.clone(),
 3721                buffer_position,
 3722                input,
 3723                push_to_lsp_host_history,
 3724                cx,
 3725            )
 3726        });
 3727        Some(cx.spawn(|editor, mut cx| async move {
 3728            if let Some(transaction) = on_type_formatting.await? {
 3729                if push_to_client_history {
 3730                    buffer
 3731                        .update(&mut cx, |buffer, _| {
 3732                            buffer.push_transaction(transaction, Instant::now());
 3733                        })
 3734                        .ok();
 3735                }
 3736                editor.update(&mut cx, |editor, cx| {
 3737                    editor.refresh_document_highlights(cx);
 3738                })?;
 3739            }
 3740            Ok(())
 3741        }))
 3742    }
 3743
 3744    fn show_completions(&mut self, _: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3745        if self.pending_rename.is_some() {
 3746            return;
 3747        }
 3748
 3749        let Some(provider) = self.completion_provider.as_ref() else {
 3750            return;
 3751        };
 3752
 3753        let position = self.selections.newest_anchor().head();
 3754        let (buffer, buffer_position) =
 3755            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3756                output
 3757            } else {
 3758                return;
 3759            };
 3760
 3761        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3762        let completions = provider.completions(&buffer, buffer_position, cx);
 3763
 3764        let id = post_inc(&mut self.next_completion_id);
 3765        let task = cx.spawn(|this, mut cx| {
 3766            async move {
 3767                let completions = completions.await.log_err();
 3768                let menu = if let Some(completions) = completions {
 3769                    let mut menu = CompletionsMenu {
 3770                        id,
 3771                        initial_position: position,
 3772                        match_candidates: completions
 3773                            .iter()
 3774                            .enumerate()
 3775                            .map(|(id, completion)| {
 3776                                StringMatchCandidate::new(
 3777                                    id,
 3778                                    completion.label.text[completion.label.filter_range.clone()]
 3779                                        .into(),
 3780                                )
 3781                            })
 3782                            .collect(),
 3783                        buffer: buffer.clone(),
 3784                        completions: Arc::new(RwLock::new(completions.into())),
 3785                        matches: Vec::new().into(),
 3786                        selected_item: 0,
 3787                        scroll_handle: UniformListScrollHandle::new(),
 3788                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 3789                            DebouncedDelay::new(),
 3790                        )),
 3791                    };
 3792                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3793                        .await;
 3794
 3795                    if menu.matches.is_empty() {
 3796                        None
 3797                    } else {
 3798                        this.update(&mut cx, |editor, cx| {
 3799                            let completions = menu.completions.clone();
 3800                            let matches = menu.matches.clone();
 3801
 3802                            let delay_ms = EditorSettings::get_global(cx)
 3803                                .completion_documentation_secondary_query_debounce;
 3804                            let delay = Duration::from_millis(delay_ms);
 3805
 3806                            editor
 3807                                .completion_documentation_pre_resolve_debounce
 3808                                .fire_new(delay, cx, |editor, cx| {
 3809                                    CompletionsMenu::pre_resolve_completion_documentation(
 3810                                        buffer,
 3811                                        completions,
 3812                                        matches,
 3813                                        editor,
 3814                                        cx,
 3815                                    )
 3816                                });
 3817                        })
 3818                        .ok();
 3819                        Some(menu)
 3820                    }
 3821                } else {
 3822                    None
 3823                };
 3824
 3825                this.update(&mut cx, |this, cx| {
 3826                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3827
 3828                    let mut context_menu = this.context_menu.write();
 3829                    match context_menu.as_ref() {
 3830                        None => {}
 3831
 3832                        Some(ContextMenu::Completions(prev_menu)) => {
 3833                            if prev_menu.id > id {
 3834                                return;
 3835                            }
 3836                        }
 3837
 3838                        _ => return,
 3839                    }
 3840
 3841                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 3842                        let menu = menu.unwrap();
 3843                        *context_menu = Some(ContextMenu::Completions(menu));
 3844                        drop(context_menu);
 3845                        this.discard_inline_completion(false, cx);
 3846                        cx.notify();
 3847                    } else if this.completion_tasks.len() <= 1 {
 3848                        // If there are no more completion tasks and the last menu was
 3849                        // empty, we should hide it. If it was already hidden, we should
 3850                        // also show the copilot completion when available.
 3851                        drop(context_menu);
 3852                        if this.hide_context_menu(cx).is_none() {
 3853                            this.update_visible_inline_completion(cx);
 3854                        }
 3855                    }
 3856                })?;
 3857
 3858                Ok::<_, anyhow::Error>(())
 3859            }
 3860            .log_err()
 3861        });
 3862
 3863        self.completion_tasks.push((id, task));
 3864    }
 3865
 3866    pub fn confirm_completion(
 3867        &mut self,
 3868        action: &ConfirmCompletion,
 3869        cx: &mut ViewContext<Self>,
 3870    ) -> Option<Task<Result<()>>> {
 3871        use language::ToOffset as _;
 3872
 3873        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3874            menu
 3875        } else {
 3876            return None;
 3877        };
 3878
 3879        let mat = completions_menu
 3880            .matches
 3881            .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
 3882        let buffer_handle = completions_menu.buffer;
 3883        let completions = completions_menu.completions.read();
 3884        let completion = completions.get(mat.candidate_id)?;
 3885        cx.stop_propagation();
 3886
 3887        let snippet;
 3888        let text;
 3889        if completion.is_snippet() {
 3890            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3891            text = snippet.as_ref().unwrap().text.clone();
 3892        } else {
 3893            snippet = None;
 3894            text = completion.new_text.clone();
 3895        };
 3896        let selections = self.selections.all::<usize>(cx);
 3897        let buffer = buffer_handle.read(cx);
 3898        let old_range = completion.old_range.to_offset(buffer);
 3899        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3900
 3901        let newest_selection = self.selections.newest_anchor();
 3902        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3903            return None;
 3904        }
 3905
 3906        let lookbehind = newest_selection
 3907            .start
 3908            .text_anchor
 3909            .to_offset(buffer)
 3910            .saturating_sub(old_range.start);
 3911        let lookahead = old_range
 3912            .end
 3913            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3914        let mut common_prefix_len = old_text
 3915            .bytes()
 3916            .zip(text.bytes())
 3917            .take_while(|(a, b)| a == b)
 3918            .count();
 3919
 3920        let snapshot = self.buffer.read(cx).snapshot(cx);
 3921        let mut range_to_replace: Option<Range<isize>> = None;
 3922        let mut ranges = Vec::new();
 3923        for selection in &selections {
 3924            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3925                let start = selection.start.saturating_sub(lookbehind);
 3926                let end = selection.end + lookahead;
 3927                if selection.id == newest_selection.id {
 3928                    range_to_replace = Some(
 3929                        ((start + common_prefix_len) as isize - selection.start as isize)
 3930                            ..(end as isize - selection.start as isize),
 3931                    );
 3932                }
 3933                ranges.push(start + common_prefix_len..end);
 3934            } else {
 3935                common_prefix_len = 0;
 3936                ranges.clear();
 3937                ranges.extend(selections.iter().map(|s| {
 3938                    if s.id == newest_selection.id {
 3939                        range_to_replace = Some(
 3940                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3941                                - selection.start as isize
 3942                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3943                                    - selection.start as isize,
 3944                        );
 3945                        old_range.clone()
 3946                    } else {
 3947                        s.start..s.end
 3948                    }
 3949                }));
 3950                break;
 3951            }
 3952        }
 3953        let text = &text[common_prefix_len..];
 3954
 3955        cx.emit(EditorEvent::InputHandled {
 3956            utf16_range_to_replace: range_to_replace,
 3957            text: text.into(),
 3958        });
 3959
 3960        self.transact(cx, |this, cx| {
 3961            if let Some(mut snippet) = snippet {
 3962                snippet.text = text.to_string();
 3963                for tabstop in snippet.tabstops.iter_mut().flatten() {
 3964                    tabstop.start -= common_prefix_len as isize;
 3965                    tabstop.end -= common_prefix_len as isize;
 3966                }
 3967
 3968                this.insert_snippet(&ranges, snippet, cx).log_err();
 3969            } else {
 3970                this.buffer.update(cx, |buffer, cx| {
 3971                    buffer.edit(
 3972                        ranges.iter().map(|range| (range.clone(), text)),
 3973                        this.autoindent_mode.clone(),
 3974                        cx,
 3975                    );
 3976                });
 3977            }
 3978
 3979            this.refresh_inline_completion(true, cx);
 3980        });
 3981
 3982        let provider = self.completion_provider.as_ref()?;
 3983        let apply_edits = provider.apply_additional_edits_for_completion(
 3984            buffer_handle,
 3985            completion.clone(),
 3986            true,
 3987            cx,
 3988        );
 3989        Some(cx.foreground_executor().spawn(async move {
 3990            apply_edits.await?;
 3991            Ok(())
 3992        }))
 3993    }
 3994
 3995    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 3996        let mut context_menu = self.context_menu.write();
 3997        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 3998            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 3999                // Toggle if we're selecting the same one
 4000                *context_menu = None;
 4001                cx.notify();
 4002                return;
 4003            } else {
 4004                // Otherwise, clear it and start a new one
 4005                *context_menu = None;
 4006                cx.notify();
 4007            }
 4008        }
 4009        drop(context_menu);
 4010        let snapshot = self.snapshot(cx);
 4011        let deployed_from_indicator = action.deployed_from_indicator;
 4012        let mut task = self.code_actions_task.take();
 4013        let action = action.clone();
 4014        cx.spawn(|this, mut cx| async move {
 4015            while let Some(prev_task) = task {
 4016                prev_task.await;
 4017                task = this.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4018            }
 4019
 4020            let spawned_test_task = this.update(&mut cx, |this, cx| {
 4021                if this.focus_handle.is_focused(cx) {
 4022                    let multibuffer_point = action
 4023                        .deployed_from_indicator
 4024                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4025                        .unwrap_or_else(|| this.selections.newest::<Point>(cx).head());
 4026                    let (buffer, buffer_row) = snapshot
 4027                        .buffer_snapshot
 4028                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4029                        .and_then(|(buffer_snapshot, range)| {
 4030                            this.buffer
 4031                                .read(cx)
 4032                                .buffer(buffer_snapshot.remote_id())
 4033                                .map(|buffer| (buffer, range.start.row))
 4034                        })?;
 4035                    let (_, code_actions) = this
 4036                        .available_code_actions
 4037                        .clone()
 4038                        .and_then(|(location, code_actions)| {
 4039                            let snapshot = location.buffer.read(cx).snapshot();
 4040                            let point_range = location.range.to_point(&snapshot);
 4041                            let point_range = point_range.start.row..=point_range.end.row;
 4042                            if point_range.contains(&buffer_row) {
 4043                                Some((location, code_actions))
 4044                            } else {
 4045                                None
 4046                            }
 4047                        })
 4048                        .unzip();
 4049                    let buffer_id = buffer.read(cx).remote_id();
 4050                    let tasks = this
 4051                        .tasks
 4052                        .get(&(buffer_id, buffer_row))
 4053                        .map(|t| Arc::new(t.to_owned()));
 4054                    if tasks.is_none() && code_actions.is_none() {
 4055                        return None;
 4056                    }
 4057
 4058                    this.completion_tasks.clear();
 4059                    this.discard_inline_completion(false, cx);
 4060                    let tasks = tasks.as_ref().zip(this.workspace.clone()).and_then(
 4061                        |(tasks, (workspace, _))| {
 4062                            let position = Point::new(buffer_row, tasks.column);
 4063                            let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4064                            let location = Location {
 4065                                buffer: buffer.clone(),
 4066                                range: range_start..range_start,
 4067                            };
 4068                            // Fill in the environmental variables from the tree-sitter captures
 4069                            let mut captured_task_variables = TaskVariables::default();
 4070                            for (capture_name, value) in tasks.extra_variables.clone() {
 4071                                captured_task_variables.insert(
 4072                                    task::VariableName::Custom(capture_name.into()),
 4073                                    value.clone(),
 4074                                );
 4075                            }
 4076
 4077                            workspace
 4078                                .update(cx, |workspace, cx| {
 4079                                    tasks::task_context_for_location(
 4080                                        captured_task_variables,
 4081                                        workspace,
 4082                                        location,
 4083                                        cx,
 4084                                    )
 4085                                })
 4086                                .ok()
 4087                                .flatten()
 4088                                .map(|task_context| {
 4089                                    Arc::new(ResolvedTasks {
 4090                                        templates: tasks
 4091                                            .templates
 4092                                            .iter()
 4093                                            .filter_map(|(kind, template)| {
 4094                                                template
 4095                                                    .resolve_task(&kind.to_id_base(), &task_context)
 4096                                                    .map(|task| (kind.clone(), task))
 4097                                            })
 4098                                            .collect(),
 4099                                        position: snapshot.buffer_snapshot.anchor_before(
 4100                                            Point::new(multibuffer_point.row, tasks.column),
 4101                                        ),
 4102                                    })
 4103                                })
 4104                        },
 4105                    );
 4106                    let spawn_straight_away = tasks
 4107                        .as_ref()
 4108                        .map_or(false, |tasks| tasks.templates.len() == 1)
 4109                        && code_actions
 4110                            .as_ref()
 4111                            .map_or(true, |actions| actions.is_empty());
 4112                    *this.context_menu.write() = Some(ContextMenu::CodeActions(CodeActionsMenu {
 4113                        buffer,
 4114                        actions: CodeActionContents {
 4115                            tasks,
 4116                            actions: code_actions,
 4117                        },
 4118                        selected_item: Default::default(),
 4119                        scroll_handle: UniformListScrollHandle::default(),
 4120                        deployed_from_indicator,
 4121                    }));
 4122                    if spawn_straight_away {
 4123                        if let Some(task) =
 4124                            this.confirm_code_action(&ConfirmCodeAction { item_ix: Some(0) }, cx)
 4125                        {
 4126                            cx.notify();
 4127                            return Some(task);
 4128                        }
 4129                    }
 4130                    cx.notify();
 4131                }
 4132                Some(Task::ready(Ok(())))
 4133            })?;
 4134            if let Some(task) = spawned_test_task {
 4135                task.await?;
 4136            }
 4137
 4138            Ok::<_, anyhow::Error>(())
 4139        })
 4140        .detach_and_log_err(cx);
 4141    }
 4142
 4143    pub fn confirm_code_action(
 4144        &mut self,
 4145        action: &ConfirmCodeAction,
 4146        cx: &mut ViewContext<Self>,
 4147    ) -> Option<Task<Result<()>>> {
 4148        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4149            menu
 4150        } else {
 4151            return None;
 4152        };
 4153        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4154        let action = actions_menu.actions.get(action_ix)?;
 4155        let title = action.label();
 4156        let buffer = actions_menu.buffer;
 4157        let workspace = self.workspace()?;
 4158
 4159        match action {
 4160            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4161                workspace.update(cx, |workspace, cx| {
 4162                    workspace::tasks::schedule_resolved_task(
 4163                        workspace,
 4164                        task_source_kind,
 4165                        resolved_task,
 4166                        false,
 4167                        cx,
 4168                    );
 4169
 4170                    Some(Task::ready(Ok(())))
 4171                })
 4172            }
 4173            CodeActionsItem::CodeAction(action) => {
 4174                let apply_code_actions = workspace
 4175                    .read(cx)
 4176                    .project()
 4177                    .clone()
 4178                    .update(cx, |project, cx| {
 4179                        project.apply_code_action(buffer, action, true, cx)
 4180                    });
 4181                let workspace = workspace.downgrade();
 4182                Some(cx.spawn(|editor, cx| async move {
 4183                    let project_transaction = apply_code_actions.await?;
 4184                    Self::open_project_transaction(
 4185                        &editor,
 4186                        workspace,
 4187                        project_transaction,
 4188                        title,
 4189                        cx,
 4190                    )
 4191                    .await
 4192                }))
 4193            }
 4194        }
 4195    }
 4196
 4197    pub async fn open_project_transaction(
 4198        this: &WeakView<Editor>,
 4199        workspace: WeakView<Workspace>,
 4200        transaction: ProjectTransaction,
 4201        title: String,
 4202        mut cx: AsyncWindowContext,
 4203    ) -> Result<()> {
 4204        let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
 4205
 4206        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4207        cx.update(|cx| {
 4208            entries.sort_unstable_by_key(|(buffer, _)| {
 4209                buffer.read(cx).file().map(|f| f.path().clone())
 4210            });
 4211        })?;
 4212
 4213        // If the project transaction's edits are all contained within this editor, then
 4214        // avoid opening a new editor to display them.
 4215
 4216        if let Some((buffer, transaction)) = entries.first() {
 4217            if entries.len() == 1 {
 4218                let excerpt = this.update(&mut cx, |editor, cx| {
 4219                    editor
 4220                        .buffer()
 4221                        .read(cx)
 4222                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4223                })?;
 4224                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4225                    if excerpted_buffer == *buffer {
 4226                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4227                            let excerpt_range = excerpt_range.to_offset(buffer);
 4228                            buffer
 4229                                .edited_ranges_for_transaction::<usize>(transaction)
 4230                                .all(|range| {
 4231                                    excerpt_range.start <= range.start
 4232                                        && excerpt_range.end >= range.end
 4233                                })
 4234                        })?;
 4235
 4236                        if all_edits_within_excerpt {
 4237                            return Ok(());
 4238                        }
 4239                    }
 4240                }
 4241            }
 4242        } else {
 4243            return Ok(());
 4244        }
 4245
 4246        let mut ranges_to_highlight = Vec::new();
 4247        let excerpt_buffer = cx.new_model(|cx| {
 4248            let mut multibuffer =
 4249                MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
 4250            for (buffer_handle, transaction) in &entries {
 4251                let buffer = buffer_handle.read(cx);
 4252                ranges_to_highlight.extend(
 4253                    multibuffer.push_excerpts_with_context_lines(
 4254                        buffer_handle.clone(),
 4255                        buffer
 4256                            .edited_ranges_for_transaction::<usize>(transaction)
 4257                            .collect(),
 4258                        DEFAULT_MULTIBUFFER_CONTEXT,
 4259                        cx,
 4260                    ),
 4261                );
 4262            }
 4263            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4264            multibuffer
 4265        })?;
 4266
 4267        workspace.update(&mut cx, |workspace, cx| {
 4268            let project = workspace.project().clone();
 4269            let editor =
 4270                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), cx));
 4271            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, cx);
 4272            editor.update(cx, |editor, cx| {
 4273                editor.highlight_background::<Self>(
 4274                    &ranges_to_highlight,
 4275                    |theme| theme.editor_highlighted_line_background,
 4276                    cx,
 4277                );
 4278            });
 4279        })?;
 4280
 4281        Ok(())
 4282    }
 4283
 4284    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4285        let project = self.project.clone()?;
 4286        let buffer = self.buffer.read(cx);
 4287        let newest_selection = self.selections.newest_anchor().clone();
 4288        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4289        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4290        if start_buffer != end_buffer {
 4291            return None;
 4292        }
 4293
 4294        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4295            cx.background_executor()
 4296                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4297                .await;
 4298
 4299            let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
 4300                project.code_actions(&start_buffer, start..end, cx)
 4301            }) {
 4302                code_actions.await
 4303            } else {
 4304                Vec::new()
 4305            };
 4306
 4307            this.update(&mut cx, |this, cx| {
 4308                this.available_code_actions = if actions.is_empty() {
 4309                    None
 4310                } else {
 4311                    Some((
 4312                        Location {
 4313                            buffer: start_buffer,
 4314                            range: start..end,
 4315                        },
 4316                        actions.into(),
 4317                    ))
 4318                };
 4319                cx.notify();
 4320            })
 4321            .log_err();
 4322        }));
 4323        None
 4324    }
 4325
 4326    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4327        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4328            self.show_git_blame_inline = false;
 4329
 4330            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4331                cx.background_executor().timer(delay).await;
 4332
 4333                this.update(&mut cx, |this, cx| {
 4334                    this.show_git_blame_inline = true;
 4335                    cx.notify();
 4336                })
 4337                .log_err();
 4338            }));
 4339        }
 4340    }
 4341
 4342    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4343        if self.pending_rename.is_some() {
 4344            return None;
 4345        }
 4346
 4347        let project = self.project.clone()?;
 4348        let buffer = self.buffer.read(cx);
 4349        let newest_selection = self.selections.newest_anchor().clone();
 4350        let cursor_position = newest_selection.head();
 4351        let (cursor_buffer, cursor_buffer_position) =
 4352            buffer.text_anchor_for_position(cursor_position, cx)?;
 4353        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4354        if cursor_buffer != tail_buffer {
 4355            return None;
 4356        }
 4357
 4358        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4359            cx.background_executor()
 4360                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 4361                .await;
 4362
 4363            let highlights = if let Some(highlights) = project
 4364                .update(&mut cx, |project, cx| {
 4365                    project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4366                })
 4367                .log_err()
 4368            {
 4369                highlights.await.log_err()
 4370            } else {
 4371                None
 4372            };
 4373
 4374            if let Some(highlights) = highlights {
 4375                this.update(&mut cx, |this, cx| {
 4376                    if this.pending_rename.is_some() {
 4377                        return;
 4378                    }
 4379
 4380                    let buffer_id = cursor_position.buffer_id;
 4381                    let buffer = this.buffer.read(cx);
 4382                    if !buffer
 4383                        .text_anchor_for_position(cursor_position, cx)
 4384                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4385                    {
 4386                        return;
 4387                    }
 4388
 4389                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4390                    let mut write_ranges = Vec::new();
 4391                    let mut read_ranges = Vec::new();
 4392                    for highlight in highlights {
 4393                        for (excerpt_id, excerpt_range) in
 4394                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4395                        {
 4396                            let start = highlight
 4397                                .range
 4398                                .start
 4399                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4400                            let end = highlight
 4401                                .range
 4402                                .end
 4403                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4404                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4405                                continue;
 4406                            }
 4407
 4408                            let range = Anchor {
 4409                                buffer_id,
 4410                                excerpt_id: excerpt_id,
 4411                                text_anchor: start,
 4412                            }..Anchor {
 4413                                buffer_id,
 4414                                excerpt_id,
 4415                                text_anchor: end,
 4416                            };
 4417                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4418                                write_ranges.push(range);
 4419                            } else {
 4420                                read_ranges.push(range);
 4421                            }
 4422                        }
 4423                    }
 4424
 4425                    this.highlight_background::<DocumentHighlightRead>(
 4426                        &read_ranges,
 4427                        |theme| theme.editor_document_highlight_read_background,
 4428                        cx,
 4429                    );
 4430                    this.highlight_background::<DocumentHighlightWrite>(
 4431                        &write_ranges,
 4432                        |theme| theme.editor_document_highlight_write_background,
 4433                        cx,
 4434                    );
 4435                    cx.notify();
 4436                })
 4437                .log_err();
 4438            }
 4439        }));
 4440        None
 4441    }
 4442
 4443    fn refresh_inline_completion(
 4444        &mut self,
 4445        debounce: bool,
 4446        cx: &mut ViewContext<Self>,
 4447    ) -> Option<()> {
 4448        let provider = self.inline_completion_provider()?;
 4449        let cursor = self.selections.newest_anchor().head();
 4450        let (buffer, cursor_buffer_position) =
 4451            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4452        if !self.show_inline_completions
 4453            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4454        {
 4455            self.discard_inline_completion(false, cx);
 4456            return None;
 4457        }
 4458
 4459        self.update_visible_inline_completion(cx);
 4460        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4461        Some(())
 4462    }
 4463
 4464    fn cycle_inline_completion(
 4465        &mut self,
 4466        direction: Direction,
 4467        cx: &mut ViewContext<Self>,
 4468    ) -> Option<()> {
 4469        let provider = self.inline_completion_provider()?;
 4470        let cursor = self.selections.newest_anchor().head();
 4471        let (buffer, cursor_buffer_position) =
 4472            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4473        if !self.show_inline_completions
 4474            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4475        {
 4476            return None;
 4477        }
 4478
 4479        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4480        self.update_visible_inline_completion(cx);
 4481
 4482        Some(())
 4483    }
 4484
 4485    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4486        if !self.has_active_inline_completion(cx) {
 4487            self.refresh_inline_completion(false, cx);
 4488            return;
 4489        }
 4490
 4491        self.update_visible_inline_completion(cx);
 4492    }
 4493
 4494    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4495        self.show_cursor_names(cx);
 4496    }
 4497
 4498    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4499        self.show_cursor_names = true;
 4500        cx.notify();
 4501        cx.spawn(|this, mut cx| async move {
 4502            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4503            this.update(&mut cx, |this, cx| {
 4504                this.show_cursor_names = false;
 4505                cx.notify()
 4506            })
 4507            .ok()
 4508        })
 4509        .detach();
 4510    }
 4511
 4512    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4513        if self.has_active_inline_completion(cx) {
 4514            self.cycle_inline_completion(Direction::Next, cx);
 4515        } else {
 4516            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4517            if is_copilot_disabled {
 4518                cx.propagate();
 4519            }
 4520        }
 4521    }
 4522
 4523    pub fn previous_inline_completion(
 4524        &mut self,
 4525        _: &PreviousInlineCompletion,
 4526        cx: &mut ViewContext<Self>,
 4527    ) {
 4528        if self.has_active_inline_completion(cx) {
 4529            self.cycle_inline_completion(Direction::Prev, cx);
 4530        } else {
 4531            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4532            if is_copilot_disabled {
 4533                cx.propagate();
 4534            }
 4535        }
 4536    }
 4537
 4538    pub fn accept_inline_completion(
 4539        &mut self,
 4540        _: &AcceptInlineCompletion,
 4541        cx: &mut ViewContext<Self>,
 4542    ) {
 4543        let Some(completion) = self.take_active_inline_completion(cx) else {
 4544            return;
 4545        };
 4546        if let Some(provider) = self.inline_completion_provider() {
 4547            provider.accept(cx);
 4548        }
 4549
 4550        cx.emit(EditorEvent::InputHandled {
 4551            utf16_range_to_replace: None,
 4552            text: completion.text.to_string().into(),
 4553        });
 4554        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 4555        self.refresh_inline_completion(true, cx);
 4556        cx.notify();
 4557    }
 4558
 4559    pub fn accept_partial_inline_completion(
 4560        &mut self,
 4561        _: &AcceptPartialInlineCompletion,
 4562        cx: &mut ViewContext<Self>,
 4563    ) {
 4564        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 4565            if let Some(completion) = self.take_active_inline_completion(cx) {
 4566                let mut partial_completion = completion
 4567                    .text
 4568                    .chars()
 4569                    .by_ref()
 4570                    .take_while(|c| c.is_alphabetic())
 4571                    .collect::<String>();
 4572                if partial_completion.is_empty() {
 4573                    partial_completion = completion
 4574                        .text
 4575                        .chars()
 4576                        .by_ref()
 4577                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4578                        .collect::<String>();
 4579                }
 4580
 4581                cx.emit(EditorEvent::InputHandled {
 4582                    utf16_range_to_replace: None,
 4583                    text: partial_completion.clone().into(),
 4584                });
 4585                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4586                self.refresh_inline_completion(true, cx);
 4587                cx.notify();
 4588            }
 4589        }
 4590    }
 4591
 4592    fn discard_inline_completion(
 4593        &mut self,
 4594        should_report_inline_completion_event: bool,
 4595        cx: &mut ViewContext<Self>,
 4596    ) -> bool {
 4597        if let Some(provider) = self.inline_completion_provider() {
 4598            provider.discard(should_report_inline_completion_event, cx);
 4599        }
 4600
 4601        self.take_active_inline_completion(cx).is_some()
 4602    }
 4603
 4604    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 4605        if let Some(completion) = self.active_inline_completion.as_ref() {
 4606            let buffer = self.buffer.read(cx).read(cx);
 4607            completion.position.is_valid(&buffer)
 4608        } else {
 4609            false
 4610        }
 4611    }
 4612
 4613    fn take_active_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<Inlay> {
 4614        let completion = self.active_inline_completion.take()?;
 4615        self.display_map.update(cx, |map, cx| {
 4616            map.splice_inlays(vec![completion.id], Default::default(), cx);
 4617        });
 4618        let buffer = self.buffer.read(cx).read(cx);
 4619
 4620        if completion.position.is_valid(&buffer) {
 4621            Some(completion)
 4622        } else {
 4623            None
 4624        }
 4625    }
 4626
 4627    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 4628        let selection = self.selections.newest_anchor();
 4629        let cursor = selection.head();
 4630
 4631        if self.context_menu.read().is_none()
 4632            && self.completion_tasks.is_empty()
 4633            && selection.start == selection.end
 4634        {
 4635            if let Some(provider) = self.inline_completion_provider() {
 4636                if let Some((buffer, cursor_buffer_position)) =
 4637                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4638                {
 4639                    if let Some(text) =
 4640                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 4641                    {
 4642                        let text = Rope::from(text);
 4643                        let mut to_remove = Vec::new();
 4644                        if let Some(completion) = self.active_inline_completion.take() {
 4645                            to_remove.push(completion.id);
 4646                        }
 4647
 4648                        let completion_inlay =
 4649                            Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
 4650                        self.active_inline_completion = Some(completion_inlay.clone());
 4651                        self.display_map.update(cx, move |map, cx| {
 4652                            map.splice_inlays(to_remove, vec![completion_inlay], cx)
 4653                        });
 4654                        cx.notify();
 4655                        return;
 4656                    }
 4657                }
 4658            }
 4659        }
 4660
 4661        self.discard_inline_completion(false, cx);
 4662    }
 4663
 4664    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4665        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4666    }
 4667
 4668    fn render_code_actions_indicator(
 4669        &self,
 4670        _style: &EditorStyle,
 4671        row: DisplayRow,
 4672        is_active: bool,
 4673        cx: &mut ViewContext<Self>,
 4674    ) -> Option<IconButton> {
 4675        if self.available_code_actions.is_some() {
 4676            Some(
 4677                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 4678                    .icon_size(IconSize::XSmall)
 4679                    .size(ui::ButtonSize::None)
 4680                    .icon_color(Color::Muted)
 4681                    .selected(is_active)
 4682                    .on_click(cx.listener(move |editor, _e, cx| {
 4683                        editor.focus(cx);
 4684                        editor.toggle_code_actions(
 4685                            &ToggleCodeActions {
 4686                                deployed_from_indicator: Some(row),
 4687                            },
 4688                            cx,
 4689                        );
 4690                    })),
 4691            )
 4692        } else {
 4693            None
 4694        }
 4695    }
 4696
 4697    fn clear_tasks(&mut self) {
 4698        self.tasks.clear()
 4699    }
 4700
 4701    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 4702        if let Some(_) = self.tasks.insert(key, value) {
 4703            // This case should hopefully be rare, but just in case...
 4704            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 4705        }
 4706    }
 4707
 4708    fn render_run_indicator(
 4709        &self,
 4710        _style: &EditorStyle,
 4711        is_active: bool,
 4712        row: DisplayRow,
 4713        cx: &mut ViewContext<Self>,
 4714    ) -> IconButton {
 4715        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 4716            .icon_size(IconSize::XSmall)
 4717            .size(ui::ButtonSize::None)
 4718            .icon_color(Color::Muted)
 4719            .selected(is_active)
 4720            .on_click(cx.listener(move |editor, _e, cx| {
 4721                editor.focus(cx);
 4722                editor.toggle_code_actions(
 4723                    &ToggleCodeActions {
 4724                        deployed_from_indicator: Some(row),
 4725                    },
 4726                    cx,
 4727                );
 4728            }))
 4729    }
 4730
 4731    pub fn context_menu_visible(&self) -> bool {
 4732        self.context_menu
 4733            .read()
 4734            .as_ref()
 4735            .map_or(false, |menu| menu.visible())
 4736    }
 4737
 4738    fn render_context_menu(
 4739        &self,
 4740        cursor_position: DisplayPoint,
 4741        style: &EditorStyle,
 4742        max_height: Pixels,
 4743        cx: &mut ViewContext<Editor>,
 4744    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 4745        self.context_menu.read().as_ref().map(|menu| {
 4746            menu.render(
 4747                cursor_position,
 4748                style,
 4749                max_height,
 4750                self.workspace.as_ref().map(|(w, _)| w.clone()),
 4751                cx,
 4752            )
 4753        })
 4754    }
 4755
 4756    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 4757        cx.notify();
 4758        self.completion_tasks.clear();
 4759        let context_menu = self.context_menu.write().take();
 4760        if context_menu.is_some() {
 4761            self.update_visible_inline_completion(cx);
 4762        }
 4763        context_menu
 4764    }
 4765
 4766    pub fn insert_snippet(
 4767        &mut self,
 4768        insertion_ranges: &[Range<usize>],
 4769        snippet: Snippet,
 4770        cx: &mut ViewContext<Self>,
 4771    ) -> Result<()> {
 4772        struct Tabstop<T> {
 4773            is_end_tabstop: bool,
 4774            ranges: Vec<Range<T>>,
 4775        }
 4776
 4777        let tabstops = self.buffer.update(cx, |buffer, cx| {
 4778            let snippet_text: Arc<str> = snippet.text.clone().into();
 4779            buffer.edit(
 4780                insertion_ranges
 4781                    .iter()
 4782                    .cloned()
 4783                    .map(|range| (range, snippet_text.clone())),
 4784                Some(AutoindentMode::EachLine),
 4785                cx,
 4786            );
 4787
 4788            let snapshot = &*buffer.read(cx);
 4789            let snippet = &snippet;
 4790            snippet
 4791                .tabstops
 4792                .iter()
 4793                .map(|tabstop| {
 4794                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 4795                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 4796                    });
 4797                    let mut tabstop_ranges = tabstop
 4798                        .iter()
 4799                        .flat_map(|tabstop_range| {
 4800                            let mut delta = 0_isize;
 4801                            insertion_ranges.iter().map(move |insertion_range| {
 4802                                let insertion_start = insertion_range.start as isize + delta;
 4803                                delta +=
 4804                                    snippet.text.len() as isize - insertion_range.len() as isize;
 4805
 4806                                let start = ((insertion_start + tabstop_range.start) as usize)
 4807                                    .min(snapshot.len());
 4808                                let end = ((insertion_start + tabstop_range.end) as usize)
 4809                                    .min(snapshot.len());
 4810                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 4811                            })
 4812                        })
 4813                        .collect::<Vec<_>>();
 4814                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 4815
 4816                    Tabstop {
 4817                        is_end_tabstop,
 4818                        ranges: tabstop_ranges,
 4819                    }
 4820                })
 4821                .collect::<Vec<_>>()
 4822        });
 4823
 4824        if let Some(tabstop) = tabstops.first() {
 4825            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4826                s.select_ranges(tabstop.ranges.iter().cloned());
 4827            });
 4828
 4829            // If we're already at the last tabstop and it's at the end of the snippet,
 4830            // we're done, we don't need to keep the state around.
 4831            if !tabstop.is_end_tabstop {
 4832                let ranges = tabstops
 4833                    .into_iter()
 4834                    .map(|tabstop| tabstop.ranges)
 4835                    .collect::<Vec<_>>();
 4836                self.snippet_stack.push(SnippetState {
 4837                    active_index: 0,
 4838                    ranges,
 4839                });
 4840            }
 4841
 4842            // Check whether the just-entered snippet ends with an auto-closable bracket.
 4843            if self.autoclose_regions.is_empty() {
 4844                let snapshot = self.buffer.read(cx).snapshot(cx);
 4845                for selection in &mut self.selections.all::<Point>(cx) {
 4846                    let selection_head = selection.head();
 4847                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 4848                        continue;
 4849                    };
 4850
 4851                    let mut bracket_pair = None;
 4852                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 4853                    let prev_chars = snapshot
 4854                        .reversed_chars_at(selection_head)
 4855                        .collect::<String>();
 4856                    for (pair, enabled) in scope.brackets() {
 4857                        if enabled
 4858                            && pair.close
 4859                            && prev_chars.starts_with(pair.start.as_str())
 4860                            && next_chars.starts_with(pair.end.as_str())
 4861                        {
 4862                            bracket_pair = Some(pair.clone());
 4863                            break;
 4864                        }
 4865                    }
 4866                    if let Some(pair) = bracket_pair {
 4867                        let start = snapshot.anchor_after(selection_head);
 4868                        let end = snapshot.anchor_after(selection_head);
 4869                        self.autoclose_regions.push(AutocloseRegion {
 4870                            selection_id: selection.id,
 4871                            range: start..end,
 4872                            pair,
 4873                        });
 4874                    }
 4875                }
 4876            }
 4877        }
 4878        Ok(())
 4879    }
 4880
 4881    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 4882        self.move_to_snippet_tabstop(Bias::Right, cx)
 4883    }
 4884
 4885    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 4886        self.move_to_snippet_tabstop(Bias::Left, cx)
 4887    }
 4888
 4889    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 4890        if let Some(mut snippet) = self.snippet_stack.pop() {
 4891            match bias {
 4892                Bias::Left => {
 4893                    if snippet.active_index > 0 {
 4894                        snippet.active_index -= 1;
 4895                    } else {
 4896                        self.snippet_stack.push(snippet);
 4897                        return false;
 4898                    }
 4899                }
 4900                Bias::Right => {
 4901                    if snippet.active_index + 1 < snippet.ranges.len() {
 4902                        snippet.active_index += 1;
 4903                    } else {
 4904                        self.snippet_stack.push(snippet);
 4905                        return false;
 4906                    }
 4907                }
 4908            }
 4909            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 4910                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4911                    s.select_anchor_ranges(current_ranges.iter().cloned())
 4912                });
 4913                // If snippet state is not at the last tabstop, push it back on the stack
 4914                if snippet.active_index + 1 < snippet.ranges.len() {
 4915                    self.snippet_stack.push(snippet);
 4916                }
 4917                return true;
 4918            }
 4919        }
 4920
 4921        false
 4922    }
 4923
 4924    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 4925        self.transact(cx, |this, cx| {
 4926            this.select_all(&SelectAll, cx);
 4927            this.insert("", cx);
 4928        });
 4929    }
 4930
 4931    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 4932        self.transact(cx, |this, cx| {
 4933            this.select_autoclose_pair(cx);
 4934            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 4935            if !this.selections.line_mode {
 4936                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 4937                for selection in &mut selections {
 4938                    if selection.is_empty() {
 4939                        let old_head = selection.head();
 4940                        let mut new_head =
 4941                            movement::left(&display_map, old_head.to_display_point(&display_map))
 4942                                .to_point(&display_map);
 4943                        if let Some((buffer, line_buffer_range)) = display_map
 4944                            .buffer_snapshot
 4945                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 4946                        {
 4947                            let indent_size =
 4948                                buffer.indent_size_for_line(line_buffer_range.start.row);
 4949                            let indent_len = match indent_size.kind {
 4950                                IndentKind::Space => {
 4951                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 4952                                }
 4953                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 4954                            };
 4955                            if old_head.column <= indent_size.len && old_head.column > 0 {
 4956                                let indent_len = indent_len.get();
 4957                                new_head = cmp::min(
 4958                                    new_head,
 4959                                    MultiBufferPoint::new(
 4960                                        old_head.row,
 4961                                        ((old_head.column - 1) / indent_len) * indent_len,
 4962                                    ),
 4963                                );
 4964                            }
 4965                        }
 4966
 4967                        selection.set_head(new_head, SelectionGoal::None);
 4968                    }
 4969                }
 4970            }
 4971
 4972            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 4973            this.insert("", cx);
 4974            this.refresh_inline_completion(true, cx);
 4975        });
 4976    }
 4977
 4978    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 4979        self.transact(cx, |this, cx| {
 4980            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4981                let line_mode = s.line_mode;
 4982                s.move_with(|map, selection| {
 4983                    if selection.is_empty() && !line_mode {
 4984                        let cursor = movement::right(map, selection.head());
 4985                        selection.end = cursor;
 4986                        selection.reversed = true;
 4987                        selection.goal = SelectionGoal::None;
 4988                    }
 4989                })
 4990            });
 4991            this.insert("", cx);
 4992            this.refresh_inline_completion(true, cx);
 4993        });
 4994    }
 4995
 4996    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 4997        if self.move_to_prev_snippet_tabstop(cx) {
 4998            return;
 4999        }
 5000
 5001        self.outdent(&Outdent, cx);
 5002    }
 5003
 5004    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5005        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5006            return;
 5007        }
 5008
 5009        let mut selections = self.selections.all_adjusted(cx);
 5010        let buffer = self.buffer.read(cx);
 5011        let snapshot = buffer.snapshot(cx);
 5012        let rows_iter = selections.iter().map(|s| s.head().row);
 5013        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5014
 5015        let mut edits = Vec::new();
 5016        let mut prev_edited_row = 0;
 5017        let mut row_delta = 0;
 5018        for selection in &mut selections {
 5019            if selection.start.row != prev_edited_row {
 5020                row_delta = 0;
 5021            }
 5022            prev_edited_row = selection.end.row;
 5023
 5024            // If the selection is non-empty, then increase the indentation of the selected lines.
 5025            if !selection.is_empty() {
 5026                row_delta =
 5027                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5028                continue;
 5029            }
 5030
 5031            // If the selection is empty and the cursor is in the leading whitespace before the
 5032            // suggested indentation, then auto-indent the line.
 5033            let cursor = selection.head();
 5034            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5035            if let Some(suggested_indent) =
 5036                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5037            {
 5038                if cursor.column < suggested_indent.len
 5039                    && cursor.column <= current_indent.len
 5040                    && current_indent.len <= suggested_indent.len
 5041                {
 5042                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5043                    selection.end = selection.start;
 5044                    if row_delta == 0 {
 5045                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5046                            cursor.row,
 5047                            current_indent,
 5048                            suggested_indent,
 5049                        ));
 5050                        row_delta = suggested_indent.len - current_indent.len;
 5051                    }
 5052                    continue;
 5053                }
 5054            }
 5055
 5056            // Otherwise, insert a hard or soft tab.
 5057            let settings = buffer.settings_at(cursor, cx);
 5058            let tab_size = if settings.hard_tabs {
 5059                IndentSize::tab()
 5060            } else {
 5061                let tab_size = settings.tab_size.get();
 5062                let char_column = snapshot
 5063                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5064                    .flat_map(str::chars)
 5065                    .count()
 5066                    + row_delta as usize;
 5067                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5068                IndentSize::spaces(chars_to_next_tab_stop)
 5069            };
 5070            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5071            selection.end = selection.start;
 5072            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5073            row_delta += tab_size.len;
 5074        }
 5075
 5076        self.transact(cx, |this, cx| {
 5077            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5078            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5079            this.refresh_inline_completion(true, cx);
 5080        });
 5081    }
 5082
 5083    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5084        if self.read_only(cx) {
 5085            return;
 5086        }
 5087        let mut selections = self.selections.all::<Point>(cx);
 5088        let mut prev_edited_row = 0;
 5089        let mut row_delta = 0;
 5090        let mut edits = Vec::new();
 5091        let buffer = self.buffer.read(cx);
 5092        let snapshot = buffer.snapshot(cx);
 5093        for selection in &mut selections {
 5094            if selection.start.row != prev_edited_row {
 5095                row_delta = 0;
 5096            }
 5097            prev_edited_row = selection.end.row;
 5098
 5099            row_delta =
 5100                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5101        }
 5102
 5103        self.transact(cx, |this, cx| {
 5104            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5105            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5106        });
 5107    }
 5108
 5109    fn indent_selection(
 5110        buffer: &MultiBuffer,
 5111        snapshot: &MultiBufferSnapshot,
 5112        selection: &mut Selection<Point>,
 5113        edits: &mut Vec<(Range<Point>, String)>,
 5114        delta_for_start_row: u32,
 5115        cx: &AppContext,
 5116    ) -> u32 {
 5117        let settings = buffer.settings_at(selection.start, cx);
 5118        let tab_size = settings.tab_size.get();
 5119        let indent_kind = if settings.hard_tabs {
 5120            IndentKind::Tab
 5121        } else {
 5122            IndentKind::Space
 5123        };
 5124        let mut start_row = selection.start.row;
 5125        let mut end_row = selection.end.row + 1;
 5126
 5127        // If a selection ends at the beginning of a line, don't indent
 5128        // that last line.
 5129        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5130            end_row -= 1;
 5131        }
 5132
 5133        // Avoid re-indenting a row that has already been indented by a
 5134        // previous selection, but still update this selection's column
 5135        // to reflect that indentation.
 5136        if delta_for_start_row > 0 {
 5137            start_row += 1;
 5138            selection.start.column += delta_for_start_row;
 5139            if selection.end.row == selection.start.row {
 5140                selection.end.column += delta_for_start_row;
 5141            }
 5142        }
 5143
 5144        let mut delta_for_end_row = 0;
 5145        let has_multiple_rows = start_row + 1 != end_row;
 5146        for row in start_row..end_row {
 5147            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5148            let indent_delta = match (current_indent.kind, indent_kind) {
 5149                (IndentKind::Space, IndentKind::Space) => {
 5150                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5151                    IndentSize::spaces(columns_to_next_tab_stop)
 5152                }
 5153                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5154                (_, IndentKind::Tab) => IndentSize::tab(),
 5155            };
 5156
 5157            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5158                0
 5159            } else {
 5160                selection.start.column
 5161            };
 5162            let row_start = Point::new(row, start);
 5163            edits.push((
 5164                row_start..row_start,
 5165                indent_delta.chars().collect::<String>(),
 5166            ));
 5167
 5168            // Update this selection's endpoints to reflect the indentation.
 5169            if row == selection.start.row {
 5170                selection.start.column += indent_delta.len;
 5171            }
 5172            if row == selection.end.row {
 5173                selection.end.column += indent_delta.len;
 5174                delta_for_end_row = indent_delta.len;
 5175            }
 5176        }
 5177
 5178        if selection.start.row == selection.end.row {
 5179            delta_for_start_row + delta_for_end_row
 5180        } else {
 5181            delta_for_end_row
 5182        }
 5183    }
 5184
 5185    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5186        if self.read_only(cx) {
 5187            return;
 5188        }
 5189        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5190        let selections = self.selections.all::<Point>(cx);
 5191        let mut deletion_ranges = Vec::new();
 5192        let mut last_outdent = None;
 5193        {
 5194            let buffer = self.buffer.read(cx);
 5195            let snapshot = buffer.snapshot(cx);
 5196            for selection in &selections {
 5197                let settings = buffer.settings_at(selection.start, cx);
 5198                let tab_size = settings.tab_size.get();
 5199                let mut rows = selection.spanned_rows(false, &display_map);
 5200
 5201                // Avoid re-outdenting a row that has already been outdented by a
 5202                // previous selection.
 5203                if let Some(last_row) = last_outdent {
 5204                    if last_row == rows.start {
 5205                        rows.start = rows.start.next_row();
 5206                    }
 5207                }
 5208                let has_multiple_rows = rows.len() > 1;
 5209                for row in rows.iter_rows() {
 5210                    let indent_size = snapshot.indent_size_for_line(row);
 5211                    if indent_size.len > 0 {
 5212                        let deletion_len = match indent_size.kind {
 5213                            IndentKind::Space => {
 5214                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5215                                if columns_to_prev_tab_stop == 0 {
 5216                                    tab_size
 5217                                } else {
 5218                                    columns_to_prev_tab_stop
 5219                                }
 5220                            }
 5221                            IndentKind::Tab => 1,
 5222                        };
 5223                        let start = if has_multiple_rows
 5224                            || deletion_len > selection.start.column
 5225                            || indent_size.len < selection.start.column
 5226                        {
 5227                            0
 5228                        } else {
 5229                            selection.start.column - deletion_len
 5230                        };
 5231                        deletion_ranges.push(
 5232                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5233                        );
 5234                        last_outdent = Some(row);
 5235                    }
 5236                }
 5237            }
 5238        }
 5239
 5240        self.transact(cx, |this, cx| {
 5241            this.buffer.update(cx, |buffer, cx| {
 5242                let empty_str: Arc<str> = "".into();
 5243                buffer.edit(
 5244                    deletion_ranges
 5245                        .into_iter()
 5246                        .map(|range| (range, empty_str.clone())),
 5247                    None,
 5248                    cx,
 5249                );
 5250            });
 5251            let selections = this.selections.all::<usize>(cx);
 5252            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5253        });
 5254    }
 5255
 5256    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5257        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5258        let selections = self.selections.all::<Point>(cx);
 5259
 5260        let mut new_cursors = Vec::new();
 5261        let mut edit_ranges = Vec::new();
 5262        let mut selections = selections.iter().peekable();
 5263        while let Some(selection) = selections.next() {
 5264            let mut rows = selection.spanned_rows(false, &display_map);
 5265            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5266
 5267            // Accumulate contiguous regions of rows that we want to delete.
 5268            while let Some(next_selection) = selections.peek() {
 5269                let next_rows = next_selection.spanned_rows(false, &display_map);
 5270                if next_rows.start <= rows.end {
 5271                    rows.end = next_rows.end;
 5272                    selections.next().unwrap();
 5273                } else {
 5274                    break;
 5275                }
 5276            }
 5277
 5278            let buffer = &display_map.buffer_snapshot;
 5279            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5280            let edit_end;
 5281            let cursor_buffer_row;
 5282            if buffer.max_point().row >= rows.end.0 {
 5283                // If there's a line after the range, delete the \n from the end of the row range
 5284                // and position the cursor on the next line.
 5285                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5286                cursor_buffer_row = rows.end;
 5287            } else {
 5288                // If there isn't a line after the range, delete the \n from the line before the
 5289                // start of the row range and position the cursor there.
 5290                edit_start = edit_start.saturating_sub(1);
 5291                edit_end = buffer.len();
 5292                cursor_buffer_row = rows.start.previous_row();
 5293            }
 5294
 5295            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5296            *cursor.column_mut() =
 5297                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5298
 5299            new_cursors.push((
 5300                selection.id,
 5301                buffer.anchor_after(cursor.to_point(&display_map)),
 5302            ));
 5303            edit_ranges.push(edit_start..edit_end);
 5304        }
 5305
 5306        self.transact(cx, |this, cx| {
 5307            let buffer = this.buffer.update(cx, |buffer, cx| {
 5308                let empty_str: Arc<str> = "".into();
 5309                buffer.edit(
 5310                    edit_ranges
 5311                        .into_iter()
 5312                        .map(|range| (range, empty_str.clone())),
 5313                    None,
 5314                    cx,
 5315                );
 5316                buffer.snapshot(cx)
 5317            });
 5318            let new_selections = new_cursors
 5319                .into_iter()
 5320                .map(|(id, cursor)| {
 5321                    let cursor = cursor.to_point(&buffer);
 5322                    Selection {
 5323                        id,
 5324                        start: cursor,
 5325                        end: cursor,
 5326                        reversed: false,
 5327                        goal: SelectionGoal::None,
 5328                    }
 5329                })
 5330                .collect();
 5331
 5332            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5333                s.select(new_selections);
 5334            });
 5335        });
 5336    }
 5337
 5338    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5339        if self.read_only(cx) {
 5340            return;
 5341        }
 5342        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5343        for selection in self.selections.all::<Point>(cx) {
 5344            let start = MultiBufferRow(selection.start.row);
 5345            let end = if selection.start.row == selection.end.row {
 5346                MultiBufferRow(selection.start.row + 1)
 5347            } else {
 5348                MultiBufferRow(selection.end.row)
 5349            };
 5350
 5351            if let Some(last_row_range) = row_ranges.last_mut() {
 5352                if start <= last_row_range.end {
 5353                    last_row_range.end = end;
 5354                    continue;
 5355                }
 5356            }
 5357            row_ranges.push(start..end);
 5358        }
 5359
 5360        let snapshot = self.buffer.read(cx).snapshot(cx);
 5361        let mut cursor_positions = Vec::new();
 5362        for row_range in &row_ranges {
 5363            let anchor = snapshot.anchor_before(Point::new(
 5364                row_range.end.previous_row().0,
 5365                snapshot.line_len(row_range.end.previous_row()),
 5366            ));
 5367            cursor_positions.push(anchor..anchor);
 5368        }
 5369
 5370        self.transact(cx, |this, cx| {
 5371            for row_range in row_ranges.into_iter().rev() {
 5372                for row in row_range.iter_rows().rev() {
 5373                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5374                    let next_line_row = row.next_row();
 5375                    let indent = snapshot.indent_size_for_line(next_line_row);
 5376                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5377
 5378                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5379                        " "
 5380                    } else {
 5381                        ""
 5382                    };
 5383
 5384                    this.buffer.update(cx, |buffer, cx| {
 5385                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5386                    });
 5387                }
 5388            }
 5389
 5390            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5391                s.select_anchor_ranges(cursor_positions)
 5392            });
 5393        });
 5394    }
 5395
 5396    pub fn sort_lines_case_sensitive(
 5397        &mut self,
 5398        _: &SortLinesCaseSensitive,
 5399        cx: &mut ViewContext<Self>,
 5400    ) {
 5401        self.manipulate_lines(cx, |lines| lines.sort())
 5402    }
 5403
 5404    pub fn sort_lines_case_insensitive(
 5405        &mut self,
 5406        _: &SortLinesCaseInsensitive,
 5407        cx: &mut ViewContext<Self>,
 5408    ) {
 5409        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5410    }
 5411
 5412    pub fn unique_lines_case_insensitive(
 5413        &mut self,
 5414        _: &UniqueLinesCaseInsensitive,
 5415        cx: &mut ViewContext<Self>,
 5416    ) {
 5417        self.manipulate_lines(cx, |lines| {
 5418            let mut seen = HashSet::default();
 5419            lines.retain(|line| seen.insert(line.to_lowercase()));
 5420        })
 5421    }
 5422
 5423    pub fn unique_lines_case_sensitive(
 5424        &mut self,
 5425        _: &UniqueLinesCaseSensitive,
 5426        cx: &mut ViewContext<Self>,
 5427    ) {
 5428        self.manipulate_lines(cx, |lines| {
 5429            let mut seen = HashSet::default();
 5430            lines.retain(|line| seen.insert(*line));
 5431        })
 5432    }
 5433
 5434    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5435        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 5436        if !revert_changes.is_empty() {
 5437            self.transact(cx, |editor, cx| {
 5438                editor.buffer().update(cx, |multi_buffer, cx| {
 5439                    for (buffer_id, changes) in revert_changes {
 5440                        if let Some(buffer) = multi_buffer.buffer(buffer_id) {
 5441                            buffer.update(cx, |buffer, cx| {
 5442                                buffer.edit(
 5443                                    changes.into_iter().map(|(range, text)| {
 5444                                        (range, text.to_string().map(Arc::<str>::from))
 5445                                    }),
 5446                                    None,
 5447                                    cx,
 5448                                );
 5449                            });
 5450                        }
 5451                    }
 5452                });
 5453                editor.change_selections(None, cx, |selections| selections.refresh());
 5454            });
 5455        }
 5456    }
 5457
 5458    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5459        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5460            let project_path = buffer.read(cx).project_path(cx)?;
 5461            let project = self.project.as_ref()?.read(cx);
 5462            let entry = project.entry_for_path(&project_path, cx)?;
 5463            let abs_path = project.absolute_path(&project_path, cx)?;
 5464            let parent = if entry.is_symlink {
 5465                abs_path.canonicalize().ok()?
 5466            } else {
 5467                abs_path
 5468            }
 5469            .parent()?
 5470            .to_path_buf();
 5471            Some(parent)
 5472        }) {
 5473            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 5474        }
 5475    }
 5476
 5477    fn gather_revert_changes(
 5478        &mut self,
 5479        selections: &[Selection<Anchor>],
 5480        cx: &mut ViewContext<'_, Editor>,
 5481    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 5482        let mut revert_changes = HashMap::default();
 5483        self.buffer.update(cx, |multi_buffer, cx| {
 5484            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 5485            for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 5486                Self::prepare_revert_change(&mut revert_changes, &multi_buffer, &hunk, cx);
 5487            }
 5488        });
 5489        revert_changes
 5490    }
 5491
 5492    fn prepare_revert_change(
 5493        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 5494        multi_buffer: &MultiBuffer,
 5495        hunk: &DiffHunk<MultiBufferRow>,
 5496        cx: &mut AppContext,
 5497    ) -> Option<()> {
 5498        let buffer = multi_buffer.buffer(hunk.buffer_id)?;
 5499        let buffer = buffer.read(cx);
 5500        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 5501        let buffer_snapshot = buffer.snapshot();
 5502        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 5503        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 5504            probe
 5505                .0
 5506                .start
 5507                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 5508                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 5509        }) {
 5510            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 5511            Some(())
 5512        } else {
 5513            None
 5514        }
 5515    }
 5516
 5517    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 5518        self.manipulate_lines(cx, |lines| lines.reverse())
 5519    }
 5520
 5521    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 5522        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 5523    }
 5524
 5525    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5526    where
 5527        Fn: FnMut(&mut Vec<&str>),
 5528    {
 5529        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5530        let buffer = self.buffer.read(cx).snapshot(cx);
 5531
 5532        let mut edits = Vec::new();
 5533
 5534        let selections = self.selections.all::<Point>(cx);
 5535        let mut selections = selections.iter().peekable();
 5536        let mut contiguous_row_selections = Vec::new();
 5537        let mut new_selections = Vec::new();
 5538        let mut added_lines = 0;
 5539        let mut removed_lines = 0;
 5540
 5541        while let Some(selection) = selections.next() {
 5542            let (start_row, end_row) = consume_contiguous_rows(
 5543                &mut contiguous_row_selections,
 5544                selection,
 5545                &display_map,
 5546                &mut selections,
 5547            );
 5548
 5549            let start_point = Point::new(start_row.0, 0);
 5550            let end_point = Point::new(
 5551                end_row.previous_row().0,
 5552                buffer.line_len(end_row.previous_row()),
 5553            );
 5554            let text = buffer
 5555                .text_for_range(start_point..end_point)
 5556                .collect::<String>();
 5557
 5558            let mut lines = text.split('\n').collect_vec();
 5559
 5560            let lines_before = lines.len();
 5561            callback(&mut lines);
 5562            let lines_after = lines.len();
 5563
 5564            edits.push((start_point..end_point, lines.join("\n")));
 5565
 5566            // Selections must change based on added and removed line count
 5567            let start_row =
 5568                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 5569            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 5570            new_selections.push(Selection {
 5571                id: selection.id,
 5572                start: start_row,
 5573                end: end_row,
 5574                goal: SelectionGoal::None,
 5575                reversed: selection.reversed,
 5576            });
 5577
 5578            if lines_after > lines_before {
 5579                added_lines += lines_after - lines_before;
 5580            } else if lines_before > lines_after {
 5581                removed_lines += lines_before - lines_after;
 5582            }
 5583        }
 5584
 5585        self.transact(cx, |this, cx| {
 5586            let buffer = this.buffer.update(cx, |buffer, cx| {
 5587                buffer.edit(edits, None, cx);
 5588                buffer.snapshot(cx)
 5589            });
 5590
 5591            // Recalculate offsets on newly edited buffer
 5592            let new_selections = new_selections
 5593                .iter()
 5594                .map(|s| {
 5595                    let start_point = Point::new(s.start.0, 0);
 5596                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 5597                    Selection {
 5598                        id: s.id,
 5599                        start: buffer.point_to_offset(start_point),
 5600                        end: buffer.point_to_offset(end_point),
 5601                        goal: s.goal,
 5602                        reversed: s.reversed,
 5603                    }
 5604                })
 5605                .collect();
 5606
 5607            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5608                s.select(new_selections);
 5609            });
 5610
 5611            this.request_autoscroll(Autoscroll::fit(), cx);
 5612        });
 5613    }
 5614
 5615    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 5616        self.manipulate_text(cx, |text| text.to_uppercase())
 5617    }
 5618
 5619    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 5620        self.manipulate_text(cx, |text| text.to_lowercase())
 5621    }
 5622
 5623    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 5624        self.manipulate_text(cx, |text| {
 5625            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 5626            // https://github.com/rutrum/convert-case/issues/16
 5627            text.split('\n')
 5628                .map(|line| line.to_case(Case::Title))
 5629                .join("\n")
 5630        })
 5631    }
 5632
 5633    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 5634        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 5635    }
 5636
 5637    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 5638        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 5639    }
 5640
 5641    pub fn convert_to_upper_camel_case(
 5642        &mut self,
 5643        _: &ConvertToUpperCamelCase,
 5644        cx: &mut ViewContext<Self>,
 5645    ) {
 5646        self.manipulate_text(cx, |text| {
 5647            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 5648            // https://github.com/rutrum/convert-case/issues/16
 5649            text.split('\n')
 5650                .map(|line| line.to_case(Case::UpperCamel))
 5651                .join("\n")
 5652        })
 5653    }
 5654
 5655    pub fn convert_to_lower_camel_case(
 5656        &mut self,
 5657        _: &ConvertToLowerCamelCase,
 5658        cx: &mut ViewContext<Self>,
 5659    ) {
 5660        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 5661    }
 5662
 5663    pub fn convert_to_opposite_case(
 5664        &mut self,
 5665        _: &ConvertToOppositeCase,
 5666        cx: &mut ViewContext<Self>,
 5667    ) {
 5668        self.manipulate_text(cx, |text| {
 5669            text.chars()
 5670                .fold(String::with_capacity(text.len()), |mut t, c| {
 5671                    if c.is_uppercase() {
 5672                        t.extend(c.to_lowercase());
 5673                    } else {
 5674                        t.extend(c.to_uppercase());
 5675                    }
 5676                    t
 5677                })
 5678        })
 5679    }
 5680
 5681    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5682    where
 5683        Fn: FnMut(&str) -> String,
 5684    {
 5685        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5686        let buffer = self.buffer.read(cx).snapshot(cx);
 5687
 5688        let mut new_selections = Vec::new();
 5689        let mut edits = Vec::new();
 5690        let mut selection_adjustment = 0i32;
 5691
 5692        for selection in self.selections.all::<usize>(cx) {
 5693            let selection_is_empty = selection.is_empty();
 5694
 5695            let (start, end) = if selection_is_empty {
 5696                let word_range = movement::surrounding_word(
 5697                    &display_map,
 5698                    selection.start.to_display_point(&display_map),
 5699                );
 5700                let start = word_range.start.to_offset(&display_map, Bias::Left);
 5701                let end = word_range.end.to_offset(&display_map, Bias::Left);
 5702                (start, end)
 5703            } else {
 5704                (selection.start, selection.end)
 5705            };
 5706
 5707            let text = buffer.text_for_range(start..end).collect::<String>();
 5708            let old_length = text.len() as i32;
 5709            let text = callback(&text);
 5710
 5711            new_selections.push(Selection {
 5712                start: (start as i32 - selection_adjustment) as usize,
 5713                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 5714                goal: SelectionGoal::None,
 5715                ..selection
 5716            });
 5717
 5718            selection_adjustment += old_length - text.len() as i32;
 5719
 5720            edits.push((start..end, text));
 5721        }
 5722
 5723        self.transact(cx, |this, cx| {
 5724            this.buffer.update(cx, |buffer, cx| {
 5725                buffer.edit(edits, None, cx);
 5726            });
 5727
 5728            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5729                s.select(new_selections);
 5730            });
 5731
 5732            this.request_autoscroll(Autoscroll::fit(), cx);
 5733        });
 5734    }
 5735
 5736    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 5737        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5738        let buffer = &display_map.buffer_snapshot;
 5739        let selections = self.selections.all::<Point>(cx);
 5740
 5741        let mut edits = Vec::new();
 5742        let mut selections_iter = selections.iter().peekable();
 5743        while let Some(selection) = selections_iter.next() {
 5744            // Avoid duplicating the same lines twice.
 5745            let mut rows = selection.spanned_rows(false, &display_map);
 5746
 5747            while let Some(next_selection) = selections_iter.peek() {
 5748                let next_rows = next_selection.spanned_rows(false, &display_map);
 5749                if next_rows.start < rows.end {
 5750                    rows.end = next_rows.end;
 5751                    selections_iter.next().unwrap();
 5752                } else {
 5753                    break;
 5754                }
 5755            }
 5756
 5757            // Copy the text from the selected row region and splice it either at the start
 5758            // or end of the region.
 5759            let start = Point::new(rows.start.0, 0);
 5760            let end = Point::new(
 5761                rows.end.previous_row().0,
 5762                buffer.line_len(rows.end.previous_row()),
 5763            );
 5764            let text = buffer
 5765                .text_for_range(start..end)
 5766                .chain(Some("\n"))
 5767                .collect::<String>();
 5768            let insert_location = if upwards {
 5769                Point::new(rows.end.0, 0)
 5770            } else {
 5771                start
 5772            };
 5773            edits.push((insert_location..insert_location, text));
 5774        }
 5775
 5776        self.transact(cx, |this, cx| {
 5777            this.buffer.update(cx, |buffer, cx| {
 5778                buffer.edit(edits, None, cx);
 5779            });
 5780
 5781            this.request_autoscroll(Autoscroll::fit(), cx);
 5782        });
 5783    }
 5784
 5785    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 5786        self.duplicate_line(true, cx);
 5787    }
 5788
 5789    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 5790        self.duplicate_line(false, cx);
 5791    }
 5792
 5793    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 5794        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5795        let buffer = self.buffer.read(cx).snapshot(cx);
 5796
 5797        let mut edits = Vec::new();
 5798        let mut unfold_ranges = Vec::new();
 5799        let mut refold_ranges = Vec::new();
 5800
 5801        let selections = self.selections.all::<Point>(cx);
 5802        let mut selections = selections.iter().peekable();
 5803        let mut contiguous_row_selections = Vec::new();
 5804        let mut new_selections = Vec::new();
 5805
 5806        while let Some(selection) = selections.next() {
 5807            // Find all the selections that span a contiguous row range
 5808            let (start_row, end_row) = consume_contiguous_rows(
 5809                &mut contiguous_row_selections,
 5810                selection,
 5811                &display_map,
 5812                &mut selections,
 5813            );
 5814
 5815            // Move the text spanned by the row range to be before the line preceding the row range
 5816            if start_row.0 > 0 {
 5817                let range_to_move = Point::new(
 5818                    start_row.previous_row().0,
 5819                    buffer.line_len(start_row.previous_row()),
 5820                )
 5821                    ..Point::new(
 5822                        end_row.previous_row().0,
 5823                        buffer.line_len(end_row.previous_row()),
 5824                    );
 5825                let insertion_point = display_map
 5826                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 5827                    .0;
 5828
 5829                // Don't move lines across excerpts
 5830                if buffer
 5831                    .excerpt_boundaries_in_range((
 5832                        Bound::Excluded(insertion_point),
 5833                        Bound::Included(range_to_move.end),
 5834                    ))
 5835                    .next()
 5836                    .is_none()
 5837                {
 5838                    let text = buffer
 5839                        .text_for_range(range_to_move.clone())
 5840                        .flat_map(|s| s.chars())
 5841                        .skip(1)
 5842                        .chain(['\n'])
 5843                        .collect::<String>();
 5844
 5845                    edits.push((
 5846                        buffer.anchor_after(range_to_move.start)
 5847                            ..buffer.anchor_before(range_to_move.end),
 5848                        String::new(),
 5849                    ));
 5850                    let insertion_anchor = buffer.anchor_after(insertion_point);
 5851                    edits.push((insertion_anchor..insertion_anchor, text));
 5852
 5853                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 5854
 5855                    // Move selections up
 5856                    new_selections.extend(contiguous_row_selections.drain(..).map(
 5857                        |mut selection| {
 5858                            selection.start.row -= row_delta;
 5859                            selection.end.row -= row_delta;
 5860                            selection
 5861                        },
 5862                    ));
 5863
 5864                    // Move folds up
 5865                    unfold_ranges.push(range_to_move.clone());
 5866                    for fold in display_map.folds_in_range(
 5867                        buffer.anchor_before(range_to_move.start)
 5868                            ..buffer.anchor_after(range_to_move.end),
 5869                    ) {
 5870                        let mut start = fold.range.start.to_point(&buffer);
 5871                        let mut end = fold.range.end.to_point(&buffer);
 5872                        start.row -= row_delta;
 5873                        end.row -= row_delta;
 5874                        refold_ranges.push((start..end, fold.placeholder.clone()));
 5875                    }
 5876                }
 5877            }
 5878
 5879            // If we didn't move line(s), preserve the existing selections
 5880            new_selections.append(&mut contiguous_row_selections);
 5881        }
 5882
 5883        self.transact(cx, |this, cx| {
 5884            this.unfold_ranges(unfold_ranges, true, true, cx);
 5885            this.buffer.update(cx, |buffer, cx| {
 5886                for (range, text) in edits {
 5887                    buffer.edit([(range, text)], None, cx);
 5888                }
 5889            });
 5890            this.fold_ranges(refold_ranges, true, cx);
 5891            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5892                s.select(new_selections);
 5893            })
 5894        });
 5895    }
 5896
 5897    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 5898        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5899        let buffer = self.buffer.read(cx).snapshot(cx);
 5900
 5901        let mut edits = Vec::new();
 5902        let mut unfold_ranges = Vec::new();
 5903        let mut refold_ranges = Vec::new();
 5904
 5905        let selections = self.selections.all::<Point>(cx);
 5906        let mut selections = selections.iter().peekable();
 5907        let mut contiguous_row_selections = Vec::new();
 5908        let mut new_selections = Vec::new();
 5909
 5910        while let Some(selection) = selections.next() {
 5911            // Find all the selections that span a contiguous row range
 5912            let (start_row, end_row) = consume_contiguous_rows(
 5913                &mut contiguous_row_selections,
 5914                selection,
 5915                &display_map,
 5916                &mut selections,
 5917            );
 5918
 5919            // Move the text spanned by the row range to be after the last line of the row range
 5920            if end_row.0 <= buffer.max_point().row {
 5921                let range_to_move =
 5922                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 5923                let insertion_point = display_map
 5924                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 5925                    .0;
 5926
 5927                // Don't move lines across excerpt boundaries
 5928                if buffer
 5929                    .excerpt_boundaries_in_range((
 5930                        Bound::Excluded(range_to_move.start),
 5931                        Bound::Included(insertion_point),
 5932                    ))
 5933                    .next()
 5934                    .is_none()
 5935                {
 5936                    let mut text = String::from("\n");
 5937                    text.extend(buffer.text_for_range(range_to_move.clone()));
 5938                    text.pop(); // Drop trailing newline
 5939                    edits.push((
 5940                        buffer.anchor_after(range_to_move.start)
 5941                            ..buffer.anchor_before(range_to_move.end),
 5942                        String::new(),
 5943                    ));
 5944                    let insertion_anchor = buffer.anchor_after(insertion_point);
 5945                    edits.push((insertion_anchor..insertion_anchor, text));
 5946
 5947                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 5948
 5949                    // Move selections down
 5950                    new_selections.extend(contiguous_row_selections.drain(..).map(
 5951                        |mut selection| {
 5952                            selection.start.row += row_delta;
 5953                            selection.end.row += row_delta;
 5954                            selection
 5955                        },
 5956                    ));
 5957
 5958                    // Move folds down
 5959                    unfold_ranges.push(range_to_move.clone());
 5960                    for fold in display_map.folds_in_range(
 5961                        buffer.anchor_before(range_to_move.start)
 5962                            ..buffer.anchor_after(range_to_move.end),
 5963                    ) {
 5964                        let mut start = fold.range.start.to_point(&buffer);
 5965                        let mut end = fold.range.end.to_point(&buffer);
 5966                        start.row += row_delta;
 5967                        end.row += row_delta;
 5968                        refold_ranges.push((start..end, fold.placeholder.clone()));
 5969                    }
 5970                }
 5971            }
 5972
 5973            // If we didn't move line(s), preserve the existing selections
 5974            new_selections.append(&mut contiguous_row_selections);
 5975        }
 5976
 5977        self.transact(cx, |this, cx| {
 5978            this.unfold_ranges(unfold_ranges, true, true, cx);
 5979            this.buffer.update(cx, |buffer, cx| {
 5980                for (range, text) in edits {
 5981                    buffer.edit([(range, text)], None, cx);
 5982                }
 5983            });
 5984            this.fold_ranges(refold_ranges, true, cx);
 5985            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 5986        });
 5987    }
 5988
 5989    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 5990        let text_layout_details = &self.text_layout_details(cx);
 5991        self.transact(cx, |this, cx| {
 5992            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5993                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 5994                let line_mode = s.line_mode;
 5995                s.move_with(|display_map, selection| {
 5996                    if !selection.is_empty() || line_mode {
 5997                        return;
 5998                    }
 5999
 6000                    let mut head = selection.head();
 6001                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6002                    if head.column() == display_map.line_len(head.row()) {
 6003                        transpose_offset = display_map
 6004                            .buffer_snapshot
 6005                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6006                    }
 6007
 6008                    if transpose_offset == 0 {
 6009                        return;
 6010                    }
 6011
 6012                    *head.column_mut() += 1;
 6013                    head = display_map.clip_point(head, Bias::Right);
 6014                    let goal = SelectionGoal::HorizontalPosition(
 6015                        display_map
 6016                            .x_for_display_point(head, &text_layout_details)
 6017                            .into(),
 6018                    );
 6019                    selection.collapse_to(head, goal);
 6020
 6021                    let transpose_start = display_map
 6022                        .buffer_snapshot
 6023                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6024                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6025                        let transpose_end = display_map
 6026                            .buffer_snapshot
 6027                            .clip_offset(transpose_offset + 1, Bias::Right);
 6028                        if let Some(ch) =
 6029                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6030                        {
 6031                            edits.push((transpose_start..transpose_offset, String::new()));
 6032                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6033                        }
 6034                    }
 6035                });
 6036                edits
 6037            });
 6038            this.buffer
 6039                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6040            let selections = this.selections.all::<usize>(cx);
 6041            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6042                s.select(selections);
 6043            });
 6044        });
 6045    }
 6046
 6047    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6048        let mut text = String::new();
 6049        let buffer = self.buffer.read(cx).snapshot(cx);
 6050        let mut selections = self.selections.all::<Point>(cx);
 6051        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6052        {
 6053            let max_point = buffer.max_point();
 6054            let mut is_first = true;
 6055            for selection in &mut selections {
 6056                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6057                if is_entire_line {
 6058                    selection.start = Point::new(selection.start.row, 0);
 6059                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6060                    selection.goal = SelectionGoal::None;
 6061                }
 6062                if is_first {
 6063                    is_first = false;
 6064                } else {
 6065                    text += "\n";
 6066                }
 6067                let mut len = 0;
 6068                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6069                    text.push_str(chunk);
 6070                    len += chunk.len();
 6071                }
 6072                clipboard_selections.push(ClipboardSelection {
 6073                    len,
 6074                    is_entire_line,
 6075                    first_line_indent: buffer
 6076                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6077                        .len,
 6078                });
 6079            }
 6080        }
 6081
 6082        self.transact(cx, |this, cx| {
 6083            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6084                s.select(selections);
 6085            });
 6086            this.insert("", cx);
 6087            cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 6088        });
 6089    }
 6090
 6091    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6092        let selections = self.selections.all::<Point>(cx);
 6093        let buffer = self.buffer.read(cx).read(cx);
 6094        let mut text = String::new();
 6095
 6096        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6097        {
 6098            let max_point = buffer.max_point();
 6099            let mut is_first = true;
 6100            for selection in selections.iter() {
 6101                let mut start = selection.start;
 6102                let mut end = selection.end;
 6103                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6104                if is_entire_line {
 6105                    start = Point::new(start.row, 0);
 6106                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6107                }
 6108                if is_first {
 6109                    is_first = false;
 6110                } else {
 6111                    text += "\n";
 6112                }
 6113                let mut len = 0;
 6114                for chunk in buffer.text_for_range(start..end) {
 6115                    text.push_str(chunk);
 6116                    len += chunk.len();
 6117                }
 6118                clipboard_selections.push(ClipboardSelection {
 6119                    len,
 6120                    is_entire_line,
 6121                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6122                });
 6123            }
 6124        }
 6125
 6126        cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 6127    }
 6128
 6129    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6130        if self.read_only(cx) {
 6131            return;
 6132        }
 6133
 6134        self.transact(cx, |this, cx| {
 6135            if let Some(item) = cx.read_from_clipboard() {
 6136                let clipboard_text = Cow::Borrowed(item.text());
 6137                if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
 6138                    let old_selections = this.selections.all::<usize>(cx);
 6139                    let all_selections_were_entire_line =
 6140                        clipboard_selections.iter().all(|s| s.is_entire_line);
 6141                    let first_selection_indent_column =
 6142                        clipboard_selections.first().map(|s| s.first_line_indent);
 6143                    if clipboard_selections.len() != old_selections.len() {
 6144                        clipboard_selections.drain(..);
 6145                    }
 6146
 6147                    this.buffer.update(cx, |buffer, cx| {
 6148                        let snapshot = buffer.read(cx);
 6149                        let mut start_offset = 0;
 6150                        let mut edits = Vec::new();
 6151                        let mut original_indent_columns = Vec::new();
 6152                        let line_mode = this.selections.line_mode;
 6153                        for (ix, selection) in old_selections.iter().enumerate() {
 6154                            let to_insert;
 6155                            let entire_line;
 6156                            let original_indent_column;
 6157                            if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6158                                let end_offset = start_offset + clipboard_selection.len;
 6159                                to_insert = &clipboard_text[start_offset..end_offset];
 6160                                entire_line = clipboard_selection.is_entire_line;
 6161                                start_offset = end_offset + 1;
 6162                                original_indent_column =
 6163                                    Some(clipboard_selection.first_line_indent);
 6164                            } else {
 6165                                to_insert = clipboard_text.as_str();
 6166                                entire_line = all_selections_were_entire_line;
 6167                                original_indent_column = first_selection_indent_column
 6168                            }
 6169
 6170                            // If the corresponding selection was empty when this slice of the
 6171                            // clipboard text was written, then the entire line containing the
 6172                            // selection was copied. If this selection is also currently empty,
 6173                            // then paste the line before the current line of the buffer.
 6174                            let range = if selection.is_empty() && !line_mode && entire_line {
 6175                                let column = selection.start.to_point(&snapshot).column as usize;
 6176                                let line_start = selection.start - column;
 6177                                line_start..line_start
 6178                            } else {
 6179                                selection.range()
 6180                            };
 6181
 6182                            edits.push((range, to_insert));
 6183                            original_indent_columns.extend(original_indent_column);
 6184                        }
 6185                        drop(snapshot);
 6186
 6187                        buffer.edit(
 6188                            edits,
 6189                            Some(AutoindentMode::Block {
 6190                                original_indent_columns,
 6191                            }),
 6192                            cx,
 6193                        );
 6194                    });
 6195
 6196                    let selections = this.selections.all::<usize>(cx);
 6197                    this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6198                } else {
 6199                    this.insert(&clipboard_text, cx);
 6200                }
 6201            }
 6202        });
 6203    }
 6204
 6205    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 6206        if self.read_only(cx) {
 6207            return;
 6208        }
 6209
 6210        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 6211            if let Some((selections, _)) = self.selection_history.transaction(tx_id).cloned() {
 6212                self.change_selections(None, cx, |s| {
 6213                    s.select_anchors(selections.to_vec());
 6214                });
 6215            }
 6216            self.request_autoscroll(Autoscroll::fit(), cx);
 6217            self.unmark_text(cx);
 6218            self.refresh_inline_completion(true, cx);
 6219            cx.emit(EditorEvent::Edited);
 6220            cx.emit(EditorEvent::TransactionUndone {
 6221                transaction_id: tx_id,
 6222            });
 6223        }
 6224    }
 6225
 6226    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 6227        if self.read_only(cx) {
 6228            return;
 6229        }
 6230
 6231        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 6232            if let Some((_, Some(selections))) = self.selection_history.transaction(tx_id).cloned()
 6233            {
 6234                self.change_selections(None, cx, |s| {
 6235                    s.select_anchors(selections.to_vec());
 6236                });
 6237            }
 6238            self.request_autoscroll(Autoscroll::fit(), cx);
 6239            self.unmark_text(cx);
 6240            self.refresh_inline_completion(true, cx);
 6241            cx.emit(EditorEvent::Edited);
 6242        }
 6243    }
 6244
 6245    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 6246        self.buffer
 6247            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 6248    }
 6249
 6250    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 6251        self.buffer
 6252            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 6253    }
 6254
 6255    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 6256        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6257            let line_mode = s.line_mode;
 6258            s.move_with(|map, selection| {
 6259                let cursor = if selection.is_empty() && !line_mode {
 6260                    movement::left(map, selection.start)
 6261                } else {
 6262                    selection.start
 6263                };
 6264                selection.collapse_to(cursor, SelectionGoal::None);
 6265            });
 6266        })
 6267    }
 6268
 6269    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 6270        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6271            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 6272        })
 6273    }
 6274
 6275    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 6276        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6277            let line_mode = s.line_mode;
 6278            s.move_with(|map, selection| {
 6279                let cursor = if selection.is_empty() && !line_mode {
 6280                    movement::right(map, selection.end)
 6281                } else {
 6282                    selection.end
 6283                };
 6284                selection.collapse_to(cursor, SelectionGoal::None)
 6285            });
 6286        })
 6287    }
 6288
 6289    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 6290        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6291            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 6292        })
 6293    }
 6294
 6295    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 6296        if self.take_rename(true, cx).is_some() {
 6297            return;
 6298        }
 6299
 6300        if matches!(self.mode, EditorMode::SingleLine) {
 6301            cx.propagate();
 6302            return;
 6303        }
 6304
 6305        let text_layout_details = &self.text_layout_details(cx);
 6306
 6307        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6308            let line_mode = s.line_mode;
 6309            s.move_with(|map, selection| {
 6310                if !selection.is_empty() && !line_mode {
 6311                    selection.goal = SelectionGoal::None;
 6312                }
 6313                let (cursor, goal) = movement::up(
 6314                    map,
 6315                    selection.start,
 6316                    selection.goal,
 6317                    false,
 6318                    &text_layout_details,
 6319                );
 6320                selection.collapse_to(cursor, goal);
 6321            });
 6322        })
 6323    }
 6324
 6325    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 6326        if self.take_rename(true, cx).is_some() {
 6327            return;
 6328        }
 6329
 6330        if matches!(self.mode, EditorMode::SingleLine) {
 6331            cx.propagate();
 6332            return;
 6333        }
 6334
 6335        let text_layout_details = &self.text_layout_details(cx);
 6336
 6337        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6338            let line_mode = s.line_mode;
 6339            s.move_with(|map, selection| {
 6340                if !selection.is_empty() && !line_mode {
 6341                    selection.goal = SelectionGoal::None;
 6342                }
 6343                let (cursor, goal) = movement::up_by_rows(
 6344                    map,
 6345                    selection.start,
 6346                    action.lines,
 6347                    selection.goal,
 6348                    false,
 6349                    &text_layout_details,
 6350                );
 6351                selection.collapse_to(cursor, goal);
 6352            });
 6353        })
 6354    }
 6355
 6356    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 6357        if self.take_rename(true, cx).is_some() {
 6358            return;
 6359        }
 6360
 6361        if matches!(self.mode, EditorMode::SingleLine) {
 6362            cx.propagate();
 6363            return;
 6364        }
 6365
 6366        let text_layout_details = &self.text_layout_details(cx);
 6367
 6368        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6369            let line_mode = s.line_mode;
 6370            s.move_with(|map, selection| {
 6371                if !selection.is_empty() && !line_mode {
 6372                    selection.goal = SelectionGoal::None;
 6373                }
 6374                let (cursor, goal) = movement::down_by_rows(
 6375                    map,
 6376                    selection.start,
 6377                    action.lines,
 6378                    selection.goal,
 6379                    false,
 6380                    &text_layout_details,
 6381                );
 6382                selection.collapse_to(cursor, goal);
 6383            });
 6384        })
 6385    }
 6386
 6387    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 6388        let text_layout_details = &self.text_layout_details(cx);
 6389        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6390            s.move_heads_with(|map, head, goal| {
 6391                movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6392            })
 6393        })
 6394    }
 6395
 6396    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 6397        let text_layout_details = &self.text_layout_details(cx);
 6398        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6399            s.move_heads_with(|map, head, goal| {
 6400                movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6401            })
 6402        })
 6403    }
 6404
 6405    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 6406        if self.take_rename(true, cx).is_some() {
 6407            return;
 6408        }
 6409
 6410        if matches!(self.mode, EditorMode::SingleLine) {
 6411            cx.propagate();
 6412            return;
 6413        }
 6414
 6415        let row_count = if let Some(row_count) = self.visible_line_count() {
 6416            row_count as u32 - 1
 6417        } else {
 6418            return;
 6419        };
 6420
 6421        let autoscroll = if action.center_cursor {
 6422            Autoscroll::center()
 6423        } else {
 6424            Autoscroll::fit()
 6425        };
 6426
 6427        let text_layout_details = &self.text_layout_details(cx);
 6428
 6429        self.change_selections(Some(autoscroll), cx, |s| {
 6430            let line_mode = s.line_mode;
 6431            s.move_with(|map, selection| {
 6432                if !selection.is_empty() && !line_mode {
 6433                    selection.goal = SelectionGoal::None;
 6434                }
 6435                let (cursor, goal) = movement::up_by_rows(
 6436                    map,
 6437                    selection.end,
 6438                    row_count,
 6439                    selection.goal,
 6440                    false,
 6441                    &text_layout_details,
 6442                );
 6443                selection.collapse_to(cursor, goal);
 6444            });
 6445        });
 6446    }
 6447
 6448    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 6449        let text_layout_details = &self.text_layout_details(cx);
 6450        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6451            s.move_heads_with(|map, head, goal| {
 6452                movement::up(map, head, goal, false, &text_layout_details)
 6453            })
 6454        })
 6455    }
 6456
 6457    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 6458        self.take_rename(true, cx);
 6459
 6460        if self.mode == EditorMode::SingleLine {
 6461            cx.propagate();
 6462            return;
 6463        }
 6464
 6465        let text_layout_details = &self.text_layout_details(cx);
 6466        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6467            let line_mode = s.line_mode;
 6468            s.move_with(|map, selection| {
 6469                if !selection.is_empty() && !line_mode {
 6470                    selection.goal = SelectionGoal::None;
 6471                }
 6472                let (cursor, goal) = movement::down(
 6473                    map,
 6474                    selection.end,
 6475                    selection.goal,
 6476                    false,
 6477                    &text_layout_details,
 6478                );
 6479                selection.collapse_to(cursor, goal);
 6480            });
 6481        });
 6482    }
 6483
 6484    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 6485        if self.take_rename(true, cx).is_some() {
 6486            return;
 6487        }
 6488
 6489        if self
 6490            .context_menu
 6491            .write()
 6492            .as_mut()
 6493            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 6494            .unwrap_or(false)
 6495        {
 6496            return;
 6497        }
 6498
 6499        if matches!(self.mode, EditorMode::SingleLine) {
 6500            cx.propagate();
 6501            return;
 6502        }
 6503
 6504        let row_count = if let Some(row_count) = self.visible_line_count() {
 6505            row_count as u32 - 1
 6506        } else {
 6507            return;
 6508        };
 6509
 6510        let autoscroll = if action.center_cursor {
 6511            Autoscroll::center()
 6512        } else {
 6513            Autoscroll::fit()
 6514        };
 6515
 6516        let text_layout_details = &self.text_layout_details(cx);
 6517        self.change_selections(Some(autoscroll), cx, |s| {
 6518            let line_mode = s.line_mode;
 6519            s.move_with(|map, selection| {
 6520                if !selection.is_empty() && !line_mode {
 6521                    selection.goal = SelectionGoal::None;
 6522                }
 6523                let (cursor, goal) = movement::down_by_rows(
 6524                    map,
 6525                    selection.end,
 6526                    row_count,
 6527                    selection.goal,
 6528                    false,
 6529                    &text_layout_details,
 6530                );
 6531                selection.collapse_to(cursor, goal);
 6532            });
 6533        });
 6534    }
 6535
 6536    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 6537        let text_layout_details = &self.text_layout_details(cx);
 6538        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6539            s.move_heads_with(|map, head, goal| {
 6540                movement::down(map, head, goal, false, &text_layout_details)
 6541            })
 6542        });
 6543    }
 6544
 6545    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 6546        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6547            context_menu.select_first(self.project.as_ref(), cx);
 6548        }
 6549    }
 6550
 6551    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 6552        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6553            context_menu.select_prev(self.project.as_ref(), cx);
 6554        }
 6555    }
 6556
 6557    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 6558        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6559            context_menu.select_next(self.project.as_ref(), cx);
 6560        }
 6561    }
 6562
 6563    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 6564        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6565            context_menu.select_last(self.project.as_ref(), cx);
 6566        }
 6567    }
 6568
 6569    pub fn move_to_previous_word_start(
 6570        &mut self,
 6571        _: &MoveToPreviousWordStart,
 6572        cx: &mut ViewContext<Self>,
 6573    ) {
 6574        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6575            s.move_cursors_with(|map, head, _| {
 6576                (
 6577                    movement::previous_word_start(map, head),
 6578                    SelectionGoal::None,
 6579                )
 6580            });
 6581        })
 6582    }
 6583
 6584    pub fn move_to_previous_subword_start(
 6585        &mut self,
 6586        _: &MoveToPreviousSubwordStart,
 6587        cx: &mut ViewContext<Self>,
 6588    ) {
 6589        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6590            s.move_cursors_with(|map, head, _| {
 6591                (
 6592                    movement::previous_subword_start(map, head),
 6593                    SelectionGoal::None,
 6594                )
 6595            });
 6596        })
 6597    }
 6598
 6599    pub fn select_to_previous_word_start(
 6600        &mut self,
 6601        _: &SelectToPreviousWordStart,
 6602        cx: &mut ViewContext<Self>,
 6603    ) {
 6604        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6605            s.move_heads_with(|map, head, _| {
 6606                (
 6607                    movement::previous_word_start(map, head),
 6608                    SelectionGoal::None,
 6609                )
 6610            });
 6611        })
 6612    }
 6613
 6614    pub fn select_to_previous_subword_start(
 6615        &mut self,
 6616        _: &SelectToPreviousSubwordStart,
 6617        cx: &mut ViewContext<Self>,
 6618    ) {
 6619        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6620            s.move_heads_with(|map, head, _| {
 6621                (
 6622                    movement::previous_subword_start(map, head),
 6623                    SelectionGoal::None,
 6624                )
 6625            });
 6626        })
 6627    }
 6628
 6629    pub fn delete_to_previous_word_start(
 6630        &mut self,
 6631        _: &DeleteToPreviousWordStart,
 6632        cx: &mut ViewContext<Self>,
 6633    ) {
 6634        self.transact(cx, |this, cx| {
 6635            this.select_autoclose_pair(cx);
 6636            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6637                let line_mode = s.line_mode;
 6638                s.move_with(|map, selection| {
 6639                    if selection.is_empty() && !line_mode {
 6640                        let cursor = movement::previous_word_start(map, selection.head());
 6641                        selection.set_head(cursor, SelectionGoal::None);
 6642                    }
 6643                });
 6644            });
 6645            this.insert("", cx);
 6646        });
 6647    }
 6648
 6649    pub fn delete_to_previous_subword_start(
 6650        &mut self,
 6651        _: &DeleteToPreviousSubwordStart,
 6652        cx: &mut ViewContext<Self>,
 6653    ) {
 6654        self.transact(cx, |this, cx| {
 6655            this.select_autoclose_pair(cx);
 6656            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6657                let line_mode = s.line_mode;
 6658                s.move_with(|map, selection| {
 6659                    if selection.is_empty() && !line_mode {
 6660                        let cursor = movement::previous_subword_start(map, selection.head());
 6661                        selection.set_head(cursor, SelectionGoal::None);
 6662                    }
 6663                });
 6664            });
 6665            this.insert("", cx);
 6666        });
 6667    }
 6668
 6669    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 6670        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6671            s.move_cursors_with(|map, head, _| {
 6672                (movement::next_word_end(map, head), SelectionGoal::None)
 6673            });
 6674        })
 6675    }
 6676
 6677    pub fn move_to_next_subword_end(
 6678        &mut self,
 6679        _: &MoveToNextSubwordEnd,
 6680        cx: &mut ViewContext<Self>,
 6681    ) {
 6682        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6683            s.move_cursors_with(|map, head, _| {
 6684                (movement::next_subword_end(map, head), SelectionGoal::None)
 6685            });
 6686        })
 6687    }
 6688
 6689    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 6690        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6691            s.move_heads_with(|map, head, _| {
 6692                (movement::next_word_end(map, head), SelectionGoal::None)
 6693            });
 6694        })
 6695    }
 6696
 6697    pub fn select_to_next_subword_end(
 6698        &mut self,
 6699        _: &SelectToNextSubwordEnd,
 6700        cx: &mut ViewContext<Self>,
 6701    ) {
 6702        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6703            s.move_heads_with(|map, head, _| {
 6704                (movement::next_subword_end(map, head), SelectionGoal::None)
 6705            });
 6706        })
 6707    }
 6708
 6709    pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
 6710        self.transact(cx, |this, cx| {
 6711            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6712                let line_mode = s.line_mode;
 6713                s.move_with(|map, selection| {
 6714                    if selection.is_empty() && !line_mode {
 6715                        let cursor = movement::next_word_end(map, selection.head());
 6716                        selection.set_head(cursor, SelectionGoal::None);
 6717                    }
 6718                });
 6719            });
 6720            this.insert("", cx);
 6721        });
 6722    }
 6723
 6724    pub fn delete_to_next_subword_end(
 6725        &mut self,
 6726        _: &DeleteToNextSubwordEnd,
 6727        cx: &mut ViewContext<Self>,
 6728    ) {
 6729        self.transact(cx, |this, cx| {
 6730            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6731                s.move_with(|map, selection| {
 6732                    if selection.is_empty() {
 6733                        let cursor = movement::next_subword_end(map, selection.head());
 6734                        selection.set_head(cursor, SelectionGoal::None);
 6735                    }
 6736                });
 6737            });
 6738            this.insert("", cx);
 6739        });
 6740    }
 6741
 6742    pub fn move_to_beginning_of_line(
 6743        &mut self,
 6744        action: &MoveToBeginningOfLine,
 6745        cx: &mut ViewContext<Self>,
 6746    ) {
 6747        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6748            s.move_cursors_with(|map, head, _| {
 6749                (
 6750                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 6751                    SelectionGoal::None,
 6752                )
 6753            });
 6754        })
 6755    }
 6756
 6757    pub fn select_to_beginning_of_line(
 6758        &mut self,
 6759        action: &SelectToBeginningOfLine,
 6760        cx: &mut ViewContext<Self>,
 6761    ) {
 6762        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6763            s.move_heads_with(|map, head, _| {
 6764                (
 6765                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 6766                    SelectionGoal::None,
 6767                )
 6768            });
 6769        });
 6770    }
 6771
 6772    pub fn delete_to_beginning_of_line(
 6773        &mut self,
 6774        _: &DeleteToBeginningOfLine,
 6775        cx: &mut ViewContext<Self>,
 6776    ) {
 6777        self.transact(cx, |this, cx| {
 6778            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6779                s.move_with(|_, selection| {
 6780                    selection.reversed = true;
 6781                });
 6782            });
 6783
 6784            this.select_to_beginning_of_line(
 6785                &SelectToBeginningOfLine {
 6786                    stop_at_soft_wraps: false,
 6787                },
 6788                cx,
 6789            );
 6790            this.backspace(&Backspace, cx);
 6791        });
 6792    }
 6793
 6794    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 6795        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6796            s.move_cursors_with(|map, head, _| {
 6797                (
 6798                    movement::line_end(map, head, action.stop_at_soft_wraps),
 6799                    SelectionGoal::None,
 6800                )
 6801            });
 6802        })
 6803    }
 6804
 6805    pub fn select_to_end_of_line(
 6806        &mut self,
 6807        action: &SelectToEndOfLine,
 6808        cx: &mut ViewContext<Self>,
 6809    ) {
 6810        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6811            s.move_heads_with(|map, head, _| {
 6812                (
 6813                    movement::line_end(map, head, action.stop_at_soft_wraps),
 6814                    SelectionGoal::None,
 6815                )
 6816            });
 6817        })
 6818    }
 6819
 6820    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 6821        self.transact(cx, |this, cx| {
 6822            this.select_to_end_of_line(
 6823                &SelectToEndOfLine {
 6824                    stop_at_soft_wraps: false,
 6825                },
 6826                cx,
 6827            );
 6828            this.delete(&Delete, cx);
 6829        });
 6830    }
 6831
 6832    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 6833        self.transact(cx, |this, cx| {
 6834            this.select_to_end_of_line(
 6835                &SelectToEndOfLine {
 6836                    stop_at_soft_wraps: false,
 6837                },
 6838                cx,
 6839            );
 6840            this.cut(&Cut, cx);
 6841        });
 6842    }
 6843
 6844    pub fn move_to_start_of_paragraph(
 6845        &mut self,
 6846        _: &MoveToStartOfParagraph,
 6847        cx: &mut ViewContext<Self>,
 6848    ) {
 6849        if matches!(self.mode, EditorMode::SingleLine) {
 6850            cx.propagate();
 6851            return;
 6852        }
 6853
 6854        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6855            s.move_with(|map, selection| {
 6856                selection.collapse_to(
 6857                    movement::start_of_paragraph(map, selection.head(), 1),
 6858                    SelectionGoal::None,
 6859                )
 6860            });
 6861        })
 6862    }
 6863
 6864    pub fn move_to_end_of_paragraph(
 6865        &mut self,
 6866        _: &MoveToEndOfParagraph,
 6867        cx: &mut ViewContext<Self>,
 6868    ) {
 6869        if matches!(self.mode, EditorMode::SingleLine) {
 6870            cx.propagate();
 6871            return;
 6872        }
 6873
 6874        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6875            s.move_with(|map, selection| {
 6876                selection.collapse_to(
 6877                    movement::end_of_paragraph(map, selection.head(), 1),
 6878                    SelectionGoal::None,
 6879                )
 6880            });
 6881        })
 6882    }
 6883
 6884    pub fn select_to_start_of_paragraph(
 6885        &mut self,
 6886        _: &SelectToStartOfParagraph,
 6887        cx: &mut ViewContext<Self>,
 6888    ) {
 6889        if matches!(self.mode, EditorMode::SingleLine) {
 6890            cx.propagate();
 6891            return;
 6892        }
 6893
 6894        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6895            s.move_heads_with(|map, head, _| {
 6896                (
 6897                    movement::start_of_paragraph(map, head, 1),
 6898                    SelectionGoal::None,
 6899                )
 6900            });
 6901        })
 6902    }
 6903
 6904    pub fn select_to_end_of_paragraph(
 6905        &mut self,
 6906        _: &SelectToEndOfParagraph,
 6907        cx: &mut ViewContext<Self>,
 6908    ) {
 6909        if matches!(self.mode, EditorMode::SingleLine) {
 6910            cx.propagate();
 6911            return;
 6912        }
 6913
 6914        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6915            s.move_heads_with(|map, head, _| {
 6916                (
 6917                    movement::end_of_paragraph(map, head, 1),
 6918                    SelectionGoal::None,
 6919                )
 6920            });
 6921        })
 6922    }
 6923
 6924    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 6925        if matches!(self.mode, EditorMode::SingleLine) {
 6926            cx.propagate();
 6927            return;
 6928        }
 6929
 6930        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6931            s.select_ranges(vec![0..0]);
 6932        });
 6933    }
 6934
 6935    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 6936        let mut selection = self.selections.last::<Point>(cx);
 6937        selection.set_head(Point::zero(), SelectionGoal::None);
 6938
 6939        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6940            s.select(vec![selection]);
 6941        });
 6942    }
 6943
 6944    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 6945        if matches!(self.mode, EditorMode::SingleLine) {
 6946            cx.propagate();
 6947            return;
 6948        }
 6949
 6950        let cursor = self.buffer.read(cx).read(cx).len();
 6951        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6952            s.select_ranges(vec![cursor..cursor])
 6953        });
 6954    }
 6955
 6956    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 6957        self.nav_history = nav_history;
 6958    }
 6959
 6960    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 6961        self.nav_history.as_ref()
 6962    }
 6963
 6964    fn push_to_nav_history(
 6965        &mut self,
 6966        cursor_anchor: Anchor,
 6967        new_position: Option<Point>,
 6968        cx: &mut ViewContext<Self>,
 6969    ) {
 6970        if let Some(nav_history) = self.nav_history.as_mut() {
 6971            let buffer = self.buffer.read(cx).read(cx);
 6972            let cursor_position = cursor_anchor.to_point(&buffer);
 6973            let scroll_state = self.scroll_manager.anchor();
 6974            let scroll_top_row = scroll_state.top_row(&buffer);
 6975            drop(buffer);
 6976
 6977            if let Some(new_position) = new_position {
 6978                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 6979                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 6980                    return;
 6981                }
 6982            }
 6983
 6984            nav_history.push(
 6985                Some(NavigationData {
 6986                    cursor_anchor,
 6987                    cursor_position,
 6988                    scroll_anchor: scroll_state,
 6989                    scroll_top_row,
 6990                }),
 6991                cx,
 6992            );
 6993        }
 6994    }
 6995
 6996    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 6997        let buffer = self.buffer.read(cx).snapshot(cx);
 6998        let mut selection = self.selections.first::<usize>(cx);
 6999        selection.set_head(buffer.len(), SelectionGoal::None);
 7000        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7001            s.select(vec![selection]);
 7002        });
 7003    }
 7004
 7005    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7006        let end = self.buffer.read(cx).read(cx).len();
 7007        self.change_selections(None, cx, |s| {
 7008            s.select_ranges(vec![0..end]);
 7009        });
 7010    }
 7011
 7012    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7013        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7014        let mut selections = self.selections.all::<Point>(cx);
 7015        let max_point = display_map.buffer_snapshot.max_point();
 7016        for selection in &mut selections {
 7017            let rows = selection.spanned_rows(true, &display_map);
 7018            selection.start = Point::new(rows.start.0, 0);
 7019            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7020            selection.reversed = false;
 7021        }
 7022        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7023            s.select(selections);
 7024        });
 7025    }
 7026
 7027    pub fn split_selection_into_lines(
 7028        &mut self,
 7029        _: &SplitSelectionIntoLines,
 7030        cx: &mut ViewContext<Self>,
 7031    ) {
 7032        let mut to_unfold = Vec::new();
 7033        let mut new_selection_ranges = Vec::new();
 7034        {
 7035            let selections = self.selections.all::<Point>(cx);
 7036            let buffer = self.buffer.read(cx).read(cx);
 7037            for selection in selections {
 7038                for row in selection.start.row..selection.end.row {
 7039                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7040                    new_selection_ranges.push(cursor..cursor);
 7041                }
 7042                new_selection_ranges.push(selection.end..selection.end);
 7043                to_unfold.push(selection.start..selection.end);
 7044            }
 7045        }
 7046        self.unfold_ranges(to_unfold, true, true, cx);
 7047        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7048            s.select_ranges(new_selection_ranges);
 7049        });
 7050    }
 7051
 7052    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7053        self.add_selection(true, cx);
 7054    }
 7055
 7056    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7057        self.add_selection(false, cx);
 7058    }
 7059
 7060    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7061        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7062        let mut selections = self.selections.all::<Point>(cx);
 7063        let text_layout_details = self.text_layout_details(cx);
 7064        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7065            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7066            let range = oldest_selection.display_range(&display_map).sorted();
 7067
 7068            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7069            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7070            let positions = start_x.min(end_x)..start_x.max(end_x);
 7071
 7072            selections.clear();
 7073            let mut stack = Vec::new();
 7074            for row in range.start.row().0..=range.end.row().0 {
 7075                if let Some(selection) = self.selections.build_columnar_selection(
 7076                    &display_map,
 7077                    DisplayRow(row),
 7078                    &positions,
 7079                    oldest_selection.reversed,
 7080                    &text_layout_details,
 7081                ) {
 7082                    stack.push(selection.id);
 7083                    selections.push(selection);
 7084                }
 7085            }
 7086
 7087            if above {
 7088                stack.reverse();
 7089            }
 7090
 7091            AddSelectionsState { above, stack }
 7092        });
 7093
 7094        let last_added_selection = *state.stack.last().unwrap();
 7095        let mut new_selections = Vec::new();
 7096        if above == state.above {
 7097            let end_row = if above {
 7098                DisplayRow(0)
 7099            } else {
 7100                display_map.max_point().row()
 7101            };
 7102
 7103            'outer: for selection in selections {
 7104                if selection.id == last_added_selection {
 7105                    let range = selection.display_range(&display_map).sorted();
 7106                    debug_assert_eq!(range.start.row(), range.end.row());
 7107                    let mut row = range.start.row();
 7108                    let positions =
 7109                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7110                            px(start)..px(end)
 7111                        } else {
 7112                            let start_x =
 7113                                display_map.x_for_display_point(range.start, &text_layout_details);
 7114                            let end_x =
 7115                                display_map.x_for_display_point(range.end, &text_layout_details);
 7116                            start_x.min(end_x)..start_x.max(end_x)
 7117                        };
 7118
 7119                    while row != end_row {
 7120                        if above {
 7121                            row.0 -= 1;
 7122                        } else {
 7123                            row.0 += 1;
 7124                        }
 7125
 7126                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7127                            &display_map,
 7128                            row,
 7129                            &positions,
 7130                            selection.reversed,
 7131                            &text_layout_details,
 7132                        ) {
 7133                            state.stack.push(new_selection.id);
 7134                            if above {
 7135                                new_selections.push(new_selection);
 7136                                new_selections.push(selection);
 7137                            } else {
 7138                                new_selections.push(selection);
 7139                                new_selections.push(new_selection);
 7140                            }
 7141
 7142                            continue 'outer;
 7143                        }
 7144                    }
 7145                }
 7146
 7147                new_selections.push(selection);
 7148            }
 7149        } else {
 7150            new_selections = selections;
 7151            new_selections.retain(|s| s.id != last_added_selection);
 7152            state.stack.pop();
 7153        }
 7154
 7155        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7156            s.select(new_selections);
 7157        });
 7158        if state.stack.len() > 1 {
 7159            self.add_selections_state = Some(state);
 7160        }
 7161    }
 7162
 7163    pub fn select_next_match_internal(
 7164        &mut self,
 7165        display_map: &DisplaySnapshot,
 7166        replace_newest: bool,
 7167        autoscroll: Option<Autoscroll>,
 7168        cx: &mut ViewContext<Self>,
 7169    ) -> Result<()> {
 7170        fn select_next_match_ranges(
 7171            this: &mut Editor,
 7172            range: Range<usize>,
 7173            replace_newest: bool,
 7174            auto_scroll: Option<Autoscroll>,
 7175            cx: &mut ViewContext<Editor>,
 7176        ) {
 7177            this.unfold_ranges([range.clone()], false, true, cx);
 7178            this.change_selections(auto_scroll, cx, |s| {
 7179                if replace_newest {
 7180                    s.delete(s.newest_anchor().id);
 7181                }
 7182                s.insert_range(range.clone());
 7183            });
 7184        }
 7185
 7186        let buffer = &display_map.buffer_snapshot;
 7187        let mut selections = self.selections.all::<usize>(cx);
 7188        if let Some(mut select_next_state) = self.select_next_state.take() {
 7189            let query = &select_next_state.query;
 7190            if !select_next_state.done {
 7191                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7192                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7193                let mut next_selected_range = None;
 7194
 7195                let bytes_after_last_selection =
 7196                    buffer.bytes_in_range(last_selection.end..buffer.len());
 7197                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 7198                let query_matches = query
 7199                    .stream_find_iter(bytes_after_last_selection)
 7200                    .map(|result| (last_selection.end, result))
 7201                    .chain(
 7202                        query
 7203                            .stream_find_iter(bytes_before_first_selection)
 7204                            .map(|result| (0, result)),
 7205                    );
 7206
 7207                for (start_offset, query_match) in query_matches {
 7208                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7209                    let offset_range =
 7210                        start_offset + query_match.start()..start_offset + query_match.end();
 7211                    let display_range = offset_range.start.to_display_point(&display_map)
 7212                        ..offset_range.end.to_display_point(&display_map);
 7213
 7214                    if !select_next_state.wordwise
 7215                        || (!movement::is_inside_word(&display_map, display_range.start)
 7216                            && !movement::is_inside_word(&display_map, display_range.end))
 7217                    {
 7218                        // TODO: This is n^2, because we might check all the selections
 7219                        if !selections
 7220                            .iter()
 7221                            .any(|selection| selection.range().overlaps(&offset_range))
 7222                        {
 7223                            next_selected_range = Some(offset_range);
 7224                            break;
 7225                        }
 7226                    }
 7227                }
 7228
 7229                if let Some(next_selected_range) = next_selected_range {
 7230                    select_next_match_ranges(
 7231                        self,
 7232                        next_selected_range,
 7233                        replace_newest,
 7234                        autoscroll,
 7235                        cx,
 7236                    );
 7237                } else {
 7238                    select_next_state.done = true;
 7239                }
 7240            }
 7241
 7242            self.select_next_state = Some(select_next_state);
 7243        } else {
 7244            let mut only_carets = true;
 7245            let mut same_text_selected = true;
 7246            let mut selected_text = None;
 7247
 7248            let mut selections_iter = selections.iter().peekable();
 7249            while let Some(selection) = selections_iter.next() {
 7250                if selection.start != selection.end {
 7251                    only_carets = false;
 7252                }
 7253
 7254                if same_text_selected {
 7255                    if selected_text.is_none() {
 7256                        selected_text =
 7257                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7258                    }
 7259
 7260                    if let Some(next_selection) = selections_iter.peek() {
 7261                        if next_selection.range().len() == selection.range().len() {
 7262                            let next_selected_text = buffer
 7263                                .text_for_range(next_selection.range())
 7264                                .collect::<String>();
 7265                            if Some(next_selected_text) != selected_text {
 7266                                same_text_selected = false;
 7267                                selected_text = None;
 7268                            }
 7269                        } else {
 7270                            same_text_selected = false;
 7271                            selected_text = None;
 7272                        }
 7273                    }
 7274                }
 7275            }
 7276
 7277            if only_carets {
 7278                for selection in &mut selections {
 7279                    let word_range = movement::surrounding_word(
 7280                        &display_map,
 7281                        selection.start.to_display_point(&display_map),
 7282                    );
 7283                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7284                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7285                    selection.goal = SelectionGoal::None;
 7286                    selection.reversed = false;
 7287                    select_next_match_ranges(
 7288                        self,
 7289                        selection.start..selection.end,
 7290                        replace_newest,
 7291                        autoscroll,
 7292                        cx,
 7293                    );
 7294                }
 7295
 7296                if selections.len() == 1 {
 7297                    let selection = selections
 7298                        .last()
 7299                        .expect("ensured that there's only one selection");
 7300                    let query = buffer
 7301                        .text_for_range(selection.start..selection.end)
 7302                        .collect::<String>();
 7303                    let is_empty = query.is_empty();
 7304                    let select_state = SelectNextState {
 7305                        query: AhoCorasick::new(&[query])?,
 7306                        wordwise: true,
 7307                        done: is_empty,
 7308                    };
 7309                    self.select_next_state = Some(select_state);
 7310                } else {
 7311                    self.select_next_state = None;
 7312                }
 7313            } else if let Some(selected_text) = selected_text {
 7314                self.select_next_state = Some(SelectNextState {
 7315                    query: AhoCorasick::new(&[selected_text])?,
 7316                    wordwise: false,
 7317                    done: false,
 7318                });
 7319                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 7320            }
 7321        }
 7322        Ok(())
 7323    }
 7324
 7325    pub fn select_all_matches(
 7326        &mut self,
 7327        _action: &SelectAllMatches,
 7328        cx: &mut ViewContext<Self>,
 7329    ) -> Result<()> {
 7330        self.push_to_selection_history();
 7331        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7332
 7333        self.select_next_match_internal(&display_map, false, None, cx)?;
 7334        let Some(select_next_state) = self.select_next_state.as_mut() else {
 7335            return Ok(());
 7336        };
 7337        if select_next_state.done {
 7338            return Ok(());
 7339        }
 7340
 7341        let mut new_selections = self.selections.all::<usize>(cx);
 7342
 7343        let buffer = &display_map.buffer_snapshot;
 7344        let query_matches = select_next_state
 7345            .query
 7346            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 7347
 7348        for query_match in query_matches {
 7349            let query_match = query_match.unwrap(); // can only fail due to I/O
 7350            let offset_range = query_match.start()..query_match.end();
 7351            let display_range = offset_range.start.to_display_point(&display_map)
 7352                ..offset_range.end.to_display_point(&display_map);
 7353
 7354            if !select_next_state.wordwise
 7355                || (!movement::is_inside_word(&display_map, display_range.start)
 7356                    && !movement::is_inside_word(&display_map, display_range.end))
 7357            {
 7358                self.selections.change_with(cx, |selections| {
 7359                    new_selections.push(Selection {
 7360                        id: selections.new_selection_id(),
 7361                        start: offset_range.start,
 7362                        end: offset_range.end,
 7363                        reversed: false,
 7364                        goal: SelectionGoal::None,
 7365                    });
 7366                });
 7367            }
 7368        }
 7369
 7370        new_selections.sort_by_key(|selection| selection.start);
 7371        let mut ix = 0;
 7372        while ix + 1 < new_selections.len() {
 7373            let current_selection = &new_selections[ix];
 7374            let next_selection = &new_selections[ix + 1];
 7375            if current_selection.range().overlaps(&next_selection.range()) {
 7376                if current_selection.id < next_selection.id {
 7377                    new_selections.remove(ix + 1);
 7378                } else {
 7379                    new_selections.remove(ix);
 7380                }
 7381            } else {
 7382                ix += 1;
 7383            }
 7384        }
 7385
 7386        select_next_state.done = true;
 7387        self.unfold_ranges(
 7388            new_selections.iter().map(|selection| selection.range()),
 7389            false,
 7390            false,
 7391            cx,
 7392        );
 7393        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 7394            selections.select(new_selections)
 7395        });
 7396
 7397        Ok(())
 7398    }
 7399
 7400    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 7401        self.push_to_selection_history();
 7402        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7403        self.select_next_match_internal(
 7404            &display_map,
 7405            action.replace_newest,
 7406            Some(Autoscroll::newest()),
 7407            cx,
 7408        )?;
 7409        Ok(())
 7410    }
 7411
 7412    pub fn select_previous(
 7413        &mut self,
 7414        action: &SelectPrevious,
 7415        cx: &mut ViewContext<Self>,
 7416    ) -> Result<()> {
 7417        self.push_to_selection_history();
 7418        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7419        let buffer = &display_map.buffer_snapshot;
 7420        let mut selections = self.selections.all::<usize>(cx);
 7421        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 7422            let query = &select_prev_state.query;
 7423            if !select_prev_state.done {
 7424                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7425                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7426                let mut next_selected_range = None;
 7427                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 7428                let bytes_before_last_selection =
 7429                    buffer.reversed_bytes_in_range(0..last_selection.start);
 7430                let bytes_after_first_selection =
 7431                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 7432                let query_matches = query
 7433                    .stream_find_iter(bytes_before_last_selection)
 7434                    .map(|result| (last_selection.start, result))
 7435                    .chain(
 7436                        query
 7437                            .stream_find_iter(bytes_after_first_selection)
 7438                            .map(|result| (buffer.len(), result)),
 7439                    );
 7440                for (end_offset, query_match) in query_matches {
 7441                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7442                    let offset_range =
 7443                        end_offset - query_match.end()..end_offset - query_match.start();
 7444                    let display_range = offset_range.start.to_display_point(&display_map)
 7445                        ..offset_range.end.to_display_point(&display_map);
 7446
 7447                    if !select_prev_state.wordwise
 7448                        || (!movement::is_inside_word(&display_map, display_range.start)
 7449                            && !movement::is_inside_word(&display_map, display_range.end))
 7450                    {
 7451                        next_selected_range = Some(offset_range);
 7452                        break;
 7453                    }
 7454                }
 7455
 7456                if let Some(next_selected_range) = next_selected_range {
 7457                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 7458                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7459                        if action.replace_newest {
 7460                            s.delete(s.newest_anchor().id);
 7461                        }
 7462                        s.insert_range(next_selected_range);
 7463                    });
 7464                } else {
 7465                    select_prev_state.done = true;
 7466                }
 7467            }
 7468
 7469            self.select_prev_state = Some(select_prev_state);
 7470        } else {
 7471            let mut only_carets = true;
 7472            let mut same_text_selected = true;
 7473            let mut selected_text = None;
 7474
 7475            let mut selections_iter = selections.iter().peekable();
 7476            while let Some(selection) = selections_iter.next() {
 7477                if selection.start != selection.end {
 7478                    only_carets = false;
 7479                }
 7480
 7481                if same_text_selected {
 7482                    if selected_text.is_none() {
 7483                        selected_text =
 7484                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7485                    }
 7486
 7487                    if let Some(next_selection) = selections_iter.peek() {
 7488                        if next_selection.range().len() == selection.range().len() {
 7489                            let next_selected_text = buffer
 7490                                .text_for_range(next_selection.range())
 7491                                .collect::<String>();
 7492                            if Some(next_selected_text) != selected_text {
 7493                                same_text_selected = false;
 7494                                selected_text = None;
 7495                            }
 7496                        } else {
 7497                            same_text_selected = false;
 7498                            selected_text = None;
 7499                        }
 7500                    }
 7501                }
 7502            }
 7503
 7504            if only_carets {
 7505                for selection in &mut selections {
 7506                    let word_range = movement::surrounding_word(
 7507                        &display_map,
 7508                        selection.start.to_display_point(&display_map),
 7509                    );
 7510                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7511                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7512                    selection.goal = SelectionGoal::None;
 7513                    selection.reversed = false;
 7514                }
 7515                if selections.len() == 1 {
 7516                    let selection = selections
 7517                        .last()
 7518                        .expect("ensured that there's only one selection");
 7519                    let query = buffer
 7520                        .text_for_range(selection.start..selection.end)
 7521                        .collect::<String>();
 7522                    let is_empty = query.is_empty();
 7523                    let select_state = SelectNextState {
 7524                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 7525                        wordwise: true,
 7526                        done: is_empty,
 7527                    };
 7528                    self.select_prev_state = Some(select_state);
 7529                } else {
 7530                    self.select_prev_state = None;
 7531                }
 7532
 7533                self.unfold_ranges(
 7534                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 7535                    false,
 7536                    true,
 7537                    cx,
 7538                );
 7539                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7540                    s.select(selections);
 7541                });
 7542            } else if let Some(selected_text) = selected_text {
 7543                self.select_prev_state = Some(SelectNextState {
 7544                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 7545                    wordwise: false,
 7546                    done: false,
 7547                });
 7548                self.select_previous(action, cx)?;
 7549            }
 7550        }
 7551        Ok(())
 7552    }
 7553
 7554    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 7555        let text_layout_details = &self.text_layout_details(cx);
 7556        self.transact(cx, |this, cx| {
 7557            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7558            let mut edits = Vec::new();
 7559            let mut selection_edit_ranges = Vec::new();
 7560            let mut last_toggled_row = None;
 7561            let snapshot = this.buffer.read(cx).read(cx);
 7562            let empty_str: Arc<str> = "".into();
 7563            let mut suffixes_inserted = Vec::new();
 7564
 7565            fn comment_prefix_range(
 7566                snapshot: &MultiBufferSnapshot,
 7567                row: MultiBufferRow,
 7568                comment_prefix: &str,
 7569                comment_prefix_whitespace: &str,
 7570            ) -> Range<Point> {
 7571                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 7572
 7573                let mut line_bytes = snapshot
 7574                    .bytes_in_range(start..snapshot.max_point())
 7575                    .flatten()
 7576                    .copied();
 7577
 7578                // If this line currently begins with the line comment prefix, then record
 7579                // the range containing the prefix.
 7580                if line_bytes
 7581                    .by_ref()
 7582                    .take(comment_prefix.len())
 7583                    .eq(comment_prefix.bytes())
 7584                {
 7585                    // Include any whitespace that matches the comment prefix.
 7586                    let matching_whitespace_len = line_bytes
 7587                        .zip(comment_prefix_whitespace.bytes())
 7588                        .take_while(|(a, b)| a == b)
 7589                        .count() as u32;
 7590                    let end = Point::new(
 7591                        start.row,
 7592                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 7593                    );
 7594                    start..end
 7595                } else {
 7596                    start..start
 7597                }
 7598            }
 7599
 7600            fn comment_suffix_range(
 7601                snapshot: &MultiBufferSnapshot,
 7602                row: MultiBufferRow,
 7603                comment_suffix: &str,
 7604                comment_suffix_has_leading_space: bool,
 7605            ) -> Range<Point> {
 7606                let end = Point::new(row.0, snapshot.line_len(row));
 7607                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 7608
 7609                let mut line_end_bytes = snapshot
 7610                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 7611                    .flatten()
 7612                    .copied();
 7613
 7614                let leading_space_len = if suffix_start_column > 0
 7615                    && line_end_bytes.next() == Some(b' ')
 7616                    && comment_suffix_has_leading_space
 7617                {
 7618                    1
 7619                } else {
 7620                    0
 7621                };
 7622
 7623                // If this line currently begins with the line comment prefix, then record
 7624                // the range containing the prefix.
 7625                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 7626                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 7627                    start..end
 7628                } else {
 7629                    end..end
 7630                }
 7631            }
 7632
 7633            // TODO: Handle selections that cross excerpts
 7634            for selection in &mut selections {
 7635                let start_column = snapshot
 7636                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 7637                    .len;
 7638                let language = if let Some(language) =
 7639                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 7640                {
 7641                    language
 7642                } else {
 7643                    continue;
 7644                };
 7645
 7646                selection_edit_ranges.clear();
 7647
 7648                // If multiple selections contain a given row, avoid processing that
 7649                // row more than once.
 7650                let mut start_row = MultiBufferRow(selection.start.row);
 7651                if last_toggled_row == Some(start_row) {
 7652                    start_row = start_row.next_row();
 7653                }
 7654                let end_row =
 7655                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 7656                        MultiBufferRow(selection.end.row - 1)
 7657                    } else {
 7658                        MultiBufferRow(selection.end.row)
 7659                    };
 7660                last_toggled_row = Some(end_row);
 7661
 7662                if start_row > end_row {
 7663                    continue;
 7664                }
 7665
 7666                // If the language has line comments, toggle those.
 7667                let full_comment_prefixes = language.line_comment_prefixes();
 7668                if !full_comment_prefixes.is_empty() {
 7669                    let first_prefix = full_comment_prefixes
 7670                        .first()
 7671                        .expect("prefixes is non-empty");
 7672                    let prefix_trimmed_lengths = full_comment_prefixes
 7673                        .iter()
 7674                        .map(|p| p.trim_end_matches(' ').len())
 7675                        .collect::<SmallVec<[usize; 4]>>();
 7676
 7677                    let mut all_selection_lines_are_comments = true;
 7678
 7679                    for row in start_row.0..=end_row.0 {
 7680                        let row = MultiBufferRow(row);
 7681                        if start_row < end_row && snapshot.is_line_blank(row) {
 7682                            continue;
 7683                        }
 7684
 7685                        let prefix_range = full_comment_prefixes
 7686                            .iter()
 7687                            .zip(prefix_trimmed_lengths.iter().copied())
 7688                            .map(|(prefix, trimmed_prefix_len)| {
 7689                                comment_prefix_range(
 7690                                    snapshot.deref(),
 7691                                    row,
 7692                                    &prefix[..trimmed_prefix_len],
 7693                                    &prefix[trimmed_prefix_len..],
 7694                                )
 7695                            })
 7696                            .max_by_key(|range| range.end.column - range.start.column)
 7697                            .expect("prefixes is non-empty");
 7698
 7699                        if prefix_range.is_empty() {
 7700                            all_selection_lines_are_comments = false;
 7701                        }
 7702
 7703                        selection_edit_ranges.push(prefix_range);
 7704                    }
 7705
 7706                    if all_selection_lines_are_comments {
 7707                        edits.extend(
 7708                            selection_edit_ranges
 7709                                .iter()
 7710                                .cloned()
 7711                                .map(|range| (range, empty_str.clone())),
 7712                        );
 7713                    } else {
 7714                        let min_column = selection_edit_ranges
 7715                            .iter()
 7716                            .map(|range| range.start.column)
 7717                            .min()
 7718                            .unwrap_or(0);
 7719                        edits.extend(selection_edit_ranges.iter().map(|range| {
 7720                            let position = Point::new(range.start.row, min_column);
 7721                            (position..position, first_prefix.clone())
 7722                        }));
 7723                    }
 7724                } else if let Some((full_comment_prefix, comment_suffix)) =
 7725                    language.block_comment_delimiters()
 7726                {
 7727                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 7728                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 7729                    let prefix_range = comment_prefix_range(
 7730                        snapshot.deref(),
 7731                        start_row,
 7732                        comment_prefix,
 7733                        comment_prefix_whitespace,
 7734                    );
 7735                    let suffix_range = comment_suffix_range(
 7736                        snapshot.deref(),
 7737                        end_row,
 7738                        comment_suffix.trim_start_matches(' '),
 7739                        comment_suffix.starts_with(' '),
 7740                    );
 7741
 7742                    if prefix_range.is_empty() || suffix_range.is_empty() {
 7743                        edits.push((
 7744                            prefix_range.start..prefix_range.start,
 7745                            full_comment_prefix.clone(),
 7746                        ));
 7747                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 7748                        suffixes_inserted.push((end_row, comment_suffix.len()));
 7749                    } else {
 7750                        edits.push((prefix_range, empty_str.clone()));
 7751                        edits.push((suffix_range, empty_str.clone()));
 7752                    }
 7753                } else {
 7754                    continue;
 7755                }
 7756            }
 7757
 7758            drop(snapshot);
 7759            this.buffer.update(cx, |buffer, cx| {
 7760                buffer.edit(edits, None, cx);
 7761            });
 7762
 7763            // Adjust selections so that they end before any comment suffixes that
 7764            // were inserted.
 7765            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 7766            let mut selections = this.selections.all::<Point>(cx);
 7767            let snapshot = this.buffer.read(cx).read(cx);
 7768            for selection in &mut selections {
 7769                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 7770                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 7771                        Ordering::Less => {
 7772                            suffixes_inserted.next();
 7773                            continue;
 7774                        }
 7775                        Ordering::Greater => break,
 7776                        Ordering::Equal => {
 7777                            if selection.end.column == snapshot.line_len(row) {
 7778                                if selection.is_empty() {
 7779                                    selection.start.column -= suffix_len as u32;
 7780                                }
 7781                                selection.end.column -= suffix_len as u32;
 7782                            }
 7783                            break;
 7784                        }
 7785                    }
 7786                }
 7787            }
 7788
 7789            drop(snapshot);
 7790            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7791
 7792            let selections = this.selections.all::<Point>(cx);
 7793            let selections_on_single_row = selections.windows(2).all(|selections| {
 7794                selections[0].start.row == selections[1].start.row
 7795                    && selections[0].end.row == selections[1].end.row
 7796                    && selections[0].start.row == selections[0].end.row
 7797            });
 7798            let selections_selecting = selections
 7799                .iter()
 7800                .any(|selection| selection.start != selection.end);
 7801            let advance_downwards = action.advance_downwards
 7802                && selections_on_single_row
 7803                && !selections_selecting
 7804                && this.mode != EditorMode::SingleLine;
 7805
 7806            if advance_downwards {
 7807                let snapshot = this.buffer.read(cx).snapshot(cx);
 7808
 7809                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7810                    s.move_cursors_with(|display_snapshot, display_point, _| {
 7811                        let mut point = display_point.to_point(display_snapshot);
 7812                        point.row += 1;
 7813                        point = snapshot.clip_point(point, Bias::Left);
 7814                        let display_point = point.to_display_point(display_snapshot);
 7815                        let goal = SelectionGoal::HorizontalPosition(
 7816                            display_snapshot
 7817                                .x_for_display_point(display_point, &text_layout_details)
 7818                                .into(),
 7819                        );
 7820                        (display_point, goal)
 7821                    })
 7822                });
 7823            }
 7824        });
 7825    }
 7826
 7827    pub fn select_larger_syntax_node(
 7828        &mut self,
 7829        _: &SelectLargerSyntaxNode,
 7830        cx: &mut ViewContext<Self>,
 7831    ) {
 7832        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7833        let buffer = self.buffer.read(cx).snapshot(cx);
 7834        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 7835
 7836        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 7837        let mut selected_larger_node = false;
 7838        let new_selections = old_selections
 7839            .iter()
 7840            .map(|selection| {
 7841                let old_range = selection.start..selection.end;
 7842                let mut new_range = old_range.clone();
 7843                while let Some(containing_range) =
 7844                    buffer.range_for_syntax_ancestor(new_range.clone())
 7845                {
 7846                    new_range = containing_range;
 7847                    if !display_map.intersects_fold(new_range.start)
 7848                        && !display_map.intersects_fold(new_range.end)
 7849                    {
 7850                        break;
 7851                    }
 7852                }
 7853
 7854                selected_larger_node |= new_range != old_range;
 7855                Selection {
 7856                    id: selection.id,
 7857                    start: new_range.start,
 7858                    end: new_range.end,
 7859                    goal: SelectionGoal::None,
 7860                    reversed: selection.reversed,
 7861                }
 7862            })
 7863            .collect::<Vec<_>>();
 7864
 7865        if selected_larger_node {
 7866            stack.push(old_selections);
 7867            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7868                s.select(new_selections);
 7869            });
 7870        }
 7871        self.select_larger_syntax_node_stack = stack;
 7872    }
 7873
 7874    pub fn select_smaller_syntax_node(
 7875        &mut self,
 7876        _: &SelectSmallerSyntaxNode,
 7877        cx: &mut ViewContext<Self>,
 7878    ) {
 7879        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 7880        if let Some(selections) = stack.pop() {
 7881            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7882                s.select(selections.to_vec());
 7883            });
 7884        }
 7885        self.select_larger_syntax_node_stack = stack;
 7886    }
 7887
 7888    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 7889        let project = self.project.clone();
 7890        cx.spawn(|this, mut cx| async move {
 7891            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 7892                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 7893            }) else {
 7894                return;
 7895            };
 7896
 7897            let Some(project) = project else {
 7898                return;
 7899            };
 7900            if project
 7901                .update(&mut cx, |this, _| this.is_remote())
 7902                .unwrap_or(true)
 7903            {
 7904                // Do not display any test indicators in remote projects.
 7905                return;
 7906            }
 7907            let new_rows =
 7908                cx.background_executor()
 7909                    .spawn({
 7910                        let snapshot = display_snapshot.clone();
 7911                        async move {
 7912                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 7913                        }
 7914                    })
 7915                    .await;
 7916            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 7917
 7918            this.update(&mut cx, |this, _| {
 7919                this.clear_tasks();
 7920                for (key, value) in rows {
 7921                    this.insert_tasks(key, value);
 7922                }
 7923            })
 7924            .ok();
 7925        })
 7926    }
 7927    fn fetch_runnable_ranges(
 7928        snapshot: &DisplaySnapshot,
 7929        range: Range<Anchor>,
 7930    ) -> Vec<language::RunnableRange> {
 7931        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 7932    }
 7933
 7934    fn runnable_rows(
 7935        project: Model<Project>,
 7936        snapshot: DisplaySnapshot,
 7937        runnable_ranges: Vec<RunnableRange>,
 7938        mut cx: AsyncWindowContext,
 7939    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 7940        runnable_ranges
 7941            .into_iter()
 7942            .filter_map(|mut runnable| {
 7943                let (tasks, _) = cx
 7944                    .update(|cx| {
 7945                        Self::resolve_runnable(project.clone(), &mut runnable.runnable, cx)
 7946                    })
 7947                    .ok()?;
 7948                if tasks.is_empty() {
 7949                    return None;
 7950                }
 7951
 7952                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 7953
 7954                let row = snapshot
 7955                    .buffer_snapshot
 7956                    .buffer_line_for_row(MultiBufferRow(point.row))?
 7957                    .1
 7958                    .start
 7959                    .row;
 7960
 7961                let context_range =
 7962                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 7963                Some((
 7964                    (runnable.buffer_id, row),
 7965                    RunnableTasks {
 7966                        templates: tasks,
 7967                        offset: MultiBufferOffset(runnable.run_range.start),
 7968                        context_range,
 7969                        column: point.column,
 7970                        extra_variables: runnable.extra_captures,
 7971                    },
 7972                ))
 7973            })
 7974            .collect()
 7975    }
 7976
 7977    fn resolve_runnable(
 7978        project: Model<Project>,
 7979        runnable: &mut Runnable,
 7980        cx: &WindowContext<'_>,
 7981    ) -> (Vec<(TaskSourceKind, TaskTemplate)>, Option<WorktreeId>) {
 7982        let (inventory, worktree_id) = project.read_with(cx, |project, cx| {
 7983            let worktree_id = project
 7984                .buffer_for_id(runnable.buffer)
 7985                .and_then(|buffer| buffer.read(cx).file())
 7986                .map(|file| WorktreeId::from_usize(file.worktree_id()));
 7987
 7988            (project.task_inventory().clone(), worktree_id)
 7989        });
 7990
 7991        let inventory = inventory.read(cx);
 7992        let tags = mem::take(&mut runnable.tags);
 7993        let mut tags: Vec<_> = tags
 7994            .into_iter()
 7995            .flat_map(|tag| {
 7996                let tag = tag.0.clone();
 7997                inventory
 7998                    .list_tasks(Some(runnable.language.clone()), worktree_id)
 7999                    .into_iter()
 8000                    .filter(move |(_, template)| {
 8001                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8002                    })
 8003            })
 8004            .sorted_by_key(|(kind, _)| kind.to_owned())
 8005            .collect();
 8006        if let Some((leading_tag_source, _)) = tags.first() {
 8007            // Strongest source wins; if we have worktree tag binding, prefer that to
 8008            // global and language bindings;
 8009            // if we have a global binding, prefer that to language binding.
 8010            let first_mismatch = tags
 8011                .iter()
 8012                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8013            if let Some(index) = first_mismatch {
 8014                tags.truncate(index);
 8015            }
 8016        }
 8017
 8018        (tags, worktree_id)
 8019    }
 8020
 8021    pub fn move_to_enclosing_bracket(
 8022        &mut self,
 8023        _: &MoveToEnclosingBracket,
 8024        cx: &mut ViewContext<Self>,
 8025    ) {
 8026        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8027            s.move_offsets_with(|snapshot, selection| {
 8028                let Some(enclosing_bracket_ranges) =
 8029                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8030                else {
 8031                    return;
 8032                };
 8033
 8034                let mut best_length = usize::MAX;
 8035                let mut best_inside = false;
 8036                let mut best_in_bracket_range = false;
 8037                let mut best_destination = None;
 8038                for (open, close) in enclosing_bracket_ranges {
 8039                    let close = close.to_inclusive();
 8040                    let length = close.end() - open.start;
 8041                    let inside = selection.start >= open.end && selection.end <= *close.start();
 8042                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 8043                        || close.contains(&selection.head());
 8044
 8045                    // If best is next to a bracket and current isn't, skip
 8046                    if !in_bracket_range && best_in_bracket_range {
 8047                        continue;
 8048                    }
 8049
 8050                    // Prefer smaller lengths unless best is inside and current isn't
 8051                    if length > best_length && (best_inside || !inside) {
 8052                        continue;
 8053                    }
 8054
 8055                    best_length = length;
 8056                    best_inside = inside;
 8057                    best_in_bracket_range = in_bracket_range;
 8058                    best_destination = Some(
 8059                        if close.contains(&selection.start) && close.contains(&selection.end) {
 8060                            if inside {
 8061                                open.end
 8062                            } else {
 8063                                open.start
 8064                            }
 8065                        } else {
 8066                            if inside {
 8067                                *close.start()
 8068                            } else {
 8069                                *close.end()
 8070                            }
 8071                        },
 8072                    );
 8073                }
 8074
 8075                if let Some(destination) = best_destination {
 8076                    selection.collapse_to(destination, SelectionGoal::None);
 8077                }
 8078            })
 8079        });
 8080    }
 8081
 8082    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 8083        self.end_selection(cx);
 8084        self.selection_history.mode = SelectionHistoryMode::Undoing;
 8085        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 8086            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8087            self.select_next_state = entry.select_next_state;
 8088            self.select_prev_state = entry.select_prev_state;
 8089            self.add_selections_state = entry.add_selections_state;
 8090            self.request_autoscroll(Autoscroll::newest(), cx);
 8091        }
 8092        self.selection_history.mode = SelectionHistoryMode::Normal;
 8093    }
 8094
 8095    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 8096        self.end_selection(cx);
 8097        self.selection_history.mode = SelectionHistoryMode::Redoing;
 8098        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 8099            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8100            self.select_next_state = entry.select_next_state;
 8101            self.select_prev_state = entry.select_prev_state;
 8102            self.add_selections_state = entry.add_selections_state;
 8103            self.request_autoscroll(Autoscroll::newest(), cx);
 8104        }
 8105        self.selection_history.mode = SelectionHistoryMode::Normal;
 8106    }
 8107
 8108    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 8109        let selections = self.selections.disjoint_anchors();
 8110
 8111        let lines = if action.lines == 0 { 3 } else { action.lines };
 8112
 8113        self.buffer.update(cx, |buffer, cx| {
 8114            buffer.expand_excerpts(
 8115                selections
 8116                    .into_iter()
 8117                    .map(|selection| selection.head().excerpt_id)
 8118                    .dedup(),
 8119                lines,
 8120                cx,
 8121            )
 8122        })
 8123    }
 8124
 8125    pub fn expand_excerpt(&mut self, excerpt: ExcerptId, cx: &mut ViewContext<Self>) {
 8126        self.buffer
 8127            .update(cx, |buffer, cx| buffer.expand_excerpts([excerpt], 3, cx))
 8128    }
 8129
 8130    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 8131        self.go_to_diagnostic_impl(Direction::Next, cx)
 8132    }
 8133
 8134    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 8135        self.go_to_diagnostic_impl(Direction::Prev, cx)
 8136    }
 8137
 8138    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 8139        let buffer = self.buffer.read(cx).snapshot(cx);
 8140        let selection = self.selections.newest::<usize>(cx);
 8141
 8142        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 8143        if direction == Direction::Next {
 8144            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 8145                let (group_id, jump_to) = popover.activation_info();
 8146                if self.activate_diagnostics(group_id, cx) {
 8147                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8148                        let mut new_selection = s.newest_anchor().clone();
 8149                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 8150                        s.select_anchors(vec![new_selection.clone()]);
 8151                    });
 8152                }
 8153                return;
 8154            }
 8155        }
 8156
 8157        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 8158            active_diagnostics
 8159                .primary_range
 8160                .to_offset(&buffer)
 8161                .to_inclusive()
 8162        });
 8163        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 8164            if active_primary_range.contains(&selection.head()) {
 8165                *active_primary_range.start()
 8166            } else {
 8167                selection.head()
 8168            }
 8169        } else {
 8170            selection.head()
 8171        };
 8172        let snapshot = self.snapshot(cx);
 8173        loop {
 8174            let diagnostics = if direction == Direction::Prev {
 8175                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 8176            } else {
 8177                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 8178            }
 8179            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 8180            let group = diagnostics
 8181                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 8182                // be sorted in a stable way
 8183                // skip until we are at current active diagnostic, if it exists
 8184                .skip_while(|entry| {
 8185                    (match direction {
 8186                        Direction::Prev => entry.range.start >= search_start,
 8187                        Direction::Next => entry.range.start <= search_start,
 8188                    }) && self
 8189                        .active_diagnostics
 8190                        .as_ref()
 8191                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 8192                })
 8193                .find_map(|entry| {
 8194                    if entry.diagnostic.is_primary
 8195                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 8196                        && !entry.range.is_empty()
 8197                        // if we match with the active diagnostic, skip it
 8198                        && Some(entry.diagnostic.group_id)
 8199                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 8200                    {
 8201                        Some((entry.range, entry.diagnostic.group_id))
 8202                    } else {
 8203                        None
 8204                    }
 8205                });
 8206
 8207            if let Some((primary_range, group_id)) = group {
 8208                if self.activate_diagnostics(group_id, cx) {
 8209                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8210                        s.select(vec![Selection {
 8211                            id: selection.id,
 8212                            start: primary_range.start,
 8213                            end: primary_range.start,
 8214                            reversed: false,
 8215                            goal: SelectionGoal::None,
 8216                        }]);
 8217                    });
 8218                }
 8219                break;
 8220            } else {
 8221                // Cycle around to the start of the buffer, potentially moving back to the start of
 8222                // the currently active diagnostic.
 8223                active_primary_range.take();
 8224                if direction == Direction::Prev {
 8225                    if search_start == buffer.len() {
 8226                        break;
 8227                    } else {
 8228                        search_start = buffer.len();
 8229                    }
 8230                } else if search_start == 0 {
 8231                    break;
 8232                } else {
 8233                    search_start = 0;
 8234                }
 8235            }
 8236        }
 8237    }
 8238
 8239    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 8240        let snapshot = self
 8241            .display_map
 8242            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8243        let selection = self.selections.newest::<Point>(cx);
 8244
 8245        if !self.seek_in_direction(
 8246            &snapshot,
 8247            selection.head(),
 8248            false,
 8249            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8250                MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
 8251            ),
 8252            cx,
 8253        ) {
 8254            let wrapped_point = Point::zero();
 8255            self.seek_in_direction(
 8256                &snapshot,
 8257                wrapped_point,
 8258                true,
 8259                snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8260                    MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 8261                ),
 8262                cx,
 8263            );
 8264        }
 8265    }
 8266
 8267    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 8268        let snapshot = self
 8269            .display_map
 8270            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8271        let selection = self.selections.newest::<Point>(cx);
 8272
 8273        if !self.seek_in_direction(
 8274            &snapshot,
 8275            selection.head(),
 8276            false,
 8277            snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8278                MultiBufferRow(0)..MultiBufferRow(selection.head().row),
 8279            ),
 8280            cx,
 8281        ) {
 8282            let wrapped_point = snapshot.buffer_snapshot.max_point();
 8283            self.seek_in_direction(
 8284                &snapshot,
 8285                wrapped_point,
 8286                true,
 8287                snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8288                    MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
 8289                ),
 8290                cx,
 8291            );
 8292        }
 8293    }
 8294
 8295    fn seek_in_direction(
 8296        &mut self,
 8297        snapshot: &DisplaySnapshot,
 8298        initial_point: Point,
 8299        is_wrapped: bool,
 8300        hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
 8301        cx: &mut ViewContext<Editor>,
 8302    ) -> bool {
 8303        let display_point = initial_point.to_display_point(snapshot);
 8304        let mut hunks = hunks
 8305            .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
 8306            .filter(|hunk| {
 8307                if is_wrapped {
 8308                    true
 8309                } else {
 8310                    !hunk.contains_display_row(display_point.row())
 8311                }
 8312            })
 8313            .dedup();
 8314
 8315        if let Some(hunk) = hunks.next() {
 8316            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8317                let row = hunk.start_display_row();
 8318                let point = DisplayPoint::new(row, 0);
 8319                s.select_display_ranges([point..point]);
 8320            });
 8321
 8322            true
 8323        } else {
 8324            false
 8325        }
 8326    }
 8327
 8328    pub fn go_to_definition(
 8329        &mut self,
 8330        _: &GoToDefinition,
 8331        cx: &mut ViewContext<Self>,
 8332    ) -> Task<Result<bool>> {
 8333        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
 8334    }
 8335
 8336    pub fn go_to_implementation(
 8337        &mut self,
 8338        _: &GoToImplementation,
 8339        cx: &mut ViewContext<Self>,
 8340    ) -> Task<Result<bool>> {
 8341        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 8342    }
 8343
 8344    pub fn go_to_implementation_split(
 8345        &mut self,
 8346        _: &GoToImplementationSplit,
 8347        cx: &mut ViewContext<Self>,
 8348    ) -> Task<Result<bool>> {
 8349        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 8350    }
 8351
 8352    pub fn go_to_type_definition(
 8353        &mut self,
 8354        _: &GoToTypeDefinition,
 8355        cx: &mut ViewContext<Self>,
 8356    ) -> Task<Result<bool>> {
 8357        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 8358    }
 8359
 8360    pub fn go_to_definition_split(
 8361        &mut self,
 8362        _: &GoToDefinitionSplit,
 8363        cx: &mut ViewContext<Self>,
 8364    ) -> Task<Result<bool>> {
 8365        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 8366    }
 8367
 8368    pub fn go_to_type_definition_split(
 8369        &mut self,
 8370        _: &GoToTypeDefinitionSplit,
 8371        cx: &mut ViewContext<Self>,
 8372    ) -> Task<Result<bool>> {
 8373        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 8374    }
 8375
 8376    fn go_to_definition_of_kind(
 8377        &mut self,
 8378        kind: GotoDefinitionKind,
 8379        split: bool,
 8380        cx: &mut ViewContext<Self>,
 8381    ) -> Task<Result<bool>> {
 8382        let Some(workspace) = self.workspace() else {
 8383            return Task::ready(Ok(false));
 8384        };
 8385        let buffer = self.buffer.read(cx);
 8386        let head = self.selections.newest::<usize>(cx).head();
 8387        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 8388            text_anchor
 8389        } else {
 8390            return Task::ready(Ok(false));
 8391        };
 8392
 8393        let project = workspace.read(cx).project().clone();
 8394        let definitions = project.update(cx, |project, cx| match kind {
 8395            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 8396            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 8397            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 8398        });
 8399
 8400        cx.spawn(|editor, mut cx| async move {
 8401            let definitions = definitions.await?;
 8402            let navigated = editor
 8403                .update(&mut cx, |editor, cx| {
 8404                    editor.navigate_to_hover_links(
 8405                        Some(kind),
 8406                        definitions
 8407                            .into_iter()
 8408                            .filter(|location| {
 8409                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 8410                            })
 8411                            .map(HoverLink::Text)
 8412                            .collect::<Vec<_>>(),
 8413                        split,
 8414                        cx,
 8415                    )
 8416                })?
 8417                .await?;
 8418            anyhow::Ok(navigated)
 8419        })
 8420    }
 8421
 8422    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 8423        let position = self.selections.newest_anchor().head();
 8424        let Some((buffer, buffer_position)) =
 8425            self.buffer.read(cx).text_anchor_for_position(position, cx)
 8426        else {
 8427            return;
 8428        };
 8429
 8430        cx.spawn(|editor, mut cx| async move {
 8431            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 8432                editor.update(&mut cx, |_, cx| {
 8433                    cx.open_url(&url);
 8434                })
 8435            } else {
 8436                Ok(())
 8437            }
 8438        })
 8439        .detach();
 8440    }
 8441
 8442    pub(crate) fn navigate_to_hover_links(
 8443        &mut self,
 8444        kind: Option<GotoDefinitionKind>,
 8445        mut definitions: Vec<HoverLink>,
 8446        split: bool,
 8447        cx: &mut ViewContext<Editor>,
 8448    ) -> Task<Result<bool>> {
 8449        // If there is one definition, just open it directly
 8450        if definitions.len() == 1 {
 8451            let definition = definitions.pop().unwrap();
 8452            let target_task = match definition {
 8453                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 8454                HoverLink::InlayHint(lsp_location, server_id) => {
 8455                    self.compute_target_location(lsp_location, server_id, cx)
 8456                }
 8457                HoverLink::Url(url) => {
 8458                    cx.open_url(&url);
 8459                    Task::ready(Ok(None))
 8460                }
 8461            };
 8462            cx.spawn(|editor, mut cx| async move {
 8463                let target = target_task.await.context("target resolution task")?;
 8464                if let Some(target) = target {
 8465                    editor.update(&mut cx, |editor, cx| {
 8466                        let Some(workspace) = editor.workspace() else {
 8467                            return false;
 8468                        };
 8469                        let pane = workspace.read(cx).active_pane().clone();
 8470
 8471                        let range = target.range.to_offset(target.buffer.read(cx));
 8472                        let range = editor.range_for_match(&range);
 8473
 8474                        /// If select range has more than one line, we
 8475                        /// just point the cursor to range.start.
 8476                        fn check_multiline_range(
 8477                            buffer: &Buffer,
 8478                            range: Range<usize>,
 8479                        ) -> Range<usize> {
 8480                            if buffer.offset_to_point(range.start).row
 8481                                == buffer.offset_to_point(range.end).row
 8482                            {
 8483                                range
 8484                            } else {
 8485                                range.start..range.start
 8486                            }
 8487                        }
 8488
 8489                        if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 8490                            let buffer = target.buffer.read(cx);
 8491                            let range = check_multiline_range(buffer, range);
 8492                            editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
 8493                                s.select_ranges([range]);
 8494                            });
 8495                        } else {
 8496                            cx.window_context().defer(move |cx| {
 8497                                let target_editor: View<Self> =
 8498                                    workspace.update(cx, |workspace, cx| {
 8499                                        let pane = if split {
 8500                                            workspace.adjacent_pane(cx)
 8501                                        } else {
 8502                                            workspace.active_pane().clone()
 8503                                        };
 8504
 8505                                        workspace.open_project_item(pane, target.buffer.clone(), cx)
 8506                                    });
 8507                                target_editor.update(cx, |target_editor, cx| {
 8508                                    // When selecting a definition in a different buffer, disable the nav history
 8509                                    // to avoid creating a history entry at the previous cursor location.
 8510                                    pane.update(cx, |pane, _| pane.disable_history());
 8511                                    let buffer = target.buffer.read(cx);
 8512                                    let range = check_multiline_range(buffer, range);
 8513                                    target_editor.change_selections(
 8514                                        Some(Autoscroll::focused()),
 8515                                        cx,
 8516                                        |s| {
 8517                                            s.select_ranges([range]);
 8518                                        },
 8519                                    );
 8520                                    pane.update(cx, |pane, _| pane.enable_history());
 8521                                });
 8522                            });
 8523                        }
 8524                        true
 8525                    })
 8526                } else {
 8527                    Ok(false)
 8528                }
 8529            })
 8530        } else if !definitions.is_empty() {
 8531            let replica_id = self.replica_id(cx);
 8532            cx.spawn(|editor, mut cx| async move {
 8533                let (title, location_tasks, workspace) = editor
 8534                    .update(&mut cx, |editor, cx| {
 8535                        let tab_kind = match kind {
 8536                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 8537                            _ => "Definitions",
 8538                        };
 8539                        let title = definitions
 8540                            .iter()
 8541                            .find_map(|definition| match definition {
 8542                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 8543                                    let buffer = origin.buffer.read(cx);
 8544                                    format!(
 8545                                        "{} for {}",
 8546                                        tab_kind,
 8547                                        buffer
 8548                                            .text_for_range(origin.range.clone())
 8549                                            .collect::<String>()
 8550                                    )
 8551                                }),
 8552                                HoverLink::InlayHint(_, _) => None,
 8553                                HoverLink::Url(_) => None,
 8554                            })
 8555                            .unwrap_or(tab_kind.to_string());
 8556                        let location_tasks = definitions
 8557                            .into_iter()
 8558                            .map(|definition| match definition {
 8559                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 8560                                HoverLink::InlayHint(lsp_location, server_id) => {
 8561                                    editor.compute_target_location(lsp_location, server_id, cx)
 8562                                }
 8563                                HoverLink::Url(_) => Task::ready(Ok(None)),
 8564                            })
 8565                            .collect::<Vec<_>>();
 8566                        (title, location_tasks, editor.workspace().clone())
 8567                    })
 8568                    .context("location tasks preparation")?;
 8569
 8570                let locations = futures::future::join_all(location_tasks)
 8571                    .await
 8572                    .into_iter()
 8573                    .filter_map(|location| location.transpose())
 8574                    .collect::<Result<_>>()
 8575                    .context("location tasks")?;
 8576
 8577                let Some(workspace) = workspace else {
 8578                    return Ok(false);
 8579                };
 8580                let opened = workspace
 8581                    .update(&mut cx, |workspace, cx| {
 8582                        Self::open_locations_in_multibuffer(
 8583                            workspace, locations, replica_id, title, split, cx,
 8584                        )
 8585                    })
 8586                    .ok();
 8587
 8588                anyhow::Ok(opened.is_some())
 8589            })
 8590        } else {
 8591            Task::ready(Ok(false))
 8592        }
 8593    }
 8594
 8595    fn compute_target_location(
 8596        &self,
 8597        lsp_location: lsp::Location,
 8598        server_id: LanguageServerId,
 8599        cx: &mut ViewContext<Editor>,
 8600    ) -> Task<anyhow::Result<Option<Location>>> {
 8601        let Some(project) = self.project.clone() else {
 8602            return Task::Ready(Some(Ok(None)));
 8603        };
 8604
 8605        cx.spawn(move |editor, mut cx| async move {
 8606            let location_task = editor.update(&mut cx, |editor, cx| {
 8607                project.update(cx, |project, cx| {
 8608                    let language_server_name =
 8609                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 8610                            project
 8611                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 8612                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 8613                        });
 8614                    language_server_name.map(|language_server_name| {
 8615                        project.open_local_buffer_via_lsp(
 8616                            lsp_location.uri.clone(),
 8617                            server_id,
 8618                            language_server_name,
 8619                            cx,
 8620                        )
 8621                    })
 8622                })
 8623            })?;
 8624            let location = match location_task {
 8625                Some(task) => Some({
 8626                    let target_buffer_handle = task.await.context("open local buffer")?;
 8627                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 8628                        let target_start = target_buffer
 8629                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 8630                        let target_end = target_buffer
 8631                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 8632                        target_buffer.anchor_after(target_start)
 8633                            ..target_buffer.anchor_before(target_end)
 8634                    })?;
 8635                    Location {
 8636                        buffer: target_buffer_handle,
 8637                        range,
 8638                    }
 8639                }),
 8640                None => None,
 8641            };
 8642            Ok(location)
 8643        })
 8644    }
 8645
 8646    pub fn find_all_references(
 8647        &mut self,
 8648        _: &FindAllReferences,
 8649        cx: &mut ViewContext<Self>,
 8650    ) -> Option<Task<Result<()>>> {
 8651        let multi_buffer = self.buffer.read(cx);
 8652        let selection = self.selections.newest::<usize>(cx);
 8653        let head = selection.head();
 8654
 8655        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 8656        let head_anchor = multi_buffer_snapshot.anchor_at(
 8657            head,
 8658            if head < selection.tail() {
 8659                Bias::Right
 8660            } else {
 8661                Bias::Left
 8662            },
 8663        );
 8664
 8665        match self
 8666            .find_all_references_task_sources
 8667            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 8668        {
 8669            Ok(_) => {
 8670                log::info!(
 8671                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 8672                );
 8673                return None;
 8674            }
 8675            Err(i) => {
 8676                self.find_all_references_task_sources.insert(i, head_anchor);
 8677            }
 8678        }
 8679
 8680        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 8681        let replica_id = self.replica_id(cx);
 8682        let workspace = self.workspace()?;
 8683        let project = workspace.read(cx).project().clone();
 8684        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 8685        Some(cx.spawn(|editor, mut cx| async move {
 8686            let _cleanup = defer({
 8687                let mut cx = cx.clone();
 8688                move || {
 8689                    let _ = editor.update(&mut cx, |editor, _| {
 8690                        if let Ok(i) =
 8691                            editor
 8692                                .find_all_references_task_sources
 8693                                .binary_search_by(|anchor| {
 8694                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 8695                                })
 8696                        {
 8697                            editor.find_all_references_task_sources.remove(i);
 8698                        }
 8699                    });
 8700                }
 8701            });
 8702
 8703            let locations = references.await?;
 8704            if locations.is_empty() {
 8705                return anyhow::Ok(());
 8706            }
 8707
 8708            workspace.update(&mut cx, |workspace, cx| {
 8709                let title = locations
 8710                    .first()
 8711                    .as_ref()
 8712                    .map(|location| {
 8713                        let buffer = location.buffer.read(cx);
 8714                        format!(
 8715                            "References to `{}`",
 8716                            buffer
 8717                                .text_for_range(location.range.clone())
 8718                                .collect::<String>()
 8719                        )
 8720                    })
 8721                    .unwrap();
 8722                Self::open_locations_in_multibuffer(
 8723                    workspace, locations, replica_id, title, false, cx,
 8724                );
 8725            })
 8726        }))
 8727    }
 8728
 8729    /// Opens a multibuffer with the given project locations in it
 8730    pub fn open_locations_in_multibuffer(
 8731        workspace: &mut Workspace,
 8732        mut locations: Vec<Location>,
 8733        replica_id: ReplicaId,
 8734        title: String,
 8735        split: bool,
 8736        cx: &mut ViewContext<Workspace>,
 8737    ) {
 8738        // If there are multiple definitions, open them in a multibuffer
 8739        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 8740        let mut locations = locations.into_iter().peekable();
 8741        let mut ranges_to_highlight = Vec::new();
 8742        let capability = workspace.project().read(cx).capability();
 8743
 8744        let excerpt_buffer = cx.new_model(|cx| {
 8745            let mut multibuffer = MultiBuffer::new(replica_id, capability);
 8746            while let Some(location) = locations.next() {
 8747                let buffer = location.buffer.read(cx);
 8748                let mut ranges_for_buffer = Vec::new();
 8749                let range = location.range.to_offset(buffer);
 8750                ranges_for_buffer.push(range.clone());
 8751
 8752                while let Some(next_location) = locations.peek() {
 8753                    if next_location.buffer == location.buffer {
 8754                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 8755                        locations.next();
 8756                    } else {
 8757                        break;
 8758                    }
 8759                }
 8760
 8761                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 8762                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 8763                    location.buffer.clone(),
 8764                    ranges_for_buffer,
 8765                    DEFAULT_MULTIBUFFER_CONTEXT,
 8766                    cx,
 8767                ))
 8768            }
 8769
 8770            multibuffer.with_title(title)
 8771        });
 8772
 8773        let editor = cx.new_view(|cx| {
 8774            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), cx)
 8775        });
 8776        editor.update(cx, |editor, cx| {
 8777            editor.highlight_background::<Self>(
 8778                &ranges_to_highlight,
 8779                |theme| theme.editor_highlighted_line_background,
 8780                cx,
 8781            );
 8782        });
 8783
 8784        let item = Box::new(editor);
 8785        let item_id = item.item_id();
 8786
 8787        if split {
 8788            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 8789        } else {
 8790            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 8791                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 8792                    pane.close_current_preview_item(cx)
 8793                } else {
 8794                    None
 8795                }
 8796            });
 8797            workspace.add_item_to_active_pane(item.clone(), destination_index, cx);
 8798        }
 8799        workspace.active_pane().update(cx, |pane, cx| {
 8800            pane.set_preview_item_id(Some(item_id), cx);
 8801        });
 8802    }
 8803
 8804    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 8805        use language::ToOffset as _;
 8806
 8807        let project = self.project.clone()?;
 8808        let selection = self.selections.newest_anchor().clone();
 8809        let (cursor_buffer, cursor_buffer_position) = self
 8810            .buffer
 8811            .read(cx)
 8812            .text_anchor_for_position(selection.head(), cx)?;
 8813        let (tail_buffer, cursor_buffer_position_end) = self
 8814            .buffer
 8815            .read(cx)
 8816            .text_anchor_for_position(selection.tail(), cx)?;
 8817        if tail_buffer != cursor_buffer {
 8818            return None;
 8819        }
 8820
 8821        let snapshot = cursor_buffer.read(cx).snapshot();
 8822        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 8823        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 8824        let prepare_rename = project.update(cx, |project, cx| {
 8825            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
 8826        });
 8827        drop(snapshot);
 8828
 8829        Some(cx.spawn(|this, mut cx| async move {
 8830            let rename_range = if let Some(range) = prepare_rename.await? {
 8831                Some(range)
 8832            } else {
 8833                this.update(&mut cx, |this, cx| {
 8834                    let buffer = this.buffer.read(cx).snapshot(cx);
 8835                    let mut buffer_highlights = this
 8836                        .document_highlights_for_position(selection.head(), &buffer)
 8837                        .filter(|highlight| {
 8838                            highlight.start.excerpt_id == selection.head().excerpt_id
 8839                                && highlight.end.excerpt_id == selection.head().excerpt_id
 8840                        });
 8841                    buffer_highlights
 8842                        .next()
 8843                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 8844                })?
 8845            };
 8846            if let Some(rename_range) = rename_range {
 8847                this.update(&mut cx, |this, cx| {
 8848                    let snapshot = cursor_buffer.read(cx).snapshot();
 8849                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 8850                    let cursor_offset_in_rename_range =
 8851                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 8852                    let cursor_offset_in_rename_range_end =
 8853                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 8854
 8855                    this.take_rename(false, cx);
 8856                    let buffer = this.buffer.read(cx).read(cx);
 8857                    let cursor_offset = selection.head().to_offset(&buffer);
 8858                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 8859                    let rename_end = rename_start + rename_buffer_range.len();
 8860                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 8861                    let mut old_highlight_id = None;
 8862                    let old_name: Arc<str> = buffer
 8863                        .chunks(rename_start..rename_end, true)
 8864                        .map(|chunk| {
 8865                            if old_highlight_id.is_none() {
 8866                                old_highlight_id = chunk.syntax_highlight_id;
 8867                            }
 8868                            chunk.text
 8869                        })
 8870                        .collect::<String>()
 8871                        .into();
 8872
 8873                    drop(buffer);
 8874
 8875                    // Position the selection in the rename editor so that it matches the current selection.
 8876                    this.show_local_selections = false;
 8877                    let rename_editor = cx.new_view(|cx| {
 8878                        let mut editor = Editor::single_line(cx);
 8879                        editor.buffer.update(cx, |buffer, cx| {
 8880                            buffer.edit([(0..0, old_name.clone())], None, cx)
 8881                        });
 8882                        let rename_selection_range = match cursor_offset_in_rename_range
 8883                            .cmp(&cursor_offset_in_rename_range_end)
 8884                        {
 8885                            Ordering::Equal => {
 8886                                editor.select_all(&SelectAll, cx);
 8887                                return editor;
 8888                            }
 8889                            Ordering::Less => {
 8890                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 8891                            }
 8892                            Ordering::Greater => {
 8893                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 8894                            }
 8895                        };
 8896                        if rename_selection_range.end > old_name.len() {
 8897                            editor.select_all(&SelectAll, cx);
 8898                        } else {
 8899                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8900                                s.select_ranges([rename_selection_range]);
 8901                            });
 8902                        }
 8903                        editor
 8904                    });
 8905
 8906                    let write_highlights =
 8907                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 8908                    let read_highlights =
 8909                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 8910                    let ranges = write_highlights
 8911                        .iter()
 8912                        .flat_map(|(_, ranges)| ranges.iter())
 8913                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 8914                        .cloned()
 8915                        .collect();
 8916
 8917                    this.highlight_text::<Rename>(
 8918                        ranges,
 8919                        HighlightStyle {
 8920                            fade_out: Some(0.6),
 8921                            ..Default::default()
 8922                        },
 8923                        cx,
 8924                    );
 8925                    let rename_focus_handle = rename_editor.focus_handle(cx);
 8926                    cx.focus(&rename_focus_handle);
 8927                    let block_id = this.insert_blocks(
 8928                        [BlockProperties {
 8929                            style: BlockStyle::Flex,
 8930                            position: range.start,
 8931                            height: 1,
 8932                            render: Box::new({
 8933                                let rename_editor = rename_editor.clone();
 8934                                move |cx: &mut BlockContext| {
 8935                                    let mut text_style = cx.editor_style.text.clone();
 8936                                    if let Some(highlight_style) = old_highlight_id
 8937                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 8938                                    {
 8939                                        text_style = text_style.highlight(highlight_style);
 8940                                    }
 8941                                    div()
 8942                                        .pl(cx.anchor_x)
 8943                                        .child(EditorElement::new(
 8944                                            &rename_editor,
 8945                                            EditorStyle {
 8946                                                background: cx.theme().system().transparent,
 8947                                                local_player: cx.editor_style.local_player,
 8948                                                text: text_style,
 8949                                                scrollbar_width: cx.editor_style.scrollbar_width,
 8950                                                syntax: cx.editor_style.syntax.clone(),
 8951                                                status: cx.editor_style.status.clone(),
 8952                                                inlay_hints_style: HighlightStyle {
 8953                                                    color: Some(cx.theme().status().hint),
 8954                                                    font_weight: Some(FontWeight::BOLD),
 8955                                                    ..HighlightStyle::default()
 8956                                                },
 8957                                                suggestions_style: HighlightStyle {
 8958                                                    color: Some(cx.theme().status().predictive),
 8959                                                    ..HighlightStyle::default()
 8960                                                },
 8961                                            },
 8962                                        ))
 8963                                        .into_any_element()
 8964                                }
 8965                            }),
 8966                            disposition: BlockDisposition::Below,
 8967                        }],
 8968                        Some(Autoscroll::fit()),
 8969                        cx,
 8970                    )[0];
 8971                    this.pending_rename = Some(RenameState {
 8972                        range,
 8973                        old_name,
 8974                        editor: rename_editor,
 8975                        block_id,
 8976                    });
 8977                })?;
 8978            }
 8979
 8980            Ok(())
 8981        }))
 8982    }
 8983
 8984    pub fn confirm_rename(
 8985        &mut self,
 8986        _: &ConfirmRename,
 8987        cx: &mut ViewContext<Self>,
 8988    ) -> Option<Task<Result<()>>> {
 8989        let rename = self.take_rename(false, cx)?;
 8990        let workspace = self.workspace()?;
 8991        let (start_buffer, start) = self
 8992            .buffer
 8993            .read(cx)
 8994            .text_anchor_for_position(rename.range.start, cx)?;
 8995        let (end_buffer, end) = self
 8996            .buffer
 8997            .read(cx)
 8998            .text_anchor_for_position(rename.range.end, cx)?;
 8999        if start_buffer != end_buffer {
 9000            return None;
 9001        }
 9002
 9003        let buffer = start_buffer;
 9004        let range = start..end;
 9005        let old_name = rename.old_name;
 9006        let new_name = rename.editor.read(cx).text(cx);
 9007
 9008        let rename = workspace
 9009            .read(cx)
 9010            .project()
 9011            .clone()
 9012            .update(cx, |project, cx| {
 9013                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
 9014            });
 9015        let workspace = workspace.downgrade();
 9016
 9017        Some(cx.spawn(|editor, mut cx| async move {
 9018            let project_transaction = rename.await?;
 9019            Self::open_project_transaction(
 9020                &editor,
 9021                workspace,
 9022                project_transaction,
 9023                format!("Rename: {}{}", old_name, new_name),
 9024                cx.clone(),
 9025            )
 9026            .await?;
 9027
 9028            editor.update(&mut cx, |editor, cx| {
 9029                editor.refresh_document_highlights(cx);
 9030            })?;
 9031            Ok(())
 9032        }))
 9033    }
 9034
 9035    fn take_rename(
 9036        &mut self,
 9037        moving_cursor: bool,
 9038        cx: &mut ViewContext<Self>,
 9039    ) -> Option<RenameState> {
 9040        let rename = self.pending_rename.take()?;
 9041        if rename.editor.focus_handle(cx).is_focused(cx) {
 9042            cx.focus(&self.focus_handle);
 9043        }
 9044
 9045        self.remove_blocks(
 9046            [rename.block_id].into_iter().collect(),
 9047            Some(Autoscroll::fit()),
 9048            cx,
 9049        );
 9050        self.clear_highlights::<Rename>(cx);
 9051        self.show_local_selections = true;
 9052
 9053        if moving_cursor {
 9054            let rename_editor = rename.editor.read(cx);
 9055            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
 9056
 9057            // Update the selection to match the position of the selection inside
 9058            // the rename editor.
 9059            let snapshot = self.buffer.read(cx).read(cx);
 9060            let rename_range = rename.range.to_offset(&snapshot);
 9061            let cursor_in_editor = snapshot
 9062                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 9063                .min(rename_range.end);
 9064            drop(snapshot);
 9065
 9066            self.change_selections(None, cx, |s| {
 9067                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 9068            });
 9069        } else {
 9070            self.refresh_document_highlights(cx);
 9071        }
 9072
 9073        Some(rename)
 9074    }
 9075
 9076    pub fn pending_rename(&self) -> Option<&RenameState> {
 9077        self.pending_rename.as_ref()
 9078    }
 9079
 9080    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9081        let project = match &self.project {
 9082            Some(project) => project.clone(),
 9083            None => return None,
 9084        };
 9085
 9086        Some(self.perform_format(project, FormatTrigger::Manual, cx))
 9087    }
 9088
 9089    fn perform_format(
 9090        &mut self,
 9091        project: Model<Project>,
 9092        trigger: FormatTrigger,
 9093        cx: &mut ViewContext<Self>,
 9094    ) -> Task<Result<()>> {
 9095        let buffer = self.buffer().clone();
 9096        let mut buffers = buffer.read(cx).all_buffers();
 9097        if trigger == FormatTrigger::Save {
 9098            buffers.retain(|buffer| buffer.read(cx).is_dirty());
 9099        }
 9100
 9101        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
 9102        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
 9103
 9104        cx.spawn(|_, mut cx| async move {
 9105            let transaction = futures::select_biased! {
 9106                () = timeout => {
 9107                    log::warn!("timed out waiting for formatting");
 9108                    None
 9109                }
 9110                transaction = format.log_err().fuse() => transaction,
 9111            };
 9112
 9113            buffer
 9114                .update(&mut cx, |buffer, cx| {
 9115                    if let Some(transaction) = transaction {
 9116                        if !buffer.is_singleton() {
 9117                            buffer.push_transaction(&transaction.0, cx);
 9118                        }
 9119                    }
 9120
 9121                    cx.notify();
 9122                })
 9123                .ok();
 9124
 9125            Ok(())
 9126        })
 9127    }
 9128
 9129    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
 9130        if let Some(project) = self.project.clone() {
 9131            self.buffer.update(cx, |multi_buffer, cx| {
 9132                project.update(cx, |project, cx| {
 9133                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
 9134                });
 9135            })
 9136        }
 9137    }
 9138
 9139    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
 9140        cx.show_character_palette();
 9141    }
 9142
 9143    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
 9144        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
 9145            let buffer = self.buffer.read(cx).snapshot(cx);
 9146            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
 9147            let is_valid = buffer
 9148                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
 9149                .any(|entry| {
 9150                    entry.diagnostic.is_primary
 9151                        && !entry.range.is_empty()
 9152                        && entry.range.start == primary_range_start
 9153                        && entry.diagnostic.message == active_diagnostics.primary_message
 9154                });
 9155
 9156            if is_valid != active_diagnostics.is_valid {
 9157                active_diagnostics.is_valid = is_valid;
 9158                let mut new_styles = HashMap::default();
 9159                for (block_id, diagnostic) in &active_diagnostics.blocks {
 9160                    new_styles.insert(
 9161                        *block_id,
 9162                        diagnostic_block_renderer(diagnostic.clone(), is_valid),
 9163                    );
 9164                }
 9165                self.display_map
 9166                    .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
 9167            }
 9168        }
 9169    }
 9170
 9171    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
 9172        self.dismiss_diagnostics(cx);
 9173        let snapshot = self.snapshot(cx);
 9174        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
 9175            let buffer = self.buffer.read(cx).snapshot(cx);
 9176
 9177            let mut primary_range = None;
 9178            let mut primary_message = None;
 9179            let mut group_end = Point::zero();
 9180            let diagnostic_group = buffer
 9181                .diagnostic_group::<MultiBufferPoint>(group_id)
 9182                .filter_map(|entry| {
 9183                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
 9184                        && (entry.range.start.row == entry.range.end.row
 9185                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
 9186                    {
 9187                        return None;
 9188                    }
 9189                    if entry.range.end > group_end {
 9190                        group_end = entry.range.end;
 9191                    }
 9192                    if entry.diagnostic.is_primary {
 9193                        primary_range = Some(entry.range.clone());
 9194                        primary_message = Some(entry.diagnostic.message.clone());
 9195                    }
 9196                    Some(entry)
 9197                })
 9198                .collect::<Vec<_>>();
 9199            let primary_range = primary_range?;
 9200            let primary_message = primary_message?;
 9201            let primary_range =
 9202                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
 9203
 9204            let blocks = display_map
 9205                .insert_blocks(
 9206                    diagnostic_group.iter().map(|entry| {
 9207                        let diagnostic = entry.diagnostic.clone();
 9208                        let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
 9209                        BlockProperties {
 9210                            style: BlockStyle::Fixed,
 9211                            position: buffer.anchor_after(entry.range.start),
 9212                            height: message_height,
 9213                            render: diagnostic_block_renderer(diagnostic, true),
 9214                            disposition: BlockDisposition::Below,
 9215                        }
 9216                    }),
 9217                    cx,
 9218                )
 9219                .into_iter()
 9220                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
 9221                .collect();
 9222
 9223            Some(ActiveDiagnosticGroup {
 9224                primary_range,
 9225                primary_message,
 9226                group_id,
 9227                blocks,
 9228                is_valid: true,
 9229            })
 9230        });
 9231        self.active_diagnostics.is_some()
 9232    }
 9233
 9234    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
 9235        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
 9236            self.display_map.update(cx, |display_map, cx| {
 9237                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
 9238            });
 9239            cx.notify();
 9240        }
 9241    }
 9242
 9243    pub fn set_selections_from_remote(
 9244        &mut self,
 9245        selections: Vec<Selection<Anchor>>,
 9246        pending_selection: Option<Selection<Anchor>>,
 9247        cx: &mut ViewContext<Self>,
 9248    ) {
 9249        let old_cursor_position = self.selections.newest_anchor().head();
 9250        self.selections.change_with(cx, |s| {
 9251            s.select_anchors(selections);
 9252            if let Some(pending_selection) = pending_selection {
 9253                s.set_pending(pending_selection, SelectMode::Character);
 9254            } else {
 9255                s.clear_pending();
 9256            }
 9257        });
 9258        self.selections_did_change(false, &old_cursor_position, true, cx);
 9259    }
 9260
 9261    fn push_to_selection_history(&mut self) {
 9262        self.selection_history.push(SelectionHistoryEntry {
 9263            selections: self.selections.disjoint_anchors(),
 9264            select_next_state: self.select_next_state.clone(),
 9265            select_prev_state: self.select_prev_state.clone(),
 9266            add_selections_state: self.add_selections_state.clone(),
 9267        });
 9268    }
 9269
 9270    pub fn transact(
 9271        &mut self,
 9272        cx: &mut ViewContext<Self>,
 9273        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
 9274    ) -> Option<TransactionId> {
 9275        self.start_transaction_at(Instant::now(), cx);
 9276        update(self, cx);
 9277        self.end_transaction_at(Instant::now(), cx)
 9278    }
 9279
 9280    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
 9281        self.end_selection(cx);
 9282        if let Some(tx_id) = self
 9283            .buffer
 9284            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
 9285        {
 9286            self.selection_history
 9287                .insert_transaction(tx_id, self.selections.disjoint_anchors());
 9288            cx.emit(EditorEvent::TransactionBegun {
 9289                transaction_id: tx_id,
 9290            })
 9291        }
 9292    }
 9293
 9294    fn end_transaction_at(
 9295        &mut self,
 9296        now: Instant,
 9297        cx: &mut ViewContext<Self>,
 9298    ) -> Option<TransactionId> {
 9299        if let Some(tx_id) = self
 9300            .buffer
 9301            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 9302        {
 9303            if let Some((_, end_selections)) = self.selection_history.transaction_mut(tx_id) {
 9304                *end_selections = Some(self.selections.disjoint_anchors());
 9305            } else {
 9306                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
 9307            }
 9308
 9309            cx.emit(EditorEvent::Edited);
 9310            Some(tx_id)
 9311        } else {
 9312            None
 9313        }
 9314    }
 9315
 9316    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
 9317        let mut fold_ranges = Vec::new();
 9318
 9319        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9320
 9321        let selections = self.selections.all_adjusted(cx);
 9322        for selection in selections {
 9323            let range = selection.range().sorted();
 9324            let buffer_start_row = range.start.row;
 9325
 9326            for row in (0..=range.end.row).rev() {
 9327                if let Some((foldable_range, fold_text)) =
 9328                    display_map.foldable_range(MultiBufferRow(row))
 9329                {
 9330                    if foldable_range.end.row >= buffer_start_row {
 9331                        fold_ranges.push((foldable_range, fold_text));
 9332                        if row <= range.start.row {
 9333                            break;
 9334                        }
 9335                    }
 9336                }
 9337            }
 9338        }
 9339
 9340        self.fold_ranges(fold_ranges, true, cx);
 9341    }
 9342
 9343    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
 9344        let buffer_row = fold_at.buffer_row;
 9345        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9346
 9347        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
 9348            let autoscroll = self
 9349                .selections
 9350                .all::<Point>(cx)
 9351                .iter()
 9352                .any(|selection| fold_range.overlaps(&selection.range()));
 9353
 9354            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
 9355        }
 9356    }
 9357
 9358    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
 9359        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9360        let buffer = &display_map.buffer_snapshot;
 9361        let selections = self.selections.all::<Point>(cx);
 9362        let ranges = selections
 9363            .iter()
 9364            .map(|s| {
 9365                let range = s.display_range(&display_map).sorted();
 9366                let mut start = range.start.to_point(&display_map);
 9367                let mut end = range.end.to_point(&display_map);
 9368                start.column = 0;
 9369                end.column = buffer.line_len(MultiBufferRow(end.row));
 9370                start..end
 9371            })
 9372            .collect::<Vec<_>>();
 9373
 9374        self.unfold_ranges(ranges, true, true, cx);
 9375    }
 9376
 9377    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
 9378        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9379
 9380        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
 9381            ..Point::new(
 9382                unfold_at.buffer_row.0,
 9383                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
 9384            );
 9385
 9386        let autoscroll = self
 9387            .selections
 9388            .all::<Point>(cx)
 9389            .iter()
 9390            .any(|selection| selection.range().overlaps(&intersection_range));
 9391
 9392        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
 9393    }
 9394
 9395    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
 9396        let selections = self.selections.all::<Point>(cx);
 9397        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9398        let line_mode = self.selections.line_mode;
 9399        let ranges = selections.into_iter().map(|s| {
 9400            if line_mode {
 9401                let start = Point::new(s.start.row, 0);
 9402                let end = Point::new(
 9403                    s.end.row,
 9404                    display_map
 9405                        .buffer_snapshot
 9406                        .line_len(MultiBufferRow(s.end.row)),
 9407                );
 9408                (start..end, display_map.fold_placeholder.clone())
 9409            } else {
 9410                (s.start..s.end, display_map.fold_placeholder.clone())
 9411            }
 9412        });
 9413        self.fold_ranges(ranges, true, cx);
 9414    }
 9415
 9416    pub fn fold_ranges<T: ToOffset + Clone>(
 9417        &mut self,
 9418        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
 9419        auto_scroll: bool,
 9420        cx: &mut ViewContext<Self>,
 9421    ) {
 9422        let mut fold_ranges = Vec::new();
 9423        let mut buffers_affected = HashMap::default();
 9424        let multi_buffer = self.buffer().read(cx);
 9425        for (fold_range, fold_text) in ranges {
 9426            if let Some((_, buffer, _)) =
 9427                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
 9428            {
 9429                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
 9430            };
 9431            fold_ranges.push((fold_range, fold_text));
 9432        }
 9433
 9434        let mut ranges = fold_ranges.into_iter().peekable();
 9435        if ranges.peek().is_some() {
 9436            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
 9437
 9438            if auto_scroll {
 9439                self.request_autoscroll(Autoscroll::fit(), cx);
 9440            }
 9441
 9442            for buffer in buffers_affected.into_values() {
 9443                self.sync_expanded_diff_hunks(buffer, cx);
 9444            }
 9445
 9446            cx.notify();
 9447
 9448            if let Some(active_diagnostics) = self.active_diagnostics.take() {
 9449                // Clear diagnostics block when folding a range that contains it.
 9450                let snapshot = self.snapshot(cx);
 9451                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
 9452                    drop(snapshot);
 9453                    self.active_diagnostics = Some(active_diagnostics);
 9454                    self.dismiss_diagnostics(cx);
 9455                } else {
 9456                    self.active_diagnostics = Some(active_diagnostics);
 9457                }
 9458            }
 9459
 9460            self.scrollbar_marker_state.dirty = true;
 9461        }
 9462    }
 9463
 9464    pub fn unfold_ranges<T: ToOffset + Clone>(
 9465        &mut self,
 9466        ranges: impl IntoIterator<Item = Range<T>>,
 9467        inclusive: bool,
 9468        auto_scroll: bool,
 9469        cx: &mut ViewContext<Self>,
 9470    ) {
 9471        let mut unfold_ranges = Vec::new();
 9472        let mut buffers_affected = HashMap::default();
 9473        let multi_buffer = self.buffer().read(cx);
 9474        for range in ranges {
 9475            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
 9476                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
 9477            };
 9478            unfold_ranges.push(range);
 9479        }
 9480
 9481        let mut ranges = unfold_ranges.into_iter().peekable();
 9482        if ranges.peek().is_some() {
 9483            self.display_map
 9484                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
 9485            if auto_scroll {
 9486                self.request_autoscroll(Autoscroll::fit(), cx);
 9487            }
 9488
 9489            for buffer in buffers_affected.into_values() {
 9490                self.sync_expanded_diff_hunks(buffer, cx);
 9491            }
 9492
 9493            cx.notify();
 9494            self.scrollbar_marker_state.dirty = true;
 9495            self.active_indent_guides_state.dirty = true;
 9496        }
 9497    }
 9498
 9499    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
 9500        if hovered != self.gutter_hovered {
 9501            self.gutter_hovered = hovered;
 9502            cx.notify();
 9503        }
 9504    }
 9505
 9506    pub fn insert_blocks(
 9507        &mut self,
 9508        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
 9509        autoscroll: Option<Autoscroll>,
 9510        cx: &mut ViewContext<Self>,
 9511    ) -> Vec<BlockId> {
 9512        let blocks = self
 9513            .display_map
 9514            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
 9515        if let Some(autoscroll) = autoscroll {
 9516            self.request_autoscroll(autoscroll, cx);
 9517        }
 9518        blocks
 9519    }
 9520
 9521    pub fn replace_blocks(
 9522        &mut self,
 9523        blocks: HashMap<BlockId, RenderBlock>,
 9524        autoscroll: Option<Autoscroll>,
 9525        cx: &mut ViewContext<Self>,
 9526    ) {
 9527        self.display_map
 9528            .update(cx, |display_map, _| display_map.replace_blocks(blocks));
 9529        if let Some(autoscroll) = autoscroll {
 9530            self.request_autoscroll(autoscroll, cx);
 9531        }
 9532    }
 9533
 9534    pub fn remove_blocks(
 9535        &mut self,
 9536        block_ids: HashSet<BlockId>,
 9537        autoscroll: Option<Autoscroll>,
 9538        cx: &mut ViewContext<Self>,
 9539    ) {
 9540        self.display_map.update(cx, |display_map, cx| {
 9541            display_map.remove_blocks(block_ids, cx)
 9542        });
 9543        if let Some(autoscroll) = autoscroll {
 9544            self.request_autoscroll(autoscroll, cx);
 9545        }
 9546    }
 9547
 9548    pub fn insert_flaps(
 9549        &mut self,
 9550        flaps: impl IntoIterator<Item = Flap>,
 9551        cx: &mut ViewContext<Self>,
 9552    ) -> Vec<FlapId> {
 9553        self.display_map
 9554            .update(cx, |map, cx| map.insert_flaps(flaps, cx))
 9555    }
 9556
 9557    pub fn remove_flaps(
 9558        &mut self,
 9559        ids: impl IntoIterator<Item = FlapId>,
 9560        cx: &mut ViewContext<Self>,
 9561    ) {
 9562        self.display_map
 9563            .update(cx, |map, cx| map.remove_flaps(ids, cx));
 9564    }
 9565
 9566    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
 9567        self.display_map
 9568            .update(cx, |map, cx| map.snapshot(cx))
 9569            .longest_row()
 9570    }
 9571
 9572    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
 9573        self.display_map
 9574            .update(cx, |map, cx| map.snapshot(cx))
 9575            .max_point()
 9576    }
 9577
 9578    pub fn text(&self, cx: &AppContext) -> String {
 9579        self.buffer.read(cx).read(cx).text()
 9580    }
 9581
 9582    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
 9583        let text = self.text(cx);
 9584        let text = text.trim();
 9585
 9586        if text.is_empty() {
 9587            return None;
 9588        }
 9589
 9590        Some(text.to_string())
 9591    }
 9592
 9593    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
 9594        self.transact(cx, |this, cx| {
 9595            this.buffer
 9596                .read(cx)
 9597                .as_singleton()
 9598                .expect("you can only call set_text on editors for singleton buffers")
 9599                .update(cx, |buffer, cx| buffer.set_text(text, cx));
 9600        });
 9601    }
 9602
 9603    pub fn display_text(&self, cx: &mut AppContext) -> String {
 9604        self.display_map
 9605            .update(cx, |map, cx| map.snapshot(cx))
 9606            .text()
 9607    }
 9608
 9609    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
 9610        let mut wrap_guides = smallvec::smallvec![];
 9611
 9612        if self.show_wrap_guides == Some(false) {
 9613            return wrap_guides;
 9614        }
 9615
 9616        let settings = self.buffer.read(cx).settings_at(0, cx);
 9617        if settings.show_wrap_guides {
 9618            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
 9619                wrap_guides.push((soft_wrap as usize, true));
 9620            }
 9621            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
 9622        }
 9623
 9624        wrap_guides
 9625    }
 9626
 9627    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
 9628        let settings = self.buffer.read(cx).settings_at(0, cx);
 9629        let mode = self
 9630            .soft_wrap_mode_override
 9631            .unwrap_or_else(|| settings.soft_wrap);
 9632        match mode {
 9633            language_settings::SoftWrap::None => SoftWrap::None,
 9634            language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
 9635            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
 9636            language_settings::SoftWrap::PreferredLineLength => {
 9637                SoftWrap::Column(settings.preferred_line_length)
 9638            }
 9639        }
 9640    }
 9641
 9642    pub fn set_soft_wrap_mode(
 9643        &mut self,
 9644        mode: language_settings::SoftWrap,
 9645        cx: &mut ViewContext<Self>,
 9646    ) {
 9647        self.soft_wrap_mode_override = Some(mode);
 9648        cx.notify();
 9649    }
 9650
 9651    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
 9652        let rem_size = cx.rem_size();
 9653        self.display_map.update(cx, |map, cx| {
 9654            map.set_font(
 9655                style.text.font(),
 9656                style.text.font_size.to_pixels(rem_size),
 9657                cx,
 9658            )
 9659        });
 9660        self.style = Some(style);
 9661    }
 9662
 9663    pub fn style(&self) -> Option<&EditorStyle> {
 9664        self.style.as_ref()
 9665    }
 9666
 9667    // Called by the element. This method is not designed to be called outside of the editor
 9668    // element's layout code because it does not notify when rewrapping is computed synchronously.
 9669    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
 9670        self.display_map
 9671            .update(cx, |map, cx| map.set_wrap_width(width, cx))
 9672    }
 9673
 9674    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
 9675        if self.soft_wrap_mode_override.is_some() {
 9676            self.soft_wrap_mode_override.take();
 9677        } else {
 9678            let soft_wrap = match self.soft_wrap_mode(cx) {
 9679                SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
 9680                SoftWrap::EditorWidth | SoftWrap::Column(_) => {
 9681                    language_settings::SoftWrap::PreferLine
 9682                }
 9683            };
 9684            self.soft_wrap_mode_override = Some(soft_wrap);
 9685        }
 9686        cx.notify();
 9687    }
 9688
 9689    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
 9690        let currently_enabled = self.should_show_indent_guides(cx);
 9691        self.show_indent_guides = Some(!currently_enabled);
 9692        cx.notify();
 9693    }
 9694
 9695    fn should_show_indent_guides(&self, cx: &mut ViewContext<Self>) -> bool {
 9696        self.show_indent_guides.unwrap_or_else(|| {
 9697            self.buffer
 9698                .read(cx)
 9699                .settings_at(0, cx)
 9700                .indent_guides
 9701                .enabled
 9702        })
 9703    }
 9704
 9705    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
 9706        let mut editor_settings = EditorSettings::get_global(cx).clone();
 9707        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
 9708        EditorSettings::override_global(editor_settings, cx);
 9709    }
 9710
 9711    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
 9712        self.show_gutter = show_gutter;
 9713        cx.notify();
 9714    }
 9715
 9716    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
 9717        self.show_line_numbers = Some(show_line_numbers);
 9718        cx.notify();
 9719    }
 9720
 9721    pub fn set_show_git_diff_gutter(
 9722        &mut self,
 9723        show_git_diff_gutter: bool,
 9724        cx: &mut ViewContext<Self>,
 9725    ) {
 9726        self.show_git_diff_gutter = Some(show_git_diff_gutter);
 9727        cx.notify();
 9728    }
 9729
 9730    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
 9731        self.show_code_actions = Some(show_code_actions);
 9732        cx.notify();
 9733    }
 9734
 9735    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
 9736        self.show_wrap_guides = Some(show_wrap_guides);
 9737        cx.notify();
 9738    }
 9739
 9740    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
 9741        self.show_indent_guides = Some(show_indent_guides);
 9742        cx.notify();
 9743    }
 9744
 9745    pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
 9746        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 9747            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
 9748                cx.reveal_path(&file.abs_path(cx));
 9749            }
 9750        }
 9751    }
 9752
 9753    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
 9754        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 9755            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
 9756                if let Some(path) = file.abs_path(cx).to_str() {
 9757                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
 9758                }
 9759            }
 9760        }
 9761    }
 9762
 9763    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
 9764        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 9765            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
 9766                if let Some(path) = file.path().to_str() {
 9767                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
 9768                }
 9769            }
 9770        }
 9771    }
 9772
 9773    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
 9774        self.show_git_blame_gutter = !self.show_git_blame_gutter;
 9775
 9776        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
 9777            self.start_git_blame(true, cx);
 9778        }
 9779
 9780        cx.notify();
 9781    }
 9782
 9783    pub fn toggle_git_blame_inline(
 9784        &mut self,
 9785        _: &ToggleGitBlameInline,
 9786        cx: &mut ViewContext<Self>,
 9787    ) {
 9788        self.toggle_git_blame_inline_internal(true, cx);
 9789        cx.notify();
 9790    }
 9791
 9792    pub fn git_blame_inline_enabled(&self) -> bool {
 9793        self.git_blame_inline_enabled
 9794    }
 9795
 9796    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
 9797        if let Some(project) = self.project.as_ref() {
 9798            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
 9799                return;
 9800            };
 9801
 9802            if buffer.read(cx).file().is_none() {
 9803                return;
 9804            }
 9805
 9806            let focused = self.focus_handle(cx).contains_focused(cx);
 9807
 9808            let project = project.clone();
 9809            let blame =
 9810                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
 9811            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
 9812            self.blame = Some(blame);
 9813        }
 9814    }
 9815
 9816    fn toggle_git_blame_inline_internal(
 9817        &mut self,
 9818        user_triggered: bool,
 9819        cx: &mut ViewContext<Self>,
 9820    ) {
 9821        if self.git_blame_inline_enabled {
 9822            self.git_blame_inline_enabled = false;
 9823            self.show_git_blame_inline = false;
 9824            self.show_git_blame_inline_delay_task.take();
 9825        } else {
 9826            self.git_blame_inline_enabled = true;
 9827            self.start_git_blame_inline(user_triggered, cx);
 9828        }
 9829
 9830        cx.notify();
 9831    }
 9832
 9833    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
 9834        self.start_git_blame(user_triggered, cx);
 9835
 9836        if ProjectSettings::get_global(cx)
 9837            .git
 9838            .inline_blame_delay()
 9839            .is_some()
 9840        {
 9841            self.start_inline_blame_timer(cx);
 9842        } else {
 9843            self.show_git_blame_inline = true
 9844        }
 9845    }
 9846
 9847    pub fn blame(&self) -> Option<&Model<GitBlame>> {
 9848        self.blame.as_ref()
 9849    }
 9850
 9851    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
 9852        self.show_git_blame_gutter && self.has_blame_entries(cx)
 9853    }
 9854
 9855    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
 9856        self.show_git_blame_inline
 9857            && self.focus_handle.is_focused(cx)
 9858            && !self.newest_selection_head_on_empty_line(cx)
 9859            && self.has_blame_entries(cx)
 9860    }
 9861
 9862    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
 9863        self.blame()
 9864            .map_or(false, |blame| blame.read(cx).has_generated_entries())
 9865    }
 9866
 9867    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
 9868        let cursor_anchor = self.selections.newest_anchor().head();
 9869
 9870        let snapshot = self.buffer.read(cx).snapshot(cx);
 9871        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
 9872
 9873        snapshot.line_len(buffer_row) == 0
 9874    }
 9875
 9876    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
 9877        let (path, repo) = maybe!({
 9878            let project_handle = self.project.as_ref()?.clone();
 9879            let project = project_handle.read(cx);
 9880            let buffer = self.buffer().read(cx).as_singleton()?;
 9881            let path = buffer
 9882                .read(cx)
 9883                .file()?
 9884                .as_local()?
 9885                .path()
 9886                .to_str()?
 9887                .to_string();
 9888            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
 9889            Some((path, repo))
 9890        })
 9891        .ok_or_else(|| anyhow!("unable to open git repository"))?;
 9892
 9893        const REMOTE_NAME: &str = "origin";
 9894        let origin_url = repo
 9895            .lock()
 9896            .remote_url(REMOTE_NAME)
 9897            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
 9898        let sha = repo
 9899            .lock()
 9900            .head_sha()
 9901            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
 9902        let selections = self.selections.all::<Point>(cx);
 9903        let selection = selections.iter().peekable().next();
 9904
 9905        let (provider, remote) =
 9906            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
 9907                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
 9908
 9909        Ok(provider.build_permalink(
 9910            remote,
 9911            BuildPermalinkParams {
 9912                sha: &sha,
 9913                path: &path,
 9914                selection: selection.map(|selection| {
 9915                    let range = selection.range();
 9916                    let start = range.start.row;
 9917                    let end = range.end.row;
 9918                    start..end
 9919                }),
 9920            },
 9921        ))
 9922    }
 9923
 9924    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
 9925        let permalink = self.get_permalink_to_line(cx);
 9926
 9927        match permalink {
 9928            Ok(permalink) => {
 9929                cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
 9930            }
 9931            Err(err) => {
 9932                let message = format!("Failed to copy permalink: {err}");
 9933
 9934                Err::<(), anyhow::Error>(err).log_err();
 9935
 9936                if let Some(workspace) = self.workspace() {
 9937                    workspace.update(cx, |workspace, cx| {
 9938                        struct CopyPermalinkToLine;
 9939
 9940                        workspace.show_toast(
 9941                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
 9942                            cx,
 9943                        )
 9944                    })
 9945                }
 9946            }
 9947        }
 9948    }
 9949
 9950    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
 9951        let permalink = self.get_permalink_to_line(cx);
 9952
 9953        match permalink {
 9954            Ok(permalink) => {
 9955                cx.open_url(permalink.as_ref());
 9956            }
 9957            Err(err) => {
 9958                let message = format!("Failed to open permalink: {err}");
 9959
 9960                Err::<(), anyhow::Error>(err).log_err();
 9961
 9962                if let Some(workspace) = self.workspace() {
 9963                    workspace.update(cx, |workspace, cx| {
 9964                        struct OpenPermalinkToLine;
 9965
 9966                        workspace.show_toast(
 9967                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
 9968                            cx,
 9969                        )
 9970                    })
 9971                }
 9972            }
 9973        }
 9974    }
 9975
 9976    /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
 9977    /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
 9978    /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
 9979    pub fn highlight_rows<T: 'static>(
 9980        &mut self,
 9981        rows: RangeInclusive<Anchor>,
 9982        color: Option<Hsla>,
 9983        should_autoscroll: bool,
 9984        cx: &mut ViewContext<Self>,
 9985    ) {
 9986        let snapshot = self.buffer().read(cx).snapshot(cx);
 9987        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
 9988        let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
 9989            highlight
 9990                .range
 9991                .start()
 9992                .cmp(&rows.start(), &snapshot)
 9993                .then(highlight.range.end().cmp(&rows.end(), &snapshot))
 9994        });
 9995        match (color, existing_highlight_index) {
 9996            (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
 9997                ix,
 9998                RowHighlight {
 9999                    index: post_inc(&mut self.highlight_order),
10000                    range: rows,
10001                    should_autoscroll,
10002                    color,
10003                },
10004            ),
10005            (None, Ok(i)) => {
10006                row_highlights.remove(i);
10007            }
10008        }
10009    }
10010
10011    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10012    pub fn clear_row_highlights<T: 'static>(&mut self) {
10013        self.highlighted_rows.remove(&TypeId::of::<T>());
10014    }
10015
10016    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10017    pub fn highlighted_rows<T: 'static>(
10018        &self,
10019    ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10020        Some(
10021            self.highlighted_rows
10022                .get(&TypeId::of::<T>())?
10023                .iter()
10024                .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10025        )
10026    }
10027
10028    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10029    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10030    /// Allows to ignore certain kinds of highlights.
10031    pub fn highlighted_display_rows(
10032        &mut self,
10033        cx: &mut WindowContext,
10034    ) -> BTreeMap<DisplayRow, Hsla> {
10035        let snapshot = self.snapshot(cx);
10036        let mut used_highlight_orders = HashMap::default();
10037        self.highlighted_rows
10038            .iter()
10039            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10040            .fold(
10041                BTreeMap::<DisplayRow, Hsla>::new(),
10042                |mut unique_rows, highlight| {
10043                    let start_row = highlight.range.start().to_display_point(&snapshot).row();
10044                    let end_row = highlight.range.end().to_display_point(&snapshot).row();
10045                    for row in start_row.0..=end_row.0 {
10046                        let used_index =
10047                            used_highlight_orders.entry(row).or_insert(highlight.index);
10048                        if highlight.index >= *used_index {
10049                            *used_index = highlight.index;
10050                            match highlight.color {
10051                                Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10052                                None => unique_rows.remove(&DisplayRow(row)),
10053                            };
10054                        }
10055                    }
10056                    unique_rows
10057                },
10058            )
10059    }
10060
10061    pub fn highlighted_display_row_for_autoscroll(
10062        &self,
10063        snapshot: &DisplaySnapshot,
10064    ) -> Option<DisplayRow> {
10065        self.highlighted_rows
10066            .values()
10067            .flat_map(|highlighted_rows| highlighted_rows.iter())
10068            .filter_map(|highlight| {
10069                if highlight.color.is_none() || !highlight.should_autoscroll {
10070                    return None;
10071                }
10072                Some(highlight.range.start().to_display_point(&snapshot).row())
10073            })
10074            .min()
10075    }
10076
10077    pub fn set_search_within_ranges(
10078        &mut self,
10079        ranges: &[Range<Anchor>],
10080        cx: &mut ViewContext<Self>,
10081    ) {
10082        self.highlight_background::<SearchWithinRange>(
10083            ranges,
10084            |colors| colors.editor_document_highlight_read_background,
10085            cx,
10086        )
10087    }
10088
10089    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10090        self.clear_background_highlights::<SearchWithinRange>(cx);
10091    }
10092
10093    pub fn highlight_background<T: 'static>(
10094        &mut self,
10095        ranges: &[Range<Anchor>],
10096        color_fetcher: fn(&ThemeColors) -> Hsla,
10097        cx: &mut ViewContext<Self>,
10098    ) {
10099        let snapshot = self.snapshot(cx);
10100        // this is to try and catch a panic sooner
10101        for range in ranges {
10102            snapshot
10103                .buffer_snapshot
10104                .summary_for_anchor::<usize>(&range.start);
10105            snapshot
10106                .buffer_snapshot
10107                .summary_for_anchor::<usize>(&range.end);
10108        }
10109
10110        self.background_highlights
10111            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10112        self.scrollbar_marker_state.dirty = true;
10113        cx.notify();
10114    }
10115
10116    pub fn clear_background_highlights<T: 'static>(
10117        &mut self,
10118        cx: &mut ViewContext<Self>,
10119    ) -> Option<BackgroundHighlight> {
10120        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10121        if !text_highlights.1.is_empty() {
10122            self.scrollbar_marker_state.dirty = true;
10123            cx.notify();
10124        }
10125        Some(text_highlights)
10126    }
10127
10128    #[cfg(feature = "test-support")]
10129    pub fn all_text_background_highlights(
10130        &mut self,
10131        cx: &mut ViewContext<Self>,
10132    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10133        let snapshot = self.snapshot(cx);
10134        let buffer = &snapshot.buffer_snapshot;
10135        let start = buffer.anchor_before(0);
10136        let end = buffer.anchor_after(buffer.len());
10137        let theme = cx.theme().colors();
10138        self.background_highlights_in_range(start..end, &snapshot, theme)
10139    }
10140
10141    fn document_highlights_for_position<'a>(
10142        &'a self,
10143        position: Anchor,
10144        buffer: &'a MultiBufferSnapshot,
10145    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
10146        let read_highlights = self
10147            .background_highlights
10148            .get(&TypeId::of::<DocumentHighlightRead>())
10149            .map(|h| &h.1);
10150        let write_highlights = self
10151            .background_highlights
10152            .get(&TypeId::of::<DocumentHighlightWrite>())
10153            .map(|h| &h.1);
10154        let left_position = position.bias_left(buffer);
10155        let right_position = position.bias_right(buffer);
10156        read_highlights
10157            .into_iter()
10158            .chain(write_highlights)
10159            .flat_map(move |ranges| {
10160                let start_ix = match ranges.binary_search_by(|probe| {
10161                    let cmp = probe.end.cmp(&left_position, buffer);
10162                    if cmp.is_ge() {
10163                        Ordering::Greater
10164                    } else {
10165                        Ordering::Less
10166                    }
10167                }) {
10168                    Ok(i) | Err(i) => i,
10169                };
10170
10171                ranges[start_ix..]
10172                    .iter()
10173                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
10174            })
10175    }
10176
10177    pub fn has_background_highlights<T: 'static>(&self) -> bool {
10178        self.background_highlights
10179            .get(&TypeId::of::<T>())
10180            .map_or(false, |(_, highlights)| !highlights.is_empty())
10181    }
10182
10183    pub fn background_highlights_in_range(
10184        &self,
10185        search_range: Range<Anchor>,
10186        display_snapshot: &DisplaySnapshot,
10187        theme: &ThemeColors,
10188    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10189        let mut results = Vec::new();
10190        for (color_fetcher, ranges) in self.background_highlights.values() {
10191            let color = color_fetcher(theme);
10192            let start_ix = match ranges.binary_search_by(|probe| {
10193                let cmp = probe
10194                    .end
10195                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10196                if cmp.is_gt() {
10197                    Ordering::Greater
10198                } else {
10199                    Ordering::Less
10200                }
10201            }) {
10202                Ok(i) | Err(i) => i,
10203            };
10204            for range in &ranges[start_ix..] {
10205                if range
10206                    .start
10207                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10208                    .is_ge()
10209                {
10210                    break;
10211                }
10212
10213                let start = range.start.to_display_point(&display_snapshot);
10214                let end = range.end.to_display_point(&display_snapshot);
10215                results.push((start..end, color))
10216            }
10217        }
10218        results
10219    }
10220
10221    pub fn background_highlight_row_ranges<T: 'static>(
10222        &self,
10223        search_range: Range<Anchor>,
10224        display_snapshot: &DisplaySnapshot,
10225        count: usize,
10226    ) -> Vec<RangeInclusive<DisplayPoint>> {
10227        let mut results = Vec::new();
10228        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
10229            return vec![];
10230        };
10231
10232        let start_ix = match ranges.binary_search_by(|probe| {
10233            let cmp = probe
10234                .end
10235                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10236            if cmp.is_gt() {
10237                Ordering::Greater
10238            } else {
10239                Ordering::Less
10240            }
10241        }) {
10242            Ok(i) | Err(i) => i,
10243        };
10244        let mut push_region = |start: Option<Point>, end: Option<Point>| {
10245            if let (Some(start_display), Some(end_display)) = (start, end) {
10246                results.push(
10247                    start_display.to_display_point(display_snapshot)
10248                        ..=end_display.to_display_point(display_snapshot),
10249                );
10250            }
10251        };
10252        let mut start_row: Option<Point> = None;
10253        let mut end_row: Option<Point> = None;
10254        if ranges.len() > count {
10255            return Vec::new();
10256        }
10257        for range in &ranges[start_ix..] {
10258            if range
10259                .start
10260                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10261                .is_ge()
10262            {
10263                break;
10264            }
10265            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
10266            if let Some(current_row) = &end_row {
10267                if end.row == current_row.row {
10268                    continue;
10269                }
10270            }
10271            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
10272            if start_row.is_none() {
10273                assert_eq!(end_row, None);
10274                start_row = Some(start);
10275                end_row = Some(end);
10276                continue;
10277            }
10278            if let Some(current_end) = end_row.as_mut() {
10279                if start.row > current_end.row + 1 {
10280                    push_region(start_row, end_row);
10281                    start_row = Some(start);
10282                    end_row = Some(end);
10283                } else {
10284                    // Merge two hunks.
10285                    *current_end = end;
10286                }
10287            } else {
10288                unreachable!();
10289            }
10290        }
10291        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
10292        push_region(start_row, end_row);
10293        results
10294    }
10295
10296    /// Get the text ranges corresponding to the redaction query
10297    pub fn redacted_ranges(
10298        &self,
10299        search_range: Range<Anchor>,
10300        display_snapshot: &DisplaySnapshot,
10301        cx: &WindowContext,
10302    ) -> Vec<Range<DisplayPoint>> {
10303        display_snapshot
10304            .buffer_snapshot
10305            .redacted_ranges(search_range, |file| {
10306                if let Some(file) = file {
10307                    file.is_private()
10308                        && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
10309                } else {
10310                    false
10311                }
10312            })
10313            .map(|range| {
10314                range.start.to_display_point(display_snapshot)
10315                    ..range.end.to_display_point(display_snapshot)
10316            })
10317            .collect()
10318    }
10319
10320    pub fn highlight_text<T: 'static>(
10321        &mut self,
10322        ranges: Vec<Range<Anchor>>,
10323        style: HighlightStyle,
10324        cx: &mut ViewContext<Self>,
10325    ) {
10326        self.display_map.update(cx, |map, _| {
10327            map.highlight_text(TypeId::of::<T>(), ranges, style)
10328        });
10329        cx.notify();
10330    }
10331
10332    pub(crate) fn highlight_inlays<T: 'static>(
10333        &mut self,
10334        highlights: Vec<InlayHighlight>,
10335        style: HighlightStyle,
10336        cx: &mut ViewContext<Self>,
10337    ) {
10338        self.display_map.update(cx, |map, _| {
10339            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
10340        });
10341        cx.notify();
10342    }
10343
10344    pub fn text_highlights<'a, T: 'static>(
10345        &'a self,
10346        cx: &'a AppContext,
10347    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
10348        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
10349    }
10350
10351    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
10352        let cleared = self
10353            .display_map
10354            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
10355        if cleared {
10356            cx.notify();
10357        }
10358    }
10359
10360    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
10361        (self.read_only(cx) || self.blink_manager.read(cx).visible())
10362            && self.focus_handle.is_focused(cx)
10363    }
10364
10365    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
10366        cx.notify();
10367    }
10368
10369    fn on_buffer_event(
10370        &mut self,
10371        multibuffer: Model<MultiBuffer>,
10372        event: &multi_buffer::Event,
10373        cx: &mut ViewContext<Self>,
10374    ) {
10375        match event {
10376            multi_buffer::Event::Edited {
10377                singleton_buffer_edited,
10378            } => {
10379                self.scrollbar_marker_state.dirty = true;
10380                self.active_indent_guides_state.dirty = true;
10381                self.refresh_active_diagnostics(cx);
10382                self.refresh_code_actions(cx);
10383                if self.has_active_inline_completion(cx) {
10384                    self.update_visible_inline_completion(cx);
10385                }
10386                cx.emit(EditorEvent::BufferEdited);
10387                cx.emit(SearchEvent::MatchesInvalidated);
10388
10389                if *singleton_buffer_edited {
10390                    if let Some(project) = &self.project {
10391                        let project = project.read(cx);
10392                        let languages_affected = multibuffer
10393                            .read(cx)
10394                            .all_buffers()
10395                            .into_iter()
10396                            .filter_map(|buffer| {
10397                                let buffer = buffer.read(cx);
10398                                let language = buffer.language()?;
10399                                if project.is_local()
10400                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
10401                                {
10402                                    None
10403                                } else {
10404                                    Some(language)
10405                                }
10406                            })
10407                            .cloned()
10408                            .collect::<HashSet<_>>();
10409                        if !languages_affected.is_empty() {
10410                            self.refresh_inlay_hints(
10411                                InlayHintRefreshReason::BufferEdited(languages_affected),
10412                                cx,
10413                            );
10414                        }
10415                    }
10416                }
10417
10418                let Some(project) = &self.project else { return };
10419                let telemetry = project.read(cx).client().telemetry().clone();
10420                telemetry.log_edit_event("editor");
10421            }
10422            multi_buffer::Event::ExcerptsAdded {
10423                buffer,
10424                predecessor,
10425                excerpts,
10426            } => {
10427                self.tasks_update_task = Some(self.refresh_runnables(cx));
10428                cx.emit(EditorEvent::ExcerptsAdded {
10429                    buffer: buffer.clone(),
10430                    predecessor: *predecessor,
10431                    excerpts: excerpts.clone(),
10432                });
10433                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
10434            }
10435            multi_buffer::Event::ExcerptsRemoved { ids } => {
10436                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
10437                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
10438            }
10439            multi_buffer::Event::Reparsed => {
10440                self.tasks_update_task = Some(self.refresh_runnables(cx));
10441
10442                cx.emit(EditorEvent::Reparsed);
10443            }
10444            multi_buffer::Event::LanguageChanged => {
10445                cx.emit(EditorEvent::Reparsed);
10446                cx.notify();
10447            }
10448            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
10449            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
10450            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
10451                cx.emit(EditorEvent::TitleChanged)
10452            }
10453            multi_buffer::Event::DiffBaseChanged => {
10454                self.scrollbar_marker_state.dirty = true;
10455                cx.emit(EditorEvent::DiffBaseChanged);
10456                cx.notify();
10457            }
10458            multi_buffer::Event::DiffUpdated { buffer } => {
10459                self.sync_expanded_diff_hunks(buffer.clone(), cx);
10460                cx.notify();
10461            }
10462            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
10463            multi_buffer::Event::DiagnosticsUpdated => {
10464                self.refresh_active_diagnostics(cx);
10465                self.scrollbar_marker_state.dirty = true;
10466                cx.notify();
10467            }
10468            _ => {}
10469        };
10470    }
10471
10472    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
10473        cx.notify();
10474    }
10475
10476    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
10477        self.refresh_inline_completion(true, cx);
10478        self.refresh_inlay_hints(
10479            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
10480                self.selections.newest_anchor().head(),
10481                &self.buffer.read(cx).snapshot(cx),
10482                cx,
10483            )),
10484            cx,
10485        );
10486        let editor_settings = EditorSettings::get_global(cx);
10487        self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
10488        self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
10489        self.current_line_highlight = editor_settings.current_line_highlight;
10490
10491        if self.mode == EditorMode::Full {
10492            let inline_blame_enabled = ProjectSettings::get_global(cx).git.inline_blame_enabled();
10493            if self.git_blame_inline_enabled != inline_blame_enabled {
10494                self.toggle_git_blame_inline_internal(false, cx);
10495            }
10496        }
10497
10498        cx.notify();
10499    }
10500
10501    pub fn set_searchable(&mut self, searchable: bool) {
10502        self.searchable = searchable;
10503    }
10504
10505    pub fn searchable(&self) -> bool {
10506        self.searchable
10507    }
10508
10509    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
10510        self.open_excerpts_common(true, cx)
10511    }
10512
10513    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
10514        self.open_excerpts_common(false, cx)
10515    }
10516
10517    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
10518        let buffer = self.buffer.read(cx);
10519        if buffer.is_singleton() {
10520            cx.propagate();
10521            return;
10522        }
10523
10524        let Some(workspace) = self.workspace() else {
10525            cx.propagate();
10526            return;
10527        };
10528
10529        let mut new_selections_by_buffer = HashMap::default();
10530        for selection in self.selections.all::<usize>(cx) {
10531            for (buffer, mut range, _) in
10532                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
10533            {
10534                if selection.reversed {
10535                    mem::swap(&mut range.start, &mut range.end);
10536                }
10537                new_selections_by_buffer
10538                    .entry(buffer)
10539                    .or_insert(Vec::new())
10540                    .push(range)
10541            }
10542        }
10543
10544        // We defer the pane interaction because we ourselves are a workspace item
10545        // and activating a new item causes the pane to call a method on us reentrantly,
10546        // which panics if we're on the stack.
10547        cx.window_context().defer(move |cx| {
10548            workspace.update(cx, |workspace, cx| {
10549                let pane = if split {
10550                    workspace.adjacent_pane(cx)
10551                } else {
10552                    workspace.active_pane().clone()
10553                };
10554
10555                for (buffer, ranges) in new_selections_by_buffer {
10556                    let editor = workspace.open_project_item::<Self>(pane.clone(), buffer, cx);
10557                    editor.update(cx, |editor, cx| {
10558                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
10559                            s.select_ranges(ranges);
10560                        });
10561                    });
10562                }
10563            })
10564        });
10565    }
10566
10567    fn jump(
10568        &mut self,
10569        path: ProjectPath,
10570        position: Point,
10571        anchor: language::Anchor,
10572        offset_from_top: u32,
10573        cx: &mut ViewContext<Self>,
10574    ) {
10575        let workspace = self.workspace();
10576        cx.spawn(|_, mut cx| async move {
10577            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
10578            let editor = workspace.update(&mut cx, |workspace, cx| {
10579                // Reset the preview item id before opening the new item
10580                workspace.active_pane().update(cx, |pane, cx| {
10581                    pane.set_preview_item_id(None, cx);
10582                });
10583                workspace.open_path_preview(path, None, true, true, cx)
10584            })?;
10585            let editor = editor
10586                .await?
10587                .downcast::<Editor>()
10588                .ok_or_else(|| anyhow!("opened item was not an editor"))?
10589                .downgrade();
10590            editor.update(&mut cx, |editor, cx| {
10591                let buffer = editor
10592                    .buffer()
10593                    .read(cx)
10594                    .as_singleton()
10595                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
10596                let buffer = buffer.read(cx);
10597                let cursor = if buffer.can_resolve(&anchor) {
10598                    language::ToPoint::to_point(&anchor, buffer)
10599                } else {
10600                    buffer.clip_point(position, Bias::Left)
10601                };
10602
10603                let nav_history = editor.nav_history.take();
10604                editor.change_selections(
10605                    Some(Autoscroll::top_relative(offset_from_top as usize)),
10606                    cx,
10607                    |s| {
10608                        s.select_ranges([cursor..cursor]);
10609                    },
10610                );
10611                editor.nav_history = nav_history;
10612
10613                anyhow::Ok(())
10614            })??;
10615
10616            anyhow::Ok(())
10617        })
10618        .detach_and_log_err(cx);
10619    }
10620
10621    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
10622        let snapshot = self.buffer.read(cx).read(cx);
10623        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
10624        Some(
10625            ranges
10626                .iter()
10627                .map(move |range| {
10628                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
10629                })
10630                .collect(),
10631        )
10632    }
10633
10634    fn selection_replacement_ranges(
10635        &self,
10636        range: Range<OffsetUtf16>,
10637        cx: &AppContext,
10638    ) -> Vec<Range<OffsetUtf16>> {
10639        let selections = self.selections.all::<OffsetUtf16>(cx);
10640        let newest_selection = selections
10641            .iter()
10642            .max_by_key(|selection| selection.id)
10643            .unwrap();
10644        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
10645        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
10646        let snapshot = self.buffer.read(cx).read(cx);
10647        selections
10648            .into_iter()
10649            .map(|mut selection| {
10650                selection.start.0 =
10651                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
10652                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
10653                snapshot.clip_offset_utf16(selection.start, Bias::Left)
10654                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
10655            })
10656            .collect()
10657    }
10658
10659    fn report_editor_event(
10660        &self,
10661        operation: &'static str,
10662        file_extension: Option<String>,
10663        cx: &AppContext,
10664    ) {
10665        if cfg!(any(test, feature = "test-support")) {
10666            return;
10667        }
10668
10669        let Some(project) = &self.project else { return };
10670
10671        // If None, we are in a file without an extension
10672        let file = self
10673            .buffer
10674            .read(cx)
10675            .as_singleton()
10676            .and_then(|b| b.read(cx).file());
10677        let file_extension = file_extension.or(file
10678            .as_ref()
10679            .and_then(|file| Path::new(file.file_name(cx)).extension())
10680            .and_then(|e| e.to_str())
10681            .map(|a| a.to_string()));
10682
10683        let vim_mode = cx
10684            .global::<SettingsStore>()
10685            .raw_user_settings()
10686            .get("vim_mode")
10687            == Some(&serde_json::Value::Bool(true));
10688
10689        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
10690            == language::language_settings::InlineCompletionProvider::Copilot;
10691        let copilot_enabled_for_language = self
10692            .buffer
10693            .read(cx)
10694            .settings_at(0, cx)
10695            .show_inline_completions;
10696
10697        let telemetry = project.read(cx).client().telemetry().clone();
10698        telemetry.report_editor_event(
10699            file_extension,
10700            vim_mode,
10701            operation,
10702            copilot_enabled,
10703            copilot_enabled_for_language,
10704        )
10705    }
10706
10707    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
10708    /// with each line being an array of {text, highlight} objects.
10709    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
10710        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
10711            return;
10712        };
10713
10714        #[derive(Serialize)]
10715        struct Chunk<'a> {
10716            text: String,
10717            highlight: Option<&'a str>,
10718        }
10719
10720        let snapshot = buffer.read(cx).snapshot();
10721        let range = self
10722            .selected_text_range(cx)
10723            .and_then(|selected_range| {
10724                if selected_range.is_empty() {
10725                    None
10726                } else {
10727                    Some(selected_range)
10728                }
10729            })
10730            .unwrap_or_else(|| 0..snapshot.len());
10731
10732        let chunks = snapshot.chunks(range, true);
10733        let mut lines = Vec::new();
10734        let mut line: VecDeque<Chunk> = VecDeque::new();
10735
10736        let Some(style) = self.style.as_ref() else {
10737            return;
10738        };
10739
10740        for chunk in chunks {
10741            let highlight = chunk
10742                .syntax_highlight_id
10743                .and_then(|id| id.name(&style.syntax));
10744            let mut chunk_lines = chunk.text.split('\n').peekable();
10745            while let Some(text) = chunk_lines.next() {
10746                let mut merged_with_last_token = false;
10747                if let Some(last_token) = line.back_mut() {
10748                    if last_token.highlight == highlight {
10749                        last_token.text.push_str(text);
10750                        merged_with_last_token = true;
10751                    }
10752                }
10753
10754                if !merged_with_last_token {
10755                    line.push_back(Chunk {
10756                        text: text.into(),
10757                        highlight,
10758                    });
10759                }
10760
10761                if chunk_lines.peek().is_some() {
10762                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
10763                        line.pop_front();
10764                    }
10765                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
10766                        line.pop_back();
10767                    }
10768
10769                    lines.push(mem::take(&mut line));
10770                }
10771            }
10772        }
10773
10774        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
10775            return;
10776        };
10777        cx.write_to_clipboard(ClipboardItem::new(lines));
10778    }
10779
10780    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
10781        &self.inlay_hint_cache
10782    }
10783
10784    pub fn replay_insert_event(
10785        &mut self,
10786        text: &str,
10787        relative_utf16_range: Option<Range<isize>>,
10788        cx: &mut ViewContext<Self>,
10789    ) {
10790        if !self.input_enabled {
10791            cx.emit(EditorEvent::InputIgnored { text: text.into() });
10792            return;
10793        }
10794        if let Some(relative_utf16_range) = relative_utf16_range {
10795            let selections = self.selections.all::<OffsetUtf16>(cx);
10796            self.change_selections(None, cx, |s| {
10797                let new_ranges = selections.into_iter().map(|range| {
10798                    let start = OffsetUtf16(
10799                        range
10800                            .head()
10801                            .0
10802                            .saturating_add_signed(relative_utf16_range.start),
10803                    );
10804                    let end = OffsetUtf16(
10805                        range
10806                            .head()
10807                            .0
10808                            .saturating_add_signed(relative_utf16_range.end),
10809                    );
10810                    start..end
10811                });
10812                s.select_ranges(new_ranges);
10813            });
10814        }
10815
10816        self.handle_input(text, cx);
10817    }
10818
10819    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
10820        let Some(project) = self.project.as_ref() else {
10821            return false;
10822        };
10823        let project = project.read(cx);
10824
10825        let mut supports = false;
10826        self.buffer().read(cx).for_each_buffer(|buffer| {
10827            if !supports {
10828                supports = project
10829                    .language_servers_for_buffer(buffer.read(cx), cx)
10830                    .any(
10831                        |(_, server)| match server.capabilities().inlay_hint_provider {
10832                            Some(lsp::OneOf::Left(enabled)) => enabled,
10833                            Some(lsp::OneOf::Right(_)) => true,
10834                            None => false,
10835                        },
10836                    )
10837            }
10838        });
10839        supports
10840    }
10841
10842    pub fn focus(&self, cx: &mut WindowContext) {
10843        cx.focus(&self.focus_handle)
10844    }
10845
10846    pub fn is_focused(&self, cx: &WindowContext) -> bool {
10847        self.focus_handle.is_focused(cx)
10848    }
10849
10850    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
10851        cx.emit(EditorEvent::Focused);
10852        if let Some(rename) = self.pending_rename.as_ref() {
10853            let rename_editor_focus_handle = rename.editor.read(cx).focus_handle.clone();
10854            cx.focus(&rename_editor_focus_handle);
10855        } else {
10856            if let Some(blame) = self.blame.as_ref() {
10857                blame.update(cx, GitBlame::focus)
10858            }
10859
10860            self.blink_manager.update(cx, BlinkManager::enable);
10861            self.show_cursor_names(cx);
10862            self.buffer.update(cx, |buffer, cx| {
10863                buffer.finalize_last_transaction(cx);
10864                if self.leader_peer_id.is_none() {
10865                    buffer.set_active_selections(
10866                        &self.selections.disjoint_anchors(),
10867                        self.selections.line_mode,
10868                        self.cursor_shape,
10869                        cx,
10870                    );
10871                }
10872            });
10873        }
10874    }
10875
10876    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
10877        self.blink_manager.update(cx, BlinkManager::disable);
10878        self.buffer
10879            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
10880
10881        if let Some(blame) = self.blame.as_ref() {
10882            blame.update(cx, GitBlame::blur)
10883        }
10884        self.hide_context_menu(cx);
10885        hide_hover(self, cx);
10886        cx.emit(EditorEvent::Blurred);
10887        cx.notify();
10888    }
10889
10890    pub fn register_action<A: Action>(
10891        &mut self,
10892        listener: impl Fn(&A, &mut WindowContext) + 'static,
10893    ) -> &mut Self {
10894        let listener = Arc::new(listener);
10895
10896        self.editor_actions.push(Box::new(move |cx| {
10897            let _view = cx.view().clone();
10898            let cx = cx.window_context();
10899            let listener = listener.clone();
10900            cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
10901                let action = action.downcast_ref().unwrap();
10902                if phase == DispatchPhase::Bubble {
10903                    listener(action, cx)
10904                }
10905            })
10906        }));
10907        self
10908    }
10909}
10910
10911fn hunks_for_selections(
10912    multi_buffer_snapshot: &MultiBufferSnapshot,
10913    selections: &[Selection<Anchor>],
10914) -> Vec<DiffHunk<MultiBufferRow>> {
10915    let mut hunks = Vec::with_capacity(selections.len());
10916    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
10917        HashMap::default();
10918    let buffer_rows_for_selections = selections.iter().map(|selection| {
10919        let head = selection.head();
10920        let tail = selection.tail();
10921        let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
10922        let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
10923        if start > end {
10924            end..start
10925        } else {
10926            start..end
10927        }
10928    });
10929
10930    for selected_multi_buffer_rows in buffer_rows_for_selections {
10931        let query_rows =
10932            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
10933        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
10934            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
10935            // when the caret is just above or just below the deleted hunk.
10936            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
10937            let related_to_selection = if allow_adjacent {
10938                hunk.associated_range.overlaps(&query_rows)
10939                    || hunk.associated_range.start == query_rows.end
10940                    || hunk.associated_range.end == query_rows.start
10941            } else {
10942                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
10943                // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
10944                hunk.associated_range.overlaps(&selected_multi_buffer_rows)
10945                    || selected_multi_buffer_rows.end == hunk.associated_range.start
10946            };
10947            if related_to_selection {
10948                if !processed_buffer_rows
10949                    .entry(hunk.buffer_id)
10950                    .or_default()
10951                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
10952                {
10953                    continue;
10954                }
10955                hunks.push(hunk);
10956            }
10957        }
10958    }
10959
10960    hunks
10961}
10962
10963pub trait CollaborationHub {
10964    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
10965    fn user_participant_indices<'a>(
10966        &self,
10967        cx: &'a AppContext,
10968    ) -> &'a HashMap<u64, ParticipantIndex>;
10969    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
10970}
10971
10972impl CollaborationHub for Model<Project> {
10973    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
10974        self.read(cx).collaborators()
10975    }
10976
10977    fn user_participant_indices<'a>(
10978        &self,
10979        cx: &'a AppContext,
10980    ) -> &'a HashMap<u64, ParticipantIndex> {
10981        self.read(cx).user_store().read(cx).participant_indices()
10982    }
10983
10984    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
10985        let this = self.read(cx);
10986        let user_ids = this.collaborators().values().map(|c| c.user_id);
10987        this.user_store().read_with(cx, |user_store, cx| {
10988            user_store.participant_names(user_ids, cx)
10989        })
10990    }
10991}
10992
10993pub trait CompletionProvider {
10994    fn completions(
10995        &self,
10996        buffer: &Model<Buffer>,
10997        buffer_position: text::Anchor,
10998        cx: &mut ViewContext<Editor>,
10999    ) -> Task<Result<Vec<Completion>>>;
11000
11001    fn resolve_completions(
11002        &self,
11003        buffer: Model<Buffer>,
11004        completion_indices: Vec<usize>,
11005        completions: Arc<RwLock<Box<[Completion]>>>,
11006        cx: &mut ViewContext<Editor>,
11007    ) -> Task<Result<bool>>;
11008
11009    fn apply_additional_edits_for_completion(
11010        &self,
11011        buffer: Model<Buffer>,
11012        completion: Completion,
11013        push_to_history: bool,
11014        cx: &mut ViewContext<Editor>,
11015    ) -> Task<Result<Option<language::Transaction>>>;
11016
11017    fn is_completion_trigger(
11018        &self,
11019        buffer: &Model<Buffer>,
11020        position: language::Anchor,
11021        text: &str,
11022        trigger_in_words: bool,
11023        cx: &mut ViewContext<Editor>,
11024    ) -> bool;
11025}
11026
11027impl CompletionProvider for Model<Project> {
11028    fn completions(
11029        &self,
11030        buffer: &Model<Buffer>,
11031        buffer_position: text::Anchor,
11032        cx: &mut ViewContext<Editor>,
11033    ) -> Task<Result<Vec<Completion>>> {
11034        self.update(cx, |project, cx| {
11035            project.completions(&buffer, buffer_position, cx)
11036        })
11037    }
11038
11039    fn resolve_completions(
11040        &self,
11041        buffer: Model<Buffer>,
11042        completion_indices: Vec<usize>,
11043        completions: Arc<RwLock<Box<[Completion]>>>,
11044        cx: &mut ViewContext<Editor>,
11045    ) -> Task<Result<bool>> {
11046        self.update(cx, |project, cx| {
11047            project.resolve_completions(buffer, completion_indices, completions, cx)
11048        })
11049    }
11050
11051    fn apply_additional_edits_for_completion(
11052        &self,
11053        buffer: Model<Buffer>,
11054        completion: Completion,
11055        push_to_history: bool,
11056        cx: &mut ViewContext<Editor>,
11057    ) -> Task<Result<Option<language::Transaction>>> {
11058        self.update(cx, |project, cx| {
11059            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
11060        })
11061    }
11062
11063    fn is_completion_trigger(
11064        &self,
11065        buffer: &Model<Buffer>,
11066        position: language::Anchor,
11067        text: &str,
11068        trigger_in_words: bool,
11069        cx: &mut ViewContext<Editor>,
11070    ) -> bool {
11071        if !EditorSettings::get_global(cx).show_completions_on_input {
11072            return false;
11073        }
11074
11075        let mut chars = text.chars();
11076        let char = if let Some(char) = chars.next() {
11077            char
11078        } else {
11079            return false;
11080        };
11081        if chars.next().is_some() {
11082            return false;
11083        }
11084
11085        let buffer = buffer.read(cx);
11086        let scope = buffer.snapshot().language_scope_at(position);
11087        if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
11088            return true;
11089        }
11090
11091        buffer
11092            .completion_triggers()
11093            .iter()
11094            .any(|string| string == text)
11095    }
11096}
11097
11098fn inlay_hint_settings(
11099    location: Anchor,
11100    snapshot: &MultiBufferSnapshot,
11101    cx: &mut ViewContext<'_, Editor>,
11102) -> InlayHintSettings {
11103    let file = snapshot.file_at(location);
11104    let language = snapshot.language_at(location);
11105    let settings = all_language_settings(file, cx);
11106    settings
11107        .language(language.map(|l| l.name()).as_deref())
11108        .inlay_hints
11109}
11110
11111fn consume_contiguous_rows(
11112    contiguous_row_selections: &mut Vec<Selection<Point>>,
11113    selection: &Selection<Point>,
11114    display_map: &DisplaySnapshot,
11115    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
11116) -> (MultiBufferRow, MultiBufferRow) {
11117    contiguous_row_selections.push(selection.clone());
11118    let start_row = MultiBufferRow(selection.start.row);
11119    let mut end_row = ending_row(selection, display_map);
11120
11121    while let Some(next_selection) = selections.peek() {
11122        if next_selection.start.row <= end_row.0 {
11123            end_row = ending_row(next_selection, display_map);
11124            contiguous_row_selections.push(selections.next().unwrap().clone());
11125        } else {
11126            break;
11127        }
11128    }
11129    (start_row, end_row)
11130}
11131
11132fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
11133    if next_selection.end.column > 0 || next_selection.is_empty() {
11134        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
11135    } else {
11136        MultiBufferRow(next_selection.end.row)
11137    }
11138}
11139
11140impl EditorSnapshot {
11141    pub fn remote_selections_in_range<'a>(
11142        &'a self,
11143        range: &'a Range<Anchor>,
11144        collaboration_hub: &dyn CollaborationHub,
11145        cx: &'a AppContext,
11146    ) -> impl 'a + Iterator<Item = RemoteSelection> {
11147        let participant_names = collaboration_hub.user_names(cx);
11148        let participant_indices = collaboration_hub.user_participant_indices(cx);
11149        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
11150        let collaborators_by_replica_id = collaborators_by_peer_id
11151            .iter()
11152            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
11153            .collect::<HashMap<_, _>>();
11154        self.buffer_snapshot
11155            .remote_selections_in_range(range)
11156            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
11157                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
11158                let participant_index = participant_indices.get(&collaborator.user_id).copied();
11159                let user_name = participant_names.get(&collaborator.user_id).cloned();
11160                Some(RemoteSelection {
11161                    replica_id,
11162                    selection,
11163                    cursor_shape,
11164                    line_mode,
11165                    participant_index,
11166                    peer_id: collaborator.peer_id,
11167                    user_name,
11168                })
11169            })
11170    }
11171
11172    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
11173        self.display_snapshot.buffer_snapshot.language_at(position)
11174    }
11175
11176    pub fn is_focused(&self) -> bool {
11177        self.is_focused
11178    }
11179
11180    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
11181        self.placeholder_text.as_ref()
11182    }
11183
11184    pub fn scroll_position(&self) -> gpui::Point<f32> {
11185        self.scroll_anchor.scroll_position(&self.display_snapshot)
11186    }
11187
11188    pub fn gutter_dimensions(
11189        &self,
11190        font_id: FontId,
11191        font_size: Pixels,
11192        em_width: Pixels,
11193        max_line_number_width: Pixels,
11194        cx: &AppContext,
11195    ) -> GutterDimensions {
11196        if !self.show_gutter {
11197            return GutterDimensions::default();
11198        }
11199        let descent = cx.text_system().descent(font_id, font_size);
11200
11201        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
11202            matches!(
11203                ProjectSettings::get_global(cx).git.git_gutter,
11204                Some(GitGutterSetting::TrackedFiles)
11205            )
11206        });
11207        let gutter_settings = EditorSettings::get_global(cx).gutter;
11208        let show_line_numbers = self
11209            .show_line_numbers
11210            .unwrap_or_else(|| gutter_settings.line_numbers);
11211        let line_gutter_width = if show_line_numbers {
11212            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
11213            let min_width_for_number_on_gutter = em_width * 4.0;
11214            max_line_number_width.max(min_width_for_number_on_gutter)
11215        } else {
11216            0.0.into()
11217        };
11218
11219        let show_code_actions = self
11220            .show_code_actions
11221            .unwrap_or_else(|| gutter_settings.code_actions);
11222
11223        let git_blame_entries_width = self
11224            .render_git_blame_gutter
11225            .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
11226
11227        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
11228        left_padding += if show_code_actions {
11229            em_width * 3.0
11230        } else if show_git_gutter && show_line_numbers {
11231            em_width * 2.0
11232        } else if show_git_gutter || show_line_numbers {
11233            em_width
11234        } else {
11235            px(0.)
11236        };
11237
11238        let right_padding = if gutter_settings.folds && show_line_numbers {
11239            em_width * 4.0
11240        } else if gutter_settings.folds {
11241            em_width * 3.0
11242        } else if show_line_numbers {
11243            em_width
11244        } else {
11245            px(0.)
11246        };
11247
11248        GutterDimensions {
11249            left_padding,
11250            right_padding,
11251            width: line_gutter_width + left_padding + right_padding,
11252            margin: -descent,
11253            git_blame_entries_width,
11254        }
11255    }
11256
11257    pub fn render_fold_toggle(
11258        &self,
11259        buffer_row: MultiBufferRow,
11260        row_contains_cursor: bool,
11261        editor: View<Editor>,
11262        cx: &mut WindowContext,
11263    ) -> Option<AnyElement> {
11264        let folded = self.is_line_folded(buffer_row);
11265
11266        if let Some(flap) = self
11267            .flap_snapshot
11268            .query_row(buffer_row, &self.buffer_snapshot)
11269        {
11270            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
11271                if folded {
11272                    editor.update(cx, |editor, cx| {
11273                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
11274                    });
11275                } else {
11276                    editor.update(cx, |editor, cx| {
11277                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
11278                    });
11279                }
11280            });
11281
11282            Some((flap.render_toggle)(
11283                buffer_row,
11284                folded,
11285                toggle_callback,
11286                cx,
11287            ))
11288        } else if folded
11289            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
11290        {
11291            Some(
11292                IconButton::new(
11293                    ("indent-fold-indicator", buffer_row.0),
11294                    ui::IconName::ChevronDown,
11295                )
11296                .on_click(cx.listener_for(&editor, move |this, _e, cx| {
11297                    if folded {
11298                        this.unfold_at(&UnfoldAt { buffer_row }, cx);
11299                    } else {
11300                        this.fold_at(&FoldAt { buffer_row }, cx);
11301                    }
11302                }))
11303                .icon_color(ui::Color::Muted)
11304                .icon_size(ui::IconSize::Small)
11305                .selected(folded)
11306                .selected_icon(ui::IconName::ChevronRight)
11307                .size(ui::ButtonSize::None)
11308                .into_any_element(),
11309            )
11310        } else {
11311            None
11312        }
11313    }
11314
11315    pub fn render_flap_trailer(
11316        &self,
11317        buffer_row: MultiBufferRow,
11318        cx: &mut WindowContext,
11319    ) -> Option<AnyElement> {
11320        let folded = self.is_line_folded(buffer_row);
11321        let flap = self
11322            .flap_snapshot
11323            .query_row(buffer_row, &self.buffer_snapshot)?;
11324        Some((flap.render_trailer)(buffer_row, folded, cx))
11325    }
11326}
11327
11328impl Deref for EditorSnapshot {
11329    type Target = DisplaySnapshot;
11330
11331    fn deref(&self) -> &Self::Target {
11332        &self.display_snapshot
11333    }
11334}
11335
11336#[derive(Clone, Debug, PartialEq, Eq)]
11337pub enum EditorEvent {
11338    InputIgnored {
11339        text: Arc<str>,
11340    },
11341    InputHandled {
11342        utf16_range_to_replace: Option<Range<isize>>,
11343        text: Arc<str>,
11344    },
11345    ExcerptsAdded {
11346        buffer: Model<Buffer>,
11347        predecessor: ExcerptId,
11348        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
11349    },
11350    ExcerptsRemoved {
11351        ids: Vec<ExcerptId>,
11352    },
11353    BufferEdited,
11354    Edited,
11355    Reparsed,
11356    Focused,
11357    Blurred,
11358    DirtyChanged,
11359    Saved,
11360    TitleChanged,
11361    DiffBaseChanged,
11362    SelectionsChanged {
11363        local: bool,
11364    },
11365    ScrollPositionChanged {
11366        local: bool,
11367        autoscroll: bool,
11368    },
11369    Closed,
11370    TransactionUndone {
11371        transaction_id: clock::Lamport,
11372    },
11373    TransactionBegun {
11374        transaction_id: clock::Lamport,
11375    },
11376}
11377
11378impl EventEmitter<EditorEvent> for Editor {}
11379
11380impl FocusableView for Editor {
11381    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
11382        self.focus_handle.clone()
11383    }
11384}
11385
11386impl Render for Editor {
11387    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
11388        let settings = ThemeSettings::get_global(cx);
11389
11390        let text_style = match self.mode {
11391            EditorMode::SingleLine | EditorMode::AutoHeight { .. } => TextStyle {
11392                color: cx.theme().colors().editor_foreground,
11393                font_family: settings.ui_font.family.clone(),
11394                font_features: settings.ui_font.features.clone(),
11395                font_size: rems(0.875).into(),
11396                font_weight: FontWeight::NORMAL,
11397                font_style: FontStyle::Normal,
11398                line_height: relative(settings.buffer_line_height.value()),
11399                background_color: None,
11400                underline: None,
11401                strikethrough: None,
11402                white_space: WhiteSpace::Normal,
11403            },
11404            EditorMode::Full => TextStyle {
11405                color: cx.theme().colors().editor_foreground,
11406                font_family: settings.buffer_font.family.clone(),
11407                font_features: settings.buffer_font.features.clone(),
11408                font_size: settings.buffer_font_size(cx).into(),
11409                font_weight: FontWeight::NORMAL,
11410                font_style: FontStyle::Normal,
11411                line_height: relative(settings.buffer_line_height.value()),
11412                background_color: None,
11413                underline: None,
11414                strikethrough: None,
11415                white_space: WhiteSpace::Normal,
11416            },
11417        };
11418
11419        let background = match self.mode {
11420            EditorMode::SingleLine => cx.theme().system().transparent,
11421            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
11422            EditorMode::Full => cx.theme().colors().editor_background,
11423        };
11424
11425        EditorElement::new(
11426            cx.view(),
11427            EditorStyle {
11428                background,
11429                local_player: cx.theme().players().local(),
11430                text: text_style,
11431                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
11432                syntax: cx.theme().syntax().clone(),
11433                status: cx.theme().status().clone(),
11434                inlay_hints_style: HighlightStyle {
11435                    color: Some(cx.theme().status().hint),
11436                    ..HighlightStyle::default()
11437                },
11438                suggestions_style: HighlightStyle {
11439                    color: Some(cx.theme().status().predictive),
11440                    ..HighlightStyle::default()
11441                },
11442            },
11443        )
11444    }
11445}
11446
11447impl ViewInputHandler for Editor {
11448    fn text_for_range(
11449        &mut self,
11450        range_utf16: Range<usize>,
11451        cx: &mut ViewContext<Self>,
11452    ) -> Option<String> {
11453        Some(
11454            self.buffer
11455                .read(cx)
11456                .read(cx)
11457                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
11458                .collect(),
11459        )
11460    }
11461
11462    fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
11463        // Prevent the IME menu from appearing when holding down an alphabetic key
11464        // while input is disabled.
11465        if !self.input_enabled {
11466            return None;
11467        }
11468
11469        let range = self.selections.newest::<OffsetUtf16>(cx).range();
11470        Some(range.start.0..range.end.0)
11471    }
11472
11473    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
11474        let snapshot = self.buffer.read(cx).read(cx);
11475        let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
11476        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
11477    }
11478
11479    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
11480        self.clear_highlights::<InputComposition>(cx);
11481        self.ime_transaction.take();
11482    }
11483
11484    fn replace_text_in_range(
11485        &mut self,
11486        range_utf16: Option<Range<usize>>,
11487        text: &str,
11488        cx: &mut ViewContext<Self>,
11489    ) {
11490        if !self.input_enabled {
11491            cx.emit(EditorEvent::InputIgnored { text: text.into() });
11492            return;
11493        }
11494
11495        self.transact(cx, |this, cx| {
11496            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
11497                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
11498                Some(this.selection_replacement_ranges(range_utf16, cx))
11499            } else {
11500                this.marked_text_ranges(cx)
11501            };
11502
11503            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
11504                let newest_selection_id = this.selections.newest_anchor().id;
11505                this.selections
11506                    .all::<OffsetUtf16>(cx)
11507                    .iter()
11508                    .zip(ranges_to_replace.iter())
11509                    .find_map(|(selection, range)| {
11510                        if selection.id == newest_selection_id {
11511                            Some(
11512                                (range.start.0 as isize - selection.head().0 as isize)
11513                                    ..(range.end.0 as isize - selection.head().0 as isize),
11514                            )
11515                        } else {
11516                            None
11517                        }
11518                    })
11519            });
11520
11521            cx.emit(EditorEvent::InputHandled {
11522                utf16_range_to_replace: range_to_replace,
11523                text: text.into(),
11524            });
11525
11526            if let Some(new_selected_ranges) = new_selected_ranges {
11527                this.change_selections(None, cx, |selections| {
11528                    selections.select_ranges(new_selected_ranges)
11529                });
11530                this.backspace(&Default::default(), cx);
11531            }
11532
11533            this.handle_input(text, cx);
11534        });
11535
11536        if let Some(transaction) = self.ime_transaction {
11537            self.buffer.update(cx, |buffer, cx| {
11538                buffer.group_until_transaction(transaction, cx);
11539            });
11540        }
11541
11542        self.unmark_text(cx);
11543    }
11544
11545    fn replace_and_mark_text_in_range(
11546        &mut self,
11547        range_utf16: Option<Range<usize>>,
11548        text: &str,
11549        new_selected_range_utf16: Option<Range<usize>>,
11550        cx: &mut ViewContext<Self>,
11551    ) {
11552        if !self.input_enabled {
11553            cx.emit(EditorEvent::InputIgnored { text: text.into() });
11554            return;
11555        }
11556
11557        let transaction = self.transact(cx, |this, cx| {
11558            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
11559                let snapshot = this.buffer.read(cx).read(cx);
11560                if let Some(relative_range_utf16) = range_utf16.as_ref() {
11561                    for marked_range in &mut marked_ranges {
11562                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
11563                        marked_range.start.0 += relative_range_utf16.start;
11564                        marked_range.start =
11565                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
11566                        marked_range.end =
11567                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
11568                    }
11569                }
11570                Some(marked_ranges)
11571            } else if let Some(range_utf16) = range_utf16 {
11572                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
11573                Some(this.selection_replacement_ranges(range_utf16, cx))
11574            } else {
11575                None
11576            };
11577
11578            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
11579                let newest_selection_id = this.selections.newest_anchor().id;
11580                this.selections
11581                    .all::<OffsetUtf16>(cx)
11582                    .iter()
11583                    .zip(ranges_to_replace.iter())
11584                    .find_map(|(selection, range)| {
11585                        if selection.id == newest_selection_id {
11586                            Some(
11587                                (range.start.0 as isize - selection.head().0 as isize)
11588                                    ..(range.end.0 as isize - selection.head().0 as isize),
11589                            )
11590                        } else {
11591                            None
11592                        }
11593                    })
11594            });
11595
11596            cx.emit(EditorEvent::InputHandled {
11597                utf16_range_to_replace: range_to_replace,
11598                text: text.into(),
11599            });
11600
11601            if let Some(ranges) = ranges_to_replace {
11602                this.change_selections(None, cx, |s| s.select_ranges(ranges));
11603            }
11604
11605            let marked_ranges = {
11606                let snapshot = this.buffer.read(cx).read(cx);
11607                this.selections
11608                    .disjoint_anchors()
11609                    .iter()
11610                    .map(|selection| {
11611                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
11612                    })
11613                    .collect::<Vec<_>>()
11614            };
11615
11616            if text.is_empty() {
11617                this.unmark_text(cx);
11618            } else {
11619                this.highlight_text::<InputComposition>(
11620                    marked_ranges.clone(),
11621                    HighlightStyle {
11622                        underline: Some(UnderlineStyle {
11623                            thickness: px(1.),
11624                            color: None,
11625                            wavy: false,
11626                        }),
11627                        ..Default::default()
11628                    },
11629                    cx,
11630                );
11631            }
11632
11633            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
11634            let use_autoclose = this.use_autoclose;
11635            this.set_use_autoclose(false);
11636            this.handle_input(text, cx);
11637            this.set_use_autoclose(use_autoclose);
11638
11639            if let Some(new_selected_range) = new_selected_range_utf16 {
11640                let snapshot = this.buffer.read(cx).read(cx);
11641                let new_selected_ranges = marked_ranges
11642                    .into_iter()
11643                    .map(|marked_range| {
11644                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
11645                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
11646                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
11647                        snapshot.clip_offset_utf16(new_start, Bias::Left)
11648                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
11649                    })
11650                    .collect::<Vec<_>>();
11651
11652                drop(snapshot);
11653                this.change_selections(None, cx, |selections| {
11654                    selections.select_ranges(new_selected_ranges)
11655                });
11656            }
11657        });
11658
11659        self.ime_transaction = self.ime_transaction.or(transaction);
11660        if let Some(transaction) = self.ime_transaction {
11661            self.buffer.update(cx, |buffer, cx| {
11662                buffer.group_until_transaction(transaction, cx);
11663            });
11664        }
11665
11666        if self.text_highlights::<InputComposition>(cx).is_none() {
11667            self.ime_transaction.take();
11668        }
11669    }
11670
11671    fn bounds_for_range(
11672        &mut self,
11673        range_utf16: Range<usize>,
11674        element_bounds: gpui::Bounds<Pixels>,
11675        cx: &mut ViewContext<Self>,
11676    ) -> Option<gpui::Bounds<Pixels>> {
11677        let text_layout_details = self.text_layout_details(cx);
11678        let style = &text_layout_details.editor_style;
11679        let font_id = cx.text_system().resolve_font(&style.text.font());
11680        let font_size = style.text.font_size.to_pixels(cx.rem_size());
11681        let line_height = style.text.line_height_in_pixels(cx.rem_size());
11682        let em_width = cx
11683            .text_system()
11684            .typographic_bounds(font_id, font_size, 'm')
11685            .unwrap()
11686            .size
11687            .width;
11688
11689        let snapshot = self.snapshot(cx);
11690        let scroll_position = snapshot.scroll_position();
11691        let scroll_left = scroll_position.x * em_width;
11692
11693        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
11694        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
11695            + self.gutter_dimensions.width;
11696        let y = line_height * (start.row().as_f32() - scroll_position.y);
11697
11698        Some(Bounds {
11699            origin: element_bounds.origin + point(x, y),
11700            size: size(em_width, line_height),
11701        })
11702    }
11703}
11704
11705trait SelectionExt {
11706    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
11707    fn spanned_rows(
11708        &self,
11709        include_end_if_at_line_start: bool,
11710        map: &DisplaySnapshot,
11711    ) -> Range<MultiBufferRow>;
11712}
11713
11714impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
11715    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
11716        let start = self
11717            .start
11718            .to_point(&map.buffer_snapshot)
11719            .to_display_point(map);
11720        let end = self
11721            .end
11722            .to_point(&map.buffer_snapshot)
11723            .to_display_point(map);
11724        if self.reversed {
11725            end..start
11726        } else {
11727            start..end
11728        }
11729    }
11730
11731    fn spanned_rows(
11732        &self,
11733        include_end_if_at_line_start: bool,
11734        map: &DisplaySnapshot,
11735    ) -> Range<MultiBufferRow> {
11736        let start = self.start.to_point(&map.buffer_snapshot);
11737        let mut end = self.end.to_point(&map.buffer_snapshot);
11738        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
11739            end.row -= 1;
11740        }
11741
11742        let buffer_start = map.prev_line_boundary(start).0;
11743        let buffer_end = map.next_line_boundary(end).0;
11744        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
11745    }
11746}
11747
11748impl<T: InvalidationRegion> InvalidationStack<T> {
11749    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
11750    where
11751        S: Clone + ToOffset,
11752    {
11753        while let Some(region) = self.last() {
11754            let all_selections_inside_invalidation_ranges =
11755                if selections.len() == region.ranges().len() {
11756                    selections
11757                        .iter()
11758                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
11759                        .all(|(selection, invalidation_range)| {
11760                            let head = selection.head().to_offset(buffer);
11761                            invalidation_range.start <= head && invalidation_range.end >= head
11762                        })
11763                } else {
11764                    false
11765                };
11766
11767            if all_selections_inside_invalidation_ranges {
11768                break;
11769            } else {
11770                self.pop();
11771            }
11772        }
11773    }
11774}
11775
11776impl<T> Default for InvalidationStack<T> {
11777    fn default() -> Self {
11778        Self(Default::default())
11779    }
11780}
11781
11782impl<T> Deref for InvalidationStack<T> {
11783    type Target = Vec<T>;
11784
11785    fn deref(&self) -> &Self::Target {
11786        &self.0
11787    }
11788}
11789
11790impl<T> DerefMut for InvalidationStack<T> {
11791    fn deref_mut(&mut self) -> &mut Self::Target {
11792        &mut self.0
11793    }
11794}
11795
11796impl InvalidationRegion for SnippetState {
11797    fn ranges(&self) -> &[Range<Anchor>] {
11798        &self.ranges[self.active_index]
11799    }
11800}
11801
11802pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
11803    let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
11804
11805    Box::new(move |cx: &mut BlockContext| {
11806        let group_id: SharedString = cx.block_id.to_string().into();
11807
11808        let mut text_style = cx.text_style().clone();
11809        text_style.color = diagnostic_style(diagnostic.severity, true, cx.theme().status());
11810        let theme_settings = ThemeSettings::get_global(cx);
11811        text_style.font_family = theme_settings.buffer_font.family.clone();
11812        text_style.font_style = theme_settings.buffer_font.style;
11813        text_style.font_features = theme_settings.buffer_font.features.clone();
11814        text_style.font_weight = theme_settings.buffer_font.weight;
11815
11816        let multi_line_diagnostic = diagnostic.message.contains('\n');
11817
11818        let buttons = |diagnostic: &Diagnostic, block_id: usize| {
11819            if multi_line_diagnostic {
11820                v_flex()
11821            } else {
11822                h_flex()
11823            }
11824            .children(diagnostic.is_primary.then(|| {
11825                IconButton::new(("close-block", block_id), IconName::XCircle)
11826                    .icon_color(Color::Muted)
11827                    .size(ButtonSize::Compact)
11828                    .style(ButtonStyle::Transparent)
11829                    .visible_on_hover(group_id.clone())
11830                    .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
11831                    .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
11832            }))
11833            .child(
11834                IconButton::new(("copy-block", block_id), IconName::Copy)
11835                    .icon_color(Color::Muted)
11836                    .size(ButtonSize::Compact)
11837                    .style(ButtonStyle::Transparent)
11838                    .visible_on_hover(group_id.clone())
11839                    .on_click({
11840                        let message = diagnostic.message.clone();
11841                        move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
11842                    })
11843                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
11844            )
11845        };
11846
11847        let icon_size = buttons(&diagnostic, cx.block_id)
11848            .into_any_element()
11849            .layout_as_root(AvailableSpace::min_size(), cx);
11850
11851        h_flex()
11852            .id(cx.block_id)
11853            .group(group_id.clone())
11854            .relative()
11855            .size_full()
11856            .pl(cx.gutter_dimensions.width)
11857            .w(cx.max_width + cx.gutter_dimensions.width)
11858            .child(
11859                div()
11860                    .flex()
11861                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
11862                    .flex_shrink(),
11863            )
11864            .child(buttons(&diagnostic, cx.block_id))
11865            .child(div().flex().flex_shrink_0().child(
11866                StyledText::new(text_without_backticks.clone()).with_highlights(
11867                    &text_style,
11868                    code_ranges.iter().map(|range| {
11869                        (
11870                            range.clone(),
11871                            HighlightStyle {
11872                                font_weight: Some(FontWeight::BOLD),
11873                                ..Default::default()
11874                            },
11875                        )
11876                    }),
11877                ),
11878            ))
11879            .into_any_element()
11880    })
11881}
11882
11883pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
11884    let mut text_without_backticks = String::new();
11885    let mut code_ranges = Vec::new();
11886
11887    if let Some(source) = &diagnostic.source {
11888        text_without_backticks.push_str(&source);
11889        code_ranges.push(0..source.len());
11890        text_without_backticks.push_str(": ");
11891    }
11892
11893    let mut prev_offset = 0;
11894    let mut in_code_block = false;
11895    for (ix, _) in diagnostic
11896        .message
11897        .match_indices('`')
11898        .chain([(diagnostic.message.len(), "")])
11899    {
11900        let prev_len = text_without_backticks.len();
11901        text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
11902        prev_offset = ix + 1;
11903        if in_code_block {
11904            code_ranges.push(prev_len..text_without_backticks.len());
11905            in_code_block = false;
11906        } else {
11907            in_code_block = true;
11908        }
11909    }
11910
11911    (text_without_backticks.into(), code_ranges)
11912}
11913
11914fn diagnostic_style(severity: DiagnosticSeverity, valid: bool, colors: &StatusColors) -> Hsla {
11915    match (severity, valid) {
11916        (DiagnosticSeverity::ERROR, true) => colors.error,
11917        (DiagnosticSeverity::ERROR, false) => colors.error,
11918        (DiagnosticSeverity::WARNING, true) => colors.warning,
11919        (DiagnosticSeverity::WARNING, false) => colors.warning,
11920        (DiagnosticSeverity::INFORMATION, true) => colors.info,
11921        (DiagnosticSeverity::INFORMATION, false) => colors.info,
11922        (DiagnosticSeverity::HINT, true) => colors.info,
11923        (DiagnosticSeverity::HINT, false) => colors.info,
11924        _ => colors.ignored,
11925    }
11926}
11927
11928pub fn styled_runs_for_code_label<'a>(
11929    label: &'a CodeLabel,
11930    syntax_theme: &'a theme::SyntaxTheme,
11931) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
11932    let fade_out = HighlightStyle {
11933        fade_out: Some(0.35),
11934        ..Default::default()
11935    };
11936
11937    let mut prev_end = label.filter_range.end;
11938    label
11939        .runs
11940        .iter()
11941        .enumerate()
11942        .flat_map(move |(ix, (range, highlight_id))| {
11943            let style = if let Some(style) = highlight_id.style(syntax_theme) {
11944                style
11945            } else {
11946                return Default::default();
11947            };
11948            let mut muted_style = style;
11949            muted_style.highlight(fade_out);
11950
11951            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
11952            if range.start >= label.filter_range.end {
11953                if range.start > prev_end {
11954                    runs.push((prev_end..range.start, fade_out));
11955                }
11956                runs.push((range.clone(), muted_style));
11957            } else if range.end <= label.filter_range.end {
11958                runs.push((range.clone(), style));
11959            } else {
11960                runs.push((range.start..label.filter_range.end, style));
11961                runs.push((label.filter_range.end..range.end, muted_style));
11962            }
11963            prev_end = cmp::max(prev_end, range.end);
11964
11965            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
11966                runs.push((prev_end..label.text.len(), fade_out));
11967            }
11968
11969            runs
11970        })
11971}
11972
11973pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
11974    let mut prev_index = 0;
11975    let mut prev_codepoint: Option<char> = None;
11976    text.char_indices()
11977        .chain([(text.len(), '\0')])
11978        .filter_map(move |(index, codepoint)| {
11979            let prev_codepoint = prev_codepoint.replace(codepoint)?;
11980            let is_boundary = index == text.len()
11981                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
11982                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
11983            if is_boundary {
11984                let chunk = &text[prev_index..index];
11985                prev_index = index;
11986                Some(chunk)
11987            } else {
11988                None
11989            }
11990        })
11991}
11992
11993trait RangeToAnchorExt {
11994    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
11995}
11996
11997impl<T: ToOffset> RangeToAnchorExt for Range<T> {
11998    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
11999        let start_offset = self.start.to_offset(snapshot);
12000        let end_offset = self.end.to_offset(snapshot);
12001        if start_offset == end_offset {
12002            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
12003        } else {
12004            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
12005        }
12006    }
12007}
12008
12009pub trait RowExt {
12010    fn as_f32(&self) -> f32;
12011
12012    fn next_row(&self) -> Self;
12013
12014    fn previous_row(&self) -> Self;
12015
12016    fn minus(&self, other: Self) -> u32;
12017}
12018
12019impl RowExt for DisplayRow {
12020    fn as_f32(&self) -> f32 {
12021        self.0 as f32
12022    }
12023
12024    fn next_row(&self) -> Self {
12025        Self(self.0 + 1)
12026    }
12027
12028    fn previous_row(&self) -> Self {
12029        Self(self.0.saturating_sub(1))
12030    }
12031
12032    fn minus(&self, other: Self) -> u32 {
12033        self.0 - other.0
12034    }
12035}
12036
12037impl RowExt for MultiBufferRow {
12038    fn as_f32(&self) -> f32 {
12039        self.0 as f32
12040    }
12041
12042    fn next_row(&self) -> Self {
12043        Self(self.0 + 1)
12044    }
12045
12046    fn previous_row(&self) -> Self {
12047        Self(self.0.saturating_sub(1))
12048    }
12049
12050    fn minus(&self, other: Self) -> u32 {
12051        self.0 - other.0
12052    }
12053}
12054
12055trait RowRangeExt {
12056    type Row;
12057
12058    fn len(&self) -> usize;
12059
12060    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
12061}
12062
12063impl RowRangeExt for Range<MultiBufferRow> {
12064    type Row = MultiBufferRow;
12065
12066    fn len(&self) -> usize {
12067        (self.end.0 - self.start.0) as usize
12068    }
12069
12070    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
12071        (self.start.0..self.end.0).map(MultiBufferRow)
12072    }
12073}
12074
12075impl RowRangeExt for Range<DisplayRow> {
12076    type Row = DisplayRow;
12077
12078    fn len(&self) -> usize {
12079        (self.end.0 - self.start.0) as usize
12080    }
12081
12082    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
12083        (self.start.0..self.end.0).map(DisplayRow)
12084    }
12085}
12086
12087fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
12088    if hunk.diff_base_byte_range.is_empty() {
12089        DiffHunkStatus::Added
12090    } else if hunk.associated_range.is_empty() {
12091        DiffHunkStatus::Removed
12092    } else {
12093        DiffHunkStatus::Modified
12094    }
12095}