editor.rs

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