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 it's behaviour.
  15pub mod actions;
  16mod blink_manager;
  17pub mod display_map;
  18mod editor_settings;
  19mod element;
  20mod inlay_hint_cache;
  21
  22mod git;
  23mod highlight_matching_bracket;
  24mod hover_popover;
  25pub mod items;
  26mod link_go_to_definition;
  27mod mouse_context_menu;
  28pub mod movement;
  29mod persistence;
  30mod rust_analyzer_ext;
  31pub mod scroll;
  32mod selections_collection;
  33
  34#[cfg(test)]
  35mod editor_tests;
  36#[cfg(any(test, feature = "test-support"))]
  37pub mod test;
  38use ::git::diff::DiffHunk;
  39pub(crate) use actions::*;
  40use aho_corasick::AhoCorasick;
  41use anyhow::{anyhow, Context as _, Result};
  42use blink_manager::BlinkManager;
  43use client::{Client, Collaborator, ParticipantIndex};
  44use clock::ReplicaId;
  45use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
  46use convert_case::{Case, Casing};
  47use copilot::Copilot;
  48pub use display_map::DisplayPoint;
  49use display_map::*;
  50pub use editor_settings::EditorSettings;
  51use element::LineWithInvisibles;
  52pub use element::{Cursor, EditorElement, HighlightedRange, HighlightedRangeLine};
  53use futures::FutureExt;
  54use fuzzy::{StringMatch, StringMatchCandidate};
  55use git::diff_hunk_to_display;
  56use gpui::{
  57    div, impl_actions, point, prelude::*, px, relative, rems, size, uniform_list, Action,
  58    AnyElement, AppContext, AsyncWindowContext, BackgroundExecutor, Bounds, ClipboardItem, Context,
  59    DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusableView, FontStyle, FontWeight,
  60    HighlightStyle, Hsla, InputHandler, InteractiveText, KeyContext, Model, MouseButton,
  61    ParentElement, Pixels, Render, SharedString, Styled, StyledText, Subscription, Task, TextStyle,
  62    UniformListScrollHandle, View, ViewContext, VisualContext, WeakView, WhiteSpace, WindowContext,
  63};
  64use highlight_matching_bracket::refresh_matching_bracket_highlights;
  65use hover_popover::{hide_hover, HoverState};
  66use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
  67pub use items::MAX_TAB_TITLE_LEN;
  68use itertools::Itertools;
  69use language::{char_kind, CharKind};
  70use language::{
  71    language_settings::{self, all_language_settings, InlayHintSettings},
  72    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CodeAction,
  73    CodeLabel, Completion, CursorShape, Diagnostic, Documentation, IndentKind, IndentSize,
  74    Language, LanguageRegistry, LanguageServerName, OffsetRangeExt, Point, Selection,
  75    SelectionGoal, TransactionId,
  76};
  77
  78use link_go_to_definition::{GoToDefinitionLink, InlayHighlight, LinkGoToDefinitionState};
  79use lsp::{DiagnosticSeverity, LanguageServerId};
  80use mouse_context_menu::MouseContextMenu;
  81use movement::TextLayoutDetails;
  82use multi_buffer::ToOffsetUtf16;
  83pub use multi_buffer::{
  84    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  85    ToPoint,
  86};
  87use ordered_float::OrderedFloat;
  88use parking_lot::RwLock;
  89use project::{FormatTrigger, Location, Project, ProjectPath, ProjectTransaction};
  90use rand::prelude::*;
  91use rpc::proto::{self, *};
  92use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  93use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  94use serde::{Deserialize, Serialize};
  95use settings::{Settings, SettingsStore};
  96use smallvec::SmallVec;
  97use snippet::Snippet;
  98use std::{
  99    any::TypeId,
 100    borrow::Cow,
 101    cmp::{self, Ordering, Reverse},
 102    mem,
 103    num::NonZeroU32,
 104    ops::{ControlFlow, Deref, DerefMut, Range, RangeInclusive},
 105    path::Path,
 106    sync::Arc,
 107    sync::Weak,
 108    time::{Duration, Instant},
 109};
 110pub use sum_tree::Bias;
 111use sum_tree::TreeMap;
 112use text::{OffsetUtf16, Rope};
 113use theme::{
 114    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
 115    ThemeColors, ThemeSettings,
 116};
 117use ui::{
 118    h_flex, prelude::*, ButtonSize, ButtonStyle, IconButton, IconName, IconSize, ListItem, Popover,
 119    Tooltip,
 120};
 121use util::{post_inc, RangeExt, ResultExt, TryFutureExt};
 122use workspace::{searchable::SearchEvent, ItemNavHistory, Pane, SplitDirection, ViewId, Workspace};
 123
 124const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
 125const MAX_LINE_LEN: usize = 1024;
 126const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
 127const MAX_SELECTION_HISTORY_LEN: usize = 1024;
 128const COPILOT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
 129#[doc(hidden)]
 130pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
 131#[doc(hidden)]
 132pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
 133
 134pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
 135
 136pub fn render_parsed_markdown(
 137    element_id: impl Into<ElementId>,
 138    parsed: &language::ParsedMarkdown,
 139    editor_style: &EditorStyle,
 140    workspace: Option<WeakView<Workspace>>,
 141    cx: &mut ViewContext<Editor>,
 142) -> InteractiveText {
 143    let code_span_background_color = cx
 144        .theme()
 145        .colors()
 146        .editor_document_highlight_read_background;
 147
 148    let highlights = gpui::combine_highlights(
 149        parsed.highlights.iter().filter_map(|(range, highlight)| {
 150            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
 151            Some((range.clone(), highlight))
 152        }),
 153        parsed
 154            .regions
 155            .iter()
 156            .zip(&parsed.region_ranges)
 157            .filter_map(|(region, range)| {
 158                if region.code {
 159                    Some((
 160                        range.clone(),
 161                        HighlightStyle {
 162                            background_color: Some(code_span_background_color),
 163                            ..Default::default()
 164                        },
 165                    ))
 166                } else {
 167                    None
 168                }
 169            }),
 170    );
 171
 172    let mut links = Vec::new();
 173    let mut link_ranges = Vec::new();
 174    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
 175        if let Some(link) = region.link.clone() {
 176            links.push(link);
 177            link_ranges.push(range.clone());
 178        }
 179    }
 180
 181    InteractiveText::new(
 182        element_id,
 183        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
 184    )
 185    .on_click(link_ranges, move |clicked_range_ix, cx| {
 186        match &links[clicked_range_ix] {
 187            markdown::Link::Web { url } => cx.open_url(url),
 188            markdown::Link::Path { path } => {
 189                if let Some(workspace) = &workspace {
 190                    _ = workspace.update(cx, |workspace, cx| {
 191                        workspace.open_abs_path(path.clone(), false, cx).detach();
 192                    });
 193                }
 194            }
 195        }
 196    })
 197}
 198
 199#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
 200pub(crate) enum InlayId {
 201    Suggestion(usize),
 202    Hint(usize),
 203}
 204
 205impl InlayId {
 206    fn id(&self) -> usize {
 207        match self {
 208            Self::Suggestion(id) => *id,
 209            Self::Hint(id) => *id,
 210        }
 211    }
 212}
 213
 214enum DocumentHighlightRead {}
 215enum DocumentHighlightWrite {}
 216enum InputComposition {}
 217
 218#[derive(Copy, Clone, PartialEq, Eq)]
 219pub enum Direction {
 220    Prev,
 221    Next,
 222}
 223
 224pub fn init_settings(cx: &mut AppContext) {
 225    EditorSettings::register(cx);
 226}
 227
 228pub fn init(cx: &mut AppContext) {
 229    init_settings(cx);
 230
 231    workspace::register_project_item::<Editor>(cx);
 232    workspace::register_followable_item::<Editor>(cx);
 233    workspace::register_deserializable_item::<Editor>(cx);
 234    cx.observe_new_views(
 235        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
 236            workspace.register_action(Editor::new_file);
 237            workspace.register_action(Editor::new_file_in_direction);
 238        },
 239    )
 240    .detach();
 241
 242    cx.on_action(move |_: &workspace::NewFile, cx| {
 243        let app_state = cx.global::<Weak<workspace::AppState>>();
 244        if let Some(app_state) = app_state.upgrade() {
 245            workspace::open_new(&app_state, cx, |workspace, cx| {
 246                Editor::new_file(workspace, &Default::default(), cx)
 247            })
 248            .detach();
 249        }
 250    });
 251    cx.on_action(move |_: &workspace::NewWindow, cx| {
 252        let app_state = cx.global::<Weak<workspace::AppState>>();
 253        if let Some(app_state) = app_state.upgrade() {
 254            workspace::open_new(&app_state, cx, |workspace, cx| {
 255                Editor::new_file(workspace, &Default::default(), cx)
 256            })
 257            .detach();
 258        }
 259    });
 260}
 261
 262trait InvalidationRegion {
 263    fn ranges(&self) -> &[Range<Anchor>];
 264}
 265
 266#[derive(Clone, Debug, PartialEq)]
 267pub enum SelectPhase {
 268    Begin {
 269        position: DisplayPoint,
 270        add: bool,
 271        click_count: usize,
 272    },
 273    BeginColumnar {
 274        position: DisplayPoint,
 275        goal_column: u32,
 276    },
 277    Extend {
 278        position: DisplayPoint,
 279        click_count: usize,
 280    },
 281    Update {
 282        position: DisplayPoint,
 283        goal_column: u32,
 284        scroll_position: gpui::Point<f32>,
 285    },
 286    End,
 287}
 288
 289#[derive(Clone, Debug)]
 290pub(crate) enum SelectMode {
 291    Character,
 292    Word(Range<Anchor>),
 293    Line(Range<Anchor>),
 294    All,
 295}
 296
 297#[derive(Copy, Clone, PartialEq, Eq, Debug)]
 298pub enum EditorMode {
 299    SingleLine,
 300    AutoHeight { max_lines: usize },
 301    Full,
 302}
 303
 304#[derive(Clone, Debug)]
 305pub enum SoftWrap {
 306    None,
 307    EditorWidth,
 308    Column(u32),
 309}
 310
 311#[derive(Clone)]
 312pub struct EditorStyle {
 313    pub background: Hsla,
 314    pub local_player: PlayerColor,
 315    pub text: TextStyle,
 316    pub scrollbar_width: Pixels,
 317    pub syntax: Arc<SyntaxTheme>,
 318    pub status: StatusColors,
 319    pub inlays_style: HighlightStyle,
 320    pub suggestions_style: HighlightStyle,
 321}
 322
 323impl Default for EditorStyle {
 324    fn default() -> Self {
 325        Self {
 326            background: Hsla::default(),
 327            local_player: PlayerColor::default(),
 328            text: TextStyle::default(),
 329            scrollbar_width: Pixels::default(),
 330            syntax: Default::default(),
 331            // HACK: Status colors don't have a real default.
 332            // We should look into removing the status colors from the editor
 333            // style and retrieve them directly from the theme.
 334            status: StatusColors::dark(),
 335            inlays_style: HighlightStyle::default(),
 336            suggestions_style: HighlightStyle::default(),
 337        }
 338    }
 339}
 340
 341type CompletionId = usize;
 342
 343// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
 344// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
 345
 346type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Vec<Range<Anchor>>);
 347type InlayBackgroundHighlight = (fn(&ThemeColors) -> Hsla, Vec<InlayHighlight>);
 348
 349pub struct Editor {
 350    handle: WeakView<Self>,
 351    focus_handle: FocusHandle,
 352    buffer: Model<MultiBuffer>,
 353    display_map: Model<DisplayMap>,
 354    pub selections: SelectionsCollection,
 355    pub scroll_manager: ScrollManager,
 356    columnar_selection_tail: Option<Anchor>,
 357    add_selections_state: Option<AddSelectionsState>,
 358    select_next_state: Option<SelectNextState>,
 359    select_prev_state: Option<SelectNextState>,
 360    selection_history: SelectionHistory,
 361    autoclose_regions: Vec<AutocloseRegion>,
 362    snippet_stack: InvalidationStack<SnippetState>,
 363    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
 364    ime_transaction: Option<TransactionId>,
 365    active_diagnostics: Option<ActiveDiagnosticGroup>,
 366    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
 367    project: Option<Model<Project>>,
 368    collaboration_hub: Option<Box<dyn CollaborationHub>>,
 369    blink_manager: Model<BlinkManager>,
 370    recently_focused: bool,
 371    hovered_cursor: Option<HoveredCursor>,
 372    pub show_local_selections: bool,
 373    mode: EditorMode,
 374    show_gutter: bool,
 375    show_wrap_guides: Option<bool>,
 376    placeholder_text: Option<Arc<str>>,
 377    highlighted_rows: Option<Range<u32>>,
 378    background_highlights: BTreeMap<TypeId, BackgroundHighlight>,
 379    inlay_background_highlights: TreeMap<Option<TypeId>, InlayBackgroundHighlight>,
 380    nav_history: Option<ItemNavHistory>,
 381    context_menu: RwLock<Option<ContextMenu>>,
 382    mouse_context_menu: Option<MouseContextMenu>,
 383    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
 384    next_completion_id: CompletionId,
 385    available_code_actions: Option<(Model<Buffer>, Arc<[CodeAction]>)>,
 386    code_actions_task: Option<Task<()>>,
 387    document_highlights_task: Option<Task<()>>,
 388    pending_rename: Option<RenameState>,
 389    searchable: bool,
 390    cursor_shape: CursorShape,
 391    collapse_matches: bool,
 392    autoindent_mode: Option<AutoindentMode>,
 393    workspace: Option<(WeakView<Workspace>, i64)>,
 394    keymap_context_layers: BTreeMap<TypeId, KeyContext>,
 395    input_enabled: bool,
 396    read_only: bool,
 397    leader_peer_id: Option<PeerId>,
 398    remote_id: Option<ViewId>,
 399    hover_state: HoverState,
 400    gutter_hovered: bool,
 401    link_go_to_definition_state: LinkGoToDefinitionState,
 402    copilot_state: CopilotState,
 403    inlay_hint_cache: InlayHintCache,
 404    next_inlay_id: usize,
 405    _subscriptions: Vec<Subscription>,
 406    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
 407    gutter_width: Pixels,
 408    style: Option<EditorStyle>,
 409    editor_actions: Vec<Box<dyn Fn(&mut ViewContext<Self>)>>,
 410    show_copilot_suggestions: bool,
 411}
 412
 413pub struct EditorSnapshot {
 414    pub mode: EditorMode,
 415    pub show_gutter: bool,
 416    pub display_snapshot: DisplaySnapshot,
 417    pub placeholder_text: Option<Arc<str>>,
 418    is_focused: bool,
 419    scroll_anchor: ScrollAnchor,
 420    ongoing_scroll: OngoingScroll,
 421}
 422
 423#[derive(Debug)]
 424pub struct RemoteSelection {
 425    pub replica_id: ReplicaId,
 426    pub selection: Selection<Anchor>,
 427    pub cursor_shape: CursorShape,
 428    pub peer_id: PeerId,
 429    pub line_mode: bool,
 430    pub participant_index: Option<ParticipantIndex>,
 431    pub user_name: Option<SharedString>,
 432}
 433
 434#[derive(Clone, Debug)]
 435struct SelectionHistoryEntry {
 436    selections: Arc<[Selection<Anchor>]>,
 437    select_next_state: Option<SelectNextState>,
 438    select_prev_state: Option<SelectNextState>,
 439    add_selections_state: Option<AddSelectionsState>,
 440}
 441
 442enum SelectionHistoryMode {
 443    Normal,
 444    Undoing,
 445    Redoing,
 446}
 447
 448struct HoveredCursor {
 449    replica_id: u16,
 450    selection_id: usize,
 451}
 452
 453impl Default for SelectionHistoryMode {
 454    fn default() -> Self {
 455        Self::Normal
 456    }
 457}
 458
 459#[derive(Default)]
 460struct SelectionHistory {
 461    #[allow(clippy::type_complexity)]
 462    selections_by_transaction:
 463        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
 464    mode: SelectionHistoryMode,
 465    undo_stack: VecDeque<SelectionHistoryEntry>,
 466    redo_stack: VecDeque<SelectionHistoryEntry>,
 467}
 468
 469impl SelectionHistory {
 470    fn insert_transaction(
 471        &mut self,
 472        transaction_id: TransactionId,
 473        selections: Arc<[Selection<Anchor>]>,
 474    ) {
 475        self.selections_by_transaction
 476            .insert(transaction_id, (selections, None));
 477    }
 478
 479    #[allow(clippy::type_complexity)]
 480    fn transaction(
 481        &self,
 482        transaction_id: TransactionId,
 483    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 484        self.selections_by_transaction.get(&transaction_id)
 485    }
 486
 487    #[allow(clippy::type_complexity)]
 488    fn transaction_mut(
 489        &mut self,
 490        transaction_id: TransactionId,
 491    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 492        self.selections_by_transaction.get_mut(&transaction_id)
 493    }
 494
 495    fn push(&mut self, entry: SelectionHistoryEntry) {
 496        if !entry.selections.is_empty() {
 497            match self.mode {
 498                SelectionHistoryMode::Normal => {
 499                    self.push_undo(entry);
 500                    self.redo_stack.clear();
 501                }
 502                SelectionHistoryMode::Undoing => self.push_redo(entry),
 503                SelectionHistoryMode::Redoing => self.push_undo(entry),
 504            }
 505        }
 506    }
 507
 508    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
 509        if self
 510            .undo_stack
 511            .back()
 512            .map_or(true, |e| e.selections != entry.selections)
 513        {
 514            self.undo_stack.push_back(entry);
 515            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 516                self.undo_stack.pop_front();
 517            }
 518        }
 519    }
 520
 521    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
 522        if self
 523            .redo_stack
 524            .back()
 525            .map_or(true, |e| e.selections != entry.selections)
 526        {
 527            self.redo_stack.push_back(entry);
 528            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 529                self.redo_stack.pop_front();
 530            }
 531        }
 532    }
 533}
 534
 535#[derive(Clone, Debug)]
 536struct AddSelectionsState {
 537    above: bool,
 538    stack: Vec<usize>,
 539}
 540
 541#[derive(Clone)]
 542struct SelectNextState {
 543    query: AhoCorasick,
 544    wordwise: bool,
 545    done: bool,
 546}
 547
 548impl std::fmt::Debug for SelectNextState {
 549    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 550        f.debug_struct(std::any::type_name::<Self>())
 551            .field("wordwise", &self.wordwise)
 552            .field("done", &self.done)
 553            .finish()
 554    }
 555}
 556
 557#[derive(Debug)]
 558struct AutocloseRegion {
 559    selection_id: usize,
 560    range: Range<Anchor>,
 561    pair: BracketPair,
 562}
 563
 564#[derive(Debug)]
 565struct SnippetState {
 566    ranges: Vec<Vec<Range<Anchor>>>,
 567    active_index: usize,
 568}
 569
 570#[doc(hidden)]
 571pub struct RenameState {
 572    pub range: Range<Anchor>,
 573    pub old_name: Arc<str>,
 574    pub editor: View<Editor>,
 575    block_id: BlockId,
 576}
 577
 578struct InvalidationStack<T>(Vec<T>);
 579
 580enum ContextMenu {
 581    Completions(CompletionsMenu),
 582    CodeActions(CodeActionsMenu),
 583}
 584
 585impl ContextMenu {
 586    fn select_first(
 587        &mut self,
 588        project: Option<&Model<Project>>,
 589        cx: &mut ViewContext<Editor>,
 590    ) -> bool {
 591        if self.visible() {
 592            match self {
 593                ContextMenu::Completions(menu) => menu.select_first(project, cx),
 594                ContextMenu::CodeActions(menu) => menu.select_first(cx),
 595            }
 596            true
 597        } else {
 598            false
 599        }
 600    }
 601
 602    fn select_prev(
 603        &mut self,
 604        project: Option<&Model<Project>>,
 605        cx: &mut ViewContext<Editor>,
 606    ) -> bool {
 607        if self.visible() {
 608            match self {
 609                ContextMenu::Completions(menu) => menu.select_prev(project, cx),
 610                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
 611            }
 612            true
 613        } else {
 614            false
 615        }
 616    }
 617
 618    fn select_next(
 619        &mut self,
 620        project: Option<&Model<Project>>,
 621        cx: &mut ViewContext<Editor>,
 622    ) -> bool {
 623        if self.visible() {
 624            match self {
 625                ContextMenu::Completions(menu) => menu.select_next(project, cx),
 626                ContextMenu::CodeActions(menu) => menu.select_next(cx),
 627            }
 628            true
 629        } else {
 630            false
 631        }
 632    }
 633
 634    fn select_last(
 635        &mut self,
 636        project: Option<&Model<Project>>,
 637        cx: &mut ViewContext<Editor>,
 638    ) -> bool {
 639        if self.visible() {
 640            match self {
 641                ContextMenu::Completions(menu) => menu.select_last(project, cx),
 642                ContextMenu::CodeActions(menu) => menu.select_last(cx),
 643            }
 644            true
 645        } else {
 646            false
 647        }
 648    }
 649
 650    fn visible(&self) -> bool {
 651        match self {
 652            ContextMenu::Completions(menu) => menu.visible(),
 653            ContextMenu::CodeActions(menu) => menu.visible(),
 654        }
 655    }
 656
 657    fn render(
 658        &self,
 659        cursor_position: DisplayPoint,
 660        style: &EditorStyle,
 661        max_height: Pixels,
 662        workspace: Option<WeakView<Workspace>>,
 663        cx: &mut ViewContext<Editor>,
 664    ) -> (DisplayPoint, AnyElement) {
 665        match self {
 666            ContextMenu::Completions(menu) => (
 667                cursor_position,
 668                menu.render(style, max_height, workspace, cx),
 669            ),
 670            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
 671        }
 672    }
 673}
 674
 675#[derive(Clone)]
 676struct CompletionsMenu {
 677    id: CompletionId,
 678    initial_position: Anchor,
 679    buffer: Model<Buffer>,
 680    completions: Arc<RwLock<Box<[Completion]>>>,
 681    match_candidates: Arc<[StringMatchCandidate]>,
 682    matches: Arc<[StringMatch]>,
 683    selected_item: usize,
 684    scroll_handle: UniformListScrollHandle,
 685}
 686
 687impl CompletionsMenu {
 688    fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
 689        self.selected_item = 0;
 690        self.scroll_handle.scroll_to_item(self.selected_item);
 691        self.attempt_resolve_selected_completion_documentation(project, cx);
 692        cx.notify();
 693    }
 694
 695    fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
 696        if self.selected_item > 0 {
 697            self.selected_item -= 1;
 698        } else {
 699            self.selected_item = self.matches.len() - 1;
 700        }
 701        self.scroll_handle.scroll_to_item(self.selected_item);
 702        self.attempt_resolve_selected_completion_documentation(project, cx);
 703        cx.notify();
 704    }
 705
 706    fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
 707        if self.selected_item + 1 < self.matches.len() {
 708            self.selected_item += 1;
 709        } else {
 710            self.selected_item = 0;
 711        }
 712        self.scroll_handle.scroll_to_item(self.selected_item);
 713        self.attempt_resolve_selected_completion_documentation(project, cx);
 714        cx.notify();
 715    }
 716
 717    fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
 718        self.selected_item = self.matches.len() - 1;
 719        self.scroll_handle.scroll_to_item(self.selected_item);
 720        self.attempt_resolve_selected_completion_documentation(project, cx);
 721        cx.notify();
 722    }
 723
 724    fn pre_resolve_completion_documentation(
 725        &self,
 726        editor: &Editor,
 727        cx: &mut ViewContext<Editor>,
 728    ) -> Option<Task<()>> {
 729        let settings = EditorSettings::get_global(cx);
 730        if !settings.show_completion_documentation {
 731            return None;
 732        }
 733
 734        let Some(project) = editor.project.clone() else {
 735            return None;
 736        };
 737
 738        let client = project.read(cx).client();
 739        let language_registry = project.read(cx).languages().clone();
 740
 741        let is_remote = project.read(cx).is_remote();
 742        let project_id = project.read(cx).remote_id();
 743
 744        let completions = self.completions.clone();
 745        let completion_indices: Vec<_> = self.matches.iter().map(|m| m.candidate_id).collect();
 746
 747        Some(cx.spawn(move |this, mut cx| async move {
 748            if is_remote {
 749                let Some(project_id) = project_id else {
 750                    log::error!("Remote project without remote_id");
 751                    return;
 752                };
 753
 754                for completion_index in completion_indices {
 755                    let completions_guard = completions.read();
 756                    let completion = &completions_guard[completion_index];
 757                    if completion.documentation.is_some() {
 758                        continue;
 759                    }
 760
 761                    let server_id = completion.server_id;
 762                    let completion = completion.lsp_completion.clone();
 763                    drop(completions_guard);
 764
 765                    Self::resolve_completion_documentation_remote(
 766                        project_id,
 767                        server_id,
 768                        completions.clone(),
 769                        completion_index,
 770                        completion,
 771                        client.clone(),
 772                        language_registry.clone(),
 773                    )
 774                    .await;
 775
 776                    _ = this.update(&mut cx, |_, cx| cx.notify());
 777                }
 778            } else {
 779                for completion_index in completion_indices {
 780                    let completions_guard = completions.read();
 781                    let completion = &completions_guard[completion_index];
 782                    if completion.documentation.is_some() {
 783                        continue;
 784                    }
 785
 786                    let server_id = completion.server_id;
 787                    let completion = completion.lsp_completion.clone();
 788                    drop(completions_guard);
 789
 790                    let server = project
 791                        .read_with(&mut cx, |project, _| {
 792                            project.language_server_for_id(server_id)
 793                        })
 794                        .ok()
 795                        .flatten();
 796                    let Some(server) = server else {
 797                        return;
 798                    };
 799
 800                    Self::resolve_completion_documentation_local(
 801                        server,
 802                        completions.clone(),
 803                        completion_index,
 804                        completion,
 805                        language_registry.clone(),
 806                    )
 807                    .await;
 808
 809                    _ = this.update(&mut cx, |_, cx| cx.notify());
 810                }
 811            }
 812        }))
 813    }
 814
 815    fn attempt_resolve_selected_completion_documentation(
 816        &mut self,
 817        project: Option<&Model<Project>>,
 818        cx: &mut ViewContext<Editor>,
 819    ) {
 820        let settings = EditorSettings::get_global(cx);
 821        if !settings.show_completion_documentation {
 822            return;
 823        }
 824
 825        let completion_index = self.matches[self.selected_item].candidate_id;
 826        let Some(project) = project else {
 827            return;
 828        };
 829        let language_registry = project.read(cx).languages().clone();
 830
 831        let completions = self.completions.clone();
 832        let completions_guard = completions.read();
 833        let completion = &completions_guard[completion_index];
 834        if completion.documentation.is_some() {
 835            return;
 836        }
 837
 838        let server_id = completion.server_id;
 839        let completion = completion.lsp_completion.clone();
 840        drop(completions_guard);
 841
 842        if project.read(cx).is_remote() {
 843            let Some(project_id) = project.read(cx).remote_id() else {
 844                log::error!("Remote project without remote_id");
 845                return;
 846            };
 847
 848            let client = project.read(cx).client();
 849
 850            cx.spawn(move |this, mut cx| async move {
 851                Self::resolve_completion_documentation_remote(
 852                    project_id,
 853                    server_id,
 854                    completions.clone(),
 855                    completion_index,
 856                    completion,
 857                    client,
 858                    language_registry.clone(),
 859                )
 860                .await;
 861
 862                _ = this.update(&mut cx, |_, cx| cx.notify());
 863            })
 864            .detach();
 865        } else {
 866            let Some(server) = project.read(cx).language_server_for_id(server_id) else {
 867                return;
 868            };
 869
 870            cx.spawn(move |this, mut cx| async move {
 871                Self::resolve_completion_documentation_local(
 872                    server,
 873                    completions,
 874                    completion_index,
 875                    completion,
 876                    language_registry,
 877                )
 878                .await;
 879
 880                _ = this.update(&mut cx, |_, cx| cx.notify());
 881            })
 882            .detach();
 883        }
 884    }
 885
 886    async fn resolve_completion_documentation_remote(
 887        project_id: u64,
 888        server_id: LanguageServerId,
 889        completions: Arc<RwLock<Box<[Completion]>>>,
 890        completion_index: usize,
 891        completion: lsp::CompletionItem,
 892        client: Arc<Client>,
 893        language_registry: Arc<LanguageRegistry>,
 894    ) {
 895        let request = proto::ResolveCompletionDocumentation {
 896            project_id,
 897            language_server_id: server_id.0 as u64,
 898            lsp_completion: serde_json::to_string(&completion).unwrap().into_bytes(),
 899        };
 900
 901        let Some(response) = client
 902            .request(request)
 903            .await
 904            .context("completion documentation resolve proto request")
 905            .log_err()
 906        else {
 907            return;
 908        };
 909
 910        if response.text.is_empty() {
 911            let mut completions = completions.write();
 912            let completion = &mut completions[completion_index];
 913            completion.documentation = Some(Documentation::Undocumented);
 914        }
 915
 916        let documentation = if response.is_markdown {
 917            Documentation::MultiLineMarkdown(
 918                markdown::parse_markdown(&response.text, &language_registry, None).await,
 919            )
 920        } else if response.text.lines().count() <= 1 {
 921            Documentation::SingleLine(response.text)
 922        } else {
 923            Documentation::MultiLinePlainText(response.text)
 924        };
 925
 926        let mut completions = completions.write();
 927        let completion = &mut completions[completion_index];
 928        completion.documentation = Some(documentation);
 929    }
 930
 931    async fn resolve_completion_documentation_local(
 932        server: Arc<lsp::LanguageServer>,
 933        completions: Arc<RwLock<Box<[Completion]>>>,
 934        completion_index: usize,
 935        completion: lsp::CompletionItem,
 936        language_registry: Arc<LanguageRegistry>,
 937    ) {
 938        let can_resolve = server
 939            .capabilities()
 940            .completion_provider
 941            .as_ref()
 942            .and_then(|options| options.resolve_provider)
 943            .unwrap_or(false);
 944        if !can_resolve {
 945            return;
 946        }
 947
 948        let request = server.request::<lsp::request::ResolveCompletionItem>(completion);
 949        let Some(completion_item) = request.await.log_err() else {
 950            return;
 951        };
 952
 953        if let Some(lsp_documentation) = completion_item.documentation {
 954            let documentation = language::prepare_completion_documentation(
 955                &lsp_documentation,
 956                &language_registry,
 957                None, // TODO: Try to reasonably work out which language the completion is for
 958            )
 959            .await;
 960
 961            let mut completions = completions.write();
 962            let completion = &mut completions[completion_index];
 963            completion.documentation = Some(documentation);
 964        } else {
 965            let mut completions = completions.write();
 966            let completion = &mut completions[completion_index];
 967            completion.documentation = Some(Documentation::Undocumented);
 968        }
 969    }
 970
 971    fn visible(&self) -> bool {
 972        !self.matches.is_empty()
 973    }
 974
 975    fn render(
 976        &self,
 977        style: &EditorStyle,
 978        max_height: Pixels,
 979        workspace: Option<WeakView<Workspace>>,
 980        cx: &mut ViewContext<Editor>,
 981    ) -> AnyElement {
 982        let settings = EditorSettings::get_global(cx);
 983        let show_completion_documentation = settings.show_completion_documentation;
 984
 985        let widest_completion_ix = self
 986            .matches
 987            .iter()
 988            .enumerate()
 989            .max_by_key(|(_, mat)| {
 990                let completions = self.completions.read();
 991                let completion = &completions[mat.candidate_id];
 992                let documentation = &completion.documentation;
 993
 994                let mut len = completion.label.text.chars().count();
 995                if let Some(Documentation::SingleLine(text)) = documentation {
 996                    if show_completion_documentation {
 997                        len += text.chars().count();
 998                    }
 999                }
1000
1001                len
1002            })
1003            .map(|(ix, _)| ix);
1004
1005        let completions = self.completions.clone();
1006        let matches = self.matches.clone();
1007        let selected_item = self.selected_item;
1008        let style = style.clone();
1009
1010        let multiline_docs = {
1011            let mat = &self.matches[selected_item];
1012            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1013                Some(Documentation::MultiLinePlainText(text)) => {
1014                    Some(div().child(SharedString::from(text.clone())))
1015                }
1016                Some(Documentation::MultiLineMarkdown(parsed)) => Some(div().child(
1017                    render_parsed_markdown("completions_markdown", parsed, &style, workspace, cx),
1018                )),
1019                _ => None,
1020            };
1021            multiline_docs.map(|div| {
1022                div.id("multiline_docs")
1023                    .max_h(max_height)
1024                    .flex_1()
1025                    .px_1p5()
1026                    .py_1()
1027                    .min_w(px(260.))
1028                    .max_w(px(640.))
1029                    .w(px(500.))
1030                    .overflow_y_scroll()
1031                    // Prevent a mouse down on documentation from being propagated to the editor,
1032                    // because that would move the cursor.
1033                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1034            })
1035        };
1036
1037        let list = uniform_list(
1038            cx.view().clone(),
1039            "completions",
1040            matches.len(),
1041            move |_editor, range, cx| {
1042                let start_ix = range.start;
1043                let completions_guard = completions.read();
1044
1045                matches[range]
1046                    .iter()
1047                    .enumerate()
1048                    .map(|(ix, mat)| {
1049                        let item_ix = start_ix + ix;
1050                        let candidate_id = mat.candidate_id;
1051                        let completion = &completions_guard[candidate_id];
1052
1053                        let documentation = if show_completion_documentation {
1054                            &completion.documentation
1055                        } else {
1056                            &None
1057                        };
1058
1059                        let highlights = gpui::combine_highlights(
1060                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1061                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
1062                                |(range, mut highlight)| {
1063                                    // Ignore font weight for syntax highlighting, as we'll use it
1064                                    // for fuzzy matches.
1065                                    highlight.font_weight = None;
1066                                    (range, highlight)
1067                                },
1068                            ),
1069                        );
1070                        let completion_label = StyledText::new(completion.label.text.clone())
1071                            .with_highlights(&style.text, highlights);
1072                        let documentation_label =
1073                            if let Some(Documentation::SingleLine(text)) = documentation {
1074                                if text.trim().is_empty() {
1075                                    None
1076                                } else {
1077                                    Some(
1078                                        h_flex().ml_4().child(
1079                                            Label::new(text.clone())
1080                                                .size(LabelSize::Small)
1081                                                .color(Color::Muted),
1082                                        ),
1083                                    )
1084                                }
1085                            } else {
1086                                None
1087                            };
1088
1089                        div().min_w(px(220.)).max_w(px(540.)).child(
1090                            ListItem::new(mat.candidate_id)
1091                                .inset(true)
1092                                .selected(item_ix == selected_item)
1093                                .on_click(cx.listener(move |editor, _event, cx| {
1094                                    cx.stop_propagation();
1095                                    editor
1096                                        .confirm_completion(
1097                                            &ConfirmCompletion {
1098                                                item_ix: Some(item_ix),
1099                                            },
1100                                            cx,
1101                                        )
1102                                        .map(|task| task.detach_and_log_err(cx));
1103                                }))
1104                                .child(h_flex().overflow_hidden().child(completion_label))
1105                                .end_slot::<Div>(documentation_label),
1106                        )
1107                    })
1108                    .collect()
1109            },
1110        )
1111        .max_h(max_height)
1112        .track_scroll(self.scroll_handle.clone())
1113        .with_width_from_item(widest_completion_ix);
1114
1115        Popover::new()
1116            .child(list)
1117            .when_some(multiline_docs, |popover, multiline_docs| {
1118                popover.aside(multiline_docs)
1119            })
1120            .into_any_element()
1121    }
1122
1123    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1124        let mut matches = if let Some(query) = query {
1125            fuzzy::match_strings(
1126                &self.match_candidates,
1127                query,
1128                query.chars().any(|c| c.is_uppercase()),
1129                100,
1130                &Default::default(),
1131                executor,
1132            )
1133            .await
1134        } else {
1135            self.match_candidates
1136                .iter()
1137                .enumerate()
1138                .map(|(candidate_id, candidate)| StringMatch {
1139                    candidate_id,
1140                    score: Default::default(),
1141                    positions: Default::default(),
1142                    string: candidate.string.clone(),
1143                })
1144                .collect()
1145        };
1146
1147        // Remove all candidates where the query's start does not match the start of any word in the candidate
1148        if let Some(query) = query {
1149            if let Some(query_start) = query.chars().next() {
1150                matches.retain(|string_match| {
1151                    split_words(&string_match.string).any(|word| {
1152                        // Check that the first codepoint of the word as lowercase matches the first
1153                        // codepoint of the query as lowercase
1154                        word.chars()
1155                            .flat_map(|codepoint| codepoint.to_lowercase())
1156                            .zip(query_start.to_lowercase())
1157                            .all(|(word_cp, query_cp)| word_cp == query_cp)
1158                    })
1159                });
1160            }
1161        }
1162
1163        let completions = self.completions.read();
1164        matches.sort_unstable_by_key(|mat| {
1165            let completion = &completions[mat.candidate_id];
1166            (
1167                completion.lsp_completion.sort_text.as_ref(),
1168                Reverse(OrderedFloat(mat.score)),
1169                completion.sort_key(),
1170            )
1171        });
1172
1173        for mat in &mut matches {
1174            let completion = &completions[mat.candidate_id];
1175            mat.string = completion.label.text.clone();
1176            for position in &mut mat.positions {
1177                *position += completion.label.filter_range.start;
1178            }
1179        }
1180        drop(completions);
1181
1182        self.matches = matches.into();
1183        self.selected_item = 0;
1184    }
1185}
1186
1187#[derive(Clone)]
1188struct CodeActionsMenu {
1189    actions: Arc<[CodeAction]>,
1190    buffer: Model<Buffer>,
1191    selected_item: usize,
1192    scroll_handle: UniformListScrollHandle,
1193    deployed_from_indicator: bool,
1194}
1195
1196impl CodeActionsMenu {
1197    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1198        self.selected_item = 0;
1199        self.scroll_handle.scroll_to_item(self.selected_item);
1200        cx.notify()
1201    }
1202
1203    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1204        if self.selected_item > 0 {
1205            self.selected_item -= 1;
1206        } else {
1207            self.selected_item = self.actions.len() - 1;
1208        }
1209        self.scroll_handle.scroll_to_item(self.selected_item);
1210        cx.notify();
1211    }
1212
1213    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1214        if self.selected_item + 1 < self.actions.len() {
1215            self.selected_item += 1;
1216        } else {
1217            self.selected_item = 0;
1218        }
1219        self.scroll_handle.scroll_to_item(self.selected_item);
1220        cx.notify();
1221    }
1222
1223    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1224        self.selected_item = self.actions.len() - 1;
1225        self.scroll_handle.scroll_to_item(self.selected_item);
1226        cx.notify()
1227    }
1228
1229    fn visible(&self) -> bool {
1230        !self.actions.is_empty()
1231    }
1232
1233    fn render(
1234        &self,
1235        mut cursor_position: DisplayPoint,
1236        _style: &EditorStyle,
1237        max_height: Pixels,
1238        cx: &mut ViewContext<Editor>,
1239    ) -> (DisplayPoint, AnyElement) {
1240        let actions = self.actions.clone();
1241        let selected_item = self.selected_item;
1242
1243        let element = uniform_list(
1244            cx.view().clone(),
1245            "code_actions_menu",
1246            self.actions.len(),
1247            move |_this, range, cx| {
1248                actions[range.clone()]
1249                    .iter()
1250                    .enumerate()
1251                    .map(|(ix, action)| {
1252                        let item_ix = range.start + ix;
1253                        let selected = selected_item == item_ix;
1254                        let colors = cx.theme().colors();
1255                        div()
1256                            .px_2()
1257                            .text_color(colors.text)
1258                            .when(selected, |style| {
1259                                style
1260                                    .bg(colors.element_active)
1261                                    .text_color(colors.text_accent)
1262                            })
1263                            .hover(|style| {
1264                                style
1265                                    .bg(colors.element_hover)
1266                                    .text_color(colors.text_accent)
1267                            })
1268                            .on_mouse_down(
1269                                MouseButton::Left,
1270                                cx.listener(move |editor, _, cx| {
1271                                    cx.stop_propagation();
1272                                    editor
1273                                        .confirm_code_action(
1274                                            &ConfirmCodeAction {
1275                                                item_ix: Some(item_ix),
1276                                            },
1277                                            cx,
1278                                        )
1279                                        .map(|task| task.detach_and_log_err(cx));
1280                                }),
1281                            )
1282                            // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1283                            .child(SharedString::from(action.lsp_action.title.clone()))
1284                    })
1285                    .collect()
1286            },
1287        )
1288        .elevation_1(cx)
1289        .px_2()
1290        .py_1()
1291        .max_h(max_height)
1292        .track_scroll(self.scroll_handle.clone())
1293        .with_width_from_item(
1294            self.actions
1295                .iter()
1296                .enumerate()
1297                .max_by_key(|(_, action)| action.lsp_action.title.chars().count())
1298                .map(|(ix, _)| ix),
1299        )
1300        .into_any_element();
1301
1302        if self.deployed_from_indicator {
1303            *cursor_position.column_mut() = 0;
1304        }
1305
1306        (cursor_position, element)
1307    }
1308}
1309
1310pub(crate) struct CopilotState {
1311    excerpt_id: Option<ExcerptId>,
1312    pending_refresh: Task<Option<()>>,
1313    pending_cycling_refresh: Task<Option<()>>,
1314    cycled: bool,
1315    completions: Vec<copilot::Completion>,
1316    active_completion_index: usize,
1317    suggestion: Option<Inlay>,
1318}
1319
1320impl Default for CopilotState {
1321    fn default() -> Self {
1322        Self {
1323            excerpt_id: None,
1324            pending_cycling_refresh: Task::ready(Some(())),
1325            pending_refresh: Task::ready(Some(())),
1326            completions: Default::default(),
1327            active_completion_index: 0,
1328            cycled: false,
1329            suggestion: None,
1330        }
1331    }
1332}
1333
1334impl CopilotState {
1335    fn active_completion(&self) -> Option<&copilot::Completion> {
1336        self.completions.get(self.active_completion_index)
1337    }
1338
1339    fn text_for_active_completion(
1340        &self,
1341        cursor: Anchor,
1342        buffer: &MultiBufferSnapshot,
1343    ) -> Option<&str> {
1344        use language::ToOffset as _;
1345
1346        let completion = self.active_completion()?;
1347        let excerpt_id = self.excerpt_id?;
1348        let completion_buffer = buffer.buffer_for_excerpt(excerpt_id)?;
1349        if excerpt_id != cursor.excerpt_id
1350            || !completion.range.start.is_valid(completion_buffer)
1351            || !completion.range.end.is_valid(completion_buffer)
1352        {
1353            return None;
1354        }
1355
1356        let mut completion_range = completion.range.to_offset(&completion_buffer);
1357        let prefix_len = Self::common_prefix(
1358            completion_buffer.chars_for_range(completion_range.clone()),
1359            completion.text.chars(),
1360        );
1361        completion_range.start += prefix_len;
1362        let suffix_len = Self::common_prefix(
1363            completion_buffer.reversed_chars_for_range(completion_range.clone()),
1364            completion.text[prefix_len..].chars().rev(),
1365        );
1366        completion_range.end = completion_range.end.saturating_sub(suffix_len);
1367
1368        if completion_range.is_empty()
1369            && completion_range.start == cursor.text_anchor.to_offset(&completion_buffer)
1370        {
1371            Some(&completion.text[prefix_len..completion.text.len() - suffix_len])
1372        } else {
1373            None
1374        }
1375    }
1376
1377    fn cycle_completions(&mut self, direction: Direction) {
1378        match direction {
1379            Direction::Prev => {
1380                self.active_completion_index = if self.active_completion_index == 0 {
1381                    self.completions.len().saturating_sub(1)
1382                } else {
1383                    self.active_completion_index - 1
1384                };
1385            }
1386            Direction::Next => {
1387                if self.completions.len() == 0 {
1388                    self.active_completion_index = 0
1389                } else {
1390                    self.active_completion_index =
1391                        (self.active_completion_index + 1) % self.completions.len();
1392                }
1393            }
1394        }
1395    }
1396
1397    fn push_completion(&mut self, new_completion: copilot::Completion) {
1398        for completion in &self.completions {
1399            if completion.text == new_completion.text && completion.range == new_completion.range {
1400                return;
1401            }
1402        }
1403        self.completions.push(new_completion);
1404    }
1405
1406    fn common_prefix<T1: Iterator<Item = char>, T2: Iterator<Item = char>>(a: T1, b: T2) -> usize {
1407        a.zip(b)
1408            .take_while(|(a, b)| a == b)
1409            .map(|(a, _)| a.len_utf8())
1410            .sum()
1411    }
1412}
1413
1414#[derive(Debug)]
1415struct ActiveDiagnosticGroup {
1416    primary_range: Range<Anchor>,
1417    primary_message: String,
1418    blocks: HashMap<BlockId, Diagnostic>,
1419    is_valid: bool,
1420}
1421
1422#[derive(Serialize, Deserialize)]
1423pub struct ClipboardSelection {
1424    pub len: usize,
1425    pub is_entire_line: bool,
1426    pub first_line_indent: u32,
1427}
1428
1429#[derive(Debug)]
1430pub(crate) struct NavigationData {
1431    cursor_anchor: Anchor,
1432    cursor_position: Point,
1433    scroll_anchor: ScrollAnchor,
1434    scroll_top_row: u32,
1435}
1436
1437enum GotoDefinitionKind {
1438    Symbol,
1439    Type,
1440}
1441
1442#[derive(Debug, Clone)]
1443enum InlayHintRefreshReason {
1444    Toggle(bool),
1445    SettingsChange(InlayHintSettings),
1446    NewLinesShown,
1447    BufferEdited(HashSet<Arc<Language>>),
1448    RefreshRequested,
1449    ExcerptsRemoved(Vec<ExcerptId>),
1450}
1451impl InlayHintRefreshReason {
1452    fn description(&self) -> &'static str {
1453        match self {
1454            Self::Toggle(_) => "toggle",
1455            Self::SettingsChange(_) => "settings change",
1456            Self::NewLinesShown => "new lines shown",
1457            Self::BufferEdited(_) => "buffer edited",
1458            Self::RefreshRequested => "refresh requested",
1459            Self::ExcerptsRemoved(_) => "excerpts removed",
1460        }
1461    }
1462}
1463
1464impl Editor {
1465    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1466        let buffer = cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), String::new()));
1467        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1468        Self::new(EditorMode::SingleLine, buffer, None, cx)
1469    }
1470
1471    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1472        let buffer = cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), String::new()));
1473        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1474        Self::new(EditorMode::Full, buffer, None, cx)
1475    }
1476
1477    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1478        let buffer = cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), String::new()));
1479        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1480        Self::new(EditorMode::AutoHeight { max_lines }, buffer, None, cx)
1481    }
1482
1483    pub fn for_buffer(
1484        buffer: Model<Buffer>,
1485        project: Option<Model<Project>>,
1486        cx: &mut ViewContext<Self>,
1487    ) -> Self {
1488        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1489        Self::new(EditorMode::Full, buffer, project, cx)
1490    }
1491
1492    pub fn for_multibuffer(
1493        buffer: Model<MultiBuffer>,
1494        project: Option<Model<Project>>,
1495        cx: &mut ViewContext<Self>,
1496    ) -> Self {
1497        Self::new(EditorMode::Full, buffer, project, cx)
1498    }
1499
1500    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1501        let mut clone = Self::new(self.mode, self.buffer.clone(), self.project.clone(), cx);
1502        self.display_map.update(cx, |display_map, cx| {
1503            let snapshot = display_map.snapshot(cx);
1504            clone.display_map.update(cx, |display_map, cx| {
1505                display_map.set_state(&snapshot, cx);
1506            });
1507        });
1508        clone.selections.clone_state(&self.selections);
1509        clone.scroll_manager.clone_state(&self.scroll_manager);
1510        clone.searchable = self.searchable;
1511        clone
1512    }
1513
1514    fn new(
1515        mode: EditorMode,
1516        buffer: Model<MultiBuffer>,
1517        project: Option<Model<Project>>,
1518        cx: &mut ViewContext<Self>,
1519    ) -> Self {
1520        let style = cx.text_style();
1521        let font_size = style.font_size.to_pixels(cx.rem_size());
1522        let display_map = cx.new_model(|cx| {
1523            DisplayMap::new(buffer.clone(), style.font(), font_size, None, 2, 1, cx)
1524        });
1525
1526        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1527
1528        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1529
1530        let soft_wrap_mode_override =
1531            (mode == EditorMode::SingleLine).then(|| language_settings::SoftWrap::None);
1532
1533        let mut project_subscriptions = Vec::new();
1534        if mode == EditorMode::Full {
1535            if let Some(project) = project.as_ref() {
1536                if buffer.read(cx).is_singleton() {
1537                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
1538                        cx.emit(EditorEvent::TitleChanged);
1539                    }));
1540                }
1541                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1542                    if let project::Event::RefreshInlayHints = event {
1543                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1544                    };
1545                }));
1546            }
1547        }
1548
1549        let inlay_hint_settings = inlay_hint_settings(
1550            selections.newest_anchor().head(),
1551            &buffer.read(cx).snapshot(cx),
1552            cx,
1553        );
1554
1555        let focus_handle = cx.focus_handle();
1556        cx.on_focus(&focus_handle, Self::handle_focus).detach();
1557        cx.on_blur(&focus_handle, Self::handle_blur).detach();
1558
1559        let mut this = Self {
1560            handle: cx.view().downgrade(),
1561            focus_handle,
1562            buffer: buffer.clone(),
1563            display_map: display_map.clone(),
1564            selections,
1565            scroll_manager: ScrollManager::new(),
1566            columnar_selection_tail: None,
1567            add_selections_state: None,
1568            select_next_state: None,
1569            select_prev_state: None,
1570            selection_history: Default::default(),
1571            autoclose_regions: Default::default(),
1572            snippet_stack: Default::default(),
1573            select_larger_syntax_node_stack: Vec::new(),
1574            ime_transaction: Default::default(),
1575            active_diagnostics: None,
1576            soft_wrap_mode_override,
1577            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1578            project,
1579            blink_manager: blink_manager.clone(),
1580            show_local_selections: true,
1581            mode,
1582            show_gutter: mode == EditorMode::Full,
1583            show_wrap_guides: None,
1584            placeholder_text: None,
1585            highlighted_rows: None,
1586            background_highlights: Default::default(),
1587            inlay_background_highlights: Default::default(),
1588            nav_history: None,
1589            context_menu: RwLock::new(None),
1590            mouse_context_menu: None,
1591            completion_tasks: Default::default(),
1592            next_completion_id: 0,
1593            next_inlay_id: 0,
1594            available_code_actions: Default::default(),
1595            code_actions_task: Default::default(),
1596            document_highlights_task: Default::default(),
1597            pending_rename: Default::default(),
1598            searchable: true,
1599            cursor_shape: Default::default(),
1600            autoindent_mode: Some(AutoindentMode::EachLine),
1601            collapse_matches: false,
1602            workspace: None,
1603            keymap_context_layers: Default::default(),
1604            input_enabled: true,
1605            read_only: false,
1606            leader_peer_id: None,
1607            remote_id: None,
1608            hover_state: Default::default(),
1609            link_go_to_definition_state: Default::default(),
1610            copilot_state: Default::default(),
1611            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1612            gutter_hovered: false,
1613            pixel_position_of_newest_cursor: None,
1614            gutter_width: Default::default(),
1615            style: None,
1616            recently_focused: false,
1617            hovered_cursor: Default::default(),
1618            editor_actions: Default::default(),
1619            show_copilot_suggestions: mode == EditorMode::Full,
1620            _subscriptions: vec![
1621                cx.observe(&buffer, Self::on_buffer_changed),
1622                cx.subscribe(&buffer, Self::on_buffer_event),
1623                cx.observe(&display_map, Self::on_display_map_changed),
1624                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1625                cx.observe_global::<SettingsStore>(Self::settings_changed),
1626                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1627                cx.observe_window_activation(|editor, cx| {
1628                    let active = cx.is_window_active();
1629                    editor.blink_manager.update(cx, |blink_manager, cx| {
1630                        if active {
1631                            blink_manager.enable(cx);
1632                        } else {
1633                            blink_manager.show_cursor(cx);
1634                            blink_manager.disable(cx);
1635                        }
1636                    });
1637                }),
1638            ],
1639        };
1640
1641        this._subscriptions.extend(project_subscriptions);
1642
1643        this.end_selection(cx);
1644        this.scroll_manager.show_scrollbar(cx);
1645
1646        if mode == EditorMode::Full {
1647            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1648            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1649        }
1650
1651        this.report_editor_event("open", None, cx);
1652        this
1653    }
1654
1655    fn key_context(&self, cx: &AppContext) -> KeyContext {
1656        let mut key_context = KeyContext::default();
1657        key_context.add("Editor");
1658        let mode = match self.mode {
1659            EditorMode::SingleLine => "single_line",
1660            EditorMode::AutoHeight { .. } => "auto_height",
1661            EditorMode::Full => "full",
1662        };
1663        key_context.set("mode", mode);
1664        if self.pending_rename.is_some() {
1665            key_context.add("renaming");
1666        }
1667        if self.context_menu_visible() {
1668            match self.context_menu.read().as_ref() {
1669                Some(ContextMenu::Completions(_)) => {
1670                    key_context.add("menu");
1671                    key_context.add("showing_completions")
1672                }
1673                Some(ContextMenu::CodeActions(_)) => {
1674                    key_context.add("menu");
1675                    key_context.add("showing_code_actions")
1676                }
1677                None => {}
1678            }
1679        }
1680
1681        for layer in self.keymap_context_layers.values() {
1682            key_context.extend(layer);
1683        }
1684
1685        if let Some(extension) = self
1686            .buffer
1687            .read(cx)
1688            .as_singleton()
1689            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1690        {
1691            key_context.set("extension", extension.to_string());
1692        }
1693
1694        key_context
1695    }
1696
1697    pub fn new_file(
1698        workspace: &mut Workspace,
1699        _: &workspace::NewFile,
1700        cx: &mut ViewContext<Workspace>,
1701    ) {
1702        let project = workspace.project().clone();
1703        if project.read(cx).is_remote() {
1704            cx.propagate();
1705        } else if let Some(buffer) = project
1706            .update(cx, |project, cx| project.create_buffer("", None, cx))
1707            .log_err()
1708        {
1709            workspace.add_item(
1710                Box::new(cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx))),
1711                cx,
1712            );
1713        }
1714    }
1715
1716    pub fn new_file_in_direction(
1717        workspace: &mut Workspace,
1718        action: &workspace::NewFileInDirection,
1719        cx: &mut ViewContext<Workspace>,
1720    ) {
1721        let project = workspace.project().clone();
1722        if project.read(cx).is_remote() {
1723            cx.propagate();
1724        } else if let Some(buffer) = project
1725            .update(cx, |project, cx| project.create_buffer("", None, cx))
1726            .log_err()
1727        {
1728            workspace.split_item(
1729                action.0,
1730                Box::new(cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx))),
1731                cx,
1732            );
1733        }
1734    }
1735
1736    pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
1737        self.buffer.read(cx).replica_id()
1738    }
1739
1740    pub fn leader_peer_id(&self) -> Option<PeerId> {
1741        self.leader_peer_id
1742    }
1743
1744    pub fn buffer(&self) -> &Model<MultiBuffer> {
1745        &self.buffer
1746    }
1747
1748    pub fn workspace(&self) -> Option<View<Workspace>> {
1749        self.workspace.as_ref()?.0.upgrade()
1750    }
1751
1752    pub fn pane(&self, cx: &AppContext) -> Option<View<Pane>> {
1753        self.workspace()?.read(cx).pane_for(&self.handle.upgrade()?)
1754    }
1755
1756    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1757        self.buffer().read(cx).title(cx)
1758    }
1759
1760    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
1761        EditorSnapshot {
1762            mode: self.mode,
1763            show_gutter: self.show_gutter,
1764            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1765            scroll_anchor: self.scroll_manager.anchor(),
1766            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1767            placeholder_text: self.placeholder_text.clone(),
1768            is_focused: self.focus_handle.is_focused(cx),
1769        }
1770    }
1771
1772    pub fn language_at<'a, T: ToOffset>(
1773        &self,
1774        point: T,
1775        cx: &'a AppContext,
1776    ) -> Option<Arc<Language>> {
1777        self.buffer.read(cx).language_at(point, cx)
1778    }
1779
1780    pub fn file_at<'a, T: ToOffset>(
1781        &self,
1782        point: T,
1783        cx: &'a AppContext,
1784    ) -> Option<Arc<dyn language::File>> {
1785        self.buffer.read(cx).read(cx).file_at(point).cloned()
1786    }
1787
1788    pub fn active_excerpt(
1789        &self,
1790        cx: &AppContext,
1791    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1792        self.buffer
1793            .read(cx)
1794            .excerpt_containing(self.selections.newest_anchor().head(), cx)
1795    }
1796
1797    pub fn mode(&self) -> EditorMode {
1798        self.mode
1799    }
1800
1801    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1802        self.collaboration_hub.as_deref()
1803    }
1804
1805    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1806        self.collaboration_hub = Some(hub);
1807    }
1808
1809    pub fn placeholder_text(&self) -> Option<&str> {
1810        self.placeholder_text.as_deref()
1811    }
1812
1813    pub fn set_placeholder_text(
1814        &mut self,
1815        placeholder_text: impl Into<Arc<str>>,
1816        cx: &mut ViewContext<Self>,
1817    ) {
1818        let placeholder_text = Some(placeholder_text.into());
1819        if self.placeholder_text != placeholder_text {
1820            self.placeholder_text = placeholder_text;
1821            cx.notify();
1822        }
1823    }
1824
1825    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1826        self.cursor_shape = cursor_shape;
1827        cx.notify();
1828    }
1829
1830    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1831        self.collapse_matches = collapse_matches;
1832    }
1833
1834    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1835        if self.collapse_matches {
1836            return range.start..range.start;
1837        }
1838        range.clone()
1839    }
1840
1841    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1842        if self.display_map.read(cx).clip_at_line_ends != clip {
1843            self.display_map
1844                .update(cx, |map, _| map.clip_at_line_ends = clip);
1845        }
1846    }
1847
1848    pub fn set_keymap_context_layer<Tag: 'static>(
1849        &mut self,
1850        context: KeyContext,
1851        cx: &mut ViewContext<Self>,
1852    ) {
1853        self.keymap_context_layers
1854            .insert(TypeId::of::<Tag>(), context);
1855        cx.notify();
1856    }
1857
1858    pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
1859        self.keymap_context_layers.remove(&TypeId::of::<Tag>());
1860        cx.notify();
1861    }
1862
1863    pub fn set_input_enabled(&mut self, input_enabled: bool) {
1864        self.input_enabled = input_enabled;
1865    }
1866
1867    pub fn set_autoindent(&mut self, autoindent: bool) {
1868        if autoindent {
1869            self.autoindent_mode = Some(AutoindentMode::EachLine);
1870        } else {
1871            self.autoindent_mode = None;
1872        }
1873    }
1874
1875    pub fn read_only(&self, cx: &AppContext) -> bool {
1876        self.read_only || self.buffer.read(cx).read_only()
1877    }
1878
1879    pub fn set_read_only(&mut self, read_only: bool) {
1880        self.read_only = read_only;
1881    }
1882
1883    pub fn set_show_copilot_suggestions(&mut self, show_copilot_suggestions: bool) {
1884        self.show_copilot_suggestions = show_copilot_suggestions;
1885    }
1886
1887    fn selections_did_change(
1888        &mut self,
1889        local: bool,
1890        old_cursor_position: &Anchor,
1891        cx: &mut ViewContext<Self>,
1892    ) {
1893        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1894            self.buffer.update(cx, |buffer, cx| {
1895                buffer.set_active_selections(
1896                    &self.selections.disjoint_anchors(),
1897                    self.selections.line_mode,
1898                    self.cursor_shape,
1899                    cx,
1900                )
1901            });
1902        }
1903
1904        let display_map = self
1905            .display_map
1906            .update(cx, |display_map, cx| display_map.snapshot(cx));
1907        let buffer = &display_map.buffer_snapshot;
1908        self.add_selections_state = None;
1909        self.select_next_state = None;
1910        self.select_prev_state = None;
1911        self.select_larger_syntax_node_stack.clear();
1912        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1913        self.snippet_stack
1914            .invalidate(&self.selections.disjoint_anchors(), buffer);
1915        self.take_rename(false, cx);
1916
1917        let new_cursor_position = self.selections.newest_anchor().head();
1918
1919        self.push_to_nav_history(
1920            old_cursor_position.clone(),
1921            Some(new_cursor_position.to_point(buffer)),
1922            cx,
1923        );
1924
1925        if local {
1926            let new_cursor_position = self.selections.newest_anchor().head();
1927            let mut context_menu = self.context_menu.write();
1928            let completion_menu = match context_menu.as_ref() {
1929                Some(ContextMenu::Completions(menu)) => Some(menu),
1930
1931                _ => {
1932                    *context_menu = None;
1933                    None
1934                }
1935            };
1936
1937            if let Some(completion_menu) = completion_menu {
1938                let cursor_position = new_cursor_position.to_offset(buffer);
1939                let (word_range, kind) =
1940                    buffer.surrounding_word(completion_menu.initial_position.clone());
1941                if kind == Some(CharKind::Word)
1942                    && word_range.to_inclusive().contains(&cursor_position)
1943                {
1944                    let mut completion_menu = completion_menu.clone();
1945                    drop(context_menu);
1946
1947                    let query = Self::completion_query(buffer, cursor_position);
1948                    cx.spawn(move |this, mut cx| async move {
1949                        completion_menu
1950                            .filter(query.as_deref(), cx.background_executor().clone())
1951                            .await;
1952
1953                        this.update(&mut cx, |this, cx| {
1954                            let mut context_menu = this.context_menu.write();
1955                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
1956                                return;
1957                            };
1958
1959                            if menu.id > completion_menu.id {
1960                                return;
1961                            }
1962
1963                            *context_menu = Some(ContextMenu::Completions(completion_menu));
1964                            drop(context_menu);
1965                            cx.notify();
1966                        })
1967                    })
1968                    .detach();
1969
1970                    self.show_completions(&ShowCompletions, cx);
1971                } else {
1972                    drop(context_menu);
1973                    self.hide_context_menu(cx);
1974                }
1975            } else {
1976                drop(context_menu);
1977            }
1978
1979            hide_hover(self, cx);
1980
1981            if old_cursor_position.to_display_point(&display_map).row()
1982                != new_cursor_position.to_display_point(&display_map).row()
1983            {
1984                self.available_code_actions.take();
1985            }
1986            self.refresh_code_actions(cx);
1987            self.refresh_document_highlights(cx);
1988            refresh_matching_bracket_highlights(self, cx);
1989            self.discard_copilot_suggestion(cx);
1990        }
1991
1992        self.blink_manager.update(cx, BlinkManager::pause_blinking);
1993        cx.emit(EditorEvent::SelectionsChanged { local });
1994
1995        if self.selections.disjoint_anchors().len() == 1 {
1996            cx.emit(SearchEvent::ActiveMatchChanged)
1997        }
1998
1999        cx.notify();
2000    }
2001
2002    pub fn change_selections<R>(
2003        &mut self,
2004        autoscroll: Option<Autoscroll>,
2005        cx: &mut ViewContext<Self>,
2006        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2007    ) -> R {
2008        let old_cursor_position = self.selections.newest_anchor().head();
2009        self.push_to_selection_history();
2010
2011        let (changed, result) = self.selections.change_with(cx, change);
2012
2013        if changed {
2014            if let Some(autoscroll) = autoscroll {
2015                self.request_autoscroll(autoscroll, cx);
2016            }
2017            self.selections_did_change(true, &old_cursor_position, cx);
2018        }
2019
2020        result
2021    }
2022
2023    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2024    where
2025        I: IntoIterator<Item = (Range<S>, T)>,
2026        S: ToOffset,
2027        T: Into<Arc<str>>,
2028    {
2029        if self.read_only(cx) {
2030            return;
2031        }
2032
2033        self.buffer
2034            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2035    }
2036
2037    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2038    where
2039        I: IntoIterator<Item = (Range<S>, T)>,
2040        S: ToOffset,
2041        T: Into<Arc<str>>,
2042    {
2043        if self.read_only(cx) {
2044            return;
2045        }
2046
2047        self.buffer.update(cx, |buffer, cx| {
2048            buffer.edit(edits, self.autoindent_mode.clone(), cx)
2049        });
2050    }
2051
2052    pub fn edit_with_block_indent<I, S, T>(
2053        &mut self,
2054        edits: I,
2055        original_indent_columns: Vec<u32>,
2056        cx: &mut ViewContext<Self>,
2057    ) where
2058        I: IntoIterator<Item = (Range<S>, T)>,
2059        S: ToOffset,
2060        T: Into<Arc<str>>,
2061    {
2062        if self.read_only(cx) {
2063            return;
2064        }
2065
2066        self.buffer.update(cx, |buffer, cx| {
2067            buffer.edit(
2068                edits,
2069                Some(AutoindentMode::Block {
2070                    original_indent_columns,
2071                }),
2072                cx,
2073            )
2074        });
2075    }
2076
2077    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2078        self.hide_context_menu(cx);
2079
2080        match phase {
2081            SelectPhase::Begin {
2082                position,
2083                add,
2084                click_count,
2085            } => self.begin_selection(position, add, click_count, cx),
2086            SelectPhase::BeginColumnar {
2087                position,
2088                goal_column,
2089            } => self.begin_columnar_selection(position, goal_column, cx),
2090            SelectPhase::Extend {
2091                position,
2092                click_count,
2093            } => self.extend_selection(position, click_count, cx),
2094            SelectPhase::Update {
2095                position,
2096                goal_column,
2097                scroll_position,
2098            } => self.update_selection(position, goal_column, scroll_position, cx),
2099            SelectPhase::End => self.end_selection(cx),
2100        }
2101    }
2102
2103    fn extend_selection(
2104        &mut self,
2105        position: DisplayPoint,
2106        click_count: usize,
2107        cx: &mut ViewContext<Self>,
2108    ) {
2109        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2110        let tail = self.selections.newest::<usize>(cx).tail();
2111        self.begin_selection(position, false, click_count, cx);
2112
2113        let position = position.to_offset(&display_map, Bias::Left);
2114        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2115
2116        let mut pending_selection = self
2117            .selections
2118            .pending_anchor()
2119            .expect("extend_selection not called with pending selection");
2120        if position >= tail {
2121            pending_selection.start = tail_anchor;
2122        } else {
2123            pending_selection.end = tail_anchor;
2124            pending_selection.reversed = true;
2125        }
2126
2127        let mut pending_mode = self.selections.pending_mode().unwrap();
2128        match &mut pending_mode {
2129            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2130            _ => {}
2131        }
2132
2133        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2134            s.set_pending(pending_selection, pending_mode)
2135        });
2136    }
2137
2138    fn begin_selection(
2139        &mut self,
2140        position: DisplayPoint,
2141        add: bool,
2142        click_count: usize,
2143        cx: &mut ViewContext<Self>,
2144    ) {
2145        if !self.focus_handle.is_focused(cx) {
2146            cx.focus(&self.focus_handle);
2147        }
2148
2149        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2150        let buffer = &display_map.buffer_snapshot;
2151        let newest_selection = self.selections.newest_anchor().clone();
2152        let position = display_map.clip_point(position, Bias::Left);
2153
2154        let start;
2155        let end;
2156        let mode;
2157        let auto_scroll;
2158        match click_count {
2159            1 => {
2160                start = buffer.anchor_before(position.to_point(&display_map));
2161                end = start.clone();
2162                mode = SelectMode::Character;
2163                auto_scroll = true;
2164            }
2165            2 => {
2166                let range = movement::surrounding_word(&display_map, position);
2167                start = buffer.anchor_before(range.start.to_point(&display_map));
2168                end = buffer.anchor_before(range.end.to_point(&display_map));
2169                mode = SelectMode::Word(start.clone()..end.clone());
2170                auto_scroll = true;
2171            }
2172            3 => {
2173                let position = display_map
2174                    .clip_point(position, Bias::Left)
2175                    .to_point(&display_map);
2176                let line_start = display_map.prev_line_boundary(position).0;
2177                let next_line_start = buffer.clip_point(
2178                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
2179                    Bias::Left,
2180                );
2181                start = buffer.anchor_before(line_start);
2182                end = buffer.anchor_before(next_line_start);
2183                mode = SelectMode::Line(start.clone()..end.clone());
2184                auto_scroll = true;
2185            }
2186            _ => {
2187                start = buffer.anchor_before(0);
2188                end = buffer.anchor_before(buffer.len());
2189                mode = SelectMode::All;
2190                auto_scroll = false;
2191            }
2192        }
2193
2194        self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
2195            if !add {
2196                s.clear_disjoint();
2197            } else if click_count > 1 {
2198                s.delete(newest_selection.id)
2199            }
2200
2201            s.set_pending_anchor_range(start..end, mode);
2202        });
2203    }
2204
2205    fn begin_columnar_selection(
2206        &mut self,
2207        position: DisplayPoint,
2208        goal_column: u32,
2209        cx: &mut ViewContext<Self>,
2210    ) {
2211        if !self.focus_handle.is_focused(cx) {
2212            cx.focus(&self.focus_handle);
2213        }
2214
2215        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2216        let tail = self.selections.newest::<Point>(cx).tail();
2217        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2218
2219        self.select_columns(
2220            tail.to_display_point(&display_map),
2221            position,
2222            goal_column,
2223            &display_map,
2224            cx,
2225        );
2226    }
2227
2228    fn update_selection(
2229        &mut self,
2230        position: DisplayPoint,
2231        goal_column: u32,
2232        scroll_position: gpui::Point<f32>,
2233        cx: &mut ViewContext<Self>,
2234    ) {
2235        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2236
2237        if let Some(tail) = self.columnar_selection_tail.as_ref() {
2238            let tail = tail.to_display_point(&display_map);
2239            self.select_columns(tail, position, goal_column, &display_map, cx);
2240        } else if let Some(mut pending) = self.selections.pending_anchor() {
2241            let buffer = self.buffer.read(cx).snapshot(cx);
2242            let head;
2243            let tail;
2244            let mode = self.selections.pending_mode().unwrap();
2245            match &mode {
2246                SelectMode::Character => {
2247                    head = position.to_point(&display_map);
2248                    tail = pending.tail().to_point(&buffer);
2249                }
2250                SelectMode::Word(original_range) => {
2251                    let original_display_range = original_range.start.to_display_point(&display_map)
2252                        ..original_range.end.to_display_point(&display_map);
2253                    let original_buffer_range = original_display_range.start.to_point(&display_map)
2254                        ..original_display_range.end.to_point(&display_map);
2255                    if movement::is_inside_word(&display_map, position)
2256                        || original_display_range.contains(&position)
2257                    {
2258                        let word_range = movement::surrounding_word(&display_map, position);
2259                        if word_range.start < original_display_range.start {
2260                            head = word_range.start.to_point(&display_map);
2261                        } else {
2262                            head = word_range.end.to_point(&display_map);
2263                        }
2264                    } else {
2265                        head = position.to_point(&display_map);
2266                    }
2267
2268                    if head <= original_buffer_range.start {
2269                        tail = original_buffer_range.end;
2270                    } else {
2271                        tail = original_buffer_range.start;
2272                    }
2273                }
2274                SelectMode::Line(original_range) => {
2275                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
2276
2277                    let position = display_map
2278                        .clip_point(position, Bias::Left)
2279                        .to_point(&display_map);
2280                    let line_start = display_map.prev_line_boundary(position).0;
2281                    let next_line_start = buffer.clip_point(
2282                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
2283                        Bias::Left,
2284                    );
2285
2286                    if line_start < original_range.start {
2287                        head = line_start
2288                    } else {
2289                        head = next_line_start
2290                    }
2291
2292                    if head <= original_range.start {
2293                        tail = original_range.end;
2294                    } else {
2295                        tail = original_range.start;
2296                    }
2297                }
2298                SelectMode::All => {
2299                    return;
2300                }
2301            };
2302
2303            if head < tail {
2304                pending.start = buffer.anchor_before(head);
2305                pending.end = buffer.anchor_before(tail);
2306                pending.reversed = true;
2307            } else {
2308                pending.start = buffer.anchor_before(tail);
2309                pending.end = buffer.anchor_before(head);
2310                pending.reversed = false;
2311            }
2312
2313            self.change_selections(None, cx, |s| {
2314                s.set_pending(pending, mode);
2315            });
2316        } else {
2317            log::error!("update_selection dispatched with no pending selection");
2318            return;
2319        }
2320
2321        self.set_scroll_position(scroll_position, cx);
2322        cx.notify();
2323    }
2324
2325    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2326        self.columnar_selection_tail.take();
2327        if self.selections.pending_anchor().is_some() {
2328            let selections = self.selections.all::<usize>(cx);
2329            self.change_selections(None, cx, |s| {
2330                s.select(selections);
2331                s.clear_pending();
2332            });
2333        }
2334    }
2335
2336    fn select_columns(
2337        &mut self,
2338        tail: DisplayPoint,
2339        head: DisplayPoint,
2340        goal_column: u32,
2341        display_map: &DisplaySnapshot,
2342        cx: &mut ViewContext<Self>,
2343    ) {
2344        let start_row = cmp::min(tail.row(), head.row());
2345        let end_row = cmp::max(tail.row(), head.row());
2346        let start_column = cmp::min(tail.column(), goal_column);
2347        let end_column = cmp::max(tail.column(), goal_column);
2348        let reversed = start_column < tail.column();
2349
2350        let selection_ranges = (start_row..=end_row)
2351            .filter_map(|row| {
2352                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2353                    let start = display_map
2354                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2355                        .to_point(display_map);
2356                    let end = display_map
2357                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2358                        .to_point(display_map);
2359                    if reversed {
2360                        Some(end..start)
2361                    } else {
2362                        Some(start..end)
2363                    }
2364                } else {
2365                    None
2366                }
2367            })
2368            .collect::<Vec<_>>();
2369
2370        self.change_selections(None, cx, |s| {
2371            s.select_ranges(selection_ranges);
2372        });
2373        cx.notify();
2374    }
2375
2376    pub fn has_pending_nonempty_selection(&self) -> bool {
2377        let pending_nonempty_selection = match self.selections.pending_anchor() {
2378            Some(Selection { start, end, .. }) => start != end,
2379            None => false,
2380        };
2381        pending_nonempty_selection || self.columnar_selection_tail.is_some()
2382    }
2383
2384    pub fn has_pending_selection(&self) -> bool {
2385        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2386    }
2387
2388    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2389        if self.take_rename(false, cx).is_some() {
2390            return;
2391        }
2392
2393        if hide_hover(self, cx) {
2394            return;
2395        }
2396
2397        if self.hide_context_menu(cx).is_some() {
2398            return;
2399        }
2400
2401        if self.discard_copilot_suggestion(cx) {
2402            return;
2403        }
2404
2405        if self.snippet_stack.pop().is_some() {
2406            return;
2407        }
2408
2409        if self.mode == EditorMode::Full {
2410            if self.active_diagnostics.is_some() {
2411                self.dismiss_diagnostics(cx);
2412                return;
2413            }
2414
2415            if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
2416                return;
2417            }
2418        }
2419
2420        cx.propagate();
2421    }
2422
2423    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2424        let text: Arc<str> = text.into();
2425
2426        if self.read_only(cx) {
2427            return;
2428        }
2429
2430        let selections = self.selections.all_adjusted(cx);
2431        let mut brace_inserted = false;
2432        let mut edits = Vec::new();
2433        let mut new_selections = Vec::with_capacity(selections.len());
2434        let mut new_autoclose_regions = Vec::new();
2435        let snapshot = self.buffer.read(cx).read(cx);
2436
2437        for (selection, autoclose_region) in
2438            self.selections_with_autoclose_regions(selections, &snapshot)
2439        {
2440            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2441                // Determine if the inserted text matches the opening or closing
2442                // bracket of any of this language's bracket pairs.
2443                let mut bracket_pair = None;
2444                let mut is_bracket_pair_start = false;
2445                if !text.is_empty() {
2446                    // `text` can be empty when an user is using IME (e.g. Chinese Wubi Simplified)
2447                    //  and they are removing the character that triggered IME popup.
2448                    for (pair, enabled) in scope.brackets() {
2449                        if enabled && pair.close && pair.start.ends_with(text.as_ref()) {
2450                            bracket_pair = Some(pair.clone());
2451                            is_bracket_pair_start = true;
2452                            break;
2453                        } else if pair.end.as_str() == text.as_ref() {
2454                            bracket_pair = Some(pair.clone());
2455                            break;
2456                        }
2457                    }
2458                }
2459
2460                if let Some(bracket_pair) = bracket_pair {
2461                    if selection.is_empty() {
2462                        if is_bracket_pair_start {
2463                            let prefix_len = bracket_pair.start.len() - text.len();
2464
2465                            // If the inserted text is a suffix of an opening bracket and the
2466                            // selection is preceded by the rest of the opening bracket, then
2467                            // insert the closing bracket.
2468                            let following_text_allows_autoclose = snapshot
2469                                .chars_at(selection.start)
2470                                .next()
2471                                .map_or(true, |c| scope.should_autoclose_before(c));
2472                            let preceding_text_matches_prefix = prefix_len == 0
2473                                || (selection.start.column >= (prefix_len as u32)
2474                                    && snapshot.contains_str_at(
2475                                        Point::new(
2476                                            selection.start.row,
2477                                            selection.start.column - (prefix_len as u32),
2478                                        ),
2479                                        &bracket_pair.start[..prefix_len],
2480                                    ));
2481                            if following_text_allows_autoclose && preceding_text_matches_prefix {
2482                                let anchor = snapshot.anchor_before(selection.end);
2483                                new_selections.push((selection.map(|_| anchor), text.len()));
2484                                new_autoclose_regions.push((
2485                                    anchor,
2486                                    text.len(),
2487                                    selection.id,
2488                                    bracket_pair.clone(),
2489                                ));
2490                                edits.push((
2491                                    selection.range(),
2492                                    format!("{}{}", text, bracket_pair.end).into(),
2493                                ));
2494                                brace_inserted = true;
2495                                continue;
2496                            }
2497                        }
2498
2499                        if let Some(region) = autoclose_region {
2500                            // If the selection is followed by an auto-inserted closing bracket,
2501                            // then don't insert that closing bracket again; just move the selection
2502                            // past the closing bracket.
2503                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
2504                                && text.as_ref() == region.pair.end.as_str();
2505                            if should_skip {
2506                                let anchor = snapshot.anchor_after(selection.end);
2507                                new_selections
2508                                    .push((selection.map(|_| anchor), region.pair.end.len()));
2509                                continue;
2510                            }
2511                        }
2512                    }
2513                    // If an opening bracket is 1 character long and is typed while
2514                    // text is selected, then surround that text with the bracket pair.
2515                    else if is_bracket_pair_start && bracket_pair.start.chars().count() == 1 {
2516                        edits.push((selection.start..selection.start, text.clone()));
2517                        edits.push((
2518                            selection.end..selection.end,
2519                            bracket_pair.end.as_str().into(),
2520                        ));
2521                        brace_inserted = true;
2522                        new_selections.push((
2523                            Selection {
2524                                id: selection.id,
2525                                start: snapshot.anchor_after(selection.start),
2526                                end: snapshot.anchor_before(selection.end),
2527                                reversed: selection.reversed,
2528                                goal: selection.goal,
2529                            },
2530                            0,
2531                        ));
2532                        continue;
2533                    }
2534                }
2535            }
2536
2537            // If not handling any auto-close operation, then just replace the selected
2538            // text with the given input and move the selection to the end of the
2539            // newly inserted text.
2540            let anchor = snapshot.anchor_after(selection.end);
2541            new_selections.push((selection.map(|_| anchor), 0));
2542            edits.push((selection.start..selection.end, text.clone()));
2543        }
2544
2545        drop(snapshot);
2546        self.transact(cx, |this, cx| {
2547            this.buffer.update(cx, |buffer, cx| {
2548                buffer.edit(edits, this.autoindent_mode.clone(), cx);
2549            });
2550
2551            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2552            let new_selection_deltas = new_selections.iter().map(|e| e.1);
2553            let snapshot = this.buffer.read(cx).read(cx);
2554            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
2555                .zip(new_selection_deltas)
2556                .map(|(selection, delta)| Selection {
2557                    id: selection.id,
2558                    start: selection.start + delta,
2559                    end: selection.end + delta,
2560                    reversed: selection.reversed,
2561                    goal: SelectionGoal::None,
2562                })
2563                .collect::<Vec<_>>();
2564
2565            let mut i = 0;
2566            for (position, delta, selection_id, pair) in new_autoclose_regions {
2567                let position = position.to_offset(&snapshot) + delta;
2568                let start = snapshot.anchor_before(position);
2569                let end = snapshot.anchor_after(position);
2570                while let Some(existing_state) = this.autoclose_regions.get(i) {
2571                    match existing_state.range.start.cmp(&start, &snapshot) {
2572                        Ordering::Less => i += 1,
2573                        Ordering::Greater => break,
2574                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
2575                            Ordering::Less => i += 1,
2576                            Ordering::Equal => break,
2577                            Ordering::Greater => break,
2578                        },
2579                    }
2580                }
2581                this.autoclose_regions.insert(
2582                    i,
2583                    AutocloseRegion {
2584                        selection_id,
2585                        range: start..end,
2586                        pair,
2587                    },
2588                );
2589            }
2590
2591            drop(snapshot);
2592            let had_active_copilot_suggestion = this.has_active_copilot_suggestion(cx);
2593            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
2594
2595            if !brace_inserted && EditorSettings::get_global(cx).use_on_type_format {
2596                if let Some(on_type_format_task) =
2597                    this.trigger_on_type_formatting(text.to_string(), cx)
2598                {
2599                    on_type_format_task.detach_and_log_err(cx);
2600                }
2601            }
2602
2603            if had_active_copilot_suggestion {
2604                this.refresh_copilot_suggestions(true, cx);
2605                if !this.has_active_copilot_suggestion(cx) {
2606                    this.trigger_completion_on_input(&text, cx);
2607                }
2608            } else {
2609                this.trigger_completion_on_input(&text, cx);
2610                this.refresh_copilot_suggestions(true, cx);
2611            }
2612        });
2613    }
2614
2615    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2616        self.transact(cx, |this, cx| {
2617            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2618                let selections = this.selections.all::<usize>(cx);
2619                let multi_buffer = this.buffer.read(cx);
2620                let buffer = multi_buffer.snapshot(cx);
2621                selections
2622                    .iter()
2623                    .map(|selection| {
2624                        let start_point = selection.start.to_point(&buffer);
2625                        let mut indent = buffer.indent_size_for_line(start_point.row);
2626                        indent.len = cmp::min(indent.len, start_point.column);
2627                        let start = selection.start;
2628                        let end = selection.end;
2629                        let is_cursor = start == end;
2630                        let language_scope = buffer.language_scope_at(start);
2631                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2632                            &language_scope
2633                        {
2634                            let leading_whitespace_len = buffer
2635                                .reversed_chars_at(start)
2636                                .take_while(|c| c.is_whitespace() && *c != '\n')
2637                                .map(|c| c.len_utf8())
2638                                .sum::<usize>();
2639
2640                            let trailing_whitespace_len = buffer
2641                                .chars_at(end)
2642                                .take_while(|c| c.is_whitespace() && *c != '\n')
2643                                .map(|c| c.len_utf8())
2644                                .sum::<usize>();
2645
2646                            let insert_extra_newline =
2647                                language.brackets().any(|(pair, enabled)| {
2648                                    let pair_start = pair.start.trim_end();
2649                                    let pair_end = pair.end.trim_start();
2650
2651                                    enabled
2652                                        && pair.newline
2653                                        && buffer.contains_str_at(
2654                                            end + trailing_whitespace_len,
2655                                            pair_end,
2656                                        )
2657                                        && buffer.contains_str_at(
2658                                            (start - leading_whitespace_len)
2659                                                .saturating_sub(pair_start.len()),
2660                                            pair_start,
2661                                        )
2662                                });
2663                            // Comment extension on newline is allowed only for cursor selections
2664                            let comment_delimiter = language.line_comment_prefix().filter(|_| {
2665                                let is_comment_extension_enabled =
2666                                    multi_buffer.settings_at(0, cx).extend_comment_on_newline;
2667                                is_cursor && is_comment_extension_enabled
2668                            });
2669                            let comment_delimiter = if let Some(delimiter) = comment_delimiter {
2670                                buffer
2671                                    .buffer_line_for_row(start_point.row)
2672                                    .is_some_and(|(snapshot, range)| {
2673                                        let mut index_of_first_non_whitespace = 0;
2674                                        let line_starts_with_comment = snapshot
2675                                            .chars_for_range(range)
2676                                            .skip_while(|c| {
2677                                                let should_skip = c.is_whitespace();
2678                                                if should_skip {
2679                                                    index_of_first_non_whitespace += 1;
2680                                                }
2681                                                should_skip
2682                                            })
2683                                            .take(delimiter.len())
2684                                            .eq(delimiter.chars());
2685                                        let cursor_is_placed_after_comment_marker =
2686                                            index_of_first_non_whitespace + delimiter.len()
2687                                                <= start_point.column as usize;
2688                                        line_starts_with_comment
2689                                            && cursor_is_placed_after_comment_marker
2690                                    })
2691                                    .then(|| delimiter.clone())
2692                            } else {
2693                                None
2694                            };
2695                            (comment_delimiter, insert_extra_newline)
2696                        } else {
2697                            (None, false)
2698                        };
2699
2700                        let capacity_for_delimiter = comment_delimiter
2701                            .as_deref()
2702                            .map(str::len)
2703                            .unwrap_or_default();
2704                        let mut new_text =
2705                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
2706                        new_text.push_str("\n");
2707                        new_text.extend(indent.chars());
2708                        if let Some(delimiter) = &comment_delimiter {
2709                            new_text.push_str(&delimiter);
2710                        }
2711                        if insert_extra_newline {
2712                            new_text = new_text.repeat(2);
2713                        }
2714
2715                        let anchor = buffer.anchor_after(end);
2716                        let new_selection = selection.map(|_| anchor);
2717                        (
2718                            (start..end, new_text),
2719                            (insert_extra_newline, new_selection),
2720                        )
2721                    })
2722                    .unzip()
2723            };
2724
2725            this.edit_with_autoindent(edits, cx);
2726            let buffer = this.buffer.read(cx).snapshot(cx);
2727            let new_selections = selection_fixup_info
2728                .into_iter()
2729                .map(|(extra_newline_inserted, new_selection)| {
2730                    let mut cursor = new_selection.end.to_point(&buffer);
2731                    if extra_newline_inserted {
2732                        cursor.row -= 1;
2733                        cursor.column = buffer.line_len(cursor.row);
2734                    }
2735                    new_selection.map(|_| cursor)
2736                })
2737                .collect();
2738
2739            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
2740            this.refresh_copilot_suggestions(true, cx);
2741        });
2742    }
2743
2744    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
2745        let buffer = self.buffer.read(cx);
2746        let snapshot = buffer.snapshot(cx);
2747
2748        let mut edits = Vec::new();
2749        let mut rows = Vec::new();
2750        let mut rows_inserted = 0;
2751
2752        for selection in self.selections.all_adjusted(cx) {
2753            let cursor = selection.head();
2754            let row = cursor.row;
2755
2756            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
2757
2758            let newline = "\n".to_string();
2759            edits.push((start_of_line..start_of_line, newline));
2760
2761            rows.push(row + rows_inserted);
2762            rows_inserted += 1;
2763        }
2764
2765        self.transact(cx, |editor, cx| {
2766            editor.edit(edits, cx);
2767
2768            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
2769                let mut index = 0;
2770                s.move_cursors_with(|map, _, _| {
2771                    let row = rows[index];
2772                    index += 1;
2773
2774                    let point = Point::new(row, 0);
2775                    let boundary = map.next_line_boundary(point).1;
2776                    let clipped = map.clip_point(boundary, Bias::Left);
2777
2778                    (clipped, SelectionGoal::None)
2779                });
2780            });
2781
2782            let mut indent_edits = Vec::new();
2783            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
2784            for row in rows {
2785                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
2786                for (row, indent) in indents {
2787                    if indent.len == 0 {
2788                        continue;
2789                    }
2790
2791                    let text = match indent.kind {
2792                        IndentKind::Space => " ".repeat(indent.len as usize),
2793                        IndentKind::Tab => "\t".repeat(indent.len as usize),
2794                    };
2795                    let point = Point::new(row, 0);
2796                    indent_edits.push((point..point, text));
2797                }
2798            }
2799            editor.edit(indent_edits, cx);
2800        });
2801    }
2802
2803    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
2804        let buffer = self.buffer.read(cx);
2805        let snapshot = buffer.snapshot(cx);
2806
2807        let mut edits = Vec::new();
2808        let mut rows = Vec::new();
2809        let mut rows_inserted = 0;
2810
2811        for selection in self.selections.all_adjusted(cx) {
2812            let cursor = selection.head();
2813            let row = cursor.row;
2814
2815            let point = Point::new(row + 1, 0);
2816            let start_of_line = snapshot.clip_point(point, Bias::Left);
2817
2818            let newline = "\n".to_string();
2819            edits.push((start_of_line..start_of_line, newline));
2820
2821            rows_inserted += 1;
2822            rows.push(row + rows_inserted);
2823        }
2824
2825        self.transact(cx, |editor, cx| {
2826            editor.edit(edits, cx);
2827
2828            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
2829                let mut index = 0;
2830                s.move_cursors_with(|map, _, _| {
2831                    let row = rows[index];
2832                    index += 1;
2833
2834                    let point = Point::new(row, 0);
2835                    let boundary = map.next_line_boundary(point).1;
2836                    let clipped = map.clip_point(boundary, Bias::Left);
2837
2838                    (clipped, SelectionGoal::None)
2839                });
2840            });
2841
2842            let mut indent_edits = Vec::new();
2843            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
2844            for row in rows {
2845                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
2846                for (row, indent) in indents {
2847                    if indent.len == 0 {
2848                        continue;
2849                    }
2850
2851                    let text = match indent.kind {
2852                        IndentKind::Space => " ".repeat(indent.len as usize),
2853                        IndentKind::Tab => "\t".repeat(indent.len as usize),
2854                    };
2855                    let point = Point::new(row, 0);
2856                    indent_edits.push((point..point, text));
2857                }
2858            }
2859            editor.edit(indent_edits, cx);
2860        });
2861    }
2862
2863    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2864        self.insert_with_autoindent_mode(
2865            text,
2866            Some(AutoindentMode::Block {
2867                original_indent_columns: Vec::new(),
2868            }),
2869            cx,
2870        );
2871    }
2872
2873    fn insert_with_autoindent_mode(
2874        &mut self,
2875        text: &str,
2876        autoindent_mode: Option<AutoindentMode>,
2877        cx: &mut ViewContext<Self>,
2878    ) {
2879        if self.read_only(cx) {
2880            return;
2881        }
2882
2883        let text: Arc<str> = text.into();
2884        self.transact(cx, |this, cx| {
2885            let old_selections = this.selections.all_adjusted(cx);
2886            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
2887                let anchors = {
2888                    let snapshot = buffer.read(cx);
2889                    old_selections
2890                        .iter()
2891                        .map(|s| {
2892                            let anchor = snapshot.anchor_after(s.head());
2893                            s.map(|_| anchor)
2894                        })
2895                        .collect::<Vec<_>>()
2896                };
2897                buffer.edit(
2898                    old_selections
2899                        .iter()
2900                        .map(|s| (s.start..s.end, text.clone())),
2901                    autoindent_mode,
2902                    cx,
2903                );
2904                anchors
2905            });
2906
2907            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
2908                s.select_anchors(selection_anchors);
2909            })
2910        });
2911    }
2912
2913    fn trigger_completion_on_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2914        if !EditorSettings::get_global(cx).show_completions_on_input {
2915            return;
2916        }
2917
2918        let selection = self.selections.newest_anchor();
2919        if self
2920            .buffer
2921            .read(cx)
2922            .is_completion_trigger(selection.head(), text, cx)
2923        {
2924            self.show_completions(&ShowCompletions, cx);
2925        } else {
2926            self.hide_context_menu(cx);
2927        }
2928    }
2929
2930    /// If any empty selections is touching the start of its innermost containing autoclose
2931    /// region, expand it to select the brackets.
2932    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
2933        let selections = self.selections.all::<usize>(cx);
2934        let buffer = self.buffer.read(cx).read(cx);
2935        let mut new_selections = Vec::new();
2936        for (mut selection, region) in self.selections_with_autoclose_regions(selections, &buffer) {
2937            if let (Some(region), true) = (region, selection.is_empty()) {
2938                let mut range = region.range.to_offset(&buffer);
2939                if selection.start == range.start {
2940                    if range.start >= region.pair.start.len() {
2941                        range.start -= region.pair.start.len();
2942                        if buffer.contains_str_at(range.start, &region.pair.start) {
2943                            if buffer.contains_str_at(range.end, &region.pair.end) {
2944                                range.end += region.pair.end.len();
2945                                selection.start = range.start;
2946                                selection.end = range.end;
2947                            }
2948                        }
2949                    }
2950                }
2951            }
2952            new_selections.push(selection);
2953        }
2954
2955        drop(buffer);
2956        self.change_selections(None, cx, |selections| selections.select(new_selections));
2957    }
2958
2959    /// Iterate the given selections, and for each one, find the smallest surrounding
2960    /// autoclose region. This uses the ordering of the selections and the autoclose
2961    /// regions to avoid repeated comparisons.
2962    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
2963        &'a self,
2964        selections: impl IntoIterator<Item = Selection<D>>,
2965        buffer: &'a MultiBufferSnapshot,
2966    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
2967        let mut i = 0;
2968        let mut regions = self.autoclose_regions.as_slice();
2969        selections.into_iter().map(move |selection| {
2970            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
2971
2972            let mut enclosing = None;
2973            while let Some(pair_state) = regions.get(i) {
2974                if pair_state.range.end.to_offset(buffer) < range.start {
2975                    regions = &regions[i + 1..];
2976                    i = 0;
2977                } else if pair_state.range.start.to_offset(buffer) > range.end {
2978                    break;
2979                } else {
2980                    if pair_state.selection_id == selection.id {
2981                        enclosing = Some(pair_state);
2982                    }
2983                    i += 1;
2984                }
2985            }
2986
2987            (selection.clone(), enclosing)
2988        })
2989    }
2990
2991    /// Remove any autoclose regions that no longer contain their selection.
2992    fn invalidate_autoclose_regions(
2993        &mut self,
2994        mut selections: &[Selection<Anchor>],
2995        buffer: &MultiBufferSnapshot,
2996    ) {
2997        self.autoclose_regions.retain(|state| {
2998            let mut i = 0;
2999            while let Some(selection) = selections.get(i) {
3000                if selection.end.cmp(&state.range.start, buffer).is_lt() {
3001                    selections = &selections[1..];
3002                    continue;
3003                }
3004                if selection.start.cmp(&state.range.end, buffer).is_gt() {
3005                    break;
3006                }
3007                if selection.id == state.selection_id {
3008                    return true;
3009                } else {
3010                    i += 1;
3011                }
3012            }
3013            false
3014        });
3015    }
3016
3017    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3018        let offset = position.to_offset(buffer);
3019        let (word_range, kind) = buffer.surrounding_word(offset);
3020        if offset > word_range.start && kind == Some(CharKind::Word) {
3021            Some(
3022                buffer
3023                    .text_for_range(word_range.start..offset)
3024                    .collect::<String>(),
3025            )
3026        } else {
3027            None
3028        }
3029    }
3030
3031    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3032        self.refresh_inlay_hints(
3033            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3034            cx,
3035        );
3036    }
3037
3038    pub fn inlay_hints_enabled(&self) -> bool {
3039        self.inlay_hint_cache.enabled
3040    }
3041
3042    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3043        if self.project.is_none() || self.mode != EditorMode::Full {
3044            return;
3045        }
3046
3047        let reason_description = reason.description();
3048        let (invalidate_cache, required_languages) = match reason {
3049            InlayHintRefreshReason::Toggle(enabled) => {
3050                self.inlay_hint_cache.enabled = enabled;
3051                if enabled {
3052                    (InvalidationStrategy::RefreshRequested, None)
3053                } else {
3054                    self.inlay_hint_cache.clear();
3055                    self.splice_inlay_hints(
3056                        self.visible_inlay_hints(cx)
3057                            .iter()
3058                            .map(|inlay| inlay.id)
3059                            .collect(),
3060                        Vec::new(),
3061                        cx,
3062                    );
3063                    return;
3064                }
3065            }
3066            InlayHintRefreshReason::SettingsChange(new_settings) => {
3067                match self.inlay_hint_cache.update_settings(
3068                    &self.buffer,
3069                    new_settings,
3070                    self.visible_inlay_hints(cx),
3071                    cx,
3072                ) {
3073                    ControlFlow::Break(Some(InlaySplice {
3074                        to_remove,
3075                        to_insert,
3076                    })) => {
3077                        self.splice_inlay_hints(to_remove, to_insert, cx);
3078                        return;
3079                    }
3080                    ControlFlow::Break(None) => return,
3081                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3082                }
3083            }
3084            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3085                if let Some(InlaySplice {
3086                    to_remove,
3087                    to_insert,
3088                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3089                {
3090                    self.splice_inlay_hints(to_remove, to_insert, cx);
3091                }
3092                return;
3093            }
3094            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3095            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3096                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3097            }
3098            InlayHintRefreshReason::RefreshRequested => {
3099                (InvalidationStrategy::RefreshRequested, None)
3100            }
3101        };
3102
3103        if let Some(InlaySplice {
3104            to_remove,
3105            to_insert,
3106        }) = self.inlay_hint_cache.spawn_hint_refresh(
3107            reason_description,
3108            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3109            invalidate_cache,
3110            cx,
3111        ) {
3112            self.splice_inlay_hints(to_remove, to_insert, cx);
3113        }
3114    }
3115
3116    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3117        self.display_map
3118            .read(cx)
3119            .current_inlays()
3120            .filter(move |inlay| {
3121                Some(inlay.id) != self.copilot_state.suggestion.as_ref().map(|h| h.id)
3122            })
3123            .cloned()
3124            .collect()
3125    }
3126
3127    pub fn excerpts_for_inlay_hints_query(
3128        &self,
3129        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3130        cx: &mut ViewContext<Editor>,
3131    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3132        let Some(project) = self.project.as_ref() else {
3133            return HashMap::default();
3134        };
3135        let project = project.read(cx);
3136        let multi_buffer = self.buffer().read(cx);
3137        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3138        let multi_buffer_visible_start = self
3139            .scroll_manager
3140            .anchor()
3141            .anchor
3142            .to_point(&multi_buffer_snapshot);
3143        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3144            multi_buffer_visible_start
3145                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3146            Bias::Left,
3147        );
3148        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3149        multi_buffer
3150            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3151            .into_iter()
3152            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3153            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3154                let buffer = buffer_handle.read(cx);
3155                let buffer_file = project::worktree::File::from_dyn(buffer.file())?;
3156                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3157                let worktree_entry = buffer_worktree
3158                    .read(cx)
3159                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3160                if worktree_entry.is_ignored {
3161                    return None;
3162                }
3163
3164                let language = buffer.language()?;
3165                if let Some(restrict_to_languages) = restrict_to_languages {
3166                    if !restrict_to_languages.contains(language) {
3167                        return None;
3168                    }
3169                }
3170                Some((
3171                    excerpt_id,
3172                    (
3173                        buffer_handle,
3174                        buffer.version().clone(),
3175                        excerpt_visible_range,
3176                    ),
3177                ))
3178            })
3179            .collect()
3180    }
3181
3182    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3183        TextLayoutDetails {
3184            text_system: cx.text_system().clone(),
3185            editor_style: self.style.clone().unwrap(),
3186            rem_size: cx.rem_size(),
3187        }
3188    }
3189
3190    fn splice_inlay_hints(
3191        &self,
3192        to_remove: Vec<InlayId>,
3193        to_insert: Vec<Inlay>,
3194        cx: &mut ViewContext<Self>,
3195    ) {
3196        self.display_map.update(cx, |display_map, cx| {
3197            display_map.splice_inlays(to_remove, to_insert, cx);
3198        });
3199        cx.notify();
3200    }
3201
3202    fn trigger_on_type_formatting(
3203        &self,
3204        input: String,
3205        cx: &mut ViewContext<Self>,
3206    ) -> Option<Task<Result<()>>> {
3207        if input.len() != 1 {
3208            return None;
3209        }
3210
3211        let project = self.project.as_ref()?;
3212        let position = self.selections.newest_anchor().head();
3213        let (buffer, buffer_position) = self
3214            .buffer
3215            .read(cx)
3216            .text_anchor_for_position(position.clone(), cx)?;
3217
3218        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3219        // hence we do LSP request & edit on host side only — add formats to host's history.
3220        let push_to_lsp_host_history = true;
3221        // If this is not the host, append its history with new edits.
3222        let push_to_client_history = project.read(cx).is_remote();
3223
3224        let on_type_formatting = project.update(cx, |project, cx| {
3225            project.on_type_format(
3226                buffer.clone(),
3227                buffer_position,
3228                input,
3229                push_to_lsp_host_history,
3230                cx,
3231            )
3232        });
3233        Some(cx.spawn(|editor, mut cx| async move {
3234            if let Some(transaction) = on_type_formatting.await? {
3235                if push_to_client_history {
3236                    buffer
3237                        .update(&mut cx, |buffer, _| {
3238                            buffer.push_transaction(transaction, Instant::now());
3239                        })
3240                        .ok();
3241                }
3242                editor.update(&mut cx, |editor, cx| {
3243                    editor.refresh_document_highlights(cx);
3244                })?;
3245            }
3246            Ok(())
3247        }))
3248    }
3249
3250    fn show_completions(&mut self, _: &ShowCompletions, cx: &mut ViewContext<Self>) {
3251        if self.pending_rename.is_some() {
3252            return;
3253        }
3254
3255        let project = if let Some(project) = self.project.clone() {
3256            project
3257        } else {
3258            return;
3259        };
3260
3261        let position = self.selections.newest_anchor().head();
3262        let (buffer, buffer_position) = if let Some(output) = self
3263            .buffer
3264            .read(cx)
3265            .text_anchor_for_position(position.clone(), cx)
3266        {
3267            output
3268        } else {
3269            return;
3270        };
3271
3272        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position.clone());
3273        let completions = project.update(cx, |project, cx| {
3274            project.completions(&buffer, buffer_position, cx)
3275        });
3276
3277        let id = post_inc(&mut self.next_completion_id);
3278        let task = cx.spawn(|this, mut cx| {
3279            async move {
3280                let completions = completions.await.log_err();
3281                let (menu, pre_resolve_task) = if let Some(completions) = completions {
3282                    let mut menu = CompletionsMenu {
3283                        id,
3284                        initial_position: position,
3285                        match_candidates: completions
3286                            .iter()
3287                            .enumerate()
3288                            .map(|(id, completion)| {
3289                                StringMatchCandidate::new(
3290                                    id,
3291                                    completion.label.text[completion.label.filter_range.clone()]
3292                                        .into(),
3293                                )
3294                            })
3295                            .collect(),
3296                        buffer,
3297                        completions: Arc::new(RwLock::new(completions.into())),
3298                        matches: Vec::new().into(),
3299                        selected_item: 0,
3300                        scroll_handle: UniformListScrollHandle::new(),
3301                    };
3302                    menu.filter(query.as_deref(), cx.background_executor().clone())
3303                        .await;
3304
3305                    if menu.matches.is_empty() {
3306                        (None, None)
3307                    } else {
3308                        let pre_resolve_task = this
3309                            .update(&mut cx, |editor, cx| {
3310                                menu.pre_resolve_completion_documentation(editor, cx)
3311                            })
3312                            .ok()
3313                            .flatten();
3314                        (Some(menu), pre_resolve_task)
3315                    }
3316                } else {
3317                    (None, None)
3318                };
3319
3320                this.update(&mut cx, |this, cx| {
3321                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3322
3323                    let mut context_menu = this.context_menu.write();
3324                    match context_menu.as_ref() {
3325                        None => {}
3326
3327                        Some(ContextMenu::Completions(prev_menu)) => {
3328                            if prev_menu.id > id {
3329                                return;
3330                            }
3331                        }
3332
3333                        _ => return,
3334                    }
3335
3336                    if this.focus_handle.is_focused(cx) && menu.is_some() {
3337                        let menu = menu.unwrap();
3338                        *context_menu = Some(ContextMenu::Completions(menu));
3339                        drop(context_menu);
3340                        this.discard_copilot_suggestion(cx);
3341                        cx.notify();
3342                    } else if this.completion_tasks.len() <= 1 {
3343                        // If there are no more completion tasks and the last menu was
3344                        // empty, we should hide it. If it was already hidden, we should
3345                        // also show the copilot suggestion when available.
3346                        drop(context_menu);
3347                        if this.hide_context_menu(cx).is_none() {
3348                            this.update_visible_copilot_suggestion(cx);
3349                        }
3350                    }
3351                })?;
3352
3353                if let Some(pre_resolve_task) = pre_resolve_task {
3354                    pre_resolve_task.await;
3355                }
3356
3357                Ok::<_, anyhow::Error>(())
3358            }
3359            .log_err()
3360        });
3361
3362        self.completion_tasks.push((id, task));
3363    }
3364
3365    pub fn confirm_completion(
3366        &mut self,
3367        action: &ConfirmCompletion,
3368        cx: &mut ViewContext<Self>,
3369    ) -> Option<Task<Result<()>>> {
3370        use language::ToOffset as _;
3371
3372        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3373            menu
3374        } else {
3375            return None;
3376        };
3377
3378        let mat = completions_menu
3379            .matches
3380            .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
3381        let buffer_handle = completions_menu.buffer;
3382        let completions = completions_menu.completions.read();
3383        let completion = completions.get(mat.candidate_id)?;
3384
3385        let snippet;
3386        let text;
3387        if completion.is_snippet() {
3388            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3389            text = snippet.as_ref().unwrap().text.clone();
3390        } else {
3391            snippet = None;
3392            text = completion.new_text.clone();
3393        };
3394        let selections = self.selections.all::<usize>(cx);
3395        let buffer = buffer_handle.read(cx);
3396        let old_range = completion.old_range.to_offset(buffer);
3397        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3398
3399        let newest_selection = self.selections.newest_anchor();
3400        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3401            return None;
3402        }
3403
3404        let lookbehind = newest_selection
3405            .start
3406            .text_anchor
3407            .to_offset(buffer)
3408            .saturating_sub(old_range.start);
3409        let lookahead = old_range
3410            .end
3411            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3412        let mut common_prefix_len = old_text
3413            .bytes()
3414            .zip(text.bytes())
3415            .take_while(|(a, b)| a == b)
3416            .count();
3417
3418        let snapshot = self.buffer.read(cx).snapshot(cx);
3419        let mut range_to_replace: Option<Range<isize>> = None;
3420        let mut ranges = Vec::new();
3421        for selection in &selections {
3422            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3423                let start = selection.start.saturating_sub(lookbehind);
3424                let end = selection.end + lookahead;
3425                if selection.id == newest_selection.id {
3426                    range_to_replace = Some(
3427                        ((start + common_prefix_len) as isize - selection.start as isize)
3428                            ..(end as isize - selection.start as isize),
3429                    );
3430                }
3431                ranges.push(start + common_prefix_len..end);
3432            } else {
3433                common_prefix_len = 0;
3434                ranges.clear();
3435                ranges.extend(selections.iter().map(|s| {
3436                    if s.id == newest_selection.id {
3437                        range_to_replace = Some(
3438                            old_range.start.to_offset_utf16(&snapshot).0 as isize
3439                                - selection.start as isize
3440                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3441                                    - selection.start as isize,
3442                        );
3443                        old_range.clone()
3444                    } else {
3445                        s.start..s.end
3446                    }
3447                }));
3448                break;
3449            }
3450        }
3451        let text = &text[common_prefix_len..];
3452
3453        cx.emit(EditorEvent::InputHandled {
3454            utf16_range_to_replace: range_to_replace,
3455            text: text.into(),
3456        });
3457
3458        self.transact(cx, |this, cx| {
3459            if let Some(mut snippet) = snippet {
3460                snippet.text = text.to_string();
3461                for tabstop in snippet.tabstops.iter_mut().flatten() {
3462                    tabstop.start -= common_prefix_len as isize;
3463                    tabstop.end -= common_prefix_len as isize;
3464                }
3465
3466                this.insert_snippet(&ranges, snippet, cx).log_err();
3467            } else {
3468                this.buffer.update(cx, |buffer, cx| {
3469                    buffer.edit(
3470                        ranges.iter().map(|range| (range.clone(), text)),
3471                        this.autoindent_mode.clone(),
3472                        cx,
3473                    );
3474                });
3475            }
3476
3477            this.refresh_copilot_suggestions(true, cx);
3478        });
3479
3480        let project = self.project.clone()?;
3481        let apply_edits = project.update(cx, |project, cx| {
3482            project.apply_additional_edits_for_completion(
3483                buffer_handle,
3484                completion.clone(),
3485                true,
3486                cx,
3487            )
3488        });
3489        Some(cx.foreground_executor().spawn(async move {
3490            apply_edits.await?;
3491            Ok(())
3492        }))
3493    }
3494
3495    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
3496        let mut context_menu = self.context_menu.write();
3497        if matches!(context_menu.as_ref(), Some(ContextMenu::CodeActions(_))) {
3498            *context_menu = None;
3499            cx.notify();
3500            return;
3501        }
3502        drop(context_menu);
3503
3504        let deployed_from_indicator = action.deployed_from_indicator;
3505        let mut task = self.code_actions_task.take();
3506        cx.spawn(|this, mut cx| async move {
3507            while let Some(prev_task) = task {
3508                prev_task.await;
3509                task = this.update(&mut cx, |this, _| this.code_actions_task.take())?;
3510            }
3511
3512            this.update(&mut cx, |this, cx| {
3513                if this.focus_handle.is_focused(cx) {
3514                    if let Some((buffer, actions)) = this.available_code_actions.clone() {
3515                        this.completion_tasks.clear();
3516                        this.discard_copilot_suggestion(cx);
3517                        *this.context_menu.write() =
3518                            Some(ContextMenu::CodeActions(CodeActionsMenu {
3519                                buffer,
3520                                actions,
3521                                selected_item: Default::default(),
3522                                scroll_handle: UniformListScrollHandle::default(),
3523                                deployed_from_indicator,
3524                            }));
3525                        cx.notify();
3526                    }
3527                }
3528            })?;
3529
3530            Ok::<_, anyhow::Error>(())
3531        })
3532        .detach_and_log_err(cx);
3533    }
3534
3535    pub fn confirm_code_action(
3536        &mut self,
3537        action: &ConfirmCodeAction,
3538        cx: &mut ViewContext<Self>,
3539    ) -> Option<Task<Result<()>>> {
3540        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
3541            menu
3542        } else {
3543            return None;
3544        };
3545        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
3546        let action = actions_menu.actions.get(action_ix)?.clone();
3547        let title = action.lsp_action.title.clone();
3548        let buffer = actions_menu.buffer;
3549        let workspace = self.workspace()?;
3550
3551        let apply_code_actions = workspace
3552            .read(cx)
3553            .project()
3554            .clone()
3555            .update(cx, |project, cx| {
3556                project.apply_code_action(buffer, action, true, cx)
3557            });
3558        let workspace = workspace.downgrade();
3559        Some(cx.spawn(|editor, cx| async move {
3560            let project_transaction = apply_code_actions.await?;
3561            Self::open_project_transaction(&editor, workspace, project_transaction, title, cx).await
3562        }))
3563    }
3564
3565    async fn open_project_transaction(
3566        this: &WeakView<Editor>,
3567        workspace: WeakView<Workspace>,
3568        transaction: ProjectTransaction,
3569        title: String,
3570        mut cx: AsyncWindowContext,
3571    ) -> Result<()> {
3572        let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
3573
3574        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
3575        cx.update(|_, cx| {
3576            entries.sort_unstable_by_key(|(buffer, _)| {
3577                buffer.read(cx).file().map(|f| f.path().clone())
3578            });
3579        })?;
3580
3581        // If the project transaction's edits are all contained within this editor, then
3582        // avoid opening a new editor to display them.
3583
3584        if let Some((buffer, transaction)) = entries.first() {
3585            if entries.len() == 1 {
3586                let excerpt = this.update(&mut cx, |editor, cx| {
3587                    editor
3588                        .buffer()
3589                        .read(cx)
3590                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
3591                })?;
3592                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
3593                    if excerpted_buffer == *buffer {
3594                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
3595                            let excerpt_range = excerpt_range.to_offset(buffer);
3596                            buffer
3597                                .edited_ranges_for_transaction::<usize>(transaction)
3598                                .all(|range| {
3599                                    excerpt_range.start <= range.start
3600                                        && excerpt_range.end >= range.end
3601                                })
3602                        })?;
3603
3604                        if all_edits_within_excerpt {
3605                            return Ok(());
3606                        }
3607                    }
3608                }
3609            }
3610        } else {
3611            return Ok(());
3612        }
3613
3614        let mut ranges_to_highlight = Vec::new();
3615        let excerpt_buffer = cx.new_model(|cx| {
3616            let mut multibuffer =
3617                MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
3618            for (buffer_handle, transaction) in &entries {
3619                let buffer = buffer_handle.read(cx);
3620                ranges_to_highlight.extend(
3621                    multibuffer.push_excerpts_with_context_lines(
3622                        buffer_handle.clone(),
3623                        buffer
3624                            .edited_ranges_for_transaction::<usize>(transaction)
3625                            .collect(),
3626                        1,
3627                        cx,
3628                    ),
3629                );
3630            }
3631            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
3632            multibuffer
3633        })?;
3634
3635        workspace.update(&mut cx, |workspace, cx| {
3636            let project = workspace.project().clone();
3637            let editor =
3638                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), cx));
3639            workspace.add_item(Box::new(editor.clone()), cx);
3640            editor.update(cx, |editor, cx| {
3641                editor.highlight_background::<Self>(
3642                    ranges_to_highlight,
3643                    |theme| theme.editor_highlighted_line_background,
3644                    cx,
3645                );
3646            });
3647        })?;
3648
3649        Ok(())
3650    }
3651
3652    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
3653        let project = self.project.clone()?;
3654        let buffer = self.buffer.read(cx);
3655        let newest_selection = self.selections.newest_anchor().clone();
3656        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
3657        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
3658        if start_buffer != end_buffer {
3659            return None;
3660        }
3661
3662        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
3663            cx.background_executor()
3664                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
3665                .await;
3666
3667            let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
3668                project.code_actions(&start_buffer, start..end, cx)
3669            }) {
3670                code_actions.await.log_err()
3671            } else {
3672                None
3673            };
3674
3675            this.update(&mut cx, |this, cx| {
3676                this.available_code_actions = actions.and_then(|actions| {
3677                    if actions.is_empty() {
3678                        None
3679                    } else {
3680                        Some((start_buffer, actions.into()))
3681                    }
3682                });
3683                cx.notify();
3684            })
3685            .log_err();
3686        }));
3687        None
3688    }
3689
3690    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
3691        if self.pending_rename.is_some() {
3692            return None;
3693        }
3694
3695        let project = self.project.clone()?;
3696        let buffer = self.buffer.read(cx);
3697        let newest_selection = self.selections.newest_anchor().clone();
3698        let cursor_position = newest_selection.head();
3699        let (cursor_buffer, cursor_buffer_position) =
3700            buffer.text_anchor_for_position(cursor_position.clone(), cx)?;
3701        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
3702        if cursor_buffer != tail_buffer {
3703            return None;
3704        }
3705
3706        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
3707            cx.background_executor()
3708                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
3709                .await;
3710
3711            let highlights = if let Some(highlights) = project
3712                .update(&mut cx, |project, cx| {
3713                    project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
3714                })
3715                .log_err()
3716            {
3717                highlights.await.log_err()
3718            } else {
3719                None
3720            };
3721
3722            if let Some(highlights) = highlights {
3723                this.update(&mut cx, |this, cx| {
3724                    if this.pending_rename.is_some() {
3725                        return;
3726                    }
3727
3728                    let buffer_id = cursor_position.buffer_id;
3729                    let buffer = this.buffer.read(cx);
3730                    if !buffer
3731                        .text_anchor_for_position(cursor_position, cx)
3732                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
3733                    {
3734                        return;
3735                    }
3736
3737                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
3738                    let mut write_ranges = Vec::new();
3739                    let mut read_ranges = Vec::new();
3740                    for highlight in highlights {
3741                        for (excerpt_id, excerpt_range) in
3742                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
3743                        {
3744                            let start = highlight
3745                                .range
3746                                .start
3747                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
3748                            let end = highlight
3749                                .range
3750                                .end
3751                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
3752                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
3753                                continue;
3754                            }
3755
3756                            let range = Anchor {
3757                                buffer_id,
3758                                excerpt_id: excerpt_id.clone(),
3759                                text_anchor: start,
3760                            }..Anchor {
3761                                buffer_id,
3762                                excerpt_id,
3763                                text_anchor: end,
3764                            };
3765                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
3766                                write_ranges.push(range);
3767                            } else {
3768                                read_ranges.push(range);
3769                            }
3770                        }
3771                    }
3772
3773                    this.highlight_background::<DocumentHighlightRead>(
3774                        read_ranges,
3775                        |theme| theme.editor_document_highlight_read_background,
3776                        cx,
3777                    );
3778                    this.highlight_background::<DocumentHighlightWrite>(
3779                        write_ranges,
3780                        |theme| theme.editor_document_highlight_write_background,
3781                        cx,
3782                    );
3783                    cx.notify();
3784                })
3785                .log_err();
3786            }
3787        }));
3788        None
3789    }
3790
3791    fn refresh_copilot_suggestions(
3792        &mut self,
3793        debounce: bool,
3794        cx: &mut ViewContext<Self>,
3795    ) -> Option<()> {
3796        let copilot = Copilot::global(cx)?;
3797        if !self.show_copilot_suggestions || !copilot.read(cx).status().is_authorized() {
3798            self.clear_copilot_suggestions(cx);
3799            return None;
3800        }
3801        self.update_visible_copilot_suggestion(cx);
3802
3803        let snapshot = self.buffer.read(cx).snapshot(cx);
3804        let cursor = self.selections.newest_anchor().head();
3805        if !self.is_copilot_enabled_at(cursor, &snapshot, cx) {
3806            self.clear_copilot_suggestions(cx);
3807            return None;
3808        }
3809
3810        let (buffer, buffer_position) =
3811            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
3812        self.copilot_state.pending_refresh = cx.spawn(|this, mut cx| async move {
3813            if debounce {
3814                cx.background_executor()
3815                    .timer(COPILOT_DEBOUNCE_TIMEOUT)
3816                    .await;
3817            }
3818
3819            let completions = copilot
3820                .update(&mut cx, |copilot, cx| {
3821                    copilot.completions(&buffer, buffer_position, cx)
3822                })
3823                .log_err()
3824                .unwrap_or(Task::ready(Ok(Vec::new())))
3825                .await
3826                .log_err()
3827                .into_iter()
3828                .flatten()
3829                .collect_vec();
3830
3831            this.update(&mut cx, |this, cx| {
3832                if !completions.is_empty() {
3833                    this.copilot_state.cycled = false;
3834                    this.copilot_state.pending_cycling_refresh = Task::ready(None);
3835                    this.copilot_state.completions.clear();
3836                    this.copilot_state.active_completion_index = 0;
3837                    this.copilot_state.excerpt_id = Some(cursor.excerpt_id);
3838                    for completion in completions {
3839                        this.copilot_state.push_completion(completion);
3840                    }
3841                    this.update_visible_copilot_suggestion(cx);
3842                }
3843            })
3844            .log_err()?;
3845            Some(())
3846        });
3847
3848        Some(())
3849    }
3850
3851    fn cycle_copilot_suggestions(
3852        &mut self,
3853        direction: Direction,
3854        cx: &mut ViewContext<Self>,
3855    ) -> Option<()> {
3856        let copilot = Copilot::global(cx)?;
3857        if !self.show_copilot_suggestions || !copilot.read(cx).status().is_authorized() {
3858            return None;
3859        }
3860
3861        if self.copilot_state.cycled {
3862            self.copilot_state.cycle_completions(direction);
3863            self.update_visible_copilot_suggestion(cx);
3864        } else {
3865            let cursor = self.selections.newest_anchor().head();
3866            let (buffer, buffer_position) =
3867                self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
3868            self.copilot_state.pending_cycling_refresh = cx.spawn(|this, mut cx| async move {
3869                let completions = copilot
3870                    .update(&mut cx, |copilot, cx| {
3871                        copilot.completions_cycling(&buffer, buffer_position, cx)
3872                    })
3873                    .log_err()?
3874                    .await;
3875
3876                this.update(&mut cx, |this, cx| {
3877                    this.copilot_state.cycled = true;
3878                    for completion in completions.log_err().into_iter().flatten() {
3879                        this.copilot_state.push_completion(completion);
3880                    }
3881                    this.copilot_state.cycle_completions(direction);
3882                    this.update_visible_copilot_suggestion(cx);
3883                })
3884                .log_err()?;
3885
3886                Some(())
3887            });
3888        }
3889
3890        Some(())
3891    }
3892
3893    fn copilot_suggest(&mut self, _: &copilot::Suggest, cx: &mut ViewContext<Self>) {
3894        if !self.has_active_copilot_suggestion(cx) {
3895            self.refresh_copilot_suggestions(false, cx);
3896            return;
3897        }
3898
3899        self.update_visible_copilot_suggestion(cx);
3900    }
3901
3902    fn next_copilot_suggestion(&mut self, _: &copilot::NextSuggestion, cx: &mut ViewContext<Self>) {
3903        if self.has_active_copilot_suggestion(cx) {
3904            self.cycle_copilot_suggestions(Direction::Next, cx);
3905        } else {
3906            let is_copilot_disabled = self.refresh_copilot_suggestions(false, cx).is_none();
3907            if is_copilot_disabled {
3908                cx.propagate();
3909            }
3910        }
3911    }
3912
3913    fn previous_copilot_suggestion(
3914        &mut self,
3915        _: &copilot::PreviousSuggestion,
3916        cx: &mut ViewContext<Self>,
3917    ) {
3918        if self.has_active_copilot_suggestion(cx) {
3919            self.cycle_copilot_suggestions(Direction::Prev, cx);
3920        } else {
3921            let is_copilot_disabled = self.refresh_copilot_suggestions(false, cx).is_none();
3922            if is_copilot_disabled {
3923                cx.propagate();
3924            }
3925        }
3926    }
3927
3928    fn accept_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) -> bool {
3929        if let Some(suggestion) = self.take_active_copilot_suggestion(cx) {
3930            if let Some((copilot, completion)) =
3931                Copilot::global(cx).zip(self.copilot_state.active_completion())
3932            {
3933                copilot
3934                    .update(cx, |copilot, cx| copilot.accept_completion(completion, cx))
3935                    .detach_and_log_err(cx);
3936
3937                self.report_copilot_event(Some(completion.uuid.clone()), true, cx)
3938            }
3939            cx.emit(EditorEvent::InputHandled {
3940                utf16_range_to_replace: None,
3941                text: suggestion.text.to_string().into(),
3942            });
3943            self.insert_with_autoindent_mode(&suggestion.text.to_string(), None, cx);
3944            cx.notify();
3945            true
3946        } else {
3947            false
3948        }
3949    }
3950
3951    fn discard_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) -> bool {
3952        if let Some(suggestion) = self.take_active_copilot_suggestion(cx) {
3953            if let Some(copilot) = Copilot::global(cx) {
3954                copilot
3955                    .update(cx, |copilot, cx| {
3956                        copilot.discard_completions(&self.copilot_state.completions, cx)
3957                    })
3958                    .detach_and_log_err(cx);
3959
3960                self.report_copilot_event(None, false, cx)
3961            }
3962
3963            self.display_map.update(cx, |map, cx| {
3964                map.splice_inlays(vec![suggestion.id], Vec::new(), cx)
3965            });
3966            cx.notify();
3967            true
3968        } else {
3969            false
3970        }
3971    }
3972
3973    fn is_copilot_enabled_at(
3974        &self,
3975        location: Anchor,
3976        snapshot: &MultiBufferSnapshot,
3977        cx: &mut ViewContext<Self>,
3978    ) -> bool {
3979        let file = snapshot.file_at(location);
3980        let language = snapshot.language_at(location);
3981        let settings = all_language_settings(file, cx);
3982        self.show_copilot_suggestions
3983            && settings.copilot_enabled(language, file.map(|f| f.path().as_ref()))
3984    }
3985
3986    fn has_active_copilot_suggestion(&self, cx: &AppContext) -> bool {
3987        if let Some(suggestion) = self.copilot_state.suggestion.as_ref() {
3988            let buffer = self.buffer.read(cx).read(cx);
3989            suggestion.position.is_valid(&buffer)
3990        } else {
3991            false
3992        }
3993    }
3994
3995    fn take_active_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) -> Option<Inlay> {
3996        let suggestion = self.copilot_state.suggestion.take()?;
3997        self.display_map.update(cx, |map, cx| {
3998            map.splice_inlays(vec![suggestion.id], Default::default(), cx);
3999        });
4000        let buffer = self.buffer.read(cx).read(cx);
4001
4002        if suggestion.position.is_valid(&buffer) {
4003            Some(suggestion)
4004        } else {
4005            None
4006        }
4007    }
4008
4009    fn update_visible_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) {
4010        let snapshot = self.buffer.read(cx).snapshot(cx);
4011        let selection = self.selections.newest_anchor();
4012        let cursor = selection.head();
4013
4014        if self.context_menu.read().is_some()
4015            || !self.completion_tasks.is_empty()
4016            || selection.start != selection.end
4017        {
4018            self.discard_copilot_suggestion(cx);
4019        } else if let Some(text) = self
4020            .copilot_state
4021            .text_for_active_completion(cursor, &snapshot)
4022        {
4023            let text = Rope::from(text);
4024            let mut to_remove = Vec::new();
4025            if let Some(suggestion) = self.copilot_state.suggestion.take() {
4026                to_remove.push(suggestion.id);
4027            }
4028
4029            let suggestion_inlay =
4030                Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
4031            self.copilot_state.suggestion = Some(suggestion_inlay.clone());
4032            self.display_map.update(cx, move |map, cx| {
4033                map.splice_inlays(to_remove, vec![suggestion_inlay], cx)
4034            });
4035            cx.notify();
4036        } else {
4037            self.discard_copilot_suggestion(cx);
4038        }
4039    }
4040
4041    fn clear_copilot_suggestions(&mut self, cx: &mut ViewContext<Self>) {
4042        self.copilot_state = Default::default();
4043        self.discard_copilot_suggestion(cx);
4044    }
4045
4046    pub fn render_code_actions_indicator(
4047        &self,
4048        _style: &EditorStyle,
4049        is_active: bool,
4050        cx: &mut ViewContext<Self>,
4051    ) -> Option<IconButton> {
4052        if self.available_code_actions.is_some() {
4053            Some(
4054                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4055                    .icon_size(IconSize::Small)
4056                    .icon_color(Color::Muted)
4057                    .selected(is_active)
4058                    .on_click(cx.listener(|editor, _e, cx| {
4059                        editor.toggle_code_actions(
4060                            &ToggleCodeActions {
4061                                deployed_from_indicator: true,
4062                            },
4063                            cx,
4064                        );
4065                    })),
4066            )
4067        } else {
4068            None
4069        }
4070    }
4071
4072    pub fn render_fold_indicators(
4073        &self,
4074        fold_data: Vec<Option<(FoldStatus, u32, bool)>>,
4075        _style: &EditorStyle,
4076        gutter_hovered: bool,
4077        _line_height: Pixels,
4078        _gutter_margin: Pixels,
4079        cx: &mut ViewContext<Self>,
4080    ) -> Vec<Option<IconButton>> {
4081        fold_data
4082            .iter()
4083            .enumerate()
4084            .map(|(ix, fold_data)| {
4085                fold_data
4086                    .map(|(fold_status, buffer_row, active)| {
4087                        (active || gutter_hovered || fold_status == FoldStatus::Folded).then(|| {
4088                            IconButton::new(ix as usize, ui::IconName::ChevronDown)
4089                                .on_click(cx.listener(move |editor, _e, cx| match fold_status {
4090                                    FoldStatus::Folded => {
4091                                        editor.unfold_at(&UnfoldAt { buffer_row }, cx);
4092                                    }
4093                                    FoldStatus::Foldable => {
4094                                        editor.fold_at(&FoldAt { buffer_row }, cx);
4095                                    }
4096                                }))
4097                                .icon_color(ui::Color::Muted)
4098                                .icon_size(ui::IconSize::Small)
4099                                .selected(fold_status == FoldStatus::Folded)
4100                                .selected_icon(ui::IconName::ChevronRight)
4101                                .size(ui::ButtonSize::None)
4102                        })
4103                    })
4104                    .flatten()
4105            })
4106            .collect()
4107    }
4108
4109    pub fn context_menu_visible(&self) -> bool {
4110        self.context_menu
4111            .read()
4112            .as_ref()
4113            .map_or(false, |menu| menu.visible())
4114    }
4115
4116    pub fn render_context_menu(
4117        &self,
4118        cursor_position: DisplayPoint,
4119        style: &EditorStyle,
4120        max_height: Pixels,
4121        cx: &mut ViewContext<Editor>,
4122    ) -> Option<(DisplayPoint, AnyElement)> {
4123        self.context_menu.read().as_ref().map(|menu| {
4124            menu.render(
4125                cursor_position,
4126                style,
4127                max_height,
4128                self.workspace.as_ref().map(|(w, _)| w.clone()),
4129                cx,
4130            )
4131        })
4132    }
4133
4134    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
4135        cx.notify();
4136        self.completion_tasks.clear();
4137        let context_menu = self.context_menu.write().take();
4138        if context_menu.is_some() {
4139            self.update_visible_copilot_suggestion(cx);
4140        }
4141        context_menu
4142    }
4143
4144    pub fn insert_snippet(
4145        &mut self,
4146        insertion_ranges: &[Range<usize>],
4147        snippet: Snippet,
4148        cx: &mut ViewContext<Self>,
4149    ) -> Result<()> {
4150        let tabstops = self.buffer.update(cx, |buffer, cx| {
4151            let snippet_text: Arc<str> = snippet.text.clone().into();
4152            buffer.edit(
4153                insertion_ranges
4154                    .iter()
4155                    .cloned()
4156                    .map(|range| (range, snippet_text.clone())),
4157                Some(AutoindentMode::EachLine),
4158                cx,
4159            );
4160
4161            let snapshot = &*buffer.read(cx);
4162            let snippet = &snippet;
4163            snippet
4164                .tabstops
4165                .iter()
4166                .map(|tabstop| {
4167                    let mut tabstop_ranges = tabstop
4168                        .iter()
4169                        .flat_map(|tabstop_range| {
4170                            let mut delta = 0_isize;
4171                            insertion_ranges.iter().map(move |insertion_range| {
4172                                let insertion_start = insertion_range.start as isize + delta;
4173                                delta +=
4174                                    snippet.text.len() as isize - insertion_range.len() as isize;
4175
4176                                let start = snapshot.anchor_before(
4177                                    (insertion_start + tabstop_range.start) as usize,
4178                                );
4179                                let end = snapshot
4180                                    .anchor_after((insertion_start + tabstop_range.end) as usize);
4181                                start..end
4182                            })
4183                        })
4184                        .collect::<Vec<_>>();
4185                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
4186                    tabstop_ranges
4187                })
4188                .collect::<Vec<_>>()
4189        });
4190
4191        if let Some(tabstop) = tabstops.first() {
4192            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
4193                s.select_ranges(tabstop.iter().cloned());
4194            });
4195            self.snippet_stack.push(SnippetState {
4196                active_index: 0,
4197                ranges: tabstops,
4198            });
4199        }
4200
4201        Ok(())
4202    }
4203
4204    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
4205        self.move_to_snippet_tabstop(Bias::Right, cx)
4206    }
4207
4208    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
4209        self.move_to_snippet_tabstop(Bias::Left, cx)
4210    }
4211
4212    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
4213        if let Some(mut snippet) = self.snippet_stack.pop() {
4214            match bias {
4215                Bias::Left => {
4216                    if snippet.active_index > 0 {
4217                        snippet.active_index -= 1;
4218                    } else {
4219                        self.snippet_stack.push(snippet);
4220                        return false;
4221                    }
4222                }
4223                Bias::Right => {
4224                    if snippet.active_index + 1 < snippet.ranges.len() {
4225                        snippet.active_index += 1;
4226                    } else {
4227                        self.snippet_stack.push(snippet);
4228                        return false;
4229                    }
4230                }
4231            }
4232            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
4233                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
4234                    s.select_anchor_ranges(current_ranges.iter().cloned())
4235                });
4236                // If snippet state is not at the last tabstop, push it back on the stack
4237                if snippet.active_index + 1 < snippet.ranges.len() {
4238                    self.snippet_stack.push(snippet);
4239                }
4240                return true;
4241            }
4242        }
4243
4244        false
4245    }
4246
4247    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
4248        self.transact(cx, |this, cx| {
4249            this.select_all(&SelectAll, cx);
4250            this.insert("", cx);
4251        });
4252    }
4253
4254    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
4255        self.transact(cx, |this, cx| {
4256            this.select_autoclose_pair(cx);
4257            let mut selections = this.selections.all::<Point>(cx);
4258            if !this.selections.line_mode {
4259                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
4260                for selection in &mut selections {
4261                    if selection.is_empty() {
4262                        let old_head = selection.head();
4263                        let mut new_head =
4264                            movement::left(&display_map, old_head.to_display_point(&display_map))
4265                                .to_point(&display_map);
4266                        if let Some((buffer, line_buffer_range)) = display_map
4267                            .buffer_snapshot
4268                            .buffer_line_for_row(old_head.row)
4269                        {
4270                            let indent_size =
4271                                buffer.indent_size_for_line(line_buffer_range.start.row);
4272                            let indent_len = match indent_size.kind {
4273                                IndentKind::Space => {
4274                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
4275                                }
4276                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
4277                            };
4278                            if old_head.column <= indent_size.len && old_head.column > 0 {
4279                                let indent_len = indent_len.get();
4280                                new_head = cmp::min(
4281                                    new_head,
4282                                    Point::new(
4283                                        old_head.row,
4284                                        ((old_head.column - 1) / indent_len) * indent_len,
4285                                    ),
4286                                );
4287                            }
4288                        }
4289
4290                        selection.set_head(new_head, SelectionGoal::None);
4291                    }
4292                }
4293            }
4294
4295            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
4296            this.insert("", cx);
4297            this.refresh_copilot_suggestions(true, cx);
4298        });
4299    }
4300
4301    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
4302        self.transact(cx, |this, cx| {
4303            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4304                let line_mode = s.line_mode;
4305                s.move_with(|map, selection| {
4306                    if selection.is_empty() && !line_mode {
4307                        let cursor = movement::right(map, selection.head());
4308                        selection.end = cursor;
4309                        selection.reversed = true;
4310                        selection.goal = SelectionGoal::None;
4311                    }
4312                })
4313            });
4314            this.insert("", cx);
4315            this.refresh_copilot_suggestions(true, cx);
4316        });
4317    }
4318
4319    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
4320        if self.move_to_prev_snippet_tabstop(cx) {
4321            return;
4322        }
4323
4324        self.outdent(&Outdent, cx);
4325    }
4326
4327    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
4328        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
4329            return;
4330        }
4331
4332        let mut selections = self.selections.all_adjusted(cx);
4333        let buffer = self.buffer.read(cx);
4334        let snapshot = buffer.snapshot(cx);
4335        let rows_iter = selections.iter().map(|s| s.head().row);
4336        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
4337
4338        let mut edits = Vec::new();
4339        let mut prev_edited_row = 0;
4340        let mut row_delta = 0;
4341        for selection in &mut selections {
4342            if selection.start.row != prev_edited_row {
4343                row_delta = 0;
4344            }
4345            prev_edited_row = selection.end.row;
4346
4347            // If the selection is non-empty, then increase the indentation of the selected lines.
4348            if !selection.is_empty() {
4349                row_delta =
4350                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
4351                continue;
4352            }
4353
4354            // If the selection is empty and the cursor is in the leading whitespace before the
4355            // suggested indentation, then auto-indent the line.
4356            let cursor = selection.head();
4357            let current_indent = snapshot.indent_size_for_line(cursor.row);
4358            if let Some(suggested_indent) = suggested_indents.get(&cursor.row).copied() {
4359                if cursor.column < suggested_indent.len
4360                    && cursor.column <= current_indent.len
4361                    && current_indent.len <= suggested_indent.len
4362                {
4363                    selection.start = Point::new(cursor.row, suggested_indent.len);
4364                    selection.end = selection.start;
4365                    if row_delta == 0 {
4366                        edits.extend(Buffer::edit_for_indent_size_adjustment(
4367                            cursor.row,
4368                            current_indent,
4369                            suggested_indent,
4370                        ));
4371                        row_delta = suggested_indent.len - current_indent.len;
4372                    }
4373                    continue;
4374                }
4375            }
4376
4377            // Accept copilot suggestion if there is only one selection and the cursor is not
4378            // in the leading whitespace.
4379            if self.selections.count() == 1
4380                && cursor.column >= current_indent.len
4381                && self.has_active_copilot_suggestion(cx)
4382            {
4383                self.accept_copilot_suggestion(cx);
4384                return;
4385            }
4386
4387            // Otherwise, insert a hard or soft tab.
4388            let settings = buffer.settings_at(cursor, cx);
4389            let tab_size = if settings.hard_tabs {
4390                IndentSize::tab()
4391            } else {
4392                let tab_size = settings.tab_size.get();
4393                let char_column = snapshot
4394                    .text_for_range(Point::new(cursor.row, 0)..cursor)
4395                    .flat_map(str::chars)
4396                    .count()
4397                    + row_delta as usize;
4398                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
4399                IndentSize::spaces(chars_to_next_tab_stop)
4400            };
4401            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
4402            selection.end = selection.start;
4403            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
4404            row_delta += tab_size.len;
4405        }
4406
4407        self.transact(cx, |this, cx| {
4408            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
4409            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
4410            this.refresh_copilot_suggestions(true, cx);
4411        });
4412    }
4413
4414    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
4415        let mut selections = self.selections.all::<Point>(cx);
4416        let mut prev_edited_row = 0;
4417        let mut row_delta = 0;
4418        let mut edits = Vec::new();
4419        let buffer = self.buffer.read(cx);
4420        let snapshot = buffer.snapshot(cx);
4421        for selection in &mut selections {
4422            if selection.start.row != prev_edited_row {
4423                row_delta = 0;
4424            }
4425            prev_edited_row = selection.end.row;
4426
4427            row_delta =
4428                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
4429        }
4430
4431        self.transact(cx, |this, cx| {
4432            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
4433            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
4434        });
4435    }
4436
4437    fn indent_selection(
4438        buffer: &MultiBuffer,
4439        snapshot: &MultiBufferSnapshot,
4440        selection: &mut Selection<Point>,
4441        edits: &mut Vec<(Range<Point>, String)>,
4442        delta_for_start_row: u32,
4443        cx: &AppContext,
4444    ) -> u32 {
4445        let settings = buffer.settings_at(selection.start, cx);
4446        let tab_size = settings.tab_size.get();
4447        let indent_kind = if settings.hard_tabs {
4448            IndentKind::Tab
4449        } else {
4450            IndentKind::Space
4451        };
4452        let mut start_row = selection.start.row;
4453        let mut end_row = selection.end.row + 1;
4454
4455        // If a selection ends at the beginning of a line, don't indent
4456        // that last line.
4457        if selection.end.column == 0 {
4458            end_row -= 1;
4459        }
4460
4461        // Avoid re-indenting a row that has already been indented by a
4462        // previous selection, but still update this selection's column
4463        // to reflect that indentation.
4464        if delta_for_start_row > 0 {
4465            start_row += 1;
4466            selection.start.column += delta_for_start_row;
4467            if selection.end.row == selection.start.row {
4468                selection.end.column += delta_for_start_row;
4469            }
4470        }
4471
4472        let mut delta_for_end_row = 0;
4473        for row in start_row..end_row {
4474            let current_indent = snapshot.indent_size_for_line(row);
4475            let indent_delta = match (current_indent.kind, indent_kind) {
4476                (IndentKind::Space, IndentKind::Space) => {
4477                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
4478                    IndentSize::spaces(columns_to_next_tab_stop)
4479                }
4480                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
4481                (_, IndentKind::Tab) => IndentSize::tab(),
4482            };
4483
4484            let row_start = Point::new(row, 0);
4485            edits.push((
4486                row_start..row_start,
4487                indent_delta.chars().collect::<String>(),
4488            ));
4489
4490            // Update this selection's endpoints to reflect the indentation.
4491            if row == selection.start.row {
4492                selection.start.column += indent_delta.len;
4493            }
4494            if row == selection.end.row {
4495                selection.end.column += indent_delta.len;
4496                delta_for_end_row = indent_delta.len;
4497            }
4498        }
4499
4500        if selection.start.row == selection.end.row {
4501            delta_for_start_row + delta_for_end_row
4502        } else {
4503            delta_for_end_row
4504        }
4505    }
4506
4507    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
4508        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4509        let selections = self.selections.all::<Point>(cx);
4510        let mut deletion_ranges = Vec::new();
4511        let mut last_outdent = None;
4512        {
4513            let buffer = self.buffer.read(cx);
4514            let snapshot = buffer.snapshot(cx);
4515            for selection in &selections {
4516                let settings = buffer.settings_at(selection.start, cx);
4517                let tab_size = settings.tab_size.get();
4518                let mut rows = selection.spanned_rows(false, &display_map);
4519
4520                // Avoid re-outdenting a row that has already been outdented by a
4521                // previous selection.
4522                if let Some(last_row) = last_outdent {
4523                    if last_row == rows.start {
4524                        rows.start += 1;
4525                    }
4526                }
4527
4528                for row in rows {
4529                    let indent_size = snapshot.indent_size_for_line(row);
4530                    if indent_size.len > 0 {
4531                        let deletion_len = match indent_size.kind {
4532                            IndentKind::Space => {
4533                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
4534                                if columns_to_prev_tab_stop == 0 {
4535                                    tab_size
4536                                } else {
4537                                    columns_to_prev_tab_stop
4538                                }
4539                            }
4540                            IndentKind::Tab => 1,
4541                        };
4542                        deletion_ranges.push(Point::new(row, 0)..Point::new(row, deletion_len));
4543                        last_outdent = Some(row);
4544                    }
4545                }
4546            }
4547        }
4548
4549        self.transact(cx, |this, cx| {
4550            this.buffer.update(cx, |buffer, cx| {
4551                let empty_str: Arc<str> = "".into();
4552                buffer.edit(
4553                    deletion_ranges
4554                        .into_iter()
4555                        .map(|range| (range, empty_str.clone())),
4556                    None,
4557                    cx,
4558                );
4559            });
4560            let selections = this.selections.all::<usize>(cx);
4561            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
4562        });
4563    }
4564
4565    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
4566        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4567        let selections = self.selections.all::<Point>(cx);
4568
4569        let mut new_cursors = Vec::new();
4570        let mut edit_ranges = Vec::new();
4571        let mut selections = selections.iter().peekable();
4572        while let Some(selection) = selections.next() {
4573            let mut rows = selection.spanned_rows(false, &display_map);
4574            let goal_display_column = selection.head().to_display_point(&display_map).column();
4575
4576            // Accumulate contiguous regions of rows that we want to delete.
4577            while let Some(next_selection) = selections.peek() {
4578                let next_rows = next_selection.spanned_rows(false, &display_map);
4579                if next_rows.start <= rows.end {
4580                    rows.end = next_rows.end;
4581                    selections.next().unwrap();
4582                } else {
4583                    break;
4584                }
4585            }
4586
4587            let buffer = &display_map.buffer_snapshot;
4588            let mut edit_start = Point::new(rows.start, 0).to_offset(buffer);
4589            let edit_end;
4590            let cursor_buffer_row;
4591            if buffer.max_point().row >= rows.end {
4592                // If there's a line after the range, delete the \n from the end of the row range
4593                // and position the cursor on the next line.
4594                edit_end = Point::new(rows.end, 0).to_offset(buffer);
4595                cursor_buffer_row = rows.end;
4596            } else {
4597                // If there isn't a line after the range, delete the \n from the line before the
4598                // start of the row range and position the cursor there.
4599                edit_start = edit_start.saturating_sub(1);
4600                edit_end = buffer.len();
4601                cursor_buffer_row = rows.start.saturating_sub(1);
4602            }
4603
4604            let mut cursor = Point::new(cursor_buffer_row, 0).to_display_point(&display_map);
4605            *cursor.column_mut() =
4606                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
4607
4608            new_cursors.push((
4609                selection.id,
4610                buffer.anchor_after(cursor.to_point(&display_map)),
4611            ));
4612            edit_ranges.push(edit_start..edit_end);
4613        }
4614
4615        self.transact(cx, |this, cx| {
4616            let buffer = this.buffer.update(cx, |buffer, cx| {
4617                let empty_str: Arc<str> = "".into();
4618                buffer.edit(
4619                    edit_ranges
4620                        .into_iter()
4621                        .map(|range| (range, empty_str.clone())),
4622                    None,
4623                    cx,
4624                );
4625                buffer.snapshot(cx)
4626            });
4627            let new_selections = new_cursors
4628                .into_iter()
4629                .map(|(id, cursor)| {
4630                    let cursor = cursor.to_point(&buffer);
4631                    Selection {
4632                        id,
4633                        start: cursor,
4634                        end: cursor,
4635                        reversed: false,
4636                        goal: SelectionGoal::None,
4637                    }
4638                })
4639                .collect();
4640
4641            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4642                s.select(new_selections);
4643            });
4644        });
4645    }
4646
4647    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
4648        let mut row_ranges = Vec::<Range<u32>>::new();
4649        for selection in self.selections.all::<Point>(cx) {
4650            let start = selection.start.row;
4651            let end = if selection.start.row == selection.end.row {
4652                selection.start.row + 1
4653            } else {
4654                selection.end.row
4655            };
4656
4657            if let Some(last_row_range) = row_ranges.last_mut() {
4658                if start <= last_row_range.end {
4659                    last_row_range.end = end;
4660                    continue;
4661                }
4662            }
4663            row_ranges.push(start..end);
4664        }
4665
4666        let snapshot = self.buffer.read(cx).snapshot(cx);
4667        let mut cursor_positions = Vec::new();
4668        for row_range in &row_ranges {
4669            let anchor = snapshot.anchor_before(Point::new(
4670                row_range.end - 1,
4671                snapshot.line_len(row_range.end - 1),
4672            ));
4673            cursor_positions.push(anchor.clone()..anchor);
4674        }
4675
4676        self.transact(cx, |this, cx| {
4677            for row_range in row_ranges.into_iter().rev() {
4678                for row in row_range.rev() {
4679                    let end_of_line = Point::new(row, snapshot.line_len(row));
4680                    let indent = snapshot.indent_size_for_line(row + 1);
4681                    let start_of_next_line = Point::new(row + 1, indent.len);
4682
4683                    let replace = if snapshot.line_len(row + 1) > indent.len {
4684                        " "
4685                    } else {
4686                        ""
4687                    };
4688
4689                    this.buffer.update(cx, |buffer, cx| {
4690                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
4691                    });
4692                }
4693            }
4694
4695            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4696                s.select_anchor_ranges(cursor_positions)
4697            });
4698        });
4699    }
4700
4701    pub fn sort_lines_case_sensitive(
4702        &mut self,
4703        _: &SortLinesCaseSensitive,
4704        cx: &mut ViewContext<Self>,
4705    ) {
4706        self.manipulate_lines(cx, |lines| lines.sort())
4707    }
4708
4709    pub fn sort_lines_case_insensitive(
4710        &mut self,
4711        _: &SortLinesCaseInsensitive,
4712        cx: &mut ViewContext<Self>,
4713    ) {
4714        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
4715    }
4716
4717    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
4718        self.manipulate_lines(cx, |lines| lines.reverse())
4719    }
4720
4721    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
4722        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
4723    }
4724
4725    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
4726    where
4727        Fn: FnMut(&mut [&str]),
4728    {
4729        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4730        let buffer = self.buffer.read(cx).snapshot(cx);
4731
4732        let mut edits = Vec::new();
4733
4734        let selections = self.selections.all::<Point>(cx);
4735        let mut selections = selections.iter().peekable();
4736        let mut contiguous_row_selections = Vec::new();
4737        let mut new_selections = Vec::new();
4738
4739        while let Some(selection) = selections.next() {
4740            let (start_row, end_row) = consume_contiguous_rows(
4741                &mut contiguous_row_selections,
4742                selection,
4743                &display_map,
4744                &mut selections,
4745            );
4746
4747            let start_point = Point::new(start_row, 0);
4748            let end_point = Point::new(end_row - 1, buffer.line_len(end_row - 1));
4749            let text = buffer
4750                .text_for_range(start_point..end_point)
4751                .collect::<String>();
4752            let mut lines = text.split("\n").collect_vec();
4753
4754            let lines_len = lines.len();
4755            callback(&mut lines);
4756
4757            // This is a current limitation with selections.
4758            // If we wanted to support removing or adding lines, we'd need to fix the logic associated with selections.
4759            debug_assert!(
4760                lines.len() == lines_len,
4761                "callback should not change the number of lines"
4762            );
4763
4764            edits.push((start_point..end_point, lines.join("\n")));
4765            let start_anchor = buffer.anchor_after(start_point);
4766            let end_anchor = buffer.anchor_before(end_point);
4767
4768            // Make selection and push
4769            new_selections.push(Selection {
4770                id: selection.id,
4771                start: start_anchor.to_offset(&buffer),
4772                end: end_anchor.to_offset(&buffer),
4773                goal: SelectionGoal::None,
4774                reversed: selection.reversed,
4775            });
4776        }
4777
4778        self.transact(cx, |this, cx| {
4779            this.buffer.update(cx, |buffer, cx| {
4780                buffer.edit(edits, None, cx);
4781            });
4782
4783            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4784                s.select(new_selections);
4785            });
4786
4787            this.request_autoscroll(Autoscroll::fit(), cx);
4788        });
4789    }
4790
4791    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
4792        self.manipulate_text(cx, |text| text.to_uppercase())
4793    }
4794
4795    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
4796        self.manipulate_text(cx, |text| text.to_lowercase())
4797    }
4798
4799    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
4800        self.manipulate_text(cx, |text| {
4801            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
4802            // https://github.com/rutrum/convert-case/issues/16
4803            text.split("\n")
4804                .map(|line| line.to_case(Case::Title))
4805                .join("\n")
4806        })
4807    }
4808
4809    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
4810        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
4811    }
4812
4813    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
4814        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
4815    }
4816
4817    pub fn convert_to_upper_camel_case(
4818        &mut self,
4819        _: &ConvertToUpperCamelCase,
4820        cx: &mut ViewContext<Self>,
4821    ) {
4822        self.manipulate_text(cx, |text| {
4823            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
4824            // https://github.com/rutrum/convert-case/issues/16
4825            text.split("\n")
4826                .map(|line| line.to_case(Case::UpperCamel))
4827                .join("\n")
4828        })
4829    }
4830
4831    pub fn convert_to_lower_camel_case(
4832        &mut self,
4833        _: &ConvertToLowerCamelCase,
4834        cx: &mut ViewContext<Self>,
4835    ) {
4836        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
4837    }
4838
4839    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
4840    where
4841        Fn: FnMut(&str) -> String,
4842    {
4843        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4844        let buffer = self.buffer.read(cx).snapshot(cx);
4845
4846        let mut new_selections = Vec::new();
4847        let mut edits = Vec::new();
4848        let mut selection_adjustment = 0i32;
4849
4850        for selection in self.selections.all::<usize>(cx) {
4851            let selection_is_empty = selection.is_empty();
4852
4853            let (start, end) = if selection_is_empty {
4854                let word_range = movement::surrounding_word(
4855                    &display_map,
4856                    selection.start.to_display_point(&display_map),
4857                );
4858                let start = word_range.start.to_offset(&display_map, Bias::Left);
4859                let end = word_range.end.to_offset(&display_map, Bias::Left);
4860                (start, end)
4861            } else {
4862                (selection.start, selection.end)
4863            };
4864
4865            let text = buffer.text_for_range(start..end).collect::<String>();
4866            let old_length = text.len() as i32;
4867            let text = callback(&text);
4868
4869            new_selections.push(Selection {
4870                start: (start as i32 - selection_adjustment) as usize,
4871                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
4872                goal: SelectionGoal::None,
4873                ..selection
4874            });
4875
4876            selection_adjustment += old_length - text.len() as i32;
4877
4878            edits.push((start..end, text));
4879        }
4880
4881        self.transact(cx, |this, cx| {
4882            this.buffer.update(cx, |buffer, cx| {
4883                buffer.edit(edits, None, cx);
4884            });
4885
4886            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4887                s.select(new_selections);
4888            });
4889
4890            this.request_autoscroll(Autoscroll::fit(), cx);
4891        });
4892    }
4893
4894    pub fn duplicate_line(&mut self, _: &DuplicateLine, cx: &mut ViewContext<Self>) {
4895        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4896        let buffer = &display_map.buffer_snapshot;
4897        let selections = self.selections.all::<Point>(cx);
4898
4899        let mut edits = Vec::new();
4900        let mut selections_iter = selections.iter().peekable();
4901        while let Some(selection) = selections_iter.next() {
4902            // Avoid duplicating the same lines twice.
4903            let mut rows = selection.spanned_rows(false, &display_map);
4904
4905            while let Some(next_selection) = selections_iter.peek() {
4906                let next_rows = next_selection.spanned_rows(false, &display_map);
4907                if next_rows.start < rows.end {
4908                    rows.end = next_rows.end;
4909                    selections_iter.next().unwrap();
4910                } else {
4911                    break;
4912                }
4913            }
4914
4915            // Copy the text from the selected row region and splice it at the start of the region.
4916            let start = Point::new(rows.start, 0);
4917            let end = Point::new(rows.end - 1, buffer.line_len(rows.end - 1));
4918            let text = buffer
4919                .text_for_range(start..end)
4920                .chain(Some("\n"))
4921                .collect::<String>();
4922            edits.push((start..start, text));
4923        }
4924
4925        self.transact(cx, |this, cx| {
4926            this.buffer.update(cx, |buffer, cx| {
4927                buffer.edit(edits, None, cx);
4928            });
4929
4930            this.request_autoscroll(Autoscroll::fit(), cx);
4931        });
4932    }
4933
4934    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
4935        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4936        let buffer = self.buffer.read(cx).snapshot(cx);
4937
4938        let mut edits = Vec::new();
4939        let mut unfold_ranges = Vec::new();
4940        let mut refold_ranges = Vec::new();
4941
4942        let selections = self.selections.all::<Point>(cx);
4943        let mut selections = selections.iter().peekable();
4944        let mut contiguous_row_selections = Vec::new();
4945        let mut new_selections = Vec::new();
4946
4947        while let Some(selection) = selections.next() {
4948            // Find all the selections that span a contiguous row range
4949            let (start_row, end_row) = consume_contiguous_rows(
4950                &mut contiguous_row_selections,
4951                selection,
4952                &display_map,
4953                &mut selections,
4954            );
4955
4956            // Move the text spanned by the row range to be before the line preceding the row range
4957            if start_row > 0 {
4958                let range_to_move = Point::new(start_row - 1, buffer.line_len(start_row - 1))
4959                    ..Point::new(end_row - 1, buffer.line_len(end_row - 1));
4960                let insertion_point = display_map
4961                    .prev_line_boundary(Point::new(start_row - 1, 0))
4962                    .0;
4963
4964                // Don't move lines across excerpts
4965                if buffer
4966                    .excerpt_boundaries_in_range((
4967                        Bound::Excluded(insertion_point),
4968                        Bound::Included(range_to_move.end),
4969                    ))
4970                    .next()
4971                    .is_none()
4972                {
4973                    let text = buffer
4974                        .text_for_range(range_to_move.clone())
4975                        .flat_map(|s| s.chars())
4976                        .skip(1)
4977                        .chain(['\n'])
4978                        .collect::<String>();
4979
4980                    edits.push((
4981                        buffer.anchor_after(range_to_move.start)
4982                            ..buffer.anchor_before(range_to_move.end),
4983                        String::new(),
4984                    ));
4985                    let insertion_anchor = buffer.anchor_after(insertion_point);
4986                    edits.push((insertion_anchor..insertion_anchor, text));
4987
4988                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
4989
4990                    // Move selections up
4991                    new_selections.extend(contiguous_row_selections.drain(..).map(
4992                        |mut selection| {
4993                            selection.start.row -= row_delta;
4994                            selection.end.row -= row_delta;
4995                            selection
4996                        },
4997                    ));
4998
4999                    // Move folds up
5000                    unfold_ranges.push(range_to_move.clone());
5001                    for fold in display_map.folds_in_range(
5002                        buffer.anchor_before(range_to_move.start)
5003                            ..buffer.anchor_after(range_to_move.end),
5004                    ) {
5005                        let mut start = fold.range.start.to_point(&buffer);
5006                        let mut end = fold.range.end.to_point(&buffer);
5007                        start.row -= row_delta;
5008                        end.row -= row_delta;
5009                        refold_ranges.push(start..end);
5010                    }
5011                }
5012            }
5013
5014            // If we didn't move line(s), preserve the existing selections
5015            new_selections.append(&mut contiguous_row_selections);
5016        }
5017
5018        self.transact(cx, |this, cx| {
5019            this.unfold_ranges(unfold_ranges, true, true, cx);
5020            this.buffer.update(cx, |buffer, cx| {
5021                for (range, text) in edits {
5022                    buffer.edit([(range, text)], None, cx);
5023                }
5024            });
5025            this.fold_ranges(refold_ranges, true, cx);
5026            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5027                s.select(new_selections);
5028            })
5029        });
5030    }
5031
5032    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
5033        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5034        let buffer = self.buffer.read(cx).snapshot(cx);
5035
5036        let mut edits = Vec::new();
5037        let mut unfold_ranges = Vec::new();
5038        let mut refold_ranges = Vec::new();
5039
5040        let selections = self.selections.all::<Point>(cx);
5041        let mut selections = selections.iter().peekable();
5042        let mut contiguous_row_selections = Vec::new();
5043        let mut new_selections = Vec::new();
5044
5045        while let Some(selection) = selections.next() {
5046            // Find all the selections that span a contiguous row range
5047            let (start_row, end_row) = consume_contiguous_rows(
5048                &mut contiguous_row_selections,
5049                selection,
5050                &display_map,
5051                &mut selections,
5052            );
5053
5054            // Move the text spanned by the row range to be after the last line of the row range
5055            if end_row <= buffer.max_point().row {
5056                let range_to_move = Point::new(start_row, 0)..Point::new(end_row, 0);
5057                let insertion_point = display_map.next_line_boundary(Point::new(end_row, 0)).0;
5058
5059                // Don't move lines across excerpt boundaries
5060                if buffer
5061                    .excerpt_boundaries_in_range((
5062                        Bound::Excluded(range_to_move.start),
5063                        Bound::Included(insertion_point),
5064                    ))
5065                    .next()
5066                    .is_none()
5067                {
5068                    let mut text = String::from("\n");
5069                    text.extend(buffer.text_for_range(range_to_move.clone()));
5070                    text.pop(); // Drop trailing newline
5071                    edits.push((
5072                        buffer.anchor_after(range_to_move.start)
5073                            ..buffer.anchor_before(range_to_move.end),
5074                        String::new(),
5075                    ));
5076                    let insertion_anchor = buffer.anchor_after(insertion_point);
5077                    edits.push((insertion_anchor..insertion_anchor, text));
5078
5079                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
5080
5081                    // Move selections down
5082                    new_selections.extend(contiguous_row_selections.drain(..).map(
5083                        |mut selection| {
5084                            selection.start.row += row_delta;
5085                            selection.end.row += row_delta;
5086                            selection
5087                        },
5088                    ));
5089
5090                    // Move folds down
5091                    unfold_ranges.push(range_to_move.clone());
5092                    for fold in display_map.folds_in_range(
5093                        buffer.anchor_before(range_to_move.start)
5094                            ..buffer.anchor_after(range_to_move.end),
5095                    ) {
5096                        let mut start = fold.range.start.to_point(&buffer);
5097                        let mut end = fold.range.end.to_point(&buffer);
5098                        start.row += row_delta;
5099                        end.row += row_delta;
5100                        refold_ranges.push(start..end);
5101                    }
5102                }
5103            }
5104
5105            // If we didn't move line(s), preserve the existing selections
5106            new_selections.append(&mut contiguous_row_selections);
5107        }
5108
5109        self.transact(cx, |this, cx| {
5110            this.unfold_ranges(unfold_ranges, true, true, cx);
5111            this.buffer.update(cx, |buffer, cx| {
5112                for (range, text) in edits {
5113                    buffer.edit([(range, text)], None, cx);
5114                }
5115            });
5116            this.fold_ranges(refold_ranges, true, cx);
5117            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
5118        });
5119    }
5120
5121    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
5122        let text_layout_details = &self.text_layout_details(cx);
5123        self.transact(cx, |this, cx| {
5124            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5125                let mut edits: Vec<(Range<usize>, String)> = Default::default();
5126                let line_mode = s.line_mode;
5127                s.move_with(|display_map, selection| {
5128                    if !selection.is_empty() || line_mode {
5129                        return;
5130                    }
5131
5132                    let mut head = selection.head();
5133                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
5134                    if head.column() == display_map.line_len(head.row()) {
5135                        transpose_offset = display_map
5136                            .buffer_snapshot
5137                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
5138                    }
5139
5140                    if transpose_offset == 0 {
5141                        return;
5142                    }
5143
5144                    *head.column_mut() += 1;
5145                    head = display_map.clip_point(head, Bias::Right);
5146                    let goal = SelectionGoal::HorizontalPosition(
5147                        display_map
5148                            .x_for_display_point(head, &text_layout_details)
5149                            .into(),
5150                    );
5151                    selection.collapse_to(head, goal);
5152
5153                    let transpose_start = display_map
5154                        .buffer_snapshot
5155                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
5156                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
5157                        let transpose_end = display_map
5158                            .buffer_snapshot
5159                            .clip_offset(transpose_offset + 1, Bias::Right);
5160                        if let Some(ch) =
5161                            display_map.buffer_snapshot.chars_at(transpose_start).next()
5162                        {
5163                            edits.push((transpose_start..transpose_offset, String::new()));
5164                            edits.push((transpose_end..transpose_end, ch.to_string()));
5165                        }
5166                    }
5167                });
5168                edits
5169            });
5170            this.buffer
5171                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
5172            let selections = this.selections.all::<usize>(cx);
5173            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5174                s.select(selections);
5175            });
5176        });
5177    }
5178
5179    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
5180        let mut text = String::new();
5181        let buffer = self.buffer.read(cx).snapshot(cx);
5182        let mut selections = self.selections.all::<Point>(cx);
5183        let mut clipboard_selections = Vec::with_capacity(selections.len());
5184        {
5185            let max_point = buffer.max_point();
5186            let mut is_first = true;
5187            for selection in &mut selections {
5188                let is_entire_line = selection.is_empty() || self.selections.line_mode;
5189                if is_entire_line {
5190                    selection.start = Point::new(selection.start.row, 0);
5191                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
5192                    selection.goal = SelectionGoal::None;
5193                }
5194                if is_first {
5195                    is_first = false;
5196                } else {
5197                    text += "\n";
5198                }
5199                let mut len = 0;
5200                for chunk in buffer.text_for_range(selection.start..selection.end) {
5201                    text.push_str(chunk);
5202                    len += chunk.len();
5203                }
5204                clipboard_selections.push(ClipboardSelection {
5205                    len,
5206                    is_entire_line,
5207                    first_line_indent: buffer.indent_size_for_line(selection.start.row).len,
5208                });
5209            }
5210        }
5211
5212        self.transact(cx, |this, cx| {
5213            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5214                s.select(selections);
5215            });
5216            this.insert("", cx);
5217            cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
5218        });
5219    }
5220
5221    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
5222        let selections = self.selections.all::<Point>(cx);
5223        let buffer = self.buffer.read(cx).read(cx);
5224        let mut text = String::new();
5225
5226        let mut clipboard_selections = Vec::with_capacity(selections.len());
5227        {
5228            let max_point = buffer.max_point();
5229            let mut is_first = true;
5230            for selection in selections.iter() {
5231                let mut start = selection.start;
5232                let mut end = selection.end;
5233                let is_entire_line = selection.is_empty() || self.selections.line_mode;
5234                if is_entire_line {
5235                    start = Point::new(start.row, 0);
5236                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
5237                }
5238                if is_first {
5239                    is_first = false;
5240                } else {
5241                    text += "\n";
5242                }
5243                let mut len = 0;
5244                for chunk in buffer.text_for_range(start..end) {
5245                    text.push_str(chunk);
5246                    len += chunk.len();
5247                }
5248                clipboard_selections.push(ClipboardSelection {
5249                    len,
5250                    is_entire_line,
5251                    first_line_indent: buffer.indent_size_for_line(start.row).len,
5252                });
5253            }
5254        }
5255
5256        cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
5257    }
5258
5259    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
5260        if self.read_only(cx) {
5261            return;
5262        }
5263
5264        self.transact(cx, |this, cx| {
5265            if let Some(item) = cx.read_from_clipboard() {
5266                let clipboard_text = Cow::Borrowed(item.text());
5267                if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
5268                    let old_selections = this.selections.all::<usize>(cx);
5269                    let all_selections_were_entire_line =
5270                        clipboard_selections.iter().all(|s| s.is_entire_line);
5271                    let first_selection_indent_column =
5272                        clipboard_selections.first().map(|s| s.first_line_indent);
5273                    if clipboard_selections.len() != old_selections.len() {
5274                        clipboard_selections.drain(..);
5275                    }
5276
5277                    this.buffer.update(cx, |buffer, cx| {
5278                        let snapshot = buffer.read(cx);
5279                        let mut start_offset = 0;
5280                        let mut edits = Vec::new();
5281                        let mut original_indent_columns = Vec::new();
5282                        let line_mode = this.selections.line_mode;
5283                        for (ix, selection) in old_selections.iter().enumerate() {
5284                            let to_insert;
5285                            let entire_line;
5286                            let original_indent_column;
5287                            if let Some(clipboard_selection) = clipboard_selections.get(ix) {
5288                                let end_offset = start_offset + clipboard_selection.len;
5289                                to_insert = &clipboard_text[start_offset..end_offset];
5290                                entire_line = clipboard_selection.is_entire_line;
5291                                start_offset = end_offset + 1;
5292                                original_indent_column =
5293                                    Some(clipboard_selection.first_line_indent);
5294                            } else {
5295                                to_insert = clipboard_text.as_str();
5296                                entire_line = all_selections_were_entire_line;
5297                                original_indent_column = first_selection_indent_column
5298                            }
5299
5300                            // If the corresponding selection was empty when this slice of the
5301                            // clipboard text was written, then the entire line containing the
5302                            // selection was copied. If this selection is also currently empty,
5303                            // then paste the line before the current line of the buffer.
5304                            let range = if selection.is_empty() && !line_mode && entire_line {
5305                                let column = selection.start.to_point(&snapshot).column as usize;
5306                                let line_start = selection.start - column;
5307                                line_start..line_start
5308                            } else {
5309                                selection.range()
5310                            };
5311
5312                            edits.push((range, to_insert));
5313                            original_indent_columns.extend(original_indent_column);
5314                        }
5315                        drop(snapshot);
5316
5317                        buffer.edit(
5318                            edits,
5319                            Some(AutoindentMode::Block {
5320                                original_indent_columns,
5321                            }),
5322                            cx,
5323                        );
5324                    });
5325
5326                    let selections = this.selections.all::<usize>(cx);
5327                    this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5328                } else {
5329                    this.insert(&clipboard_text, cx);
5330                }
5331            }
5332        });
5333    }
5334
5335    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
5336        if self.read_only(cx) {
5337            return;
5338        }
5339
5340        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
5341            if let Some((selections, _)) = self.selection_history.transaction(tx_id).cloned() {
5342                self.change_selections(None, cx, |s| {
5343                    s.select_anchors(selections.to_vec());
5344                });
5345            }
5346            self.request_autoscroll(Autoscroll::fit(), cx);
5347            self.unmark_text(cx);
5348            self.refresh_copilot_suggestions(true, cx);
5349            cx.emit(EditorEvent::Edited);
5350        }
5351    }
5352
5353    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
5354        if self.read_only(cx) {
5355            return;
5356        }
5357
5358        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
5359            if let Some((_, Some(selections))) = self.selection_history.transaction(tx_id).cloned()
5360            {
5361                self.change_selections(None, cx, |s| {
5362                    s.select_anchors(selections.to_vec());
5363                });
5364            }
5365            self.request_autoscroll(Autoscroll::fit(), cx);
5366            self.unmark_text(cx);
5367            self.refresh_copilot_suggestions(true, cx);
5368            cx.emit(EditorEvent::Edited);
5369        }
5370    }
5371
5372    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
5373        self.buffer
5374            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
5375    }
5376
5377    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
5378        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5379            let line_mode = s.line_mode;
5380            s.move_with(|map, selection| {
5381                let cursor = if selection.is_empty() && !line_mode {
5382                    movement::left(map, selection.start)
5383                } else {
5384                    selection.start
5385                };
5386                selection.collapse_to(cursor, SelectionGoal::None);
5387            });
5388        })
5389    }
5390
5391    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
5392        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5393            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
5394        })
5395    }
5396
5397    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
5398        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5399            let line_mode = s.line_mode;
5400            s.move_with(|map, selection| {
5401                let cursor = if selection.is_empty() && !line_mode {
5402                    movement::right(map, selection.end)
5403                } else {
5404                    selection.end
5405                };
5406                selection.collapse_to(cursor, SelectionGoal::None)
5407            });
5408        })
5409    }
5410
5411    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
5412        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5413            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
5414        })
5415    }
5416
5417    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
5418        if self.take_rename(true, cx).is_some() {
5419            return;
5420        }
5421
5422        if matches!(self.mode, EditorMode::SingleLine) {
5423            cx.propagate();
5424            return;
5425        }
5426
5427        let text_layout_details = &self.text_layout_details(cx);
5428
5429        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5430            let line_mode = s.line_mode;
5431            s.move_with(|map, selection| {
5432                if !selection.is_empty() && !line_mode {
5433                    selection.goal = SelectionGoal::None;
5434                }
5435                let (cursor, goal) = movement::up(
5436                    map,
5437                    selection.start,
5438                    selection.goal,
5439                    false,
5440                    &text_layout_details,
5441                );
5442                selection.collapse_to(cursor, goal);
5443            });
5444        })
5445    }
5446
5447    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
5448        if self.take_rename(true, cx).is_some() {
5449            return;
5450        }
5451
5452        if matches!(self.mode, EditorMode::SingleLine) {
5453            cx.propagate();
5454            return;
5455        }
5456
5457        let row_count = if let Some(row_count) = self.visible_line_count() {
5458            row_count as u32 - 1
5459        } else {
5460            return;
5461        };
5462
5463        let autoscroll = if action.center_cursor {
5464            Autoscroll::center()
5465        } else {
5466            Autoscroll::fit()
5467        };
5468
5469        let text_layout_details = &self.text_layout_details(cx);
5470
5471        self.change_selections(Some(autoscroll), cx, |s| {
5472            let line_mode = s.line_mode;
5473            s.move_with(|map, selection| {
5474                if !selection.is_empty() && !line_mode {
5475                    selection.goal = SelectionGoal::None;
5476                }
5477                let (cursor, goal) = movement::up_by_rows(
5478                    map,
5479                    selection.end,
5480                    row_count,
5481                    selection.goal,
5482                    false,
5483                    &text_layout_details,
5484                );
5485                selection.collapse_to(cursor, goal);
5486            });
5487        });
5488    }
5489
5490    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
5491        let text_layout_details = &self.text_layout_details(cx);
5492        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5493            s.move_heads_with(|map, head, goal| {
5494                movement::up(map, head, goal, false, &text_layout_details)
5495            })
5496        })
5497    }
5498
5499    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
5500        self.take_rename(true, cx);
5501
5502        if self.mode == EditorMode::SingleLine {
5503            cx.propagate();
5504            return;
5505        }
5506
5507        let text_layout_details = &self.text_layout_details(cx);
5508        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5509            let line_mode = s.line_mode;
5510            s.move_with(|map, selection| {
5511                if !selection.is_empty() && !line_mode {
5512                    selection.goal = SelectionGoal::None;
5513                }
5514                let (cursor, goal) = movement::down(
5515                    map,
5516                    selection.end,
5517                    selection.goal,
5518                    false,
5519                    &text_layout_details,
5520                );
5521                selection.collapse_to(cursor, goal);
5522            });
5523        });
5524    }
5525
5526    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
5527        if self.take_rename(true, cx).is_some() {
5528            return;
5529        }
5530
5531        if self
5532            .context_menu
5533            .write()
5534            .as_mut()
5535            .map(|menu| menu.select_last(self.project.as_ref(), cx))
5536            .unwrap_or(false)
5537        {
5538            return;
5539        }
5540
5541        if matches!(self.mode, EditorMode::SingleLine) {
5542            cx.propagate();
5543            return;
5544        }
5545
5546        let row_count = if let Some(row_count) = self.visible_line_count() {
5547            row_count as u32 - 1
5548        } else {
5549            return;
5550        };
5551
5552        let autoscroll = if action.center_cursor {
5553            Autoscroll::center()
5554        } else {
5555            Autoscroll::fit()
5556        };
5557
5558        let text_layout_details = &self.text_layout_details(cx);
5559        self.change_selections(Some(autoscroll), cx, |s| {
5560            let line_mode = s.line_mode;
5561            s.move_with(|map, selection| {
5562                if !selection.is_empty() && !line_mode {
5563                    selection.goal = SelectionGoal::None;
5564                }
5565                let (cursor, goal) = movement::down_by_rows(
5566                    map,
5567                    selection.end,
5568                    row_count,
5569                    selection.goal,
5570                    false,
5571                    &text_layout_details,
5572                );
5573                selection.collapse_to(cursor, goal);
5574            });
5575        });
5576    }
5577
5578    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
5579        let text_layout_details = &self.text_layout_details(cx);
5580        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5581            s.move_heads_with(|map, head, goal| {
5582                movement::down(map, head, goal, false, &text_layout_details)
5583            })
5584        });
5585    }
5586
5587    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
5588        if let Some(context_menu) = self.context_menu.write().as_mut() {
5589            context_menu.select_first(self.project.as_ref(), cx);
5590        }
5591    }
5592
5593    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
5594        if let Some(context_menu) = self.context_menu.write().as_mut() {
5595            context_menu.select_prev(self.project.as_ref(), cx);
5596        }
5597    }
5598
5599    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
5600        if let Some(context_menu) = self.context_menu.write().as_mut() {
5601            context_menu.select_next(self.project.as_ref(), cx);
5602        }
5603    }
5604
5605    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
5606        if let Some(context_menu) = self.context_menu.write().as_mut() {
5607            context_menu.select_last(self.project.as_ref(), cx);
5608        }
5609    }
5610
5611    pub fn move_to_previous_word_start(
5612        &mut self,
5613        _: &MoveToPreviousWordStart,
5614        cx: &mut ViewContext<Self>,
5615    ) {
5616        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5617            s.move_cursors_with(|map, head, _| {
5618                (
5619                    movement::previous_word_start(map, head),
5620                    SelectionGoal::None,
5621                )
5622            });
5623        })
5624    }
5625
5626    pub fn move_to_previous_subword_start(
5627        &mut self,
5628        _: &MoveToPreviousSubwordStart,
5629        cx: &mut ViewContext<Self>,
5630    ) {
5631        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5632            s.move_cursors_with(|map, head, _| {
5633                (
5634                    movement::previous_subword_start(map, head),
5635                    SelectionGoal::None,
5636                )
5637            });
5638        })
5639    }
5640
5641    pub fn select_to_previous_word_start(
5642        &mut self,
5643        _: &SelectToPreviousWordStart,
5644        cx: &mut ViewContext<Self>,
5645    ) {
5646        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5647            s.move_heads_with(|map, head, _| {
5648                (
5649                    movement::previous_word_start(map, head),
5650                    SelectionGoal::None,
5651                )
5652            });
5653        })
5654    }
5655
5656    pub fn select_to_previous_subword_start(
5657        &mut self,
5658        _: &SelectToPreviousSubwordStart,
5659        cx: &mut ViewContext<Self>,
5660    ) {
5661        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5662            s.move_heads_with(|map, head, _| {
5663                (
5664                    movement::previous_subword_start(map, head),
5665                    SelectionGoal::None,
5666                )
5667            });
5668        })
5669    }
5670
5671    pub fn delete_to_previous_word_start(
5672        &mut self,
5673        _: &DeleteToPreviousWordStart,
5674        cx: &mut ViewContext<Self>,
5675    ) {
5676        self.transact(cx, |this, cx| {
5677            this.select_autoclose_pair(cx);
5678            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5679                let line_mode = s.line_mode;
5680                s.move_with(|map, selection| {
5681                    if selection.is_empty() && !line_mode {
5682                        let cursor = movement::previous_word_start(map, selection.head());
5683                        selection.set_head(cursor, SelectionGoal::None);
5684                    }
5685                });
5686            });
5687            this.insert("", cx);
5688        });
5689    }
5690
5691    pub fn delete_to_previous_subword_start(
5692        &mut self,
5693        _: &DeleteToPreviousSubwordStart,
5694        cx: &mut ViewContext<Self>,
5695    ) {
5696        self.transact(cx, |this, cx| {
5697            this.select_autoclose_pair(cx);
5698            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5699                let line_mode = s.line_mode;
5700                s.move_with(|map, selection| {
5701                    if selection.is_empty() && !line_mode {
5702                        let cursor = movement::previous_subword_start(map, selection.head());
5703                        selection.set_head(cursor, SelectionGoal::None);
5704                    }
5705                });
5706            });
5707            this.insert("", cx);
5708        });
5709    }
5710
5711    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
5712        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5713            s.move_cursors_with(|map, head, _| {
5714                (movement::next_word_end(map, head), SelectionGoal::None)
5715            });
5716        })
5717    }
5718
5719    pub fn move_to_next_subword_end(
5720        &mut self,
5721        _: &MoveToNextSubwordEnd,
5722        cx: &mut ViewContext<Self>,
5723    ) {
5724        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5725            s.move_cursors_with(|map, head, _| {
5726                (movement::next_subword_end(map, head), SelectionGoal::None)
5727            });
5728        })
5729    }
5730
5731    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
5732        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5733            s.move_heads_with(|map, head, _| {
5734                (movement::next_word_end(map, head), SelectionGoal::None)
5735            });
5736        })
5737    }
5738
5739    pub fn select_to_next_subword_end(
5740        &mut self,
5741        _: &SelectToNextSubwordEnd,
5742        cx: &mut ViewContext<Self>,
5743    ) {
5744        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5745            s.move_heads_with(|map, head, _| {
5746                (movement::next_subword_end(map, head), SelectionGoal::None)
5747            });
5748        })
5749    }
5750
5751    pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
5752        self.transact(cx, |this, cx| {
5753            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5754                let line_mode = s.line_mode;
5755                s.move_with(|map, selection| {
5756                    if selection.is_empty() && !line_mode {
5757                        let cursor = movement::next_word_end(map, selection.head());
5758                        selection.set_head(cursor, SelectionGoal::None);
5759                    }
5760                });
5761            });
5762            this.insert("", cx);
5763        });
5764    }
5765
5766    pub fn delete_to_next_subword_end(
5767        &mut self,
5768        _: &DeleteToNextSubwordEnd,
5769        cx: &mut ViewContext<Self>,
5770    ) {
5771        self.transact(cx, |this, cx| {
5772            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5773                s.move_with(|map, selection| {
5774                    if selection.is_empty() {
5775                        let cursor = movement::next_subword_end(map, selection.head());
5776                        selection.set_head(cursor, SelectionGoal::None);
5777                    }
5778                });
5779            });
5780            this.insert("", cx);
5781        });
5782    }
5783
5784    pub fn move_to_beginning_of_line(
5785        &mut self,
5786        _: &MoveToBeginningOfLine,
5787        cx: &mut ViewContext<Self>,
5788    ) {
5789        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5790            s.move_cursors_with(|map, head, _| {
5791                (
5792                    movement::indented_line_beginning(map, head, true),
5793                    SelectionGoal::None,
5794                )
5795            });
5796        })
5797    }
5798
5799    pub fn select_to_beginning_of_line(
5800        &mut self,
5801        action: &SelectToBeginningOfLine,
5802        cx: &mut ViewContext<Self>,
5803    ) {
5804        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5805            s.move_heads_with(|map, head, _| {
5806                (
5807                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
5808                    SelectionGoal::None,
5809                )
5810            });
5811        });
5812    }
5813
5814    pub fn delete_to_beginning_of_line(
5815        &mut self,
5816        _: &DeleteToBeginningOfLine,
5817        cx: &mut ViewContext<Self>,
5818    ) {
5819        self.transact(cx, |this, cx| {
5820            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5821                s.move_with(|_, selection| {
5822                    selection.reversed = true;
5823                });
5824            });
5825
5826            this.select_to_beginning_of_line(
5827                &SelectToBeginningOfLine {
5828                    stop_at_soft_wraps: false,
5829                },
5830                cx,
5831            );
5832            this.backspace(&Backspace, cx);
5833        });
5834    }
5835
5836    pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
5837        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5838            s.move_cursors_with(|map, head, _| {
5839                (movement::line_end(map, head, true), SelectionGoal::None)
5840            });
5841        })
5842    }
5843
5844    pub fn select_to_end_of_line(
5845        &mut self,
5846        action: &SelectToEndOfLine,
5847        cx: &mut ViewContext<Self>,
5848    ) {
5849        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5850            s.move_heads_with(|map, head, _| {
5851                (
5852                    movement::line_end(map, head, action.stop_at_soft_wraps),
5853                    SelectionGoal::None,
5854                )
5855            });
5856        })
5857    }
5858
5859    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
5860        self.transact(cx, |this, cx| {
5861            this.select_to_end_of_line(
5862                &SelectToEndOfLine {
5863                    stop_at_soft_wraps: false,
5864                },
5865                cx,
5866            );
5867            this.delete(&Delete, cx);
5868        });
5869    }
5870
5871    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
5872        self.transact(cx, |this, cx| {
5873            this.select_to_end_of_line(
5874                &SelectToEndOfLine {
5875                    stop_at_soft_wraps: false,
5876                },
5877                cx,
5878            );
5879            this.cut(&Cut, cx);
5880        });
5881    }
5882
5883    pub fn move_to_start_of_paragraph(
5884        &mut self,
5885        _: &MoveToStartOfParagraph,
5886        cx: &mut ViewContext<Self>,
5887    ) {
5888        if matches!(self.mode, EditorMode::SingleLine) {
5889            cx.propagate();
5890            return;
5891        }
5892
5893        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5894            s.move_with(|map, selection| {
5895                selection.collapse_to(
5896                    movement::start_of_paragraph(map, selection.head(), 1),
5897                    SelectionGoal::None,
5898                )
5899            });
5900        })
5901    }
5902
5903    pub fn move_to_end_of_paragraph(
5904        &mut self,
5905        _: &MoveToEndOfParagraph,
5906        cx: &mut ViewContext<Self>,
5907    ) {
5908        if matches!(self.mode, EditorMode::SingleLine) {
5909            cx.propagate();
5910            return;
5911        }
5912
5913        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5914            s.move_with(|map, selection| {
5915                selection.collapse_to(
5916                    movement::end_of_paragraph(map, selection.head(), 1),
5917                    SelectionGoal::None,
5918                )
5919            });
5920        })
5921    }
5922
5923    pub fn select_to_start_of_paragraph(
5924        &mut self,
5925        _: &SelectToStartOfParagraph,
5926        cx: &mut ViewContext<Self>,
5927    ) {
5928        if matches!(self.mode, EditorMode::SingleLine) {
5929            cx.propagate();
5930            return;
5931        }
5932
5933        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5934            s.move_heads_with(|map, head, _| {
5935                (
5936                    movement::start_of_paragraph(map, head, 1),
5937                    SelectionGoal::None,
5938                )
5939            });
5940        })
5941    }
5942
5943    pub fn select_to_end_of_paragraph(
5944        &mut self,
5945        _: &SelectToEndOfParagraph,
5946        cx: &mut ViewContext<Self>,
5947    ) {
5948        if matches!(self.mode, EditorMode::SingleLine) {
5949            cx.propagate();
5950            return;
5951        }
5952
5953        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5954            s.move_heads_with(|map, head, _| {
5955                (
5956                    movement::end_of_paragraph(map, head, 1),
5957                    SelectionGoal::None,
5958                )
5959            });
5960        })
5961    }
5962
5963    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
5964        if matches!(self.mode, EditorMode::SingleLine) {
5965            cx.propagate();
5966            return;
5967        }
5968
5969        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5970            s.select_ranges(vec![0..0]);
5971        });
5972    }
5973
5974    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
5975        let mut selection = self.selections.last::<Point>(cx);
5976        selection.set_head(Point::zero(), SelectionGoal::None);
5977
5978        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5979            s.select(vec![selection]);
5980        });
5981    }
5982
5983    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
5984        if matches!(self.mode, EditorMode::SingleLine) {
5985            cx.propagate();
5986            return;
5987        }
5988
5989        let cursor = self.buffer.read(cx).read(cx).len();
5990        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5991            s.select_ranges(vec![cursor..cursor])
5992        });
5993    }
5994
5995    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
5996        self.nav_history = nav_history;
5997    }
5998
5999    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
6000        self.nav_history.as_ref()
6001    }
6002
6003    fn push_to_nav_history(
6004        &mut self,
6005        cursor_anchor: Anchor,
6006        new_position: Option<Point>,
6007        cx: &mut ViewContext<Self>,
6008    ) {
6009        if let Some(nav_history) = self.nav_history.as_mut() {
6010            let buffer = self.buffer.read(cx).read(cx);
6011            let cursor_position = cursor_anchor.to_point(&buffer);
6012            let scroll_state = self.scroll_manager.anchor();
6013            let scroll_top_row = scroll_state.top_row(&buffer);
6014            drop(buffer);
6015
6016            if let Some(new_position) = new_position {
6017                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
6018                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
6019                    return;
6020                }
6021            }
6022
6023            nav_history.push(
6024                Some(NavigationData {
6025                    cursor_anchor,
6026                    cursor_position,
6027                    scroll_anchor: scroll_state,
6028                    scroll_top_row,
6029                }),
6030                cx,
6031            );
6032        }
6033    }
6034
6035    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
6036        let buffer = self.buffer.read(cx).snapshot(cx);
6037        let mut selection = self.selections.first::<usize>(cx);
6038        selection.set_head(buffer.len(), SelectionGoal::None);
6039        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6040            s.select(vec![selection]);
6041        });
6042    }
6043
6044    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
6045        let end = self.buffer.read(cx).read(cx).len();
6046        self.change_selections(None, cx, |s| {
6047            s.select_ranges(vec![0..end]);
6048        });
6049    }
6050
6051    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
6052        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6053        let mut selections = self.selections.all::<Point>(cx);
6054        let max_point = display_map.buffer_snapshot.max_point();
6055        for selection in &mut selections {
6056            let rows = selection.spanned_rows(true, &display_map);
6057            selection.start = Point::new(rows.start, 0);
6058            selection.end = cmp::min(max_point, Point::new(rows.end, 0));
6059            selection.reversed = false;
6060        }
6061        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6062            s.select(selections);
6063        });
6064    }
6065
6066    pub fn split_selection_into_lines(
6067        &mut self,
6068        _: &SplitSelectionIntoLines,
6069        cx: &mut ViewContext<Self>,
6070    ) {
6071        let mut to_unfold = Vec::new();
6072        let mut new_selection_ranges = Vec::new();
6073        {
6074            let selections = self.selections.all::<Point>(cx);
6075            let buffer = self.buffer.read(cx).read(cx);
6076            for selection in selections {
6077                for row in selection.start.row..selection.end.row {
6078                    let cursor = Point::new(row, buffer.line_len(row));
6079                    new_selection_ranges.push(cursor..cursor);
6080                }
6081                new_selection_ranges.push(selection.end..selection.end);
6082                to_unfold.push(selection.start..selection.end);
6083            }
6084        }
6085        self.unfold_ranges(to_unfold, true, true, cx);
6086        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6087            s.select_ranges(new_selection_ranges);
6088        });
6089    }
6090
6091    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
6092        self.add_selection(true, cx);
6093    }
6094
6095    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
6096        self.add_selection(false, cx);
6097    }
6098
6099    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
6100        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6101        let mut selections = self.selections.all::<Point>(cx);
6102        let text_layout_details = self.text_layout_details(cx);
6103        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
6104            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
6105            let range = oldest_selection.display_range(&display_map).sorted();
6106
6107            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
6108            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
6109            let positions = start_x.min(end_x)..start_x.max(end_x);
6110
6111            selections.clear();
6112            let mut stack = Vec::new();
6113            for row in range.start.row()..=range.end.row() {
6114                if let Some(selection) = self.selections.build_columnar_selection(
6115                    &display_map,
6116                    row,
6117                    &positions,
6118                    oldest_selection.reversed,
6119                    &text_layout_details,
6120                ) {
6121                    stack.push(selection.id);
6122                    selections.push(selection);
6123                }
6124            }
6125
6126            if above {
6127                stack.reverse();
6128            }
6129
6130            AddSelectionsState { above, stack }
6131        });
6132
6133        let last_added_selection = *state.stack.last().unwrap();
6134        let mut new_selections = Vec::new();
6135        if above == state.above {
6136            let end_row = if above {
6137                0
6138            } else {
6139                display_map.max_point().row()
6140            };
6141
6142            'outer: for selection in selections {
6143                if selection.id == last_added_selection {
6144                    let range = selection.display_range(&display_map).sorted();
6145                    debug_assert_eq!(range.start.row(), range.end.row());
6146                    let mut row = range.start.row();
6147                    let positions =
6148                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
6149                            px(start)..px(end)
6150                        } else {
6151                            let start_x =
6152                                display_map.x_for_display_point(range.start, &text_layout_details);
6153                            let end_x =
6154                                display_map.x_for_display_point(range.end, &text_layout_details);
6155                            start_x.min(end_x)..start_x.max(end_x)
6156                        };
6157
6158                    while row != end_row {
6159                        if above {
6160                            row -= 1;
6161                        } else {
6162                            row += 1;
6163                        }
6164
6165                        if let Some(new_selection) = self.selections.build_columnar_selection(
6166                            &display_map,
6167                            row,
6168                            &positions,
6169                            selection.reversed,
6170                            &text_layout_details,
6171                        ) {
6172                            state.stack.push(new_selection.id);
6173                            if above {
6174                                new_selections.push(new_selection);
6175                                new_selections.push(selection);
6176                            } else {
6177                                new_selections.push(selection);
6178                                new_selections.push(new_selection);
6179                            }
6180
6181                            continue 'outer;
6182                        }
6183                    }
6184                }
6185
6186                new_selections.push(selection);
6187            }
6188        } else {
6189            new_selections = selections;
6190            new_selections.retain(|s| s.id != last_added_selection);
6191            state.stack.pop();
6192        }
6193
6194        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6195            s.select(new_selections);
6196        });
6197        if state.stack.len() > 1 {
6198            self.add_selections_state = Some(state);
6199        }
6200    }
6201
6202    pub fn select_next_match_internal(
6203        &mut self,
6204        display_map: &DisplaySnapshot,
6205        replace_newest: bool,
6206        autoscroll: Option<Autoscroll>,
6207        cx: &mut ViewContext<Self>,
6208    ) -> Result<()> {
6209        fn select_next_match_ranges(
6210            this: &mut Editor,
6211            range: Range<usize>,
6212            replace_newest: bool,
6213            auto_scroll: Option<Autoscroll>,
6214            cx: &mut ViewContext<Editor>,
6215        ) {
6216            this.unfold_ranges([range.clone()], false, true, cx);
6217            this.change_selections(auto_scroll, cx, |s| {
6218                if replace_newest {
6219                    s.delete(s.newest_anchor().id);
6220                }
6221                s.insert_range(range.clone());
6222            });
6223        }
6224
6225        let buffer = &display_map.buffer_snapshot;
6226        let mut selections = self.selections.all::<usize>(cx);
6227        if let Some(mut select_next_state) = self.select_next_state.take() {
6228            let query = &select_next_state.query;
6229            if !select_next_state.done {
6230                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
6231                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
6232                let mut next_selected_range = None;
6233
6234                let bytes_after_last_selection =
6235                    buffer.bytes_in_range(last_selection.end..buffer.len());
6236                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
6237                let query_matches = query
6238                    .stream_find_iter(bytes_after_last_selection)
6239                    .map(|result| (last_selection.end, result))
6240                    .chain(
6241                        query
6242                            .stream_find_iter(bytes_before_first_selection)
6243                            .map(|result| (0, result)),
6244                    );
6245
6246                for (start_offset, query_match) in query_matches {
6247                    let query_match = query_match.unwrap(); // can only fail due to I/O
6248                    let offset_range =
6249                        start_offset + query_match.start()..start_offset + query_match.end();
6250                    let display_range = offset_range.start.to_display_point(&display_map)
6251                        ..offset_range.end.to_display_point(&display_map);
6252
6253                    if !select_next_state.wordwise
6254                        || (!movement::is_inside_word(&display_map, display_range.start)
6255                            && !movement::is_inside_word(&display_map, display_range.end))
6256                    {
6257                        if selections
6258                            .iter()
6259                            .find(|selection| selection.range().overlaps(&offset_range))
6260                            .is_none()
6261                        {
6262                            next_selected_range = Some(offset_range);
6263                            break;
6264                        }
6265                    }
6266                }
6267
6268                if let Some(next_selected_range) = next_selected_range {
6269                    select_next_match_ranges(
6270                        self,
6271                        next_selected_range,
6272                        replace_newest,
6273                        autoscroll,
6274                        cx,
6275                    );
6276                } else {
6277                    select_next_state.done = true;
6278                }
6279            }
6280
6281            self.select_next_state = Some(select_next_state);
6282        } else {
6283            let mut only_carets = true;
6284            let mut same_text_selected = true;
6285            let mut selected_text = None;
6286
6287            let mut selections_iter = selections.iter().peekable();
6288            while let Some(selection) = selections_iter.next() {
6289                if selection.start != selection.end {
6290                    only_carets = false;
6291                }
6292
6293                if same_text_selected {
6294                    if selected_text.is_none() {
6295                        selected_text =
6296                            Some(buffer.text_for_range(selection.range()).collect::<String>());
6297                    }
6298
6299                    if let Some(next_selection) = selections_iter.peek() {
6300                        if next_selection.range().len() == selection.range().len() {
6301                            let next_selected_text = buffer
6302                                .text_for_range(next_selection.range())
6303                                .collect::<String>();
6304                            if Some(next_selected_text) != selected_text {
6305                                same_text_selected = false;
6306                                selected_text = None;
6307                            }
6308                        } else {
6309                            same_text_selected = false;
6310                            selected_text = None;
6311                        }
6312                    }
6313                }
6314            }
6315
6316            if only_carets {
6317                for selection in &mut selections {
6318                    let word_range = movement::surrounding_word(
6319                        &display_map,
6320                        selection.start.to_display_point(&display_map),
6321                    );
6322                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
6323                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
6324                    selection.goal = SelectionGoal::None;
6325                    selection.reversed = false;
6326                    select_next_match_ranges(
6327                        self,
6328                        selection.start..selection.end,
6329                        replace_newest,
6330                        autoscroll,
6331                        cx,
6332                    );
6333                }
6334
6335                if selections.len() == 1 {
6336                    let selection = selections
6337                        .last()
6338                        .expect("ensured that there's only one selection");
6339                    let query = buffer
6340                        .text_for_range(selection.start..selection.end)
6341                        .collect::<String>();
6342                    let is_empty = query.is_empty();
6343                    let select_state = SelectNextState {
6344                        query: AhoCorasick::new(&[query])?,
6345                        wordwise: true,
6346                        done: is_empty,
6347                    };
6348                    self.select_next_state = Some(select_state);
6349                } else {
6350                    self.select_next_state = None;
6351                }
6352            } else if let Some(selected_text) = selected_text {
6353                self.select_next_state = Some(SelectNextState {
6354                    query: AhoCorasick::new(&[selected_text])?,
6355                    wordwise: false,
6356                    done: false,
6357                });
6358                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
6359            }
6360        }
6361        Ok(())
6362    }
6363
6364    pub fn select_all_matches(
6365        &mut self,
6366        action: &SelectAllMatches,
6367        cx: &mut ViewContext<Self>,
6368    ) -> Result<()> {
6369        self.push_to_selection_history();
6370        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6371
6372        loop {
6373            self.select_next_match_internal(&display_map, action.replace_newest, None, cx)?;
6374
6375            if self
6376                .select_next_state
6377                .as_ref()
6378                .map(|selection_state| selection_state.done)
6379                .unwrap_or(true)
6380            {
6381                break;
6382            }
6383        }
6384
6385        Ok(())
6386    }
6387
6388    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
6389        self.push_to_selection_history();
6390        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6391        self.select_next_match_internal(
6392            &display_map,
6393            action.replace_newest,
6394            Some(Autoscroll::newest()),
6395            cx,
6396        )?;
6397        Ok(())
6398    }
6399
6400    pub fn select_previous(
6401        &mut self,
6402        action: &SelectPrevious,
6403        cx: &mut ViewContext<Self>,
6404    ) -> Result<()> {
6405        self.push_to_selection_history();
6406        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6407        let buffer = &display_map.buffer_snapshot;
6408        let mut selections = self.selections.all::<usize>(cx);
6409        if let Some(mut select_prev_state) = self.select_prev_state.take() {
6410            let query = &select_prev_state.query;
6411            if !select_prev_state.done {
6412                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
6413                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
6414                let mut next_selected_range = None;
6415                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
6416                let bytes_before_last_selection =
6417                    buffer.reversed_bytes_in_range(0..last_selection.start);
6418                let bytes_after_first_selection =
6419                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
6420                let query_matches = query
6421                    .stream_find_iter(bytes_before_last_selection)
6422                    .map(|result| (last_selection.start, result))
6423                    .chain(
6424                        query
6425                            .stream_find_iter(bytes_after_first_selection)
6426                            .map(|result| (buffer.len(), result)),
6427                    );
6428                for (end_offset, query_match) in query_matches {
6429                    let query_match = query_match.unwrap(); // can only fail due to I/O
6430                    let offset_range =
6431                        end_offset - query_match.end()..end_offset - query_match.start();
6432                    let display_range = offset_range.start.to_display_point(&display_map)
6433                        ..offset_range.end.to_display_point(&display_map);
6434
6435                    if !select_prev_state.wordwise
6436                        || (!movement::is_inside_word(&display_map, display_range.start)
6437                            && !movement::is_inside_word(&display_map, display_range.end))
6438                    {
6439                        next_selected_range = Some(offset_range);
6440                        break;
6441                    }
6442                }
6443
6444                if let Some(next_selected_range) = next_selected_range {
6445                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
6446                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
6447                        if action.replace_newest {
6448                            s.delete(s.newest_anchor().id);
6449                        }
6450                        s.insert_range(next_selected_range);
6451                    });
6452                } else {
6453                    select_prev_state.done = true;
6454                }
6455            }
6456
6457            self.select_prev_state = Some(select_prev_state);
6458        } else {
6459            let mut only_carets = true;
6460            let mut same_text_selected = true;
6461            let mut selected_text = None;
6462
6463            let mut selections_iter = selections.iter().peekable();
6464            while let Some(selection) = selections_iter.next() {
6465                if selection.start != selection.end {
6466                    only_carets = false;
6467                }
6468
6469                if same_text_selected {
6470                    if selected_text.is_none() {
6471                        selected_text =
6472                            Some(buffer.text_for_range(selection.range()).collect::<String>());
6473                    }
6474
6475                    if let Some(next_selection) = selections_iter.peek() {
6476                        if next_selection.range().len() == selection.range().len() {
6477                            let next_selected_text = buffer
6478                                .text_for_range(next_selection.range())
6479                                .collect::<String>();
6480                            if Some(next_selected_text) != selected_text {
6481                                same_text_selected = false;
6482                                selected_text = None;
6483                            }
6484                        } else {
6485                            same_text_selected = false;
6486                            selected_text = None;
6487                        }
6488                    }
6489                }
6490            }
6491
6492            if only_carets {
6493                for selection in &mut selections {
6494                    let word_range = movement::surrounding_word(
6495                        &display_map,
6496                        selection.start.to_display_point(&display_map),
6497                    );
6498                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
6499                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
6500                    selection.goal = SelectionGoal::None;
6501                    selection.reversed = false;
6502                }
6503                if selections.len() == 1 {
6504                    let selection = selections
6505                        .last()
6506                        .expect("ensured that there's only one selection");
6507                    let query = buffer
6508                        .text_for_range(selection.start..selection.end)
6509                        .collect::<String>();
6510                    let is_empty = query.is_empty();
6511                    let select_state = SelectNextState {
6512                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
6513                        wordwise: true,
6514                        done: is_empty,
6515                    };
6516                    self.select_prev_state = Some(select_state);
6517                } else {
6518                    self.select_prev_state = None;
6519                }
6520
6521                self.unfold_ranges(
6522                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
6523                    false,
6524                    true,
6525                    cx,
6526                );
6527                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
6528                    s.select(selections);
6529                });
6530            } else if let Some(selected_text) = selected_text {
6531                self.select_prev_state = Some(SelectNextState {
6532                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
6533                    wordwise: false,
6534                    done: false,
6535                });
6536                self.select_previous(action, cx)?;
6537            }
6538        }
6539        Ok(())
6540    }
6541
6542    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
6543        let text_layout_details = &self.text_layout_details(cx);
6544        self.transact(cx, |this, cx| {
6545            let mut selections = this.selections.all::<Point>(cx);
6546            let mut edits = Vec::new();
6547            let mut selection_edit_ranges = Vec::new();
6548            let mut last_toggled_row = None;
6549            let snapshot = this.buffer.read(cx).read(cx);
6550            let empty_str: Arc<str> = "".into();
6551            let mut suffixes_inserted = Vec::new();
6552
6553            fn comment_prefix_range(
6554                snapshot: &MultiBufferSnapshot,
6555                row: u32,
6556                comment_prefix: &str,
6557                comment_prefix_whitespace: &str,
6558            ) -> Range<Point> {
6559                let start = Point::new(row, snapshot.indent_size_for_line(row).len);
6560
6561                let mut line_bytes = snapshot
6562                    .bytes_in_range(start..snapshot.max_point())
6563                    .flatten()
6564                    .copied();
6565
6566                // If this line currently begins with the line comment prefix, then record
6567                // the range containing the prefix.
6568                if line_bytes
6569                    .by_ref()
6570                    .take(comment_prefix.len())
6571                    .eq(comment_prefix.bytes())
6572                {
6573                    // Include any whitespace that matches the comment prefix.
6574                    let matching_whitespace_len = line_bytes
6575                        .zip(comment_prefix_whitespace.bytes())
6576                        .take_while(|(a, b)| a == b)
6577                        .count() as u32;
6578                    let end = Point::new(
6579                        start.row,
6580                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
6581                    );
6582                    start..end
6583                } else {
6584                    start..start
6585                }
6586            }
6587
6588            fn comment_suffix_range(
6589                snapshot: &MultiBufferSnapshot,
6590                row: u32,
6591                comment_suffix: &str,
6592                comment_suffix_has_leading_space: bool,
6593            ) -> Range<Point> {
6594                let end = Point::new(row, snapshot.line_len(row));
6595                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
6596
6597                let mut line_end_bytes = snapshot
6598                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
6599                    .flatten()
6600                    .copied();
6601
6602                let leading_space_len = if suffix_start_column > 0
6603                    && line_end_bytes.next() == Some(b' ')
6604                    && comment_suffix_has_leading_space
6605                {
6606                    1
6607                } else {
6608                    0
6609                };
6610
6611                // If this line currently begins with the line comment prefix, then record
6612                // the range containing the prefix.
6613                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
6614                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
6615                    start..end
6616                } else {
6617                    end..end
6618                }
6619            }
6620
6621            // TODO: Handle selections that cross excerpts
6622            for selection in &mut selections {
6623                let start_column = snapshot.indent_size_for_line(selection.start.row).len;
6624                let language = if let Some(language) =
6625                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
6626                {
6627                    language
6628                } else {
6629                    continue;
6630                };
6631
6632                selection_edit_ranges.clear();
6633
6634                // If multiple selections contain a given row, avoid processing that
6635                // row more than once.
6636                let mut start_row = selection.start.row;
6637                if last_toggled_row == Some(start_row) {
6638                    start_row += 1;
6639                }
6640                let end_row =
6641                    if selection.end.row > selection.start.row && selection.end.column == 0 {
6642                        selection.end.row - 1
6643                    } else {
6644                        selection.end.row
6645                    };
6646                last_toggled_row = Some(end_row);
6647
6648                if start_row > end_row {
6649                    continue;
6650                }
6651
6652                // If the language has line comments, toggle those.
6653                if let Some(full_comment_prefix) = language.line_comment_prefix() {
6654                    // Split the comment prefix's trailing whitespace into a separate string,
6655                    // as that portion won't be used for detecting if a line is a comment.
6656                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
6657                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
6658                    let mut all_selection_lines_are_comments = true;
6659
6660                    for row in start_row..=end_row {
6661                        if snapshot.is_line_blank(row) && start_row < end_row {
6662                            continue;
6663                        }
6664
6665                        let prefix_range = comment_prefix_range(
6666                            snapshot.deref(),
6667                            row,
6668                            comment_prefix,
6669                            comment_prefix_whitespace,
6670                        );
6671                        if prefix_range.is_empty() {
6672                            all_selection_lines_are_comments = false;
6673                        }
6674                        selection_edit_ranges.push(prefix_range);
6675                    }
6676
6677                    if all_selection_lines_are_comments {
6678                        edits.extend(
6679                            selection_edit_ranges
6680                                .iter()
6681                                .cloned()
6682                                .map(|range| (range, empty_str.clone())),
6683                        );
6684                    } else {
6685                        let min_column = selection_edit_ranges
6686                            .iter()
6687                            .map(|r| r.start.column)
6688                            .min()
6689                            .unwrap_or(0);
6690                        edits.extend(selection_edit_ranges.iter().map(|range| {
6691                            let position = Point::new(range.start.row, min_column);
6692                            (position..position, full_comment_prefix.clone())
6693                        }));
6694                    }
6695                } else if let Some((full_comment_prefix, comment_suffix)) =
6696                    language.block_comment_delimiters()
6697                {
6698                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
6699                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
6700                    let prefix_range = comment_prefix_range(
6701                        snapshot.deref(),
6702                        start_row,
6703                        comment_prefix,
6704                        comment_prefix_whitespace,
6705                    );
6706                    let suffix_range = comment_suffix_range(
6707                        snapshot.deref(),
6708                        end_row,
6709                        comment_suffix.trim_start_matches(' '),
6710                        comment_suffix.starts_with(' '),
6711                    );
6712
6713                    if prefix_range.is_empty() || suffix_range.is_empty() {
6714                        edits.push((
6715                            prefix_range.start..prefix_range.start,
6716                            full_comment_prefix.clone(),
6717                        ));
6718                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
6719                        suffixes_inserted.push((end_row, comment_suffix.len()));
6720                    } else {
6721                        edits.push((prefix_range, empty_str.clone()));
6722                        edits.push((suffix_range, empty_str.clone()));
6723                    }
6724                } else {
6725                    continue;
6726                }
6727            }
6728
6729            drop(snapshot);
6730            this.buffer.update(cx, |buffer, cx| {
6731                buffer.edit(edits, None, cx);
6732            });
6733
6734            // Adjust selections so that they end before any comment suffixes that
6735            // were inserted.
6736            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
6737            let mut selections = this.selections.all::<Point>(cx);
6738            let snapshot = this.buffer.read(cx).read(cx);
6739            for selection in &mut selections {
6740                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
6741                    match row.cmp(&selection.end.row) {
6742                        Ordering::Less => {
6743                            suffixes_inserted.next();
6744                            continue;
6745                        }
6746                        Ordering::Greater => break,
6747                        Ordering::Equal => {
6748                            if selection.end.column == snapshot.line_len(row) {
6749                                if selection.is_empty() {
6750                                    selection.start.column -= suffix_len as u32;
6751                                }
6752                                selection.end.column -= suffix_len as u32;
6753                            }
6754                            break;
6755                        }
6756                    }
6757                }
6758            }
6759
6760            drop(snapshot);
6761            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6762
6763            let selections = this.selections.all::<Point>(cx);
6764            let selections_on_single_row = selections.windows(2).all(|selections| {
6765                selections[0].start.row == selections[1].start.row
6766                    && selections[0].end.row == selections[1].end.row
6767                    && selections[0].start.row == selections[0].end.row
6768            });
6769            let selections_selecting = selections
6770                .iter()
6771                .any(|selection| selection.start != selection.end);
6772            let advance_downwards = action.advance_downwards
6773                && selections_on_single_row
6774                && !selections_selecting
6775                && this.mode != EditorMode::SingleLine;
6776
6777            if advance_downwards {
6778                let snapshot = this.buffer.read(cx).snapshot(cx);
6779
6780                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6781                    s.move_cursors_with(|display_snapshot, display_point, _| {
6782                        let mut point = display_point.to_point(display_snapshot);
6783                        point.row += 1;
6784                        point = snapshot.clip_point(point, Bias::Left);
6785                        let display_point = point.to_display_point(display_snapshot);
6786                        let goal = SelectionGoal::HorizontalPosition(
6787                            display_snapshot
6788                                .x_for_display_point(display_point, &text_layout_details)
6789                                .into(),
6790                        );
6791                        (display_point, goal)
6792                    })
6793                });
6794            }
6795        });
6796    }
6797
6798    pub fn select_larger_syntax_node(
6799        &mut self,
6800        _: &SelectLargerSyntaxNode,
6801        cx: &mut ViewContext<Self>,
6802    ) {
6803        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6804        let buffer = self.buffer.read(cx).snapshot(cx);
6805        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
6806
6807        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
6808        let mut selected_larger_node = false;
6809        let new_selections = old_selections
6810            .iter()
6811            .map(|selection| {
6812                let old_range = selection.start..selection.end;
6813                let mut new_range = old_range.clone();
6814                while let Some(containing_range) =
6815                    buffer.range_for_syntax_ancestor(new_range.clone())
6816                {
6817                    new_range = containing_range;
6818                    if !display_map.intersects_fold(new_range.start)
6819                        && !display_map.intersects_fold(new_range.end)
6820                    {
6821                        break;
6822                    }
6823                }
6824
6825                selected_larger_node |= new_range != old_range;
6826                Selection {
6827                    id: selection.id,
6828                    start: new_range.start,
6829                    end: new_range.end,
6830                    goal: SelectionGoal::None,
6831                    reversed: selection.reversed,
6832                }
6833            })
6834            .collect::<Vec<_>>();
6835
6836        if selected_larger_node {
6837            stack.push(old_selections);
6838            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6839                s.select(new_selections);
6840            });
6841        }
6842        self.select_larger_syntax_node_stack = stack;
6843    }
6844
6845    pub fn select_smaller_syntax_node(
6846        &mut self,
6847        _: &SelectSmallerSyntaxNode,
6848        cx: &mut ViewContext<Self>,
6849    ) {
6850        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
6851        if let Some(selections) = stack.pop() {
6852            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6853                s.select(selections.to_vec());
6854            });
6855        }
6856        self.select_larger_syntax_node_stack = stack;
6857    }
6858
6859    pub fn move_to_enclosing_bracket(
6860        &mut self,
6861        _: &MoveToEnclosingBracket,
6862        cx: &mut ViewContext<Self>,
6863    ) {
6864        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6865            s.move_offsets_with(|snapshot, selection| {
6866                let Some(enclosing_bracket_ranges) =
6867                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
6868                else {
6869                    return;
6870                };
6871
6872                let mut best_length = usize::MAX;
6873                let mut best_inside = false;
6874                let mut best_in_bracket_range = false;
6875                let mut best_destination = None;
6876                for (open, close) in enclosing_bracket_ranges {
6877                    let close = close.to_inclusive();
6878                    let length = close.end() - open.start;
6879                    let inside = selection.start >= open.end && selection.end <= *close.start();
6880                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
6881                        || close.contains(&selection.head());
6882
6883                    // If best is next to a bracket and current isn't, skip
6884                    if !in_bracket_range && best_in_bracket_range {
6885                        continue;
6886                    }
6887
6888                    // Prefer smaller lengths unless best is inside and current isn't
6889                    if length > best_length && (best_inside || !inside) {
6890                        continue;
6891                    }
6892
6893                    best_length = length;
6894                    best_inside = inside;
6895                    best_in_bracket_range = in_bracket_range;
6896                    best_destination = Some(
6897                        if close.contains(&selection.start) && close.contains(&selection.end) {
6898                            if inside {
6899                                open.end
6900                            } else {
6901                                open.start
6902                            }
6903                        } else {
6904                            if inside {
6905                                *close.start()
6906                            } else {
6907                                *close.end()
6908                            }
6909                        },
6910                    );
6911                }
6912
6913                if let Some(destination) = best_destination {
6914                    selection.collapse_to(destination, SelectionGoal::None);
6915                }
6916            })
6917        });
6918    }
6919
6920    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
6921        self.end_selection(cx);
6922        self.selection_history.mode = SelectionHistoryMode::Undoing;
6923        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
6924            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
6925            self.select_next_state = entry.select_next_state;
6926            self.select_prev_state = entry.select_prev_state;
6927            self.add_selections_state = entry.add_selections_state;
6928            self.request_autoscroll(Autoscroll::newest(), cx);
6929        }
6930        self.selection_history.mode = SelectionHistoryMode::Normal;
6931    }
6932
6933    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
6934        self.end_selection(cx);
6935        self.selection_history.mode = SelectionHistoryMode::Redoing;
6936        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
6937            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
6938            self.select_next_state = entry.select_next_state;
6939            self.select_prev_state = entry.select_prev_state;
6940            self.add_selections_state = entry.add_selections_state;
6941            self.request_autoscroll(Autoscroll::newest(), cx);
6942        }
6943        self.selection_history.mode = SelectionHistoryMode::Normal;
6944    }
6945
6946    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
6947        self.go_to_diagnostic_impl(Direction::Next, cx)
6948    }
6949
6950    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
6951        self.go_to_diagnostic_impl(Direction::Prev, cx)
6952    }
6953
6954    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
6955        let buffer = self.buffer.read(cx).snapshot(cx);
6956        let selection = self.selections.newest::<usize>(cx);
6957
6958        // If there is an active Diagnostic Popover jump to its diagnostic instead.
6959        if direction == Direction::Next {
6960            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
6961                let (group_id, jump_to) = popover.activation_info();
6962                if self.activate_diagnostics(group_id, cx) {
6963                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6964                        let mut new_selection = s.newest_anchor().clone();
6965                        new_selection.collapse_to(jump_to, SelectionGoal::None);
6966                        s.select_anchors(vec![new_selection.clone()]);
6967                    });
6968                }
6969                return;
6970            }
6971        }
6972
6973        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
6974            active_diagnostics
6975                .primary_range
6976                .to_offset(&buffer)
6977                .to_inclusive()
6978        });
6979        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
6980            if active_primary_range.contains(&selection.head()) {
6981                *active_primary_range.end()
6982            } else {
6983                selection.head()
6984            }
6985        } else {
6986            selection.head()
6987        };
6988
6989        loop {
6990            let mut diagnostics = if direction == Direction::Prev {
6991                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
6992            } else {
6993                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
6994            };
6995            let group = diagnostics.find_map(|entry| {
6996                if entry.diagnostic.is_primary
6997                    && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
6998                    && !entry.range.is_empty()
6999                    && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
7000                    && !entry.range.contains(&search_start)
7001                {
7002                    Some((entry.range, entry.diagnostic.group_id))
7003                } else {
7004                    None
7005                }
7006            });
7007
7008            if let Some((primary_range, group_id)) = group {
7009                if self.activate_diagnostics(group_id, cx) {
7010                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7011                        s.select(vec![Selection {
7012                            id: selection.id,
7013                            start: primary_range.start,
7014                            end: primary_range.start,
7015                            reversed: false,
7016                            goal: SelectionGoal::None,
7017                        }]);
7018                    });
7019                }
7020                break;
7021            } else {
7022                // Cycle around to the start of the buffer, potentially moving back to the start of
7023                // the currently active diagnostic.
7024                active_primary_range.take();
7025                if direction == Direction::Prev {
7026                    if search_start == buffer.len() {
7027                        break;
7028                    } else {
7029                        search_start = buffer.len();
7030                    }
7031                } else if search_start == 0 {
7032                    break;
7033                } else {
7034                    search_start = 0;
7035                }
7036            }
7037        }
7038    }
7039
7040    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
7041        let snapshot = self
7042            .display_map
7043            .update(cx, |display_map, cx| display_map.snapshot(cx));
7044        let selection = self.selections.newest::<Point>(cx);
7045
7046        if !self.seek_in_direction(
7047            &snapshot,
7048            selection.head(),
7049            false,
7050            snapshot
7051                .buffer_snapshot
7052                .git_diff_hunks_in_range((selection.head().row + 1)..u32::MAX),
7053            cx,
7054        ) {
7055            let wrapped_point = Point::zero();
7056            self.seek_in_direction(
7057                &snapshot,
7058                wrapped_point,
7059                true,
7060                snapshot
7061                    .buffer_snapshot
7062                    .git_diff_hunks_in_range((wrapped_point.row + 1)..u32::MAX),
7063                cx,
7064            );
7065        }
7066    }
7067
7068    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
7069        let snapshot = self
7070            .display_map
7071            .update(cx, |display_map, cx| display_map.snapshot(cx));
7072        let selection = self.selections.newest::<Point>(cx);
7073
7074        if !self.seek_in_direction(
7075            &snapshot,
7076            selection.head(),
7077            false,
7078            snapshot
7079                .buffer_snapshot
7080                .git_diff_hunks_in_range_rev(0..selection.head().row),
7081            cx,
7082        ) {
7083            let wrapped_point = snapshot.buffer_snapshot.max_point();
7084            self.seek_in_direction(
7085                &snapshot,
7086                wrapped_point,
7087                true,
7088                snapshot
7089                    .buffer_snapshot
7090                    .git_diff_hunks_in_range_rev(0..wrapped_point.row),
7091                cx,
7092            );
7093        }
7094    }
7095
7096    fn seek_in_direction(
7097        &mut self,
7098        snapshot: &DisplaySnapshot,
7099        initial_point: Point,
7100        is_wrapped: bool,
7101        hunks: impl Iterator<Item = DiffHunk<u32>>,
7102        cx: &mut ViewContext<Editor>,
7103    ) -> bool {
7104        let display_point = initial_point.to_display_point(snapshot);
7105        let mut hunks = hunks
7106            .map(|hunk| diff_hunk_to_display(hunk, &snapshot))
7107            .filter(|hunk| {
7108                if is_wrapped {
7109                    true
7110                } else {
7111                    !hunk.contains_display_row(display_point.row())
7112                }
7113            })
7114            .dedup();
7115
7116        if let Some(hunk) = hunks.next() {
7117            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7118                let row = hunk.start_display_row();
7119                let point = DisplayPoint::new(row, 0);
7120                s.select_display_ranges([point..point]);
7121            });
7122
7123            true
7124        } else {
7125            false
7126        }
7127    }
7128
7129    pub fn go_to_definition(&mut self, _: &GoToDefinition, cx: &mut ViewContext<Self>) {
7130        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
7131    }
7132
7133    pub fn go_to_type_definition(&mut self, _: &GoToTypeDefinition, cx: &mut ViewContext<Self>) {
7134        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx);
7135    }
7136
7137    pub fn go_to_definition_split(&mut self, _: &GoToDefinitionSplit, cx: &mut ViewContext<Self>) {
7138        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx);
7139    }
7140
7141    pub fn go_to_type_definition_split(
7142        &mut self,
7143        _: &GoToTypeDefinitionSplit,
7144        cx: &mut ViewContext<Self>,
7145    ) {
7146        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx);
7147    }
7148
7149    fn go_to_definition_of_kind(
7150        &mut self,
7151        kind: GotoDefinitionKind,
7152        split: bool,
7153        cx: &mut ViewContext<Self>,
7154    ) {
7155        let Some(workspace) = self.workspace() else {
7156            return;
7157        };
7158        let buffer = self.buffer.read(cx);
7159        let head = self.selections.newest::<usize>(cx).head();
7160        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
7161            text_anchor
7162        } else {
7163            return;
7164        };
7165
7166        let project = workspace.read(cx).project().clone();
7167        let definitions = project.update(cx, |project, cx| match kind {
7168            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
7169            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
7170        });
7171
7172        cx.spawn(|editor, mut cx| async move {
7173            let definitions = definitions.await?;
7174            editor.update(&mut cx, |editor, cx| {
7175                editor.navigate_to_definitions(
7176                    definitions
7177                        .into_iter()
7178                        .map(GoToDefinitionLink::Text)
7179                        .collect(),
7180                    split,
7181                    cx,
7182                );
7183            })?;
7184            Ok::<(), anyhow::Error>(())
7185        })
7186        .detach_and_log_err(cx);
7187    }
7188
7189    pub fn navigate_to_definitions(
7190        &mut self,
7191        mut definitions: Vec<GoToDefinitionLink>,
7192        split: bool,
7193        cx: &mut ViewContext<Editor>,
7194    ) {
7195        let Some(workspace) = self.workspace() else {
7196            return;
7197        };
7198        let pane = workspace.read(cx).active_pane().clone();
7199        // If there is one definition, just open it directly
7200        if definitions.len() == 1 {
7201            let definition = definitions.pop().unwrap();
7202            let target_task = match definition {
7203                GoToDefinitionLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
7204                GoToDefinitionLink::InlayHint(lsp_location, server_id) => {
7205                    self.compute_target_location(lsp_location, server_id, cx)
7206                }
7207            };
7208            cx.spawn(|editor, mut cx| async move {
7209                let target = target_task.await.context("target resolution task")?;
7210                if let Some(target) = target {
7211                    editor.update(&mut cx, |editor, cx| {
7212                        let range = target.range.to_offset(target.buffer.read(cx));
7213                        let range = editor.range_for_match(&range);
7214                        if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
7215                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
7216                                s.select_ranges([range]);
7217                            });
7218                        } else {
7219                            cx.window_context().defer(move |cx| {
7220                                let target_editor: View<Self> =
7221                                    workspace.update(cx, |workspace, cx| {
7222                                        if split {
7223                                            workspace.split_project_item(target.buffer.clone(), cx)
7224                                        } else {
7225                                            workspace.open_project_item(target.buffer.clone(), cx)
7226                                        }
7227                                    });
7228                                target_editor.update(cx, |target_editor, cx| {
7229                                    // When selecting a definition in a different buffer, disable the nav history
7230                                    // to avoid creating a history entry at the previous cursor location.
7231                                    pane.update(cx, |pane, _| pane.disable_history());
7232                                    target_editor.change_selections(
7233                                        Some(Autoscroll::fit()),
7234                                        cx,
7235                                        |s| {
7236                                            s.select_ranges([range]);
7237                                        },
7238                                    );
7239                                    pane.update(cx, |pane, _| pane.enable_history());
7240                                });
7241                            });
7242                        }
7243                    })
7244                } else {
7245                    Ok(())
7246                }
7247            })
7248            .detach_and_log_err(cx);
7249        } else if !definitions.is_empty() {
7250            let replica_id = self.replica_id(cx);
7251            cx.spawn(|editor, mut cx| async move {
7252                let (title, location_tasks) = editor
7253                    .update(&mut cx, |editor, cx| {
7254                        let title = definitions
7255                            .iter()
7256                            .find_map(|definition| match definition {
7257                                GoToDefinitionLink::Text(link) => {
7258                                    link.origin.as_ref().map(|origin| {
7259                                        let buffer = origin.buffer.read(cx);
7260                                        format!(
7261                                            "Definitions for {}",
7262                                            buffer
7263                                                .text_for_range(origin.range.clone())
7264                                                .collect::<String>()
7265                                        )
7266                                    })
7267                                }
7268                                GoToDefinitionLink::InlayHint(_, _) => None,
7269                            })
7270                            .unwrap_or("Definitions".to_string());
7271                        let location_tasks = definitions
7272                            .into_iter()
7273                            .map(|definition| match definition {
7274                                GoToDefinitionLink::Text(link) => {
7275                                    Task::Ready(Some(Ok(Some(link.target))))
7276                                }
7277                                GoToDefinitionLink::InlayHint(lsp_location, server_id) => {
7278                                    editor.compute_target_location(lsp_location, server_id, cx)
7279                                }
7280                            })
7281                            .collect::<Vec<_>>();
7282                        (title, location_tasks)
7283                    })
7284                    .context("location tasks preparation")?;
7285
7286                let locations = futures::future::join_all(location_tasks)
7287                    .await
7288                    .into_iter()
7289                    .filter_map(|location| location.transpose())
7290                    .collect::<Result<_>>()
7291                    .context("location tasks")?;
7292                workspace
7293                    .update(&mut cx, |workspace, cx| {
7294                        Self::open_locations_in_multibuffer(
7295                            workspace, locations, replica_id, title, split, cx,
7296                        )
7297                    })
7298                    .ok();
7299
7300                anyhow::Ok(())
7301            })
7302            .detach_and_log_err(cx);
7303        }
7304    }
7305
7306    fn compute_target_location(
7307        &self,
7308        lsp_location: lsp::Location,
7309        server_id: LanguageServerId,
7310        cx: &mut ViewContext<Editor>,
7311    ) -> Task<anyhow::Result<Option<Location>>> {
7312        let Some(project) = self.project.clone() else {
7313            return Task::Ready(Some(Ok(None)));
7314        };
7315
7316        cx.spawn(move |editor, mut cx| async move {
7317            let location_task = editor.update(&mut cx, |editor, cx| {
7318                project.update(cx, |project, cx| {
7319                    let language_server_name =
7320                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
7321                            project
7322                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
7323                                .map(|(_, lsp_adapter)| {
7324                                    LanguageServerName(Arc::from(lsp_adapter.name()))
7325                                })
7326                        });
7327                    language_server_name.map(|language_server_name| {
7328                        project.open_local_buffer_via_lsp(
7329                            lsp_location.uri.clone(),
7330                            server_id,
7331                            language_server_name,
7332                            cx,
7333                        )
7334                    })
7335                })
7336            })?;
7337            let location = match location_task {
7338                Some(task) => Some({
7339                    let target_buffer_handle = task.await.context("open local buffer")?;
7340                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
7341                        let target_start = target_buffer
7342                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
7343                        let target_end = target_buffer
7344                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
7345                        target_buffer.anchor_after(target_start)
7346                            ..target_buffer.anchor_before(target_end)
7347                    })?;
7348                    Location {
7349                        buffer: target_buffer_handle,
7350                        range,
7351                    }
7352                }),
7353                None => None,
7354            };
7355            Ok(location)
7356        })
7357    }
7358
7359    pub fn find_all_references(
7360        &mut self,
7361        _: &FindAllReferences,
7362        cx: &mut ViewContext<Self>,
7363    ) -> Option<Task<Result<()>>> {
7364        let buffer = self.buffer.read(cx);
7365        let head = self.selections.newest::<usize>(cx).head();
7366        let (buffer, head) = buffer.text_anchor_for_position(head, cx)?;
7367        let replica_id = self.replica_id(cx);
7368
7369        let workspace = self.workspace()?;
7370        let project = workspace.read(cx).project().clone();
7371        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
7372        Some(cx.spawn(|_, mut cx| async move {
7373            let locations = references.await?;
7374            if locations.is_empty() {
7375                return Ok(());
7376            }
7377
7378            workspace.update(&mut cx, |workspace, cx| {
7379                let title = locations
7380                    .first()
7381                    .as_ref()
7382                    .map(|location| {
7383                        let buffer = location.buffer.read(cx);
7384                        format!(
7385                            "References to `{}`",
7386                            buffer
7387                                .text_for_range(location.range.clone())
7388                                .collect::<String>()
7389                        )
7390                    })
7391                    .unwrap();
7392                Self::open_locations_in_multibuffer(
7393                    workspace, locations, replica_id, title, false, cx,
7394                );
7395            })?;
7396
7397            Ok(())
7398        }))
7399    }
7400
7401    /// Opens a multibuffer with the given project locations in it
7402    pub fn open_locations_in_multibuffer(
7403        workspace: &mut Workspace,
7404        mut locations: Vec<Location>,
7405        replica_id: ReplicaId,
7406        title: String,
7407        split: bool,
7408        cx: &mut ViewContext<Workspace>,
7409    ) {
7410        // If there are multiple definitions, open them in a multibuffer
7411        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
7412        let mut locations = locations.into_iter().peekable();
7413        let mut ranges_to_highlight = Vec::new();
7414        let capability = workspace.project().read(cx).capability();
7415
7416        let excerpt_buffer = cx.new_model(|cx| {
7417            let mut multibuffer = MultiBuffer::new(replica_id, capability);
7418            while let Some(location) = locations.next() {
7419                let buffer = location.buffer.read(cx);
7420                let mut ranges_for_buffer = Vec::new();
7421                let range = location.range.to_offset(buffer);
7422                ranges_for_buffer.push(range.clone());
7423
7424                while let Some(next_location) = locations.peek() {
7425                    if next_location.buffer == location.buffer {
7426                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
7427                        locations.next();
7428                    } else {
7429                        break;
7430                    }
7431                }
7432
7433                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
7434                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
7435                    location.buffer.clone(),
7436                    ranges_for_buffer,
7437                    1,
7438                    cx,
7439                ))
7440            }
7441
7442            multibuffer.with_title(title)
7443        });
7444
7445        let editor = cx.new_view(|cx| {
7446            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), cx)
7447        });
7448        editor.update(cx, |editor, cx| {
7449            editor.highlight_background::<Self>(
7450                ranges_to_highlight,
7451                |theme| theme.editor_highlighted_line_background,
7452                cx,
7453            );
7454        });
7455        if split {
7456            workspace.split_item(SplitDirection::Right, Box::new(editor), cx);
7457        } else {
7458            workspace.add_item(Box::new(editor), cx);
7459        }
7460    }
7461
7462    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
7463        use language::ToOffset as _;
7464
7465        let project = self.project.clone()?;
7466        let selection = self.selections.newest_anchor().clone();
7467        let (cursor_buffer, cursor_buffer_position) = self
7468            .buffer
7469            .read(cx)
7470            .text_anchor_for_position(selection.head(), cx)?;
7471        let (tail_buffer, _) = self
7472            .buffer
7473            .read(cx)
7474            .text_anchor_for_position(selection.tail(), cx)?;
7475        if tail_buffer != cursor_buffer {
7476            return None;
7477        }
7478
7479        let snapshot = cursor_buffer.read(cx).snapshot();
7480        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
7481        let prepare_rename = project.update(cx, |project, cx| {
7482            project.prepare_rename(cursor_buffer, cursor_buffer_offset, cx)
7483        });
7484
7485        Some(cx.spawn(|this, mut cx| async move {
7486            let rename_range = if let Some(range) = prepare_rename.await? {
7487                Some(range)
7488            } else {
7489                this.update(&mut cx, |this, cx| {
7490                    let buffer = this.buffer.read(cx).snapshot(cx);
7491                    let mut buffer_highlights = this
7492                        .document_highlights_for_position(selection.head(), &buffer)
7493                        .filter(|highlight| {
7494                            highlight.start.excerpt_id == selection.head().excerpt_id
7495                                && highlight.end.excerpt_id == selection.head().excerpt_id
7496                        });
7497                    buffer_highlights
7498                        .next()
7499                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
7500                })?
7501            };
7502            if let Some(rename_range) = rename_range {
7503                let rename_buffer_range = rename_range.to_offset(&snapshot);
7504                let cursor_offset_in_rename_range =
7505                    cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
7506
7507                this.update(&mut cx, |this, cx| {
7508                    this.take_rename(false, cx);
7509                    let buffer = this.buffer.read(cx).read(cx);
7510                    let cursor_offset = selection.head().to_offset(&buffer);
7511                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
7512                    let rename_end = rename_start + rename_buffer_range.len();
7513                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
7514                    let mut old_highlight_id = None;
7515                    let old_name: Arc<str> = buffer
7516                        .chunks(rename_start..rename_end, true)
7517                        .map(|chunk| {
7518                            if old_highlight_id.is_none() {
7519                                old_highlight_id = chunk.syntax_highlight_id;
7520                            }
7521                            chunk.text
7522                        })
7523                        .collect::<String>()
7524                        .into();
7525
7526                    drop(buffer);
7527
7528                    // Position the selection in the rename editor so that it matches the current selection.
7529                    this.show_local_selections = false;
7530                    let rename_editor = cx.new_view(|cx| {
7531                        let mut editor = Editor::single_line(cx);
7532                        editor.buffer.update(cx, |buffer, cx| {
7533                            buffer.edit([(0..0, old_name.clone())], None, cx)
7534                        });
7535                        editor.select_all(&SelectAll, cx);
7536                        editor
7537                    });
7538
7539                    let ranges = this
7540                        .clear_background_highlights::<DocumentHighlightWrite>(cx)
7541                        .into_iter()
7542                        .flat_map(|(_, ranges)| ranges.into_iter())
7543                        .chain(
7544                            this.clear_background_highlights::<DocumentHighlightRead>(cx)
7545                                .into_iter()
7546                                .flat_map(|(_, ranges)| ranges.into_iter()),
7547                        )
7548                        .collect();
7549
7550                    this.highlight_text::<Rename>(
7551                        ranges,
7552                        HighlightStyle {
7553                            fade_out: Some(0.6),
7554                            ..Default::default()
7555                        },
7556                        cx,
7557                    );
7558                    let rename_focus_handle = rename_editor.focus_handle(cx);
7559                    cx.focus(&rename_focus_handle);
7560                    let block_id = this.insert_blocks(
7561                        [BlockProperties {
7562                            style: BlockStyle::Flex,
7563                            position: range.start.clone(),
7564                            height: 1,
7565                            render: Arc::new({
7566                                let rename_editor = rename_editor.clone();
7567                                move |cx: &mut BlockContext| {
7568                                    let mut text_style = cx.editor_style.text.clone();
7569                                    if let Some(highlight_style) = old_highlight_id
7570                                        .and_then(|h| h.style(&cx.editor_style.syntax))
7571                                    {
7572                                        text_style = text_style.highlight(highlight_style);
7573                                    }
7574                                    div()
7575                                        .pl(cx.anchor_x)
7576                                        .child(EditorElement::new(
7577                                            &rename_editor,
7578                                            EditorStyle {
7579                                                background: cx.theme().system().transparent,
7580                                                local_player: cx.editor_style.local_player,
7581                                                text: text_style,
7582                                                scrollbar_width: cx.editor_style.scrollbar_width,
7583                                                syntax: cx.editor_style.syntax.clone(),
7584                                                status: cx.editor_style.status.clone(),
7585                                                inlays_style: HighlightStyle {
7586                                                    color: Some(cx.theme().status().hint),
7587                                                    font_weight: Some(FontWeight::BOLD),
7588                                                    ..HighlightStyle::default()
7589                                                },
7590                                                suggestions_style: HighlightStyle {
7591                                                    color: Some(cx.theme().status().predictive),
7592                                                    ..HighlightStyle::default()
7593                                                },
7594                                            },
7595                                        ))
7596                                        .into_any_element()
7597                                }
7598                            }),
7599                            disposition: BlockDisposition::Below,
7600                        }],
7601                        Some(Autoscroll::fit()),
7602                        cx,
7603                    )[0];
7604                    this.pending_rename = Some(RenameState {
7605                        range,
7606                        old_name,
7607                        editor: rename_editor,
7608                        block_id,
7609                    });
7610                })?;
7611            }
7612
7613            Ok(())
7614        }))
7615    }
7616
7617    pub fn confirm_rename(
7618        &mut self,
7619        _: &ConfirmRename,
7620        cx: &mut ViewContext<Self>,
7621    ) -> Option<Task<Result<()>>> {
7622        let rename = self.take_rename(false, cx)?;
7623        let workspace = self.workspace()?;
7624        let (start_buffer, start) = self
7625            .buffer
7626            .read(cx)
7627            .text_anchor_for_position(rename.range.start.clone(), cx)?;
7628        let (end_buffer, end) = self
7629            .buffer
7630            .read(cx)
7631            .text_anchor_for_position(rename.range.end.clone(), cx)?;
7632        if start_buffer != end_buffer {
7633            return None;
7634        }
7635
7636        let buffer = start_buffer;
7637        let range = start..end;
7638        let old_name = rename.old_name;
7639        let new_name = rename.editor.read(cx).text(cx);
7640
7641        let rename = workspace
7642            .read(cx)
7643            .project()
7644            .clone()
7645            .update(cx, |project, cx| {
7646                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
7647            });
7648        let workspace = workspace.downgrade();
7649
7650        Some(cx.spawn(|editor, mut cx| async move {
7651            let project_transaction = rename.await?;
7652            Self::open_project_transaction(
7653                &editor,
7654                workspace,
7655                project_transaction,
7656                format!("Rename: {}{}", old_name, new_name),
7657                cx.clone(),
7658            )
7659            .await?;
7660
7661            editor.update(&mut cx, |editor, cx| {
7662                editor.refresh_document_highlights(cx);
7663            })?;
7664            Ok(())
7665        }))
7666    }
7667
7668    fn take_rename(
7669        &mut self,
7670        moving_cursor: bool,
7671        cx: &mut ViewContext<Self>,
7672    ) -> Option<RenameState> {
7673        let rename = self.pending_rename.take()?;
7674        if rename.editor.focus_handle(cx).is_focused(cx) {
7675            cx.focus(&self.focus_handle);
7676        }
7677
7678        self.remove_blocks(
7679            [rename.block_id].into_iter().collect(),
7680            Some(Autoscroll::fit()),
7681            cx,
7682        );
7683        self.clear_highlights::<Rename>(cx);
7684        self.show_local_selections = true;
7685
7686        if moving_cursor {
7687            let rename_editor = rename.editor.read(cx);
7688            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
7689
7690            // Update the selection to match the position of the selection inside
7691            // the rename editor.
7692            let snapshot = self.buffer.read(cx).read(cx);
7693            let rename_range = rename.range.to_offset(&snapshot);
7694            let cursor_in_editor = snapshot
7695                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
7696                .min(rename_range.end);
7697            drop(snapshot);
7698
7699            self.change_selections(None, cx, |s| {
7700                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
7701            });
7702        } else {
7703            self.refresh_document_highlights(cx);
7704        }
7705
7706        Some(rename)
7707    }
7708
7709    #[cfg(any(test, feature = "test-support"))]
7710    pub fn pending_rename(&self) -> Option<&RenameState> {
7711        self.pending_rename.as_ref()
7712    }
7713
7714    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
7715        let project = match &self.project {
7716            Some(project) => project.clone(),
7717            None => return None,
7718        };
7719
7720        Some(self.perform_format(project, FormatTrigger::Manual, cx))
7721    }
7722
7723    fn perform_format(
7724        &mut self,
7725        project: Model<Project>,
7726        trigger: FormatTrigger,
7727        cx: &mut ViewContext<Self>,
7728    ) -> Task<Result<()>> {
7729        let buffer = self.buffer().clone();
7730        let buffers = buffer.read(cx).all_buffers();
7731
7732        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
7733        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
7734
7735        cx.spawn(|_, mut cx| async move {
7736            let transaction = futures::select_biased! {
7737                _ = timeout => {
7738                    log::warn!("timed out waiting for formatting");
7739                    None
7740                }
7741                transaction = format.log_err().fuse() => transaction,
7742            };
7743
7744            buffer
7745                .update(&mut cx, |buffer, cx| {
7746                    if let Some(transaction) = transaction {
7747                        if !buffer.is_singleton() {
7748                            buffer.push_transaction(&transaction.0, cx);
7749                        }
7750                    }
7751
7752                    cx.notify();
7753                })
7754                .ok();
7755
7756            Ok(())
7757        })
7758    }
7759
7760    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
7761        if let Some(project) = self.project.clone() {
7762            self.buffer.update(cx, |multi_buffer, cx| {
7763                project.update(cx, |project, cx| {
7764                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
7765                });
7766            })
7767        }
7768    }
7769
7770    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
7771        cx.show_character_palette();
7772    }
7773
7774    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
7775        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
7776            let buffer = self.buffer.read(cx).snapshot(cx);
7777            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
7778            let is_valid = buffer
7779                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
7780                .any(|entry| {
7781                    entry.diagnostic.is_primary
7782                        && !entry.range.is_empty()
7783                        && entry.range.start == primary_range_start
7784                        && entry.diagnostic.message == active_diagnostics.primary_message
7785                });
7786
7787            if is_valid != active_diagnostics.is_valid {
7788                active_diagnostics.is_valid = is_valid;
7789                let mut new_styles = HashMap::default();
7790                for (block_id, diagnostic) in &active_diagnostics.blocks {
7791                    new_styles.insert(
7792                        *block_id,
7793                        diagnostic_block_renderer(diagnostic.clone(), is_valid),
7794                    );
7795                }
7796                self.display_map
7797                    .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
7798            }
7799        }
7800    }
7801
7802    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
7803        self.dismiss_diagnostics(cx);
7804        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
7805            let buffer = self.buffer.read(cx).snapshot(cx);
7806
7807            let mut primary_range = None;
7808            let mut primary_message = None;
7809            let mut group_end = Point::zero();
7810            let diagnostic_group = buffer
7811                .diagnostic_group::<Point>(group_id)
7812                .map(|entry| {
7813                    if entry.range.end > group_end {
7814                        group_end = entry.range.end;
7815                    }
7816                    if entry.diagnostic.is_primary {
7817                        primary_range = Some(entry.range.clone());
7818                        primary_message = Some(entry.diagnostic.message.clone());
7819                    }
7820                    entry
7821                })
7822                .collect::<Vec<_>>();
7823            let primary_range = primary_range?;
7824            let primary_message = primary_message?;
7825            let primary_range =
7826                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
7827
7828            let blocks = display_map
7829                .insert_blocks(
7830                    diagnostic_group.iter().map(|entry| {
7831                        let diagnostic = entry.diagnostic.clone();
7832                        let message_height = diagnostic.message.lines().count() as u8;
7833                        BlockProperties {
7834                            style: BlockStyle::Fixed,
7835                            position: buffer.anchor_after(entry.range.start),
7836                            height: message_height,
7837                            render: diagnostic_block_renderer(diagnostic, true),
7838                            disposition: BlockDisposition::Below,
7839                        }
7840                    }),
7841                    cx,
7842                )
7843                .into_iter()
7844                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
7845                .collect();
7846
7847            Some(ActiveDiagnosticGroup {
7848                primary_range,
7849                primary_message,
7850                blocks,
7851                is_valid: true,
7852            })
7853        });
7854        self.active_diagnostics.is_some()
7855    }
7856
7857    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
7858        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
7859            self.display_map.update(cx, |display_map, cx| {
7860                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
7861            });
7862            cx.notify();
7863        }
7864    }
7865
7866    pub fn set_selections_from_remote(
7867        &mut self,
7868        selections: Vec<Selection<Anchor>>,
7869        pending_selection: Option<Selection<Anchor>>,
7870        cx: &mut ViewContext<Self>,
7871    ) {
7872        let old_cursor_position = self.selections.newest_anchor().head();
7873        self.selections.change_with(cx, |s| {
7874            s.select_anchors(selections);
7875            if let Some(pending_selection) = pending_selection {
7876                s.set_pending(pending_selection, SelectMode::Character);
7877            } else {
7878                s.clear_pending();
7879            }
7880        });
7881        self.selections_did_change(false, &old_cursor_position, cx);
7882    }
7883
7884    fn push_to_selection_history(&mut self) {
7885        self.selection_history.push(SelectionHistoryEntry {
7886            selections: self.selections.disjoint_anchors(),
7887            select_next_state: self.select_next_state.clone(),
7888            select_prev_state: self.select_prev_state.clone(),
7889            add_selections_state: self.add_selections_state.clone(),
7890        });
7891    }
7892
7893    pub fn transact(
7894        &mut self,
7895        cx: &mut ViewContext<Self>,
7896        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
7897    ) -> Option<TransactionId> {
7898        self.start_transaction_at(Instant::now(), cx);
7899        update(self, cx);
7900        self.end_transaction_at(Instant::now(), cx)
7901    }
7902
7903    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
7904        self.end_selection(cx);
7905        if let Some(tx_id) = self
7906            .buffer
7907            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
7908        {
7909            self.selection_history
7910                .insert_transaction(tx_id, self.selections.disjoint_anchors());
7911        }
7912    }
7913
7914    fn end_transaction_at(
7915        &mut self,
7916        now: Instant,
7917        cx: &mut ViewContext<Self>,
7918    ) -> Option<TransactionId> {
7919        if let Some(tx_id) = self
7920            .buffer
7921            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
7922        {
7923            if let Some((_, end_selections)) = self.selection_history.transaction_mut(tx_id) {
7924                *end_selections = Some(self.selections.disjoint_anchors());
7925            } else {
7926                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
7927            }
7928
7929            cx.emit(EditorEvent::Edited);
7930            Some(tx_id)
7931        } else {
7932            None
7933        }
7934    }
7935
7936    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
7937        let mut fold_ranges = Vec::new();
7938
7939        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7940
7941        let selections = self.selections.all_adjusted(cx);
7942        for selection in selections {
7943            let range = selection.range().sorted();
7944            let buffer_start_row = range.start.row;
7945
7946            for row in (0..=range.end.row).rev() {
7947                let fold_range = display_map.foldable_range(row);
7948
7949                if let Some(fold_range) = fold_range {
7950                    if fold_range.end.row >= buffer_start_row {
7951                        fold_ranges.push(fold_range);
7952                        if row <= range.start.row {
7953                            break;
7954                        }
7955                    }
7956                }
7957            }
7958        }
7959
7960        self.fold_ranges(fold_ranges, true, cx);
7961    }
7962
7963    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
7964        let buffer_row = fold_at.buffer_row;
7965        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7966
7967        if let Some(fold_range) = display_map.foldable_range(buffer_row) {
7968            let autoscroll = self
7969                .selections
7970                .all::<Point>(cx)
7971                .iter()
7972                .any(|selection| fold_range.overlaps(&selection.range()));
7973
7974            self.fold_ranges(std::iter::once(fold_range), autoscroll, cx);
7975        }
7976    }
7977
7978    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
7979        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7980        let buffer = &display_map.buffer_snapshot;
7981        let selections = self.selections.all::<Point>(cx);
7982        let ranges = selections
7983            .iter()
7984            .map(|s| {
7985                let range = s.display_range(&display_map).sorted();
7986                let mut start = range.start.to_point(&display_map);
7987                let mut end = range.end.to_point(&display_map);
7988                start.column = 0;
7989                end.column = buffer.line_len(end.row);
7990                start..end
7991            })
7992            .collect::<Vec<_>>();
7993
7994        self.unfold_ranges(ranges, true, true, cx);
7995    }
7996
7997    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
7998        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7999
8000        let intersection_range = Point::new(unfold_at.buffer_row, 0)
8001            ..Point::new(
8002                unfold_at.buffer_row,
8003                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
8004            );
8005
8006        let autoscroll = self
8007            .selections
8008            .all::<Point>(cx)
8009            .iter()
8010            .any(|selection| selection.range().overlaps(&intersection_range));
8011
8012        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
8013    }
8014
8015    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
8016        let selections = self.selections.all::<Point>(cx);
8017        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8018        let line_mode = self.selections.line_mode;
8019        let ranges = selections.into_iter().map(|s| {
8020            if line_mode {
8021                let start = Point::new(s.start.row, 0);
8022                let end = Point::new(s.end.row, display_map.buffer_snapshot.line_len(s.end.row));
8023                start..end
8024            } else {
8025                s.start..s.end
8026            }
8027        });
8028        self.fold_ranges(ranges, true, cx);
8029    }
8030
8031    pub fn fold_ranges<T: ToOffset + Clone>(
8032        &mut self,
8033        ranges: impl IntoIterator<Item = Range<T>>,
8034        auto_scroll: bool,
8035        cx: &mut ViewContext<Self>,
8036    ) {
8037        let mut ranges = ranges.into_iter().peekable();
8038        if ranges.peek().is_some() {
8039            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
8040
8041            if auto_scroll {
8042                self.request_autoscroll(Autoscroll::fit(), cx);
8043            }
8044
8045            cx.notify();
8046        }
8047    }
8048
8049    pub fn unfold_ranges<T: ToOffset + Clone>(
8050        &mut self,
8051        ranges: impl IntoIterator<Item = Range<T>>,
8052        inclusive: bool,
8053        auto_scroll: bool,
8054        cx: &mut ViewContext<Self>,
8055    ) {
8056        let mut ranges = ranges.into_iter().peekable();
8057        if ranges.peek().is_some() {
8058            self.display_map
8059                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
8060            if auto_scroll {
8061                self.request_autoscroll(Autoscroll::fit(), cx);
8062            }
8063
8064            cx.notify();
8065        }
8066    }
8067
8068    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
8069        if hovered != self.gutter_hovered {
8070            self.gutter_hovered = hovered;
8071            cx.notify();
8072        }
8073    }
8074
8075    pub fn insert_blocks(
8076        &mut self,
8077        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
8078        autoscroll: Option<Autoscroll>,
8079        cx: &mut ViewContext<Self>,
8080    ) -> Vec<BlockId> {
8081        let blocks = self
8082            .display_map
8083            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
8084        if let Some(autoscroll) = autoscroll {
8085            self.request_autoscroll(autoscroll, cx);
8086        }
8087        blocks
8088    }
8089
8090    pub fn replace_blocks(
8091        &mut self,
8092        blocks: HashMap<BlockId, RenderBlock>,
8093        autoscroll: Option<Autoscroll>,
8094        cx: &mut ViewContext<Self>,
8095    ) {
8096        self.display_map
8097            .update(cx, |display_map, _| display_map.replace_blocks(blocks));
8098        if let Some(autoscroll) = autoscroll {
8099            self.request_autoscroll(autoscroll, cx);
8100        }
8101    }
8102
8103    pub fn remove_blocks(
8104        &mut self,
8105        block_ids: HashSet<BlockId>,
8106        autoscroll: Option<Autoscroll>,
8107        cx: &mut ViewContext<Self>,
8108    ) {
8109        self.display_map.update(cx, |display_map, cx| {
8110            display_map.remove_blocks(block_ids, cx)
8111        });
8112        if let Some(autoscroll) = autoscroll {
8113            self.request_autoscroll(autoscroll, cx);
8114        }
8115    }
8116
8117    pub fn longest_row(&self, cx: &mut AppContext) -> u32 {
8118        self.display_map
8119            .update(cx, |map, cx| map.snapshot(cx))
8120            .longest_row()
8121    }
8122
8123    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
8124        self.display_map
8125            .update(cx, |map, cx| map.snapshot(cx))
8126            .max_point()
8127    }
8128
8129    pub fn text(&self, cx: &AppContext) -> String {
8130        self.buffer.read(cx).read(cx).text()
8131    }
8132
8133    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
8134        let text = self.text(cx);
8135        let text = text.trim();
8136
8137        if text.is_empty() {
8138            return None;
8139        }
8140
8141        Some(text.to_string())
8142    }
8143
8144    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
8145        self.transact(cx, |this, cx| {
8146            this.buffer
8147                .read(cx)
8148                .as_singleton()
8149                .expect("you can only call set_text on editors for singleton buffers")
8150                .update(cx, |buffer, cx| buffer.set_text(text, cx));
8151        });
8152    }
8153
8154    pub fn display_text(&self, cx: &mut AppContext) -> String {
8155        self.display_map
8156            .update(cx, |map, cx| map.snapshot(cx))
8157            .text()
8158    }
8159
8160    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
8161        let mut wrap_guides = smallvec::smallvec![];
8162
8163        if self.show_wrap_guides == Some(false) {
8164            return wrap_guides;
8165        }
8166
8167        let settings = self.buffer.read(cx).settings_at(0, cx);
8168        if settings.show_wrap_guides {
8169            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
8170                wrap_guides.push((soft_wrap as usize, true));
8171            }
8172            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
8173        }
8174
8175        wrap_guides
8176    }
8177
8178    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
8179        let settings = self.buffer.read(cx).settings_at(0, cx);
8180        let mode = self
8181            .soft_wrap_mode_override
8182            .unwrap_or_else(|| settings.soft_wrap);
8183        match mode {
8184            language_settings::SoftWrap::None => SoftWrap::None,
8185            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
8186            language_settings::SoftWrap::PreferredLineLength => {
8187                SoftWrap::Column(settings.preferred_line_length)
8188            }
8189        }
8190    }
8191
8192    pub fn set_soft_wrap_mode(
8193        &mut self,
8194        mode: language_settings::SoftWrap,
8195        cx: &mut ViewContext<Self>,
8196    ) {
8197        self.soft_wrap_mode_override = Some(mode);
8198        cx.notify();
8199    }
8200
8201    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
8202        let rem_size = cx.rem_size();
8203        self.display_map.update(cx, |map, cx| {
8204            map.set_font(
8205                style.text.font(),
8206                style.text.font_size.to_pixels(rem_size),
8207                cx,
8208            )
8209        });
8210        self.style = Some(style);
8211    }
8212
8213    #[cfg(any(test, feature = "test-support"))]
8214    pub fn style(&self) -> Option<&EditorStyle> {
8215        self.style.as_ref()
8216    }
8217
8218    // Called by the element. This method is not designed to be called outside of the editor
8219    // element's layout code because it does not notify when rewrapping is computed synchronously.
8220    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
8221        self.display_map
8222            .update(cx, |map, cx| map.set_wrap_width(width, cx))
8223    }
8224
8225    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
8226        if self.soft_wrap_mode_override.is_some() {
8227            self.soft_wrap_mode_override.take();
8228        } else {
8229            let soft_wrap = match self.soft_wrap_mode(cx) {
8230                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
8231                SoftWrap::EditorWidth | SoftWrap::Column(_) => language_settings::SoftWrap::None,
8232            };
8233            self.soft_wrap_mode_override = Some(soft_wrap);
8234        }
8235        cx.notify();
8236    }
8237
8238    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
8239        self.show_gutter = show_gutter;
8240        cx.notify();
8241    }
8242
8243    pub fn set_show_wrap_guides(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
8244        self.show_wrap_guides = Some(show_gutter);
8245        cx.notify();
8246    }
8247
8248    pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
8249        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
8250            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
8251                cx.reveal_path(&file.abs_path(cx));
8252            }
8253        }
8254    }
8255
8256    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
8257        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
8258            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
8259                if let Some(path) = file.abs_path(cx).to_str() {
8260                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
8261                }
8262            }
8263        }
8264    }
8265
8266    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
8267        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
8268            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
8269                if let Some(path) = file.path().to_str() {
8270                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
8271                }
8272            }
8273        }
8274    }
8275
8276    pub fn highlight_rows(&mut self, rows: Option<Range<u32>>) {
8277        self.highlighted_rows = rows;
8278    }
8279
8280    pub fn highlighted_rows(&self) -> Option<Range<u32>> {
8281        self.highlighted_rows.clone()
8282    }
8283
8284    pub fn highlight_background<T: 'static>(
8285        &mut self,
8286        ranges: Vec<Range<Anchor>>,
8287        color_fetcher: fn(&ThemeColors) -> Hsla,
8288        cx: &mut ViewContext<Self>,
8289    ) {
8290        self.background_highlights
8291            .insert(TypeId::of::<T>(), (color_fetcher, ranges));
8292        cx.notify();
8293    }
8294
8295    pub(crate) fn highlight_inlay_background<T: 'static>(
8296        &mut self,
8297        ranges: Vec<InlayHighlight>,
8298        color_fetcher: fn(&ThemeColors) -> Hsla,
8299        cx: &mut ViewContext<Self>,
8300    ) {
8301        // TODO: no actual highlights happen for inlays currently, find a way to do that
8302        self.inlay_background_highlights
8303            .insert(Some(TypeId::of::<T>()), (color_fetcher, ranges));
8304        cx.notify();
8305    }
8306
8307    pub fn clear_background_highlights<T: 'static>(
8308        &mut self,
8309        cx: &mut ViewContext<Self>,
8310    ) -> Option<BackgroundHighlight> {
8311        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>());
8312        let inlay_highlights = self
8313            .inlay_background_highlights
8314            .remove(&Some(TypeId::of::<T>()));
8315        if text_highlights.is_some() || inlay_highlights.is_some() {
8316            cx.notify();
8317        }
8318        text_highlights
8319    }
8320
8321    #[cfg(feature = "test-support")]
8322    pub fn all_text_background_highlights(
8323        &mut self,
8324        cx: &mut ViewContext<Self>,
8325    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
8326        let snapshot = self.snapshot(cx);
8327        let buffer = &snapshot.buffer_snapshot;
8328        let start = buffer.anchor_before(0);
8329        let end = buffer.anchor_after(buffer.len());
8330        let theme = cx.theme().colors();
8331        self.background_highlights_in_range(start..end, &snapshot, theme)
8332    }
8333
8334    fn document_highlights_for_position<'a>(
8335        &'a self,
8336        position: Anchor,
8337        buffer: &'a MultiBufferSnapshot,
8338    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
8339        let read_highlights = self
8340            .background_highlights
8341            .get(&TypeId::of::<DocumentHighlightRead>())
8342            .map(|h| &h.1);
8343        let write_highlights = self
8344            .background_highlights
8345            .get(&TypeId::of::<DocumentHighlightWrite>())
8346            .map(|h| &h.1);
8347        let left_position = position.bias_left(buffer);
8348        let right_position = position.bias_right(buffer);
8349        read_highlights
8350            .into_iter()
8351            .chain(write_highlights)
8352            .flat_map(move |ranges| {
8353                let start_ix = match ranges.binary_search_by(|probe| {
8354                    let cmp = probe.end.cmp(&left_position, buffer);
8355                    if cmp.is_ge() {
8356                        Ordering::Greater
8357                    } else {
8358                        Ordering::Less
8359                    }
8360                }) {
8361                    Ok(i) | Err(i) => i,
8362                };
8363
8364                let right_position = right_position.clone();
8365                ranges[start_ix..]
8366                    .iter()
8367                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
8368            })
8369    }
8370
8371    pub fn has_background_highlights<T: 'static>(&self) -> bool {
8372        self.background_highlights
8373            .get(&TypeId::of::<T>())
8374            .map_or(false, |(_, highlights)| !highlights.is_empty())
8375    }
8376
8377    pub fn background_highlights_in_range(
8378        &self,
8379        search_range: Range<Anchor>,
8380        display_snapshot: &DisplaySnapshot,
8381        theme: &ThemeColors,
8382    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
8383        let mut results = Vec::new();
8384        for (color_fetcher, ranges) in self.background_highlights.values() {
8385            let color = color_fetcher(theme);
8386            let start_ix = match ranges.binary_search_by(|probe| {
8387                let cmp = probe
8388                    .end
8389                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
8390                if cmp.is_gt() {
8391                    Ordering::Greater
8392                } else {
8393                    Ordering::Less
8394                }
8395            }) {
8396                Ok(i) | Err(i) => i,
8397            };
8398            for range in &ranges[start_ix..] {
8399                if range
8400                    .start
8401                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
8402                    .is_ge()
8403                {
8404                    break;
8405                }
8406
8407                let start = range.start.to_display_point(&display_snapshot);
8408                let end = range.end.to_display_point(&display_snapshot);
8409                results.push((start..end, color))
8410            }
8411        }
8412        results
8413    }
8414
8415    pub fn background_highlight_row_ranges<T: 'static>(
8416        &self,
8417        search_range: Range<Anchor>,
8418        display_snapshot: &DisplaySnapshot,
8419        count: usize,
8420    ) -> Vec<RangeInclusive<DisplayPoint>> {
8421        let mut results = Vec::new();
8422        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
8423            return vec![];
8424        };
8425
8426        let start_ix = match ranges.binary_search_by(|probe| {
8427            let cmp = probe
8428                .end
8429                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
8430            if cmp.is_gt() {
8431                Ordering::Greater
8432            } else {
8433                Ordering::Less
8434            }
8435        }) {
8436            Ok(i) | Err(i) => i,
8437        };
8438        let mut push_region = |start: Option<Point>, end: Option<Point>| {
8439            if let (Some(start_display), Some(end_display)) = (start, end) {
8440                results.push(
8441                    start_display.to_display_point(display_snapshot)
8442                        ..=end_display.to_display_point(display_snapshot),
8443                );
8444            }
8445        };
8446        let mut start_row: Option<Point> = None;
8447        let mut end_row: Option<Point> = None;
8448        if ranges.len() > count {
8449            return Vec::new();
8450        }
8451        for range in &ranges[start_ix..] {
8452            if range
8453                .start
8454                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
8455                .is_ge()
8456            {
8457                break;
8458            }
8459            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
8460            if let Some(current_row) = &end_row {
8461                if end.row == current_row.row {
8462                    continue;
8463                }
8464            }
8465            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
8466            if start_row.is_none() {
8467                assert_eq!(end_row, None);
8468                start_row = Some(start);
8469                end_row = Some(end);
8470                continue;
8471            }
8472            if let Some(current_end) = end_row.as_mut() {
8473                if start.row > current_end.row + 1 {
8474                    push_region(start_row, end_row);
8475                    start_row = Some(start);
8476                    end_row = Some(end);
8477                } else {
8478                    // Merge two hunks.
8479                    *current_end = end;
8480                }
8481            } else {
8482                unreachable!();
8483            }
8484        }
8485        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
8486        push_region(start_row, end_row);
8487        results
8488    }
8489
8490    pub fn highlight_text<T: 'static>(
8491        &mut self,
8492        ranges: Vec<Range<Anchor>>,
8493        style: HighlightStyle,
8494        cx: &mut ViewContext<Self>,
8495    ) {
8496        self.display_map.update(cx, |map, _| {
8497            map.highlight_text(TypeId::of::<T>(), ranges, style)
8498        });
8499        cx.notify();
8500    }
8501
8502    pub(crate) fn highlight_inlays<T: 'static>(
8503        &mut self,
8504        highlights: Vec<InlayHighlight>,
8505        style: HighlightStyle,
8506        cx: &mut ViewContext<Self>,
8507    ) {
8508        self.display_map.update(cx, |map, _| {
8509            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
8510        });
8511        cx.notify();
8512    }
8513
8514    pub fn text_highlights<'a, T: 'static>(
8515        &'a self,
8516        cx: &'a AppContext,
8517    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
8518        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
8519    }
8520
8521    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
8522        let cleared = self
8523            .display_map
8524            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
8525        if cleared {
8526            cx.notify();
8527        }
8528    }
8529
8530    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
8531        (self.read_only(cx) || self.blink_manager.read(cx).visible())
8532            && self.focus_handle.is_focused(cx)
8533    }
8534
8535    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
8536        cx.notify();
8537    }
8538
8539    fn on_buffer_event(
8540        &mut self,
8541        multibuffer: Model<MultiBuffer>,
8542        event: &multi_buffer::Event,
8543        cx: &mut ViewContext<Self>,
8544    ) {
8545        match event {
8546            multi_buffer::Event::Edited {
8547                singleton_buffer_edited,
8548            } => {
8549                self.refresh_active_diagnostics(cx);
8550                self.refresh_code_actions(cx);
8551                if self.has_active_copilot_suggestion(cx) {
8552                    self.update_visible_copilot_suggestion(cx);
8553                }
8554                cx.emit(EditorEvent::BufferEdited);
8555                cx.emit(SearchEvent::MatchesInvalidated);
8556
8557                if *singleton_buffer_edited {
8558                    if let Some(project) = &self.project {
8559                        let project = project.read(cx);
8560                        let languages_affected = multibuffer
8561                            .read(cx)
8562                            .all_buffers()
8563                            .into_iter()
8564                            .filter_map(|buffer| {
8565                                let buffer = buffer.read(cx);
8566                                let language = buffer.language()?;
8567                                if project.is_local()
8568                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
8569                                {
8570                                    None
8571                                } else {
8572                                    Some(language)
8573                                }
8574                            })
8575                            .cloned()
8576                            .collect::<HashSet<_>>();
8577                        if !languages_affected.is_empty() {
8578                            self.refresh_inlay_hints(
8579                                InlayHintRefreshReason::BufferEdited(languages_affected),
8580                                cx,
8581                            );
8582                        }
8583                    }
8584                }
8585
8586                let Some(project) = &self.project else { return };
8587                let telemetry = project.read(cx).client().telemetry().clone();
8588                telemetry.log_edit_event("editor");
8589            }
8590            multi_buffer::Event::ExcerptsAdded {
8591                buffer,
8592                predecessor,
8593                excerpts,
8594            } => {
8595                cx.emit(EditorEvent::ExcerptsAdded {
8596                    buffer: buffer.clone(),
8597                    predecessor: *predecessor,
8598                    excerpts: excerpts.clone(),
8599                });
8600                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
8601            }
8602            multi_buffer::Event::ExcerptsRemoved { ids } => {
8603                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
8604                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
8605            }
8606            multi_buffer::Event::Reparsed => cx.emit(EditorEvent::Reparsed),
8607            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
8608            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
8609            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
8610                cx.emit(EditorEvent::TitleChanged)
8611            }
8612            multi_buffer::Event::DiffBaseChanged => cx.emit(EditorEvent::DiffBaseChanged),
8613            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
8614            multi_buffer::Event::DiagnosticsUpdated => {
8615                self.refresh_active_diagnostics(cx);
8616            }
8617            _ => {}
8618        };
8619    }
8620
8621    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
8622        cx.notify();
8623    }
8624
8625    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
8626        self.refresh_copilot_suggestions(true, cx);
8627        self.refresh_inlay_hints(
8628            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
8629                self.selections.newest_anchor().head(),
8630                &self.buffer.read(cx).snapshot(cx),
8631                cx,
8632            )),
8633            cx,
8634        );
8635        cx.notify();
8636    }
8637
8638    pub fn set_searchable(&mut self, searchable: bool) {
8639        self.searchable = searchable;
8640    }
8641
8642    pub fn searchable(&self) -> bool {
8643        self.searchable
8644    }
8645
8646    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
8647        let buffer = self.buffer.read(cx);
8648        if buffer.is_singleton() {
8649            cx.propagate();
8650            return;
8651        }
8652
8653        let Some(workspace) = self.workspace() else {
8654            cx.propagate();
8655            return;
8656        };
8657
8658        let mut new_selections_by_buffer = HashMap::default();
8659        for selection in self.selections.all::<usize>(cx) {
8660            for (buffer, mut range, _) in
8661                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
8662            {
8663                if selection.reversed {
8664                    mem::swap(&mut range.start, &mut range.end);
8665                }
8666                new_selections_by_buffer
8667                    .entry(buffer)
8668                    .or_insert(Vec::new())
8669                    .push(range)
8670            }
8671        }
8672
8673        self.push_to_nav_history(self.selections.newest_anchor().head(), None, cx);
8674
8675        // We defer the pane interaction because we ourselves are a workspace item
8676        // and activating a new item causes the pane to call a method on us reentrantly,
8677        // which panics if we're on the stack.
8678        cx.window_context().defer(move |cx| {
8679            workspace.update(cx, |workspace, cx| {
8680                let pane = workspace.active_pane().clone();
8681                pane.update(cx, |pane, _| pane.disable_history());
8682
8683                for (buffer, ranges) in new_selections_by_buffer.into_iter() {
8684                    let editor = workspace.open_project_item::<Self>(buffer, cx);
8685                    editor.update(cx, |editor, cx| {
8686                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
8687                            s.select_ranges(ranges);
8688                        });
8689                    });
8690                }
8691
8692                pane.update(cx, |pane, _| pane.enable_history());
8693            })
8694        });
8695    }
8696
8697    fn jump(
8698        &mut self,
8699        path: ProjectPath,
8700        position: Point,
8701        anchor: language::Anchor,
8702        cx: &mut ViewContext<Self>,
8703    ) {
8704        let workspace = self.workspace();
8705        cx.spawn(|_, mut cx| async move {
8706            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
8707            let editor = workspace.update(&mut cx, |workspace, cx| {
8708                workspace.open_path(path, None, true, cx)
8709            })?;
8710            let editor = editor
8711                .await?
8712                .downcast::<Editor>()
8713                .ok_or_else(|| anyhow!("opened item was not an editor"))?
8714                .downgrade();
8715            editor.update(&mut cx, |editor, cx| {
8716                let buffer = editor
8717                    .buffer()
8718                    .read(cx)
8719                    .as_singleton()
8720                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
8721                let buffer = buffer.read(cx);
8722                let cursor = if buffer.can_resolve(&anchor) {
8723                    language::ToPoint::to_point(&anchor, buffer)
8724                } else {
8725                    buffer.clip_point(position, Bias::Left)
8726                };
8727
8728                let nav_history = editor.nav_history.take();
8729                editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
8730                    s.select_ranges([cursor..cursor]);
8731                });
8732                editor.nav_history = nav_history;
8733
8734                anyhow::Ok(())
8735            })??;
8736
8737            anyhow::Ok(())
8738        })
8739        .detach_and_log_err(cx);
8740    }
8741
8742    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
8743        let snapshot = self.buffer.read(cx).read(cx);
8744        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
8745        Some(
8746            ranges
8747                .iter()
8748                .map(move |range| {
8749                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
8750                })
8751                .collect(),
8752        )
8753    }
8754
8755    fn selection_replacement_ranges(
8756        &self,
8757        range: Range<OffsetUtf16>,
8758        cx: &AppContext,
8759    ) -> Vec<Range<OffsetUtf16>> {
8760        let selections = self.selections.all::<OffsetUtf16>(cx);
8761        let newest_selection = selections
8762            .iter()
8763            .max_by_key(|selection| selection.id)
8764            .unwrap();
8765        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
8766        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
8767        let snapshot = self.buffer.read(cx).read(cx);
8768        selections
8769            .into_iter()
8770            .map(|mut selection| {
8771                selection.start.0 =
8772                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
8773                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
8774                snapshot.clip_offset_utf16(selection.start, Bias::Left)
8775                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
8776            })
8777            .collect()
8778    }
8779
8780    fn report_copilot_event(
8781        &self,
8782        suggestion_id: Option<String>,
8783        suggestion_accepted: bool,
8784        cx: &AppContext,
8785    ) {
8786        let Some(project) = &self.project else { return };
8787
8788        // If None, we are either getting suggestions in a new, unsaved file, or in a file without an extension
8789        let file_extension = self
8790            .buffer
8791            .read(cx)
8792            .as_singleton()
8793            .and_then(|b| b.read(cx).file())
8794            .and_then(|file| Path::new(file.file_name(cx)).extension())
8795            .and_then(|e| e.to_str())
8796            .map(|a| a.to_string());
8797
8798        let telemetry = project.read(cx).client().telemetry().clone();
8799
8800        telemetry.report_copilot_event(suggestion_id, suggestion_accepted, file_extension)
8801    }
8802
8803    #[cfg(any(test, feature = "test-support"))]
8804    fn report_editor_event(
8805        &self,
8806        _operation: &'static str,
8807        _file_extension: Option<String>,
8808        _cx: &AppContext,
8809    ) {
8810    }
8811
8812    #[cfg(not(any(test, feature = "test-support")))]
8813    fn report_editor_event(
8814        &self,
8815        operation: &'static str,
8816        file_extension: Option<String>,
8817        cx: &AppContext,
8818    ) {
8819        let Some(project) = &self.project else { return };
8820
8821        // If None, we are in a file without an extension
8822        let file = self
8823            .buffer
8824            .read(cx)
8825            .as_singleton()
8826            .and_then(|b| b.read(cx).file());
8827        let file_extension = file_extension.or(file
8828            .as_ref()
8829            .and_then(|file| Path::new(file.file_name(cx)).extension())
8830            .and_then(|e| e.to_str())
8831            .map(|a| a.to_string()));
8832
8833        let vim_mode = cx
8834            .global::<SettingsStore>()
8835            .raw_user_settings()
8836            .get("vim_mode")
8837            == Some(&serde_json::Value::Bool(true));
8838        let copilot_enabled = all_language_settings(file, cx).copilot_enabled(None, None);
8839        let copilot_enabled_for_language = self
8840            .buffer
8841            .read(cx)
8842            .settings_at(0, cx)
8843            .show_copilot_suggestions;
8844
8845        let telemetry = project.read(cx).client().telemetry().clone();
8846        telemetry.report_editor_event(
8847            file_extension,
8848            vim_mode,
8849            operation,
8850            copilot_enabled,
8851            copilot_enabled_for_language,
8852        )
8853    }
8854
8855    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
8856    /// with each line being an array of {text, highlight} objects.
8857    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
8858        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
8859            return;
8860        };
8861
8862        #[derive(Serialize)]
8863        struct Chunk<'a> {
8864            text: String,
8865            highlight: Option<&'a str>,
8866        }
8867
8868        let snapshot = buffer.read(cx).snapshot();
8869        let range = self
8870            .selected_text_range(cx)
8871            .and_then(|selected_range| {
8872                if selected_range.is_empty() {
8873                    None
8874                } else {
8875                    Some(selected_range)
8876                }
8877            })
8878            .unwrap_or_else(|| 0..snapshot.len());
8879
8880        let chunks = snapshot.chunks(range, true);
8881        let mut lines = Vec::new();
8882        let mut line: VecDeque<Chunk> = VecDeque::new();
8883
8884        let Some(style) = self.style.as_ref() else {
8885            return;
8886        };
8887
8888        for chunk in chunks {
8889            let highlight = chunk
8890                .syntax_highlight_id
8891                .and_then(|id| id.name(&style.syntax));
8892            let mut chunk_lines = chunk.text.split("\n").peekable();
8893            while let Some(text) = chunk_lines.next() {
8894                let mut merged_with_last_token = false;
8895                if let Some(last_token) = line.back_mut() {
8896                    if last_token.highlight == highlight {
8897                        last_token.text.push_str(text);
8898                        merged_with_last_token = true;
8899                    }
8900                }
8901
8902                if !merged_with_last_token {
8903                    line.push_back(Chunk {
8904                        text: text.into(),
8905                        highlight,
8906                    });
8907                }
8908
8909                if chunk_lines.peek().is_some() {
8910                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
8911                        line.pop_front();
8912                    }
8913                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
8914                        line.pop_back();
8915                    }
8916
8917                    lines.push(mem::take(&mut line));
8918                }
8919            }
8920        }
8921
8922        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
8923            return;
8924        };
8925        cx.write_to_clipboard(ClipboardItem::new(lines));
8926    }
8927
8928    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
8929        &self.inlay_hint_cache
8930    }
8931
8932    pub fn replay_insert_event(
8933        &mut self,
8934        text: &str,
8935        relative_utf16_range: Option<Range<isize>>,
8936        cx: &mut ViewContext<Self>,
8937    ) {
8938        if !self.input_enabled {
8939            cx.emit(EditorEvent::InputIgnored { text: text.into() });
8940            return;
8941        }
8942        if let Some(relative_utf16_range) = relative_utf16_range {
8943            let selections = self.selections.all::<OffsetUtf16>(cx);
8944            self.change_selections(None, cx, |s| {
8945                let new_ranges = selections.into_iter().map(|range| {
8946                    let start = OffsetUtf16(
8947                        range
8948                            .head()
8949                            .0
8950                            .saturating_add_signed(relative_utf16_range.start),
8951                    );
8952                    let end = OffsetUtf16(
8953                        range
8954                            .head()
8955                            .0
8956                            .saturating_add_signed(relative_utf16_range.end),
8957                    );
8958                    start..end
8959                });
8960                s.select_ranges(new_ranges);
8961            });
8962        }
8963
8964        self.handle_input(text, cx);
8965    }
8966
8967    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
8968        let Some(project) = self.project.as_ref() else {
8969            return false;
8970        };
8971        let project = project.read(cx);
8972
8973        let mut supports = false;
8974        self.buffer().read(cx).for_each_buffer(|buffer| {
8975            if !supports {
8976                supports = project
8977                    .language_servers_for_buffer(buffer.read(cx), cx)
8978                    .any(
8979                        |(_, server)| match server.capabilities().inlay_hint_provider {
8980                            Some(lsp::OneOf::Left(enabled)) => enabled,
8981                            Some(lsp::OneOf::Right(_)) => true,
8982                            None => false,
8983                        },
8984                    )
8985            }
8986        });
8987        supports
8988    }
8989
8990    pub fn focus(&self, cx: &mut WindowContext) {
8991        cx.focus(&self.focus_handle)
8992    }
8993
8994    pub fn is_focused(&self, cx: &WindowContext) -> bool {
8995        self.focus_handle.is_focused(cx)
8996    }
8997
8998    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
8999        cx.emit(EditorEvent::Focused);
9000
9001        if let Some(rename) = self.pending_rename.as_ref() {
9002            let rename_editor_focus_handle = rename.editor.read(cx).focus_handle.clone();
9003            cx.focus(&rename_editor_focus_handle);
9004        } else {
9005            self.blink_manager.update(cx, BlinkManager::enable);
9006            self.recently_focused = true;
9007            cx.notify();
9008            cx.spawn(|this, mut cx| async move {
9009                cx.background_executor().timer(Duration::from_secs(2)).await;
9010                this.update(&mut cx, |this, cx| {
9011                    this.recently_focused = false;
9012                    cx.notify()
9013                })
9014                .ok()
9015            })
9016            .detach();
9017            self.buffer.update(cx, |buffer, cx| {
9018                buffer.finalize_last_transaction(cx);
9019                if self.leader_peer_id.is_none() {
9020                    buffer.set_active_selections(
9021                        &self.selections.disjoint_anchors(),
9022                        self.selections.line_mode,
9023                        self.cursor_shape,
9024                        cx,
9025                    );
9026                }
9027            });
9028        }
9029    }
9030
9031    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
9032        self.blink_manager.update(cx, BlinkManager::disable);
9033        self.buffer
9034            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
9035        self.hide_context_menu(cx);
9036        hide_hover(self, cx);
9037        cx.emit(EditorEvent::Blurred);
9038        cx.notify();
9039    }
9040
9041    pub fn register_action<A: Action>(
9042        &mut self,
9043        listener: impl Fn(&A, &mut WindowContext) + 'static,
9044    ) -> &mut Self {
9045        let listener = Arc::new(listener);
9046
9047        self.editor_actions.push(Box::new(move |cx| {
9048            let _view = cx.view().clone();
9049            let cx = cx.window_context();
9050            let listener = listener.clone();
9051            cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
9052                let action = action.downcast_ref().unwrap();
9053                if phase == DispatchPhase::Bubble {
9054                    listener(action, cx)
9055                }
9056            })
9057        }));
9058        self
9059    }
9060}
9061
9062pub trait CollaborationHub {
9063    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
9064    fn user_participant_indices<'a>(
9065        &self,
9066        cx: &'a AppContext,
9067    ) -> &'a HashMap<u64, ParticipantIndex>;
9068    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
9069}
9070
9071impl CollaborationHub for Model<Project> {
9072    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
9073        self.read(cx).collaborators()
9074    }
9075
9076    fn user_participant_indices<'a>(
9077        &self,
9078        cx: &'a AppContext,
9079    ) -> &'a HashMap<u64, ParticipantIndex> {
9080        self.read(cx).user_store().read(cx).participant_indices()
9081    }
9082
9083    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
9084        let this = self.read(cx);
9085        let user_ids = this.collaborators().values().map(|c| c.user_id);
9086        this.user_store().read_with(cx, |user_store, cx| {
9087            user_store.participant_names(user_ids, cx)
9088        })
9089    }
9090}
9091
9092fn inlay_hint_settings(
9093    location: Anchor,
9094    snapshot: &MultiBufferSnapshot,
9095    cx: &mut ViewContext<'_, Editor>,
9096) -> InlayHintSettings {
9097    let file = snapshot.file_at(location);
9098    let language = snapshot.language_at(location);
9099    let settings = all_language_settings(file, cx);
9100    settings
9101        .language(language.map(|l| l.name()).as_deref())
9102        .inlay_hints
9103}
9104
9105fn consume_contiguous_rows(
9106    contiguous_row_selections: &mut Vec<Selection<Point>>,
9107    selection: &Selection<Point>,
9108    display_map: &DisplaySnapshot,
9109    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
9110) -> (u32, u32) {
9111    contiguous_row_selections.push(selection.clone());
9112    let start_row = selection.start.row;
9113    let mut end_row = ending_row(selection, display_map);
9114
9115    while let Some(next_selection) = selections.peek() {
9116        if next_selection.start.row <= end_row {
9117            end_row = ending_row(next_selection, display_map);
9118            contiguous_row_selections.push(selections.next().unwrap().clone());
9119        } else {
9120            break;
9121        }
9122    }
9123    (start_row, end_row)
9124}
9125
9126fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> u32 {
9127    if next_selection.end.column > 0 || next_selection.is_empty() {
9128        display_map.next_line_boundary(next_selection.end).0.row + 1
9129    } else {
9130        next_selection.end.row
9131    }
9132}
9133
9134impl EditorSnapshot {
9135    pub fn remote_selections_in_range<'a>(
9136        &'a self,
9137        range: &'a Range<Anchor>,
9138        collaboration_hub: &dyn CollaborationHub,
9139        cx: &'a AppContext,
9140    ) -> impl 'a + Iterator<Item = RemoteSelection> {
9141        let participant_names = collaboration_hub.user_names(cx);
9142        let participant_indices = collaboration_hub.user_participant_indices(cx);
9143        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
9144        let collaborators_by_replica_id = collaborators_by_peer_id
9145            .iter()
9146            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
9147            .collect::<HashMap<_, _>>();
9148        self.buffer_snapshot
9149            .remote_selections_in_range(range)
9150            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
9151                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
9152                let participant_index = participant_indices.get(&collaborator.user_id).copied();
9153                let user_name = participant_names.get(&collaborator.user_id).cloned();
9154                Some(RemoteSelection {
9155                    replica_id,
9156                    selection,
9157                    cursor_shape,
9158                    line_mode,
9159                    participant_index,
9160                    peer_id: collaborator.peer_id,
9161                    user_name,
9162                })
9163            })
9164    }
9165
9166    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
9167        self.display_snapshot.buffer_snapshot.language_at(position)
9168    }
9169
9170    pub fn is_focused(&self) -> bool {
9171        self.is_focused
9172    }
9173
9174    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
9175        self.placeholder_text.as_ref()
9176    }
9177
9178    pub fn scroll_position(&self) -> gpui::Point<f32> {
9179        self.scroll_anchor.scroll_position(&self.display_snapshot)
9180    }
9181}
9182
9183impl Deref for EditorSnapshot {
9184    type Target = DisplaySnapshot;
9185
9186    fn deref(&self) -> &Self::Target {
9187        &self.display_snapshot
9188    }
9189}
9190
9191#[derive(Clone, Debug, PartialEq, Eq)]
9192pub enum EditorEvent {
9193    InputIgnored {
9194        text: Arc<str>,
9195    },
9196    InputHandled {
9197        utf16_range_to_replace: Option<Range<isize>>,
9198        text: Arc<str>,
9199    },
9200    ExcerptsAdded {
9201        buffer: Model<Buffer>,
9202        predecessor: ExcerptId,
9203        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
9204    },
9205    ExcerptsRemoved {
9206        ids: Vec<ExcerptId>,
9207    },
9208    BufferEdited,
9209    Edited,
9210    Reparsed,
9211    Focused,
9212    Blurred,
9213    DirtyChanged,
9214    Saved,
9215    TitleChanged,
9216    DiffBaseChanged,
9217    SelectionsChanged {
9218        local: bool,
9219    },
9220    ScrollPositionChanged {
9221        local: bool,
9222        autoscroll: bool,
9223    },
9224    Closed,
9225}
9226
9227impl EventEmitter<EditorEvent> for Editor {}
9228
9229impl FocusableView for Editor {
9230    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
9231        self.focus_handle.clone()
9232    }
9233}
9234
9235impl Render for Editor {
9236    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
9237        let settings = ThemeSettings::get_global(cx);
9238        let text_style = match self.mode {
9239            EditorMode::SingleLine | EditorMode::AutoHeight { .. } => TextStyle {
9240                color: cx.theme().colors().editor_foreground,
9241                font_family: settings.ui_font.family.clone(),
9242                font_features: settings.ui_font.features,
9243                font_size: rems(0.875).into(),
9244                font_weight: FontWeight::NORMAL,
9245                font_style: FontStyle::Normal,
9246                line_height: relative(settings.buffer_line_height.value()),
9247                background_color: None,
9248                underline: None,
9249                white_space: WhiteSpace::Normal,
9250            },
9251
9252            EditorMode::Full => TextStyle {
9253                color: cx.theme().colors().editor_foreground,
9254                font_family: settings.buffer_font.family.clone(),
9255                font_features: settings.buffer_font.features,
9256                font_size: settings.buffer_font_size(cx).into(),
9257                font_weight: FontWeight::NORMAL,
9258                font_style: FontStyle::Normal,
9259                line_height: relative(settings.buffer_line_height.value()),
9260                background_color: None,
9261                underline: None,
9262                white_space: WhiteSpace::Normal,
9263            },
9264        };
9265
9266        let background = match self.mode {
9267            EditorMode::SingleLine => cx.theme().system().transparent,
9268            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
9269            EditorMode::Full => cx.theme().colors().editor_background,
9270        };
9271
9272        EditorElement::new(
9273            cx.view(),
9274            EditorStyle {
9275                background,
9276                local_player: cx.theme().players().local(),
9277                text: text_style,
9278                scrollbar_width: px(12.),
9279                syntax: cx.theme().syntax().clone(),
9280                status: cx.theme().status().clone(),
9281                inlays_style: HighlightStyle {
9282                    color: Some(cx.theme().status().hint),
9283                    font_weight: Some(FontWeight::BOLD),
9284                    ..HighlightStyle::default()
9285                },
9286                suggestions_style: HighlightStyle {
9287                    color: Some(cx.theme().status().predictive),
9288                    ..HighlightStyle::default()
9289                },
9290            },
9291        )
9292    }
9293}
9294
9295impl InputHandler for Editor {
9296    fn text_for_range(
9297        &mut self,
9298        range_utf16: Range<usize>,
9299        cx: &mut ViewContext<Self>,
9300    ) -> Option<String> {
9301        Some(
9302            self.buffer
9303                .read(cx)
9304                .read(cx)
9305                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
9306                .collect(),
9307        )
9308    }
9309
9310    fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
9311        // Prevent the IME menu from appearing when holding down an alphabetic key
9312        // while input is disabled.
9313        if !self.input_enabled {
9314            return None;
9315        }
9316
9317        let range = self.selections.newest::<OffsetUtf16>(cx).range();
9318        Some(range.start.0..range.end.0)
9319    }
9320
9321    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
9322        let snapshot = self.buffer.read(cx).read(cx);
9323        let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
9324        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
9325    }
9326
9327    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
9328        self.clear_highlights::<InputComposition>(cx);
9329        self.ime_transaction.take();
9330    }
9331
9332    fn replace_text_in_range(
9333        &mut self,
9334        range_utf16: Option<Range<usize>>,
9335        text: &str,
9336        cx: &mut ViewContext<Self>,
9337    ) {
9338        if !self.input_enabled {
9339            cx.emit(EditorEvent::InputIgnored { text: text.into() });
9340            return;
9341        }
9342
9343        self.transact(cx, |this, cx| {
9344            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
9345                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
9346                Some(this.selection_replacement_ranges(range_utf16, cx))
9347            } else {
9348                this.marked_text_ranges(cx)
9349            };
9350
9351            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
9352                let newest_selection_id = this.selections.newest_anchor().id;
9353                this.selections
9354                    .all::<OffsetUtf16>(cx)
9355                    .iter()
9356                    .zip(ranges_to_replace.iter())
9357                    .find_map(|(selection, range)| {
9358                        if selection.id == newest_selection_id {
9359                            Some(
9360                                (range.start.0 as isize - selection.head().0 as isize)
9361                                    ..(range.end.0 as isize - selection.head().0 as isize),
9362                            )
9363                        } else {
9364                            None
9365                        }
9366                    })
9367            });
9368
9369            cx.emit(EditorEvent::InputHandled {
9370                utf16_range_to_replace: range_to_replace,
9371                text: text.into(),
9372            });
9373
9374            if let Some(new_selected_ranges) = new_selected_ranges {
9375                this.change_selections(None, cx, |selections| {
9376                    selections.select_ranges(new_selected_ranges)
9377                });
9378            }
9379
9380            this.handle_input(text, cx);
9381        });
9382
9383        if let Some(transaction) = self.ime_transaction {
9384            self.buffer.update(cx, |buffer, cx| {
9385                buffer.group_until_transaction(transaction, cx);
9386            });
9387        }
9388
9389        self.unmark_text(cx);
9390    }
9391
9392    fn replace_and_mark_text_in_range(
9393        &mut self,
9394        range_utf16: Option<Range<usize>>,
9395        text: &str,
9396        new_selected_range_utf16: Option<Range<usize>>,
9397        cx: &mut ViewContext<Self>,
9398    ) {
9399        if !self.input_enabled {
9400            cx.emit(EditorEvent::InputIgnored { text: text.into() });
9401            return;
9402        }
9403
9404        let transaction = self.transact(cx, |this, cx| {
9405            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
9406                let snapshot = this.buffer.read(cx).read(cx);
9407                if let Some(relative_range_utf16) = range_utf16.as_ref() {
9408                    for marked_range in &mut marked_ranges {
9409                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
9410                        marked_range.start.0 += relative_range_utf16.start;
9411                        marked_range.start =
9412                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
9413                        marked_range.end =
9414                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
9415                    }
9416                }
9417                Some(marked_ranges)
9418            } else if let Some(range_utf16) = range_utf16 {
9419                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
9420                Some(this.selection_replacement_ranges(range_utf16, cx))
9421            } else {
9422                None
9423            };
9424
9425            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
9426                let newest_selection_id = this.selections.newest_anchor().id;
9427                this.selections
9428                    .all::<OffsetUtf16>(cx)
9429                    .iter()
9430                    .zip(ranges_to_replace.iter())
9431                    .find_map(|(selection, range)| {
9432                        if selection.id == newest_selection_id {
9433                            Some(
9434                                (range.start.0 as isize - selection.head().0 as isize)
9435                                    ..(range.end.0 as isize - selection.head().0 as isize),
9436                            )
9437                        } else {
9438                            None
9439                        }
9440                    })
9441            });
9442
9443            cx.emit(EditorEvent::InputHandled {
9444                utf16_range_to_replace: range_to_replace,
9445                text: text.into(),
9446            });
9447
9448            if let Some(ranges) = ranges_to_replace {
9449                this.change_selections(None, cx, |s| s.select_ranges(ranges));
9450            }
9451
9452            let marked_ranges = {
9453                let snapshot = this.buffer.read(cx).read(cx);
9454                this.selections
9455                    .disjoint_anchors()
9456                    .iter()
9457                    .map(|selection| {
9458                        selection.start.bias_left(&*snapshot)..selection.end.bias_right(&*snapshot)
9459                    })
9460                    .collect::<Vec<_>>()
9461            };
9462
9463            if text.is_empty() {
9464                this.unmark_text(cx);
9465            } else {
9466                this.highlight_text::<InputComposition>(
9467                    marked_ranges.clone(),
9468                    HighlightStyle::default(), // todo!() this.style(cx).composition_mark,
9469                    cx,
9470                );
9471            }
9472
9473            this.handle_input(text, cx);
9474
9475            if let Some(new_selected_range) = new_selected_range_utf16 {
9476                let snapshot = this.buffer.read(cx).read(cx);
9477                let new_selected_ranges = marked_ranges
9478                    .into_iter()
9479                    .map(|marked_range| {
9480                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
9481                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
9482                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
9483                        snapshot.clip_offset_utf16(new_start, Bias::Left)
9484                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
9485                    })
9486                    .collect::<Vec<_>>();
9487
9488                drop(snapshot);
9489                this.change_selections(None, cx, |selections| {
9490                    selections.select_ranges(new_selected_ranges)
9491                });
9492            }
9493        });
9494
9495        self.ime_transaction = self.ime_transaction.or(transaction);
9496        if let Some(transaction) = self.ime_transaction {
9497            self.buffer.update(cx, |buffer, cx| {
9498                buffer.group_until_transaction(transaction, cx);
9499            });
9500        }
9501
9502        if self.text_highlights::<InputComposition>(cx).is_none() {
9503            self.ime_transaction.take();
9504        }
9505    }
9506
9507    fn bounds_for_range(
9508        &mut self,
9509        range_utf16: Range<usize>,
9510        element_bounds: gpui::Bounds<Pixels>,
9511        cx: &mut ViewContext<Self>,
9512    ) -> Option<gpui::Bounds<Pixels>> {
9513        let text_layout_details = self.text_layout_details(cx);
9514        let style = &text_layout_details.editor_style;
9515        let font_id = cx.text_system().resolve_font(&style.text.font());
9516        let font_size = style.text.font_size.to_pixels(cx.rem_size());
9517        let line_height = style.text.line_height_in_pixels(cx.rem_size());
9518        let em_width = cx
9519            .text_system()
9520            .typographic_bounds(font_id, font_size, 'm')
9521            .unwrap()
9522            .size
9523            .width;
9524
9525        let snapshot = self.snapshot(cx);
9526        let scroll_position = snapshot.scroll_position();
9527        let scroll_left = scroll_position.x * em_width;
9528
9529        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
9530        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
9531            + self.gutter_width;
9532        let y = line_height * (start.row() as f32 - scroll_position.y);
9533
9534        Some(Bounds {
9535            origin: element_bounds.origin + point(x, y),
9536            size: size(em_width, line_height),
9537        })
9538    }
9539}
9540
9541trait SelectionExt {
9542    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize>;
9543    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point>;
9544    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
9545    fn spanned_rows(&self, include_end_if_at_line_start: bool, map: &DisplaySnapshot)
9546        -> Range<u32>;
9547}
9548
9549impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
9550    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
9551        let start = self.start.to_point(buffer);
9552        let end = self.end.to_point(buffer);
9553        if self.reversed {
9554            end..start
9555        } else {
9556            start..end
9557        }
9558    }
9559
9560    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
9561        let start = self.start.to_offset(buffer);
9562        let end = self.end.to_offset(buffer);
9563        if self.reversed {
9564            end..start
9565        } else {
9566            start..end
9567        }
9568    }
9569
9570    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
9571        let start = self
9572            .start
9573            .to_point(&map.buffer_snapshot)
9574            .to_display_point(map);
9575        let end = self
9576            .end
9577            .to_point(&map.buffer_snapshot)
9578            .to_display_point(map);
9579        if self.reversed {
9580            end..start
9581        } else {
9582            start..end
9583        }
9584    }
9585
9586    fn spanned_rows(
9587        &self,
9588        include_end_if_at_line_start: bool,
9589        map: &DisplaySnapshot,
9590    ) -> Range<u32> {
9591        let start = self.start.to_point(&map.buffer_snapshot);
9592        let mut end = self.end.to_point(&map.buffer_snapshot);
9593        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
9594            end.row -= 1;
9595        }
9596
9597        let buffer_start = map.prev_line_boundary(start).0;
9598        let buffer_end = map.next_line_boundary(end).0;
9599        buffer_start.row..buffer_end.row + 1
9600    }
9601}
9602
9603impl<T: InvalidationRegion> InvalidationStack<T> {
9604    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
9605    where
9606        S: Clone + ToOffset,
9607    {
9608        while let Some(region) = self.last() {
9609            let all_selections_inside_invalidation_ranges =
9610                if selections.len() == region.ranges().len() {
9611                    selections
9612                        .iter()
9613                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
9614                        .all(|(selection, invalidation_range)| {
9615                            let head = selection.head().to_offset(buffer);
9616                            invalidation_range.start <= head && invalidation_range.end >= head
9617                        })
9618                } else {
9619                    false
9620                };
9621
9622            if all_selections_inside_invalidation_ranges {
9623                break;
9624            } else {
9625                self.pop();
9626            }
9627        }
9628    }
9629}
9630
9631impl<T> Default for InvalidationStack<T> {
9632    fn default() -> Self {
9633        Self(Default::default())
9634    }
9635}
9636
9637impl<T> Deref for InvalidationStack<T> {
9638    type Target = Vec<T>;
9639
9640    fn deref(&self) -> &Self::Target {
9641        &self.0
9642    }
9643}
9644
9645impl<T> DerefMut for InvalidationStack<T> {
9646    fn deref_mut(&mut self) -> &mut Self::Target {
9647        &mut self.0
9648    }
9649}
9650
9651impl InvalidationRegion for SnippetState {
9652    fn ranges(&self) -> &[Range<Anchor>] {
9653        &self.ranges[self.active_index]
9654    }
9655}
9656
9657pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
9658    let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
9659
9660    Arc::new(move |cx: &mut BlockContext| {
9661        let color = Some(cx.theme().colors().text_accent);
9662        let group_id: SharedString = cx.block_id.to_string().into();
9663        // TODO: Nate: We should tint the background of the block with the severity color
9664        // We need to extend the theme before we can do this
9665        h_flex()
9666            .id(cx.block_id)
9667            .group(group_id.clone())
9668            .relative()
9669            .pl(cx.anchor_x)
9670            .size_full()
9671            .gap_2()
9672            .child(
9673                StyledText::new(text_without_backticks.clone()).with_highlights(
9674                    &cx.text_style(),
9675                    code_ranges.iter().map(|range| {
9676                        (
9677                            range.clone(),
9678                            HighlightStyle {
9679                                color,
9680                                ..Default::default()
9681                            },
9682                        )
9683                    }),
9684                ),
9685            )
9686            .child(
9687                IconButton::new(("copy-block", cx.block_id), IconName::Copy)
9688                    .icon_color(Color::Muted)
9689                    .size(ButtonSize::Compact)
9690                    .style(ButtonStyle::Transparent)
9691                    .visible_on_hover(group_id)
9692                    .on_click(cx.listener({
9693                        let message = diagnostic.message.clone();
9694                        move |_, _, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
9695                    }))
9696                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
9697            )
9698            .into_any_element()
9699    })
9700}
9701
9702pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
9703    let mut text_without_backticks = String::new();
9704    let mut code_ranges = Vec::new();
9705
9706    if let Some(source) = &diagnostic.source {
9707        text_without_backticks.push_str(&source);
9708        code_ranges.push(0..source.len());
9709        text_without_backticks.push_str(": ");
9710    }
9711
9712    let mut prev_offset = 0;
9713    let mut in_code_block = false;
9714    for (ix, _) in diagnostic
9715        .message
9716        .match_indices('`')
9717        .chain([(diagnostic.message.len(), "")])
9718    {
9719        let prev_len = text_without_backticks.len();
9720        text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
9721        prev_offset = ix + 1;
9722        if in_code_block {
9723            code_ranges.push(prev_len..text_without_backticks.len());
9724            in_code_block = false;
9725        } else {
9726            in_code_block = true;
9727        }
9728    }
9729
9730    (text_without_backticks.into(), code_ranges)
9731}
9732
9733fn diagnostic_style(severity: DiagnosticSeverity, valid: bool, colors: &StatusColors) -> Hsla {
9734    match (severity, valid) {
9735        (DiagnosticSeverity::ERROR, true) => colors.error,
9736        (DiagnosticSeverity::ERROR, false) => colors.error,
9737        (DiagnosticSeverity::WARNING, true) => colors.warning,
9738        (DiagnosticSeverity::WARNING, false) => colors.warning,
9739        (DiagnosticSeverity::INFORMATION, true) => colors.info,
9740        (DiagnosticSeverity::INFORMATION, false) => colors.info,
9741        (DiagnosticSeverity::HINT, true) => colors.info,
9742        (DiagnosticSeverity::HINT, false) => colors.info,
9743        _ => colors.ignored,
9744    }
9745}
9746
9747pub fn styled_runs_for_code_label<'a>(
9748    label: &'a CodeLabel,
9749    syntax_theme: &'a theme::SyntaxTheme,
9750) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
9751    let fade_out = HighlightStyle {
9752        fade_out: Some(0.35),
9753        ..Default::default()
9754    };
9755
9756    let mut prev_end = label.filter_range.end;
9757    label
9758        .runs
9759        .iter()
9760        .enumerate()
9761        .flat_map(move |(ix, (range, highlight_id))| {
9762            let style = if let Some(style) = highlight_id.style(syntax_theme) {
9763                style
9764            } else {
9765                return Default::default();
9766            };
9767            let mut muted_style = style;
9768            muted_style.highlight(fade_out);
9769
9770            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
9771            if range.start >= label.filter_range.end {
9772                if range.start > prev_end {
9773                    runs.push((prev_end..range.start, fade_out));
9774                }
9775                runs.push((range.clone(), muted_style));
9776            } else if range.end <= label.filter_range.end {
9777                runs.push((range.clone(), style));
9778            } else {
9779                runs.push((range.start..label.filter_range.end, style));
9780                runs.push((label.filter_range.end..range.end, muted_style));
9781            }
9782            prev_end = cmp::max(prev_end, range.end);
9783
9784            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
9785                runs.push((prev_end..label.text.len(), fade_out));
9786            }
9787
9788            runs
9789        })
9790}
9791
9792pub(crate) fn split_words<'a>(text: &'a str) -> impl std::iter::Iterator<Item = &'a str> + 'a {
9793    let mut index = 0;
9794    let mut codepoints = text.char_indices().peekable();
9795
9796    std::iter::from_fn(move || {
9797        let start_index = index;
9798        while let Some((new_index, codepoint)) = codepoints.next() {
9799            index = new_index + codepoint.len_utf8();
9800            let current_upper = codepoint.is_uppercase();
9801            let next_upper = codepoints
9802                .peek()
9803                .map(|(_, c)| c.is_uppercase())
9804                .unwrap_or(false);
9805
9806            if !current_upper && next_upper {
9807                return Some(&text[start_index..index]);
9808            }
9809        }
9810
9811        index = text.len();
9812        if start_index < text.len() {
9813            return Some(&text[start_index..]);
9814        }
9815        None
9816    })
9817    .flat_map(|word| word.split_inclusive('_'))
9818    .flat_map(|word| word.split_inclusive('-'))
9819}
9820
9821trait RangeToAnchorExt {
9822    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
9823}
9824
9825impl<T: ToOffset> RangeToAnchorExt for Range<T> {
9826    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
9827        snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
9828    }
9829}