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 clock::ReplicaId;
  12pub use display_map::DisplayPoint;
  13use display_map::*;
  14pub use element::*;
  15use gpui::{
  16    action,
  17    elements::Text,
  18    geometry::vector::{vec2f, Vector2F},
  19    keymap::Binding,
  20    text_layout, AppContext, ClipboardItem, Element, ElementBox, Entity, ModelHandle,
  21    MutableAppContext, RenderContext, View, ViewContext, WeakViewHandle,
  22};
  23use items::BufferItemHandle;
  24use language::{
  25    BracketPair, Buffer, Diagnostic, DiagnosticSeverity, Language, Point, Selection, SelectionGoal,
  26    TransactionId,
  27};
  28pub use multi_buffer::MultiBuffer;
  29use multi_buffer::{
  30    Anchor, AnchorRangeExt, MultiBufferChunks, MultiBufferSnapshot, ToOffset, ToPoint,
  31};
  32use serde::{Deserialize, Serialize};
  33use smallvec::SmallVec;
  34use smol::Timer;
  35use std::{
  36    cell::RefCell,
  37    cmp,
  38    collections::HashMap,
  39    iter::{self, FromIterator},
  40    mem,
  41    ops::{Deref, Range, RangeInclusive, Sub},
  42    rc::Rc,
  43    sync::Arc,
  44    time::{Duration, Instant},
  45};
  46use sum_tree::Bias;
  47use text::rope::TextDimension;
  48use theme::{DiagnosticStyle, EditorStyle};
  49use util::post_inc;
  50use workspace::{EntryOpener, Workspace};
  51
  52const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  53const MAX_LINE_LEN: usize = 1024;
  54
  55action!(Cancel);
  56action!(Backspace);
  57action!(Delete);
  58action!(Input, String);
  59action!(Newline);
  60action!(Tab);
  61action!(Outdent);
  62action!(DeleteLine);
  63action!(DeleteToPreviousWordBoundary);
  64action!(DeleteToNextWordBoundary);
  65action!(DeleteToBeginningOfLine);
  66action!(DeleteToEndOfLine);
  67action!(CutToEndOfLine);
  68action!(DuplicateLine);
  69action!(MoveLineUp);
  70action!(MoveLineDown);
  71action!(Cut);
  72action!(Copy);
  73action!(Paste);
  74action!(Undo);
  75action!(Redo);
  76action!(MoveUp);
  77action!(MoveDown);
  78action!(MoveLeft);
  79action!(MoveRight);
  80action!(MoveToPreviousWordBoundary);
  81action!(MoveToNextWordBoundary);
  82action!(MoveToBeginningOfLine);
  83action!(MoveToEndOfLine);
  84action!(MoveToBeginning);
  85action!(MoveToEnd);
  86action!(SelectUp);
  87action!(SelectDown);
  88action!(SelectLeft);
  89action!(SelectRight);
  90action!(SelectToPreviousWordBoundary);
  91action!(SelectToNextWordBoundary);
  92action!(SelectToBeginningOfLine, bool);
  93action!(SelectToEndOfLine);
  94action!(SelectToBeginning);
  95action!(SelectToEnd);
  96action!(SelectAll);
  97action!(SelectLine);
  98action!(SplitSelectionIntoLines);
  99action!(AddSelectionAbove);
 100action!(AddSelectionBelow);
 101action!(SelectNext, bool);
 102action!(ToggleComments);
 103action!(SelectLargerSyntaxNode);
 104action!(SelectSmallerSyntaxNode);
 105action!(MoveToEnclosingBracket);
 106action!(ShowNextDiagnostic);
 107action!(PageUp);
 108action!(PageDown);
 109action!(Fold);
 110action!(Unfold);
 111action!(FoldSelectedRanges);
 112action!(Scroll, Vector2F);
 113action!(Select, SelectPhase);
 114
 115pub fn init(cx: &mut MutableAppContext, entry_openers: &mut Vec<Box<dyn EntryOpener>>) {
 116    entry_openers.push(Box::new(items::BufferOpener));
 117    cx.add_bindings(vec![
 118        Binding::new("escape", Cancel, Some("Editor")),
 119        Binding::new("backspace", Backspace, Some("Editor")),
 120        Binding::new("ctrl-h", Backspace, Some("Editor")),
 121        Binding::new("delete", Delete, Some("Editor")),
 122        Binding::new("ctrl-d", Delete, Some("Editor")),
 123        Binding::new("enter", Newline, Some("Editor && mode == full")),
 124        Binding::new(
 125            "alt-enter",
 126            Input("\n".into()),
 127            Some("Editor && mode == auto_height"),
 128        ),
 129        Binding::new("tab", Tab, Some("Editor")),
 130        Binding::new("shift-tab", Outdent, Some("Editor")),
 131        Binding::new("ctrl-shift-K", DeleteLine, Some("Editor")),
 132        Binding::new(
 133            "alt-backspace",
 134            DeleteToPreviousWordBoundary,
 135            Some("Editor"),
 136        ),
 137        Binding::new("alt-h", DeleteToPreviousWordBoundary, Some("Editor")),
 138        Binding::new("alt-delete", DeleteToNextWordBoundary, Some("Editor")),
 139        Binding::new("alt-d", DeleteToNextWordBoundary, Some("Editor")),
 140        Binding::new("cmd-backspace", DeleteToBeginningOfLine, Some("Editor")),
 141        Binding::new("cmd-delete", DeleteToEndOfLine, Some("Editor")),
 142        Binding::new("ctrl-k", CutToEndOfLine, Some("Editor")),
 143        Binding::new("cmd-shift-D", DuplicateLine, Some("Editor")),
 144        Binding::new("ctrl-cmd-up", MoveLineUp, Some("Editor")),
 145        Binding::new("ctrl-cmd-down", MoveLineDown, Some("Editor")),
 146        Binding::new("cmd-x", Cut, Some("Editor")),
 147        Binding::new("cmd-c", Copy, Some("Editor")),
 148        Binding::new("cmd-v", Paste, Some("Editor")),
 149        Binding::new("cmd-z", Undo, Some("Editor")),
 150        Binding::new("cmd-shift-Z", Redo, Some("Editor")),
 151        Binding::new("up", MoveUp, Some("Editor")),
 152        Binding::new("down", MoveDown, Some("Editor")),
 153        Binding::new("left", MoveLeft, Some("Editor")),
 154        Binding::new("right", MoveRight, Some("Editor")),
 155        Binding::new("ctrl-p", MoveUp, Some("Editor")),
 156        Binding::new("ctrl-n", MoveDown, Some("Editor")),
 157        Binding::new("ctrl-b", MoveLeft, Some("Editor")),
 158        Binding::new("ctrl-f", MoveRight, Some("Editor")),
 159        Binding::new("alt-left", MoveToPreviousWordBoundary, Some("Editor")),
 160        Binding::new("alt-b", MoveToPreviousWordBoundary, Some("Editor")),
 161        Binding::new("alt-right", MoveToNextWordBoundary, Some("Editor")),
 162        Binding::new("alt-f", MoveToNextWordBoundary, Some("Editor")),
 163        Binding::new("cmd-left", MoveToBeginningOfLine, Some("Editor")),
 164        Binding::new("ctrl-a", MoveToBeginningOfLine, Some("Editor")),
 165        Binding::new("cmd-right", MoveToEndOfLine, Some("Editor")),
 166        Binding::new("ctrl-e", MoveToEndOfLine, Some("Editor")),
 167        Binding::new("cmd-up", MoveToBeginning, Some("Editor")),
 168        Binding::new("cmd-down", MoveToEnd, Some("Editor")),
 169        Binding::new("shift-up", SelectUp, Some("Editor")),
 170        Binding::new("ctrl-shift-P", SelectUp, Some("Editor")),
 171        Binding::new("shift-down", SelectDown, Some("Editor")),
 172        Binding::new("ctrl-shift-N", SelectDown, Some("Editor")),
 173        Binding::new("shift-left", SelectLeft, Some("Editor")),
 174        Binding::new("ctrl-shift-B", SelectLeft, Some("Editor")),
 175        Binding::new("shift-right", SelectRight, Some("Editor")),
 176        Binding::new("ctrl-shift-F", SelectRight, Some("Editor")),
 177        Binding::new(
 178            "alt-shift-left",
 179            SelectToPreviousWordBoundary,
 180            Some("Editor"),
 181        ),
 182        Binding::new("alt-shift-B", SelectToPreviousWordBoundary, Some("Editor")),
 183        Binding::new("alt-shift-right", SelectToNextWordBoundary, Some("Editor")),
 184        Binding::new("alt-shift-F", SelectToNextWordBoundary, Some("Editor")),
 185        Binding::new(
 186            "cmd-shift-left",
 187            SelectToBeginningOfLine(true),
 188            Some("Editor"),
 189        ),
 190        Binding::new(
 191            "ctrl-shift-A",
 192            SelectToBeginningOfLine(true),
 193            Some("Editor"),
 194        ),
 195        Binding::new("cmd-shift-right", SelectToEndOfLine, Some("Editor")),
 196        Binding::new("ctrl-shift-E", SelectToEndOfLine, Some("Editor")),
 197        Binding::new("cmd-shift-up", SelectToBeginning, Some("Editor")),
 198        Binding::new("cmd-shift-down", SelectToEnd, Some("Editor")),
 199        Binding::new("cmd-a", SelectAll, Some("Editor")),
 200        Binding::new("cmd-l", SelectLine, Some("Editor")),
 201        Binding::new("cmd-shift-L", SplitSelectionIntoLines, Some("Editor")),
 202        Binding::new("cmd-alt-up", AddSelectionAbove, Some("Editor")),
 203        Binding::new("cmd-ctrl-p", AddSelectionAbove, Some("Editor")),
 204        Binding::new("cmd-alt-down", AddSelectionBelow, Some("Editor")),
 205        Binding::new("cmd-ctrl-n", AddSelectionBelow, Some("Editor")),
 206        Binding::new("cmd-d", SelectNext(false), Some("Editor")),
 207        Binding::new("cmd-k cmd-d", SelectNext(true), Some("Editor")),
 208        Binding::new("cmd-/", ToggleComments, Some("Editor")),
 209        Binding::new("alt-up", SelectLargerSyntaxNode, Some("Editor")),
 210        Binding::new("ctrl-w", SelectLargerSyntaxNode, Some("Editor")),
 211        Binding::new("alt-down", SelectSmallerSyntaxNode, Some("Editor")),
 212        Binding::new("ctrl-shift-W", SelectSmallerSyntaxNode, Some("Editor")),
 213        Binding::new("f8", ShowNextDiagnostic, Some("Editor")),
 214        Binding::new("ctrl-m", MoveToEnclosingBracket, Some("Editor")),
 215        Binding::new("pageup", PageUp, Some("Editor")),
 216        Binding::new("pagedown", PageDown, Some("Editor")),
 217        Binding::new("alt-cmd-[", Fold, Some("Editor")),
 218        Binding::new("alt-cmd-]", Unfold, Some("Editor")),
 219        Binding::new("alt-cmd-f", FoldSelectedRanges, Some("Editor")),
 220    ]);
 221
 222    cx.add_action(Editor::open_new);
 223    cx.add_action(|this: &mut Editor, action: &Scroll, cx| this.set_scroll_position(action.0, cx));
 224    cx.add_action(Editor::select);
 225    cx.add_action(Editor::cancel);
 226    cx.add_action(Editor::handle_input);
 227    cx.add_action(Editor::newline);
 228    cx.add_action(Editor::backspace);
 229    cx.add_action(Editor::delete);
 230    cx.add_action(Editor::tab);
 231    cx.add_action(Editor::outdent);
 232    cx.add_action(Editor::delete_line);
 233    cx.add_action(Editor::delete_to_previous_word_boundary);
 234    cx.add_action(Editor::delete_to_next_word_boundary);
 235    cx.add_action(Editor::delete_to_beginning_of_line);
 236    cx.add_action(Editor::delete_to_end_of_line);
 237    cx.add_action(Editor::cut_to_end_of_line);
 238    cx.add_action(Editor::duplicate_line);
 239    cx.add_action(Editor::move_line_up);
 240    cx.add_action(Editor::move_line_down);
 241    cx.add_action(Editor::cut);
 242    cx.add_action(Editor::copy);
 243    cx.add_action(Editor::paste);
 244    cx.add_action(Editor::undo);
 245    cx.add_action(Editor::redo);
 246    cx.add_action(Editor::move_up);
 247    cx.add_action(Editor::move_down);
 248    cx.add_action(Editor::move_left);
 249    cx.add_action(Editor::move_right);
 250    cx.add_action(Editor::move_to_previous_word_boundary);
 251    cx.add_action(Editor::move_to_next_word_boundary);
 252    cx.add_action(Editor::move_to_beginning_of_line);
 253    cx.add_action(Editor::move_to_end_of_line);
 254    cx.add_action(Editor::move_to_beginning);
 255    cx.add_action(Editor::move_to_end);
 256    cx.add_action(Editor::select_up);
 257    cx.add_action(Editor::select_down);
 258    cx.add_action(Editor::select_left);
 259    cx.add_action(Editor::select_right);
 260    cx.add_action(Editor::select_to_previous_word_boundary);
 261    cx.add_action(Editor::select_to_next_word_boundary);
 262    cx.add_action(Editor::select_to_beginning_of_line);
 263    cx.add_action(Editor::select_to_end_of_line);
 264    cx.add_action(Editor::select_to_beginning);
 265    cx.add_action(Editor::select_to_end);
 266    cx.add_action(Editor::select_all);
 267    cx.add_action(Editor::select_line);
 268    cx.add_action(Editor::split_selection_into_lines);
 269    cx.add_action(Editor::add_selection_above);
 270    cx.add_action(Editor::add_selection_below);
 271    cx.add_action(Editor::select_next);
 272    cx.add_action(Editor::toggle_comments);
 273    cx.add_action(Editor::select_larger_syntax_node);
 274    cx.add_action(Editor::select_smaller_syntax_node);
 275    cx.add_action(Editor::move_to_enclosing_bracket);
 276    cx.add_action(Editor::show_next_diagnostic);
 277    cx.add_action(Editor::page_up);
 278    cx.add_action(Editor::page_down);
 279    cx.add_action(Editor::fold);
 280    cx.add_action(Editor::unfold);
 281    cx.add_action(Editor::fold_selected_ranges);
 282}
 283
 284trait SelectionExt {
 285    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize>;
 286    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point>;
 287    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
 288    fn spanned_rows(
 289        &self,
 290        include_end_if_at_line_start: bool,
 291        map: &DisplaySnapshot,
 292    ) -> SpannedRows;
 293}
 294
 295struct SpannedRows {
 296    buffer_rows: Range<u32>,
 297    display_rows: Range<u32>,
 298}
 299
 300#[derive(Clone, Debug)]
 301pub enum SelectPhase {
 302    Begin {
 303        position: DisplayPoint,
 304        add: bool,
 305        click_count: usize,
 306    },
 307    BeginColumnar {
 308        position: DisplayPoint,
 309        overshoot: u32,
 310    },
 311    Extend {
 312        position: DisplayPoint,
 313        click_count: usize,
 314    },
 315    Update {
 316        position: DisplayPoint,
 317        overshoot: u32,
 318        scroll_position: Vector2F,
 319    },
 320    End,
 321}
 322
 323#[derive(Clone, Debug)]
 324enum SelectMode {
 325    Character,
 326    Word(Range<Anchor>),
 327    Line(Range<Anchor>),
 328    All,
 329}
 330
 331#[derive(PartialEq, Eq)]
 332pub enum Autoscroll {
 333    Fit,
 334    Center,
 335    Newest,
 336}
 337
 338#[derive(Copy, Clone, PartialEq, Eq)]
 339pub enum EditorMode {
 340    SingleLine,
 341    AutoHeight { max_lines: usize },
 342    Full,
 343}
 344
 345#[derive(Clone)]
 346pub struct EditorSettings {
 347    pub tab_size: usize,
 348    pub soft_wrap: SoftWrap,
 349    pub style: EditorStyle,
 350}
 351
 352#[derive(Clone)]
 353pub enum SoftWrap {
 354    None,
 355    EditorWidth,
 356    Column(u32),
 357}
 358
 359pub struct Editor {
 360    handle: WeakViewHandle<Self>,
 361    buffer: ModelHandle<MultiBuffer>,
 362    display_map: ModelHandle<DisplayMap>,
 363    next_selection_id: usize,
 364    selections: Arc<[Selection<Anchor>]>,
 365    pending_selection: Option<PendingSelection>,
 366    columnar_selection_tail: Option<Anchor>,
 367    add_selections_state: Option<AddSelectionsState>,
 368    select_next_state: Option<SelectNextState>,
 369    selection_history:
 370        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
 371    autoclose_stack: Vec<BracketPairState>,
 372    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
 373    active_diagnostics: Option<ActiveDiagnosticGroup>,
 374    scroll_position: Vector2F,
 375    scroll_top_anchor: Anchor,
 376    autoscroll_request: Option<Autoscroll>,
 377    build_settings: Rc<RefCell<dyn Fn(&AppContext) -> EditorSettings>>,
 378    focused: bool,
 379    show_local_cursors: bool,
 380    blink_epoch: usize,
 381    blinking_paused: bool,
 382    mode: EditorMode,
 383    placeholder_text: Option<Arc<str>>,
 384    highlighted_row: Option<u32>,
 385}
 386
 387pub struct EditorSnapshot {
 388    pub mode: EditorMode,
 389    pub display_snapshot: DisplaySnapshot,
 390    pub placeholder_text: Option<Arc<str>>,
 391    is_focused: bool,
 392    scroll_position: Vector2F,
 393    scroll_top_anchor: Anchor,
 394}
 395
 396struct PendingSelection {
 397    selection: Selection<Anchor>,
 398    mode: SelectMode,
 399}
 400
 401struct AddSelectionsState {
 402    above: bool,
 403    stack: Vec<usize>,
 404}
 405
 406struct SelectNextState {
 407    query: AhoCorasick,
 408    wordwise: bool,
 409    done: bool,
 410}
 411
 412#[derive(Debug)]
 413struct BracketPairState {
 414    ranges: Vec<Range<Anchor>>,
 415    pair: BracketPair,
 416}
 417
 418#[derive(Debug)]
 419struct ActiveDiagnosticGroup {
 420    primary_range: Range<Anchor>,
 421    primary_message: String,
 422    blocks: HashMap<BlockId, Diagnostic>,
 423    is_valid: bool,
 424}
 425
 426#[derive(Serialize, Deserialize)]
 427struct ClipboardSelection {
 428    len: usize,
 429    is_entire_line: bool,
 430}
 431
 432impl Editor {
 433    pub fn single_line(
 434        build_settings: impl 'static + Fn(&AppContext) -> EditorSettings,
 435        cx: &mut ViewContext<Self>,
 436    ) -> Self {
 437        let buffer = cx.add_model(|cx| Buffer::new(0, String::new(), cx));
 438        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
 439        let mut view = Self::for_buffer(buffer, build_settings, cx);
 440        view.mode = EditorMode::SingleLine;
 441        view
 442    }
 443
 444    pub fn auto_height(
 445        max_lines: usize,
 446        build_settings: impl 'static + Fn(&AppContext) -> EditorSettings,
 447        cx: &mut ViewContext<Self>,
 448    ) -> Self {
 449        let buffer = cx.add_model(|cx| Buffer::new(0, String::new(), cx));
 450        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
 451        let mut view = Self::for_buffer(buffer, build_settings, cx);
 452        view.mode = EditorMode::AutoHeight { max_lines };
 453        view
 454    }
 455
 456    pub fn for_buffer(
 457        buffer: ModelHandle<MultiBuffer>,
 458        build_settings: impl 'static + Fn(&AppContext) -> EditorSettings,
 459        cx: &mut ViewContext<Self>,
 460    ) -> Self {
 461        Self::new(buffer, Rc::new(RefCell::new(build_settings)), cx)
 462    }
 463
 464    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 465        let mut clone = Self::new(self.buffer.clone(), self.build_settings.clone(), cx);
 466        clone.scroll_position = self.scroll_position;
 467        clone.scroll_top_anchor = self.scroll_top_anchor.clone();
 468        clone
 469    }
 470
 471    pub fn new(
 472        buffer: ModelHandle<MultiBuffer>,
 473        build_settings: Rc<RefCell<dyn Fn(&AppContext) -> EditorSettings>>,
 474        cx: &mut ViewContext<Self>,
 475    ) -> Self {
 476        let settings = build_settings.borrow_mut()(cx);
 477        let display_map = cx.add_model(|cx| {
 478            DisplayMap::new(
 479                buffer.clone(),
 480                settings.tab_size,
 481                settings.style.text.font_id,
 482                settings.style.text.font_size,
 483                None,
 484                cx,
 485            )
 486        });
 487        cx.observe(&buffer, Self::on_buffer_changed).detach();
 488        cx.subscribe(&buffer, Self::on_buffer_event).detach();
 489        cx.observe(&display_map, Self::on_display_map_changed)
 490            .detach();
 491
 492        let mut next_selection_id = 0;
 493        let selections = Arc::from(
 494            &[Selection {
 495                id: post_inc(&mut next_selection_id),
 496                start: Anchor::min(),
 497                end: Anchor::min(),
 498                reversed: false,
 499                goal: SelectionGoal::None,
 500            }][..],
 501        );
 502
 503        Self {
 504            handle: cx.weak_handle(),
 505            buffer,
 506            display_map,
 507            selections,
 508            pending_selection: None,
 509            columnar_selection_tail: None,
 510            next_selection_id,
 511            add_selections_state: None,
 512            select_next_state: None,
 513            selection_history: Default::default(),
 514            autoclose_stack: Default::default(),
 515            select_larger_syntax_node_stack: Vec::new(),
 516            active_diagnostics: None,
 517            build_settings,
 518            scroll_position: Vector2F::zero(),
 519            scroll_top_anchor: Anchor::min(),
 520            autoscroll_request: None,
 521            focused: false,
 522            show_local_cursors: false,
 523            blink_epoch: 0,
 524            blinking_paused: false,
 525            mode: EditorMode::Full,
 526            placeholder_text: None,
 527            highlighted_row: None,
 528        }
 529    }
 530
 531    pub fn open_new(
 532        workspace: &mut Workspace,
 533        _: &workspace::OpenNew,
 534        cx: &mut ViewContext<Workspace>,
 535    ) {
 536        let buffer = cx.add_model(|cx| {
 537            Buffer::new(0, "", cx).with_language(Some(language::PLAIN_TEXT.clone()), None, cx)
 538        });
 539        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
 540        workspace.add_item(BufferItemHandle(buffer), cx);
 541    }
 542
 543    pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
 544        self.buffer.read(cx).replica_id()
 545    }
 546
 547    pub fn buffer(&self) -> &ModelHandle<MultiBuffer> {
 548        &self.buffer
 549    }
 550
 551    pub fn snapshot(&mut self, cx: &mut MutableAppContext) -> EditorSnapshot {
 552        EditorSnapshot {
 553            mode: self.mode,
 554            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 555            scroll_position: self.scroll_position,
 556            scroll_top_anchor: self.scroll_top_anchor.clone(),
 557            placeholder_text: self.placeholder_text.clone(),
 558            is_focused: self
 559                .handle
 560                .upgrade(cx)
 561                .map_or(false, |handle| handle.is_focused(cx)),
 562        }
 563    }
 564
 565    pub fn language<'a>(&self, cx: &'a AppContext) -> Option<&'a Arc<Language>> {
 566        self.buffer.read(cx).language(cx)
 567    }
 568
 569    pub fn set_placeholder_text(
 570        &mut self,
 571        placeholder_text: impl Into<Arc<str>>,
 572        cx: &mut ViewContext<Self>,
 573    ) {
 574        self.placeholder_text = Some(placeholder_text.into());
 575        cx.notify();
 576    }
 577
 578    pub fn set_scroll_position(&mut self, scroll_position: Vector2F, cx: &mut ViewContext<Self>) {
 579        let map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 580        let scroll_top_buffer_offset =
 581            DisplayPoint::new(scroll_position.y() as u32, 0).to_offset(&map, Bias::Right);
 582        self.scroll_top_anchor = map
 583            .buffer_snapshot
 584            .anchor_at(scroll_top_buffer_offset, Bias::Right);
 585        self.scroll_position = vec2f(
 586            scroll_position.x(),
 587            scroll_position.y() - self.scroll_top_anchor.to_display_point(&map).row() as f32,
 588        );
 589
 590        debug_assert_eq!(
 591            compute_scroll_position(&map, self.scroll_position, &self.scroll_top_anchor),
 592            scroll_position
 593        );
 594
 595        cx.notify();
 596    }
 597
 598    pub fn scroll_position(&self, cx: &mut ViewContext<Self>) -> Vector2F {
 599        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 600        compute_scroll_position(&display_map, self.scroll_position, &self.scroll_top_anchor)
 601    }
 602
 603    pub fn clamp_scroll_left(&mut self, max: f32) -> bool {
 604        if max < self.scroll_position.x() {
 605            self.scroll_position.set_x(max);
 606            true
 607        } else {
 608            false
 609        }
 610    }
 611
 612    pub fn autoscroll_vertically(
 613        &mut self,
 614        viewport_height: f32,
 615        line_height: f32,
 616        cx: &mut ViewContext<Self>,
 617    ) -> bool {
 618        let visible_lines = viewport_height / line_height;
 619        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 620        let mut scroll_position =
 621            compute_scroll_position(&display_map, self.scroll_position, &self.scroll_top_anchor);
 622        let max_scroll_top = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
 623            (display_map.max_point().row() as f32 - visible_lines + 1.).max(0.)
 624        } else {
 625            display_map.max_point().row().saturating_sub(1) as f32
 626        };
 627        if scroll_position.y() > max_scroll_top {
 628            scroll_position.set_y(max_scroll_top);
 629            self.set_scroll_position(scroll_position, cx);
 630        }
 631
 632        let autoscroll = if let Some(autoscroll) = self.autoscroll_request.take() {
 633            autoscroll
 634        } else {
 635            return false;
 636        };
 637
 638        let first_cursor_top;
 639        let last_cursor_bottom;
 640        if autoscroll == Autoscroll::Newest {
 641            let newest_selection = self.newest_selection::<Point>(&display_map.buffer_snapshot);
 642            first_cursor_top = newest_selection.head().to_display_point(&display_map).row() as f32;
 643            last_cursor_bottom = first_cursor_top + 1.;
 644        } else {
 645            let selections = self.local_selections::<Point>(cx);
 646            first_cursor_top = selections
 647                .first()
 648                .unwrap()
 649                .head()
 650                .to_display_point(&display_map)
 651                .row() as f32;
 652            last_cursor_bottom = selections
 653                .last()
 654                .unwrap()
 655                .head()
 656                .to_display_point(&display_map)
 657                .row() as f32
 658                + 1.0;
 659        }
 660
 661        let margin = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
 662            0.
 663        } else {
 664            ((visible_lines - (last_cursor_bottom - first_cursor_top)) / 2.0).floor()
 665        };
 666        if margin < 0.0 {
 667            return false;
 668        }
 669
 670        match autoscroll {
 671            Autoscroll::Fit | Autoscroll::Newest => {
 672                let margin = margin.min(3.0);
 673                let target_top = (first_cursor_top - margin).max(0.0);
 674                let target_bottom = last_cursor_bottom + margin;
 675                let start_row = scroll_position.y();
 676                let end_row = start_row + visible_lines;
 677
 678                if target_top < start_row {
 679                    scroll_position.set_y(target_top);
 680                    self.set_scroll_position(scroll_position, cx);
 681                } else if target_bottom >= end_row {
 682                    scroll_position.set_y(target_bottom - visible_lines);
 683                    self.set_scroll_position(scroll_position, cx);
 684                }
 685            }
 686            Autoscroll::Center => {
 687                scroll_position.set_y((first_cursor_top - margin).max(0.0));
 688                self.set_scroll_position(scroll_position, cx);
 689            }
 690        }
 691
 692        true
 693    }
 694
 695    pub fn autoscroll_horizontally(
 696        &mut self,
 697        start_row: u32,
 698        viewport_width: f32,
 699        scroll_width: f32,
 700        max_glyph_width: f32,
 701        layouts: &[text_layout::Line],
 702        cx: &mut ViewContext<Self>,
 703    ) -> bool {
 704        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 705        let selections = self.local_selections::<Point>(cx);
 706        let mut target_left = std::f32::INFINITY;
 707        let mut target_right = 0.0_f32;
 708        for selection in selections {
 709            let head = selection.head().to_display_point(&display_map);
 710            if head.row() >= start_row && head.row() < start_row + layouts.len() as u32 {
 711                let start_column = head.column().saturating_sub(3);
 712                let end_column = cmp::min(display_map.line_len(head.row()), head.column() + 3);
 713                target_left = target_left.min(
 714                    layouts[(head.row() - start_row) as usize].x_for_index(start_column as usize),
 715                );
 716                target_right = target_right.max(
 717                    layouts[(head.row() - start_row) as usize].x_for_index(end_column as usize)
 718                        + max_glyph_width,
 719                );
 720            }
 721        }
 722        target_right = target_right.min(scroll_width);
 723
 724        if target_right - target_left > viewport_width {
 725            return false;
 726        }
 727
 728        let scroll_left = self.scroll_position.x() * max_glyph_width;
 729        let scroll_right = scroll_left + viewport_width;
 730
 731        if target_left < scroll_left {
 732            self.scroll_position.set_x(target_left / max_glyph_width);
 733            true
 734        } else if target_right > scroll_right {
 735            self.scroll_position
 736                .set_x((target_right - viewport_width) / max_glyph_width);
 737            true
 738        } else {
 739            false
 740        }
 741    }
 742
 743    fn select(&mut self, Select(phase): &Select, cx: &mut ViewContext<Self>) {
 744        match phase {
 745            SelectPhase::Begin {
 746                position,
 747                add,
 748                click_count,
 749            } => self.begin_selection(*position, *add, *click_count, cx),
 750            SelectPhase::BeginColumnar {
 751                position,
 752                overshoot,
 753            } => self.begin_columnar_selection(*position, *overshoot, cx),
 754            SelectPhase::Extend {
 755                position,
 756                click_count,
 757            } => self.extend_selection(*position, *click_count, cx),
 758            SelectPhase::Update {
 759                position,
 760                overshoot,
 761                scroll_position,
 762            } => self.update_selection(*position, *overshoot, *scroll_position, cx),
 763            SelectPhase::End => self.end_selection(cx),
 764        }
 765    }
 766
 767    fn extend_selection(
 768        &mut self,
 769        position: DisplayPoint,
 770        click_count: usize,
 771        cx: &mut ViewContext<Self>,
 772    ) {
 773        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 774        let tail = self
 775            .newest_selection::<usize>(&display_map.buffer_snapshot)
 776            .tail();
 777        self.begin_selection(position, false, click_count, cx);
 778
 779        let position = position.to_offset(&display_map, Bias::Left);
 780        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 781        let pending = self.pending_selection.as_mut().unwrap();
 782
 783        if position >= tail {
 784            pending.selection.start = tail_anchor.clone();
 785        } else {
 786            pending.selection.end = tail_anchor.clone();
 787            pending.selection.reversed = true;
 788        }
 789
 790        match &mut pending.mode {
 791            SelectMode::Word(range) | SelectMode::Line(range) => {
 792                *range = tail_anchor.clone()..tail_anchor
 793            }
 794            _ => {}
 795        }
 796    }
 797
 798    fn begin_selection(
 799        &mut self,
 800        position: DisplayPoint,
 801        add: bool,
 802        click_count: usize,
 803        cx: &mut ViewContext<Self>,
 804    ) {
 805        if !self.focused {
 806            cx.focus_self();
 807            cx.emit(Event::Activate);
 808        }
 809
 810        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 811        let buffer = &display_map.buffer_snapshot;
 812        let start;
 813        let end;
 814        let mode;
 815        match click_count {
 816            1 => {
 817                start = buffer.anchor_before(position.to_point(&display_map));
 818                end = start.clone();
 819                mode = SelectMode::Character;
 820            }
 821            2 => {
 822                let range = movement::surrounding_word(&display_map, position);
 823                start = buffer.anchor_before(range.start.to_point(&display_map));
 824                end = buffer.anchor_before(range.end.to_point(&display_map));
 825                mode = SelectMode::Word(start.clone()..end.clone());
 826            }
 827            3 => {
 828                let position = display_map.clip_point(position, Bias::Left);
 829                let line_start = movement::line_beginning(&display_map, position, false);
 830                let mut next_line_start = line_start.clone();
 831                *next_line_start.row_mut() += 1;
 832                *next_line_start.column_mut() = 0;
 833                next_line_start = display_map.clip_point(next_line_start, Bias::Right);
 834
 835                start = buffer.anchor_before(line_start.to_point(&display_map));
 836                end = buffer.anchor_before(next_line_start.to_point(&display_map));
 837                mode = SelectMode::Line(start.clone()..end.clone());
 838            }
 839            _ => {
 840                start = buffer.anchor_before(0);
 841                end = buffer.anchor_before(buffer.len());
 842                mode = SelectMode::All;
 843            }
 844        }
 845
 846        let selection = Selection {
 847            id: post_inc(&mut self.next_selection_id),
 848            start,
 849            end,
 850            reversed: false,
 851            goal: SelectionGoal::None,
 852        };
 853
 854        if !add {
 855            self.update_selections::<usize>(Vec::new(), None, cx);
 856        } else if click_count > 1 {
 857            // Remove the newest selection since it was only added as part of this multi-click.
 858            let newest_selection = self.newest_selection::<usize>(buffer);
 859            let mut selections = self.local_selections(cx);
 860            selections.retain(|selection| selection.id != newest_selection.id);
 861            self.update_selections::<usize>(selections, None, cx)
 862        }
 863
 864        self.pending_selection = Some(PendingSelection { selection, mode });
 865
 866        cx.notify();
 867    }
 868
 869    fn begin_columnar_selection(
 870        &mut self,
 871        position: DisplayPoint,
 872        overshoot: u32,
 873        cx: &mut ViewContext<Self>,
 874    ) {
 875        if !self.focused {
 876            cx.focus_self();
 877            cx.emit(Event::Activate);
 878        }
 879
 880        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 881        let tail = self
 882            .newest_selection::<Point>(&display_map.buffer_snapshot)
 883            .tail();
 884        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 885
 886        self.select_columns(
 887            tail.to_display_point(&display_map),
 888            position,
 889            overshoot,
 890            &display_map,
 891            cx,
 892        );
 893    }
 894
 895    fn update_selection(
 896        &mut self,
 897        position: DisplayPoint,
 898        overshoot: u32,
 899        scroll_position: Vector2F,
 900        cx: &mut ViewContext<Self>,
 901    ) {
 902        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 903
 904        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 905            let tail = tail.to_display_point(&display_map);
 906            self.select_columns(tail, position, overshoot, &display_map, cx);
 907        } else if let Some(PendingSelection { selection, mode }) = self.pending_selection.as_mut() {
 908            let buffer = self.buffer.read(cx).snapshot(cx);
 909            let head;
 910            let tail;
 911            match mode {
 912                SelectMode::Character => {
 913                    head = position.to_point(&display_map);
 914                    tail = selection.tail().to_point(&buffer);
 915                }
 916                SelectMode::Word(original_range) => {
 917                    let original_display_range = original_range.start.to_display_point(&display_map)
 918                        ..original_range.end.to_display_point(&display_map);
 919                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 920                        ..original_display_range.end.to_point(&display_map);
 921                    if movement::is_inside_word(&display_map, position)
 922                        || original_display_range.contains(&position)
 923                    {
 924                        let word_range = movement::surrounding_word(&display_map, position);
 925                        if word_range.start < original_display_range.start {
 926                            head = word_range.start.to_point(&display_map);
 927                        } else {
 928                            head = word_range.end.to_point(&display_map);
 929                        }
 930                    } else {
 931                        head = position.to_point(&display_map);
 932                    }
 933
 934                    if head <= original_buffer_range.start {
 935                        tail = original_buffer_range.end;
 936                    } else {
 937                        tail = original_buffer_range.start;
 938                    }
 939                }
 940                SelectMode::Line(original_range) => {
 941                    let original_display_range = original_range.start.to_display_point(&display_map)
 942                        ..original_range.end.to_display_point(&display_map);
 943                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 944                        ..original_display_range.end.to_point(&display_map);
 945                    let line_start = movement::line_beginning(&display_map, position, false);
 946                    let mut next_line_start = line_start.clone();
 947                    *next_line_start.row_mut() += 1;
 948                    *next_line_start.column_mut() = 0;
 949                    next_line_start = display_map.clip_point(next_line_start, Bias::Right);
 950
 951                    if line_start < original_display_range.start {
 952                        head = line_start.to_point(&display_map);
 953                    } else {
 954                        head = next_line_start.to_point(&display_map);
 955                    }
 956
 957                    if head <= original_buffer_range.start {
 958                        tail = original_buffer_range.end;
 959                    } else {
 960                        tail = original_buffer_range.start;
 961                    }
 962                }
 963                SelectMode::All => {
 964                    return;
 965                }
 966            };
 967
 968            if head < tail {
 969                selection.start = buffer.anchor_before(head);
 970                selection.end = buffer.anchor_before(tail);
 971                selection.reversed = true;
 972            } else {
 973                selection.start = buffer.anchor_before(tail);
 974                selection.end = buffer.anchor_before(head);
 975                selection.reversed = false;
 976            }
 977        } else {
 978            log::error!("update_selection dispatched with no pending selection");
 979            return;
 980        }
 981
 982        self.set_scroll_position(scroll_position, cx);
 983        cx.notify();
 984    }
 985
 986    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 987        self.columnar_selection_tail.take();
 988        if self.pending_selection.is_some() {
 989            let selections = self.local_selections::<usize>(cx);
 990            self.update_selections(selections, None, cx);
 991        }
 992    }
 993
 994    fn select_columns(
 995        &mut self,
 996        tail: DisplayPoint,
 997        head: DisplayPoint,
 998        overshoot: u32,
 999        display_map: &DisplaySnapshot,
1000        cx: &mut ViewContext<Self>,
1001    ) {
1002        let start_row = cmp::min(tail.row(), head.row());
1003        let end_row = cmp::max(tail.row(), head.row());
1004        let start_column = cmp::min(tail.column(), head.column() + overshoot);
1005        let end_column = cmp::max(tail.column(), head.column() + overshoot);
1006        let reversed = start_column < tail.column();
1007
1008        let selections = (start_row..=end_row)
1009            .filter_map(|row| {
1010                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
1011                    let start = display_map
1012                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
1013                        .to_point(&display_map);
1014                    let end = display_map
1015                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
1016                        .to_point(&display_map);
1017                    Some(Selection {
1018                        id: post_inc(&mut self.next_selection_id),
1019                        start,
1020                        end,
1021                        reversed,
1022                        goal: SelectionGoal::None,
1023                    })
1024                } else {
1025                    None
1026                }
1027            })
1028            .collect::<Vec<_>>();
1029
1030        self.update_selections(selections, None, cx);
1031        cx.notify();
1032    }
1033
1034    pub fn is_selecting(&self) -> bool {
1035        self.pending_selection.is_some() || self.columnar_selection_tail.is_some()
1036    }
1037
1038    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
1039        if self.active_diagnostics.is_some() {
1040            self.dismiss_diagnostics(cx);
1041        } else if let Some(PendingSelection { selection, .. }) = self.pending_selection.take() {
1042            let buffer = self.buffer.read(cx).snapshot(cx);
1043            let selection = Selection {
1044                id: selection.id,
1045                start: selection.start.to_point(&buffer),
1046                end: selection.end.to_point(&buffer),
1047                reversed: selection.reversed,
1048                goal: selection.goal,
1049            };
1050            if self.local_selections::<Point>(cx).is_empty() {
1051                self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
1052            }
1053        } else {
1054            let buffer = self.buffer.read(cx).snapshot(cx);
1055            let mut oldest_selection = self.oldest_selection::<usize>(&buffer);
1056            if self.selection_count() == 1 {
1057                oldest_selection.start = oldest_selection.head().clone();
1058                oldest_selection.end = oldest_selection.head().clone();
1059            }
1060            self.update_selections(vec![oldest_selection], Some(Autoscroll::Fit), cx);
1061        }
1062    }
1063
1064    pub fn select_ranges<I, T>(
1065        &mut self,
1066        ranges: I,
1067        autoscroll: Option<Autoscroll>,
1068        cx: &mut ViewContext<Self>,
1069    ) where
1070        I: IntoIterator<Item = Range<T>>,
1071        T: ToOffset,
1072    {
1073        let buffer = self.buffer.read(cx).snapshot(cx);
1074        let selections = ranges
1075            .into_iter()
1076            .map(|range| {
1077                let mut start = range.start.to_offset(&buffer);
1078                let mut end = range.end.to_offset(&buffer);
1079                let reversed = if start > end {
1080                    mem::swap(&mut start, &mut end);
1081                    true
1082                } else {
1083                    false
1084                };
1085                Selection {
1086                    id: post_inc(&mut self.next_selection_id),
1087                    start,
1088                    end,
1089                    reversed,
1090                    goal: SelectionGoal::None,
1091                }
1092            })
1093            .collect();
1094        self.update_selections(selections, autoscroll, cx);
1095    }
1096
1097    #[cfg(test)]
1098    fn select_display_ranges<'a, T>(
1099        &mut self,
1100        ranges: T,
1101        cx: &mut ViewContext<Self>,
1102    ) -> anyhow::Result<()>
1103    where
1104        T: IntoIterator<Item = &'a Range<DisplayPoint>>,
1105    {
1106        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1107        let selections = ranges
1108            .into_iter()
1109            .map(|range| {
1110                let mut start = range.start;
1111                let mut end = range.end;
1112                let reversed = if start > end {
1113                    mem::swap(&mut start, &mut end);
1114                    true
1115                } else {
1116                    false
1117                };
1118                Selection {
1119                    id: post_inc(&mut self.next_selection_id),
1120                    start: start.to_point(&display_map),
1121                    end: end.to_point(&display_map),
1122                    reversed,
1123                    goal: SelectionGoal::None,
1124                }
1125            })
1126            .collect();
1127        self.update_selections(selections, None, cx);
1128        Ok(())
1129    }
1130
1131    pub fn handle_input(&mut self, action: &Input, cx: &mut ViewContext<Self>) {
1132        let text = action.0.as_ref();
1133        if !self.skip_autoclose_end(text, cx) {
1134            self.start_transaction(cx);
1135            self.insert(text, cx);
1136            self.autoclose_pairs(cx);
1137            self.end_transaction(cx);
1138        }
1139    }
1140
1141    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
1142        self.start_transaction(cx);
1143        let mut old_selections = SmallVec::<[_; 32]>::new();
1144        {
1145            let selections = self.local_selections::<Point>(cx);
1146            let buffer = self.buffer.read(cx).snapshot(cx);
1147            for selection in selections.iter() {
1148                let start_point = selection.start;
1149                let indent = buffer
1150                    .indent_column_for_line(start_point.row)
1151                    .min(start_point.column);
1152                let start = selection.start.to_offset(&buffer);
1153                let end = selection.end.to_offset(&buffer);
1154
1155                let mut insert_extra_newline = false;
1156                if let Some(language) = buffer.language() {
1157                    let leading_whitespace_len = buffer
1158                        .reversed_chars_at(start)
1159                        .take_while(|c| c.is_whitespace() && *c != '\n')
1160                        .map(|c| c.len_utf8())
1161                        .sum::<usize>();
1162
1163                    let trailing_whitespace_len = buffer
1164                        .chars_at(end)
1165                        .take_while(|c| c.is_whitespace() && *c != '\n')
1166                        .map(|c| c.len_utf8())
1167                        .sum::<usize>();
1168
1169                    insert_extra_newline = language.brackets().iter().any(|pair| {
1170                        let pair_start = pair.start.trim_end();
1171                        let pair_end = pair.end.trim_start();
1172
1173                        pair.newline
1174                            && buffer.contains_str_at(end + trailing_whitespace_len, pair_end)
1175                            && buffer.contains_str_at(
1176                                (start - leading_whitespace_len).saturating_sub(pair_start.len()),
1177                                pair_start,
1178                            )
1179                    });
1180                }
1181
1182                old_selections.push((selection.id, start..end, indent, insert_extra_newline));
1183            }
1184        }
1185
1186        let mut new_selections = Vec::with_capacity(old_selections.len());
1187        self.buffer.update(cx, |buffer, cx| {
1188            let mut delta = 0_isize;
1189            let mut pending_edit: Option<PendingEdit> = None;
1190            for (_, range, indent, insert_extra_newline) in &old_selections {
1191                if pending_edit.as_ref().map_or(false, |pending| {
1192                    pending.indent != *indent
1193                        || pending.insert_extra_newline != *insert_extra_newline
1194                }) {
1195                    let pending = pending_edit.take().unwrap();
1196                    let mut new_text = String::with_capacity(1 + pending.indent as usize);
1197                    new_text.push('\n');
1198                    new_text.extend(iter::repeat(' ').take(pending.indent as usize));
1199                    if pending.insert_extra_newline {
1200                        new_text = new_text.repeat(2);
1201                    }
1202                    buffer.edit_with_autoindent(pending.ranges, new_text, cx);
1203                    delta += pending.delta;
1204                }
1205
1206                let start = (range.start as isize + delta) as usize;
1207                let end = (range.end as isize + delta) as usize;
1208                let mut text_len = *indent as usize + 1;
1209                if *insert_extra_newline {
1210                    text_len *= 2;
1211                }
1212
1213                let pending = pending_edit.get_or_insert_with(Default::default);
1214                pending.delta += text_len as isize - (end - start) as isize;
1215                pending.indent = *indent;
1216                pending.insert_extra_newline = *insert_extra_newline;
1217                pending.ranges.push(start..end);
1218            }
1219
1220            let pending = pending_edit.unwrap();
1221            let mut new_text = String::with_capacity(1 + pending.indent as usize);
1222            new_text.push('\n');
1223            new_text.extend(iter::repeat(' ').take(pending.indent as usize));
1224            if pending.insert_extra_newline {
1225                new_text = new_text.repeat(2);
1226            }
1227            buffer.edit_with_autoindent(pending.ranges, new_text, cx);
1228
1229            let mut delta = 0_isize;
1230            new_selections.extend(old_selections.into_iter().map(
1231                |(id, range, indent, insert_extra_newline)| {
1232                    let start = (range.start as isize + delta) as usize;
1233                    let end = (range.end as isize + delta) as usize;
1234                    let text_before_cursor_len = indent as usize + 1;
1235                    let cursor = start + text_before_cursor_len;
1236                    let text_len = if insert_extra_newline {
1237                        text_before_cursor_len * 2
1238                    } else {
1239                        text_before_cursor_len
1240                    };
1241                    delta += text_len as isize - (end - start) as isize;
1242                    Selection {
1243                        id,
1244                        start: cursor,
1245                        end: cursor,
1246                        reversed: false,
1247                        goal: SelectionGoal::None,
1248                    }
1249                },
1250            ))
1251        });
1252
1253        self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
1254        self.end_transaction(cx);
1255
1256        #[derive(Default)]
1257        struct PendingEdit {
1258            indent: u32,
1259            insert_extra_newline: bool,
1260            delta: isize,
1261            ranges: SmallVec<[Range<usize>; 32]>,
1262        }
1263    }
1264
1265    fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
1266        self.start_transaction(cx);
1267        let old_selections = self.local_selections::<usize>(cx);
1268        let mut new_selections = Vec::new();
1269        self.buffer.update(cx, |buffer, cx| {
1270            let edit_ranges = old_selections.iter().map(|s| s.start..s.end);
1271            buffer.edit_with_autoindent(edit_ranges, text, cx);
1272            let text_len = text.len() as isize;
1273            let mut delta = 0_isize;
1274            new_selections = old_selections
1275                .into_iter()
1276                .map(|selection| {
1277                    let start = selection.start as isize;
1278                    let end = selection.end as isize;
1279                    let cursor = (start + delta + text_len) as usize;
1280                    let deleted_count = end - start;
1281                    delta += text_len - deleted_count;
1282                    Selection {
1283                        id: selection.id,
1284                        start: cursor,
1285                        end: cursor,
1286                        reversed: false,
1287                        goal: SelectionGoal::None,
1288                    }
1289                })
1290                .collect();
1291        });
1292
1293        self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
1294        self.end_transaction(cx);
1295    }
1296
1297    fn autoclose_pairs(&mut self, cx: &mut ViewContext<Self>) {
1298        let selections = self.local_selections::<usize>(cx);
1299        let new_autoclose_pair = self.buffer.update(cx, |buffer, cx| {
1300            let snapshot = buffer.snapshot(cx);
1301            let autoclose_pair = snapshot.language().and_then(|language| {
1302                let first_selection_start = selections.first().unwrap().start;
1303                let pair = language.brackets().iter().find(|pair| {
1304                    snapshot.contains_str_at(
1305                        first_selection_start.saturating_sub(pair.start.len()),
1306                        &pair.start,
1307                    )
1308                });
1309                pair.and_then(|pair| {
1310                    let should_autoclose = selections[1..].iter().all(|selection| {
1311                        snapshot.contains_str_at(
1312                            selection.start.saturating_sub(pair.start.len()),
1313                            &pair.start,
1314                        )
1315                    });
1316
1317                    if should_autoclose {
1318                        Some(pair.clone())
1319                    } else {
1320                        None
1321                    }
1322                })
1323            });
1324
1325            autoclose_pair.and_then(|pair| {
1326                let selection_ranges = selections
1327                    .iter()
1328                    .map(|selection| {
1329                        let start = selection.start.to_offset(&snapshot);
1330                        start..start
1331                    })
1332                    .collect::<SmallVec<[_; 32]>>();
1333
1334                buffer.edit(selection_ranges, &pair.end, cx);
1335                let snapshot = buffer.snapshot(cx);
1336
1337                if pair.end.len() == 1 {
1338                    let mut delta = 0;
1339                    Some(BracketPairState {
1340                        ranges: selections
1341                            .iter()
1342                            .map(move |selection| {
1343                                let offset = selection.start + delta;
1344                                delta += 1;
1345                                snapshot.anchor_before(offset)..snapshot.anchor_after(offset)
1346                            })
1347                            .collect(),
1348                        pair,
1349                    })
1350                } else {
1351                    None
1352                }
1353            })
1354        });
1355        self.autoclose_stack.extend(new_autoclose_pair);
1356    }
1357
1358    fn skip_autoclose_end(&mut self, text: &str, cx: &mut ViewContext<Self>) -> bool {
1359        let old_selections = self.local_selections::<usize>(cx);
1360        let autoclose_pair = if let Some(autoclose_pair) = self.autoclose_stack.last() {
1361            autoclose_pair
1362        } else {
1363            return false;
1364        };
1365        if text != autoclose_pair.pair.end {
1366            return false;
1367        }
1368
1369        debug_assert_eq!(old_selections.len(), autoclose_pair.ranges.len());
1370
1371        let buffer = self.buffer.read(cx).snapshot(cx);
1372        if old_selections
1373            .iter()
1374            .zip(autoclose_pair.ranges.iter().map(|r| r.to_offset(&buffer)))
1375            .all(|(selection, autoclose_range)| {
1376                let autoclose_range_end = autoclose_range.end.to_offset(&buffer);
1377                selection.is_empty() && selection.start == autoclose_range_end
1378            })
1379        {
1380            let new_selections = old_selections
1381                .into_iter()
1382                .map(|selection| {
1383                    let cursor = selection.start + 1;
1384                    Selection {
1385                        id: selection.id,
1386                        start: cursor,
1387                        end: cursor,
1388                        reversed: false,
1389                        goal: SelectionGoal::None,
1390                    }
1391                })
1392                .collect();
1393            self.autoclose_stack.pop();
1394            self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
1395            true
1396        } else {
1397            false
1398        }
1399    }
1400
1401    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
1402        self.start_transaction(cx);
1403        self.select_all(&SelectAll, cx);
1404        self.insert("", cx);
1405        self.end_transaction(cx);
1406    }
1407
1408    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
1409        self.start_transaction(cx);
1410        let mut selections = self.local_selections::<Point>(cx);
1411        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1412        for selection in &mut selections {
1413            if selection.is_empty() {
1414                let head = selection.head().to_display_point(&display_map);
1415                let cursor = movement::left(&display_map, head)
1416                    .unwrap()
1417                    .to_point(&display_map);
1418                selection.set_head(cursor);
1419                selection.goal = SelectionGoal::None;
1420            }
1421        }
1422        self.update_selections(selections, Some(Autoscroll::Fit), cx);
1423        self.insert("", cx);
1424        self.end_transaction(cx);
1425    }
1426
1427    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
1428        self.start_transaction(cx);
1429        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1430        let mut selections = self.local_selections::<Point>(cx);
1431        for selection in &mut selections {
1432            if selection.is_empty() {
1433                let head = selection.head().to_display_point(&display_map);
1434                let cursor = movement::right(&display_map, head)
1435                    .unwrap()
1436                    .to_point(&display_map);
1437                selection.set_head(cursor);
1438                selection.goal = SelectionGoal::None;
1439            }
1440        }
1441        self.update_selections(selections, Some(Autoscroll::Fit), cx);
1442        self.insert(&"", cx);
1443        self.end_transaction(cx);
1444    }
1445
1446    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
1447        self.start_transaction(cx);
1448        let tab_size = self.build_settings.borrow()(cx).tab_size;
1449        let mut selections = self.local_selections::<Point>(cx);
1450        let mut last_indent = None;
1451        self.buffer.update(cx, |buffer, cx| {
1452            for selection in &mut selections {
1453                if selection.is_empty() {
1454                    let char_column = buffer
1455                        .read(cx)
1456                        .text_for_range(Point::new(selection.start.row, 0)..selection.start)
1457                        .flat_map(str::chars)
1458                        .count();
1459                    let chars_to_next_tab_stop = tab_size - (char_column % tab_size);
1460                    buffer.edit(
1461                        [selection.start..selection.start],
1462                        " ".repeat(chars_to_next_tab_stop),
1463                        cx,
1464                    );
1465                    selection.start.column += chars_to_next_tab_stop as u32;
1466                    selection.end = selection.start;
1467                } else {
1468                    let mut start_row = selection.start.row;
1469                    let mut end_row = selection.end.row + 1;
1470
1471                    // If a selection ends at the beginning of a line, don't indent
1472                    // that last line.
1473                    if selection.end.column == 0 {
1474                        end_row -= 1;
1475                    }
1476
1477                    // Avoid re-indenting a row that has already been indented by a
1478                    // previous selection, but still update this selection's column
1479                    // to reflect that indentation.
1480                    if let Some((last_indent_row, last_indent_len)) = last_indent {
1481                        if last_indent_row == selection.start.row {
1482                            selection.start.column += last_indent_len;
1483                            start_row += 1;
1484                        }
1485                        if last_indent_row == selection.end.row {
1486                            selection.end.column += last_indent_len;
1487                        }
1488                    }
1489
1490                    for row in start_row..end_row {
1491                        let indent_column = buffer.read(cx).indent_column_for_line(row) as usize;
1492                        let columns_to_next_tab_stop = tab_size - (indent_column % tab_size);
1493                        let row_start = Point::new(row, 0);
1494                        buffer.edit(
1495                            [row_start..row_start],
1496                            " ".repeat(columns_to_next_tab_stop),
1497                            cx,
1498                        );
1499
1500                        // Update this selection's endpoints to reflect the indentation.
1501                        if row == selection.start.row {
1502                            selection.start.column += columns_to_next_tab_stop as u32;
1503                        }
1504                        if row == selection.end.row {
1505                            selection.end.column += columns_to_next_tab_stop as u32;
1506                        }
1507
1508                        last_indent = Some((row, columns_to_next_tab_stop as u32));
1509                    }
1510                }
1511            }
1512        });
1513
1514        self.update_selections(selections, Some(Autoscroll::Fit), cx);
1515        self.end_transaction(cx);
1516    }
1517
1518    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
1519        self.start_transaction(cx);
1520        let tab_size = self.build_settings.borrow()(cx).tab_size;
1521        let selections = self.local_selections::<Point>(cx);
1522        let mut deletion_ranges = Vec::new();
1523        let mut last_outdent = None;
1524        {
1525            let buffer = self.buffer.read(cx).read(cx);
1526            for selection in &selections {
1527                let mut start_row = selection.start.row;
1528                let mut end_row = selection.end.row + 1;
1529
1530                // If a selection ends at the beginning of a line, don't indent
1531                // that last line.
1532                if selection.end.column == 0 {
1533                    end_row -= 1;
1534                }
1535
1536                // Avoid re-outdenting a row that has already been outdented by a
1537                // previous selection.
1538                if let Some(last_row) = last_outdent {
1539                    if last_row == selection.start.row {
1540                        start_row += 1;
1541                    }
1542                }
1543
1544                for row in start_row..end_row {
1545                    let column = buffer.indent_column_for_line(row) as usize;
1546                    if column > 0 {
1547                        let mut deletion_len = (column % tab_size) as u32;
1548                        if deletion_len == 0 {
1549                            deletion_len = tab_size as u32;
1550                        }
1551                        deletion_ranges.push(Point::new(row, 0)..Point::new(row, deletion_len));
1552                        last_outdent = Some(row);
1553                    }
1554                }
1555            }
1556        }
1557        self.buffer.update(cx, |buffer, cx| {
1558            buffer.edit(deletion_ranges, "", cx);
1559        });
1560
1561        self.update_selections(
1562            self.local_selections::<usize>(cx),
1563            Some(Autoscroll::Fit),
1564            cx,
1565        );
1566        self.end_transaction(cx);
1567    }
1568
1569    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
1570        self.start_transaction(cx);
1571
1572        let selections = self.local_selections::<Point>(cx);
1573        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1574        let buffer = self.buffer.read(cx).snapshot(cx);
1575
1576        let mut row_delta = 0;
1577        let mut new_cursors = Vec::new();
1578        let mut edit_ranges = Vec::new();
1579        let mut selections = selections.iter().peekable();
1580        while let Some(selection) = selections.next() {
1581            let mut rows = selection.spanned_rows(false, &display_map).buffer_rows;
1582            let goal_display_column = selection.head().to_display_point(&display_map).column();
1583
1584            // Accumulate contiguous regions of rows that we want to delete.
1585            while let Some(next_selection) = selections.peek() {
1586                let next_rows = next_selection.spanned_rows(false, &display_map).buffer_rows;
1587                if next_rows.start <= rows.end {
1588                    rows.end = next_rows.end;
1589                    selections.next().unwrap();
1590                } else {
1591                    break;
1592                }
1593            }
1594
1595            let mut edit_start = Point::new(rows.start, 0).to_offset(&buffer);
1596            let edit_end;
1597            let cursor_buffer_row;
1598            if buffer.max_point().row >= rows.end {
1599                // If there's a line after the range, delete the \n from the end of the row range
1600                // and position the cursor on the next line.
1601                edit_end = Point::new(rows.end, 0).to_offset(&buffer);
1602                cursor_buffer_row = rows.start;
1603            } else {
1604                // If there isn't a line after the range, delete the \n from the line before the
1605                // start of the row range and position the cursor there.
1606                edit_start = edit_start.saturating_sub(1);
1607                edit_end = buffer.len();
1608                cursor_buffer_row = rows.start.saturating_sub(1);
1609            }
1610
1611            let mut cursor =
1612                Point::new(cursor_buffer_row - row_delta, 0).to_display_point(&display_map);
1613            *cursor.column_mut() =
1614                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
1615            row_delta += rows.len() as u32;
1616
1617            new_cursors.push((selection.id, cursor.to_point(&display_map)));
1618            edit_ranges.push(edit_start..edit_end);
1619        }
1620
1621        new_cursors.sort_unstable_by_key(|(_, point)| point.clone());
1622        let new_selections = new_cursors
1623            .into_iter()
1624            .map(|(id, cursor)| Selection {
1625                id,
1626                start: cursor,
1627                end: cursor,
1628                reversed: false,
1629                goal: SelectionGoal::None,
1630            })
1631            .collect();
1632        self.buffer
1633            .update(cx, |buffer, cx| buffer.edit(edit_ranges, "", cx));
1634        self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
1635        self.end_transaction(cx);
1636    }
1637
1638    pub fn duplicate_line(&mut self, _: &DuplicateLine, cx: &mut ViewContext<Self>) {
1639        self.start_transaction(cx);
1640
1641        let mut selections = self.local_selections::<Point>(cx);
1642        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1643        let buffer = &display_map.buffer_snapshot;
1644
1645        let mut edits = Vec::new();
1646        let mut selections_iter = selections.iter().peekable();
1647        while let Some(selection) = selections_iter.next() {
1648            // Avoid duplicating the same lines twice.
1649            let mut rows = selection.spanned_rows(false, &display_map).buffer_rows;
1650
1651            while let Some(next_selection) = selections_iter.peek() {
1652                let next_rows = next_selection.spanned_rows(false, &display_map).buffer_rows;
1653                if next_rows.start <= rows.end - 1 {
1654                    rows.end = next_rows.end;
1655                    selections_iter.next().unwrap();
1656                } else {
1657                    break;
1658                }
1659            }
1660
1661            // Copy the text from the selected row region and splice it at the start of the region.
1662            let start = Point::new(rows.start, 0);
1663            let end = Point::new(rows.end - 1, buffer.line_len(rows.end - 1));
1664            let text = buffer
1665                .text_for_range(start..end)
1666                .chain(Some("\n"))
1667                .collect::<String>();
1668            edits.push((start, text, rows.len() as u32));
1669        }
1670
1671        let mut edits_iter = edits.iter().peekable();
1672        let mut row_delta = 0;
1673        for selection in selections.iter_mut() {
1674            while let Some((point, _, line_count)) = edits_iter.peek() {
1675                if *point <= selection.start {
1676                    row_delta += line_count;
1677                    edits_iter.next();
1678                } else {
1679                    break;
1680                }
1681            }
1682            selection.start.row += row_delta;
1683            selection.end.row += row_delta;
1684        }
1685
1686        self.buffer.update(cx, |buffer, cx| {
1687            for (point, text, _) in edits.into_iter().rev() {
1688                buffer.edit(Some(point..point), text, cx);
1689            }
1690        });
1691
1692        self.update_selections(selections, Some(Autoscroll::Fit), cx);
1693        self.end_transaction(cx);
1694    }
1695
1696    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
1697        self.start_transaction(cx);
1698
1699        let selections = self.local_selections::<Point>(cx);
1700        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1701        let buffer = self.buffer.read(cx).snapshot(cx);
1702
1703        let mut edits = Vec::new();
1704        let mut new_selection_ranges = Vec::new();
1705        let mut old_folds = Vec::new();
1706        let mut new_folds = Vec::new();
1707
1708        let mut selections = selections.iter().peekable();
1709        let mut contiguous_selections = Vec::new();
1710        while let Some(selection) = selections.next() {
1711            // Accumulate contiguous regions of rows that we want to move.
1712            contiguous_selections.push(selection.point_range(&buffer));
1713            let SpannedRows {
1714                mut buffer_rows,
1715                mut display_rows,
1716            } = selection.spanned_rows(false, &display_map);
1717
1718            while let Some(next_selection) = selections.peek() {
1719                let SpannedRows {
1720                    buffer_rows: next_buffer_rows,
1721                    display_rows: next_display_rows,
1722                } = next_selection.spanned_rows(false, &display_map);
1723                if next_buffer_rows.start <= buffer_rows.end {
1724                    buffer_rows.end = next_buffer_rows.end;
1725                    display_rows.end = next_display_rows.end;
1726                    contiguous_selections.push(next_selection.point_range(&buffer));
1727                    selections.next().unwrap();
1728                } else {
1729                    break;
1730                }
1731            }
1732
1733            // Cut the text from the selected rows and paste it at the start of the previous line.
1734            if display_rows.start != 0 {
1735                let start = Point::new(buffer_rows.start, 0).to_offset(&buffer);
1736                let end = Point::new(buffer_rows.end - 1, buffer.line_len(buffer_rows.end - 1))
1737                    .to_offset(&buffer);
1738
1739                let prev_row_display_start = DisplayPoint::new(display_rows.start - 1, 0);
1740                let prev_row_buffer_start = display_map.prev_row_boundary(prev_row_display_start).1;
1741                let prev_row_buffer_start_offset = prev_row_buffer_start.to_offset(&buffer);
1742
1743                let mut text = String::new();
1744                text.extend(buffer.text_for_range(start..end));
1745                text.push('\n');
1746                edits.push((
1747                    prev_row_buffer_start_offset..prev_row_buffer_start_offset,
1748                    text,
1749                ));
1750                edits.push((start - 1..end, String::new()));
1751
1752                let row_delta = buffer_rows.start - prev_row_buffer_start.row;
1753
1754                // Move selections up.
1755                for range in &mut contiguous_selections {
1756                    range.start.row -= row_delta;
1757                    range.end.row -= row_delta;
1758                }
1759
1760                // Move folds up.
1761                old_folds.push(start..end);
1762                for fold in display_map.folds_in_range(start..end) {
1763                    let mut start = fold.start.to_point(&buffer);
1764                    let mut end = fold.end.to_point(&buffer);
1765                    start.row -= row_delta;
1766                    end.row -= row_delta;
1767                    new_folds.push(start..end);
1768                }
1769            }
1770
1771            new_selection_ranges.extend(contiguous_selections.drain(..));
1772        }
1773
1774        self.unfold_ranges(old_folds, cx);
1775        self.buffer.update(cx, |buffer, cx| {
1776            for (range, text) in edits.into_iter().rev() {
1777                buffer.edit(Some(range), text, cx);
1778            }
1779        });
1780        self.fold_ranges(new_folds, cx);
1781        self.select_ranges(new_selection_ranges, Some(Autoscroll::Fit), cx);
1782
1783        self.end_transaction(cx);
1784    }
1785
1786    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
1787        self.start_transaction(cx);
1788
1789        let selections = self.local_selections::<Point>(cx);
1790        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1791        let buffer = self.buffer.read(cx).snapshot(cx);
1792
1793        let mut edits = Vec::new();
1794        let mut new_selection_ranges = Vec::new();
1795        let mut old_folds = Vec::new();
1796        let mut new_folds = Vec::new();
1797
1798        let mut selections = selections.iter().peekable();
1799        let mut contiguous_selections = Vec::new();
1800        while let Some(selection) = selections.next() {
1801            // Accumulate contiguous regions of rows that we want to move.
1802            contiguous_selections.push(selection.point_range(&buffer));
1803            let SpannedRows {
1804                mut buffer_rows,
1805                mut display_rows,
1806            } = selection.spanned_rows(false, &display_map);
1807            while let Some(next_selection) = selections.peek() {
1808                let SpannedRows {
1809                    buffer_rows: next_buffer_rows,
1810                    display_rows: next_display_rows,
1811                } = next_selection.spanned_rows(false, &display_map);
1812                if next_buffer_rows.start <= buffer_rows.end {
1813                    buffer_rows.end = next_buffer_rows.end;
1814                    display_rows.end = next_display_rows.end;
1815                    contiguous_selections.push(next_selection.point_range(&buffer));
1816                    selections.next().unwrap();
1817                } else {
1818                    break;
1819                }
1820            }
1821
1822            // Cut the text from the selected rows and paste it at the end of the next line.
1823            if display_rows.end <= display_map.max_point().row() {
1824                let start = Point::new(buffer_rows.start, 0).to_offset(&buffer);
1825                let end = Point::new(buffer_rows.end - 1, buffer.line_len(buffer_rows.end - 1))
1826                    .to_offset(&buffer);
1827
1828                let next_row_display_end =
1829                    DisplayPoint::new(display_rows.end, display_map.line_len(display_rows.end));
1830                let next_row_buffer_end = display_map.next_row_boundary(next_row_display_end).1;
1831                let next_row_buffer_end_offset = next_row_buffer_end.to_offset(&buffer);
1832
1833                let mut text = String::new();
1834                text.push('\n');
1835                text.extend(buffer.text_for_range(start..end));
1836                edits.push((start..end + 1, String::new()));
1837                edits.push((next_row_buffer_end_offset..next_row_buffer_end_offset, text));
1838
1839                let row_delta = next_row_buffer_end.row - buffer_rows.end + 1;
1840
1841                // Move selections down.
1842                for range in &mut contiguous_selections {
1843                    range.start.row += row_delta;
1844                    range.end.row += row_delta;
1845                }
1846
1847                // Move folds down.
1848                old_folds.push(start..end);
1849                for fold in display_map.folds_in_range(start..end) {
1850                    let mut start = fold.start.to_point(&buffer);
1851                    let mut end = fold.end.to_point(&buffer);
1852                    start.row += row_delta;
1853                    end.row += row_delta;
1854                    new_folds.push(start..end);
1855                }
1856            }
1857
1858            new_selection_ranges.extend(contiguous_selections.drain(..));
1859        }
1860
1861        self.unfold_ranges(old_folds, cx);
1862        self.buffer.update(cx, |buffer, cx| {
1863            for (range, text) in edits.into_iter().rev() {
1864                buffer.edit(Some(range), text, cx);
1865            }
1866        });
1867        self.fold_ranges(new_folds, cx);
1868        self.select_ranges(new_selection_ranges, Some(Autoscroll::Fit), cx);
1869
1870        self.end_transaction(cx);
1871    }
1872
1873    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
1874        self.start_transaction(cx);
1875        let mut text = String::new();
1876        let mut selections = self.local_selections::<Point>(cx);
1877        let mut clipboard_selections = Vec::with_capacity(selections.len());
1878        {
1879            let buffer = self.buffer.read(cx).read(cx);
1880            let max_point = buffer.max_point();
1881            for selection in &mut selections {
1882                let is_entire_line = selection.is_empty();
1883                if is_entire_line {
1884                    selection.start = Point::new(selection.start.row, 0);
1885                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
1886                }
1887                let mut len = 0;
1888                for chunk in buffer.text_for_range(selection.start..selection.end) {
1889                    text.push_str(chunk);
1890                    len += chunk.len();
1891                }
1892                clipboard_selections.push(ClipboardSelection {
1893                    len,
1894                    is_entire_line,
1895                });
1896            }
1897        }
1898        self.update_selections(selections, Some(Autoscroll::Fit), cx);
1899        self.insert("", cx);
1900        self.end_transaction(cx);
1901
1902        cx.as_mut()
1903            .write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
1904    }
1905
1906    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
1907        let selections = self.local_selections::<Point>(cx);
1908        let mut text = String::new();
1909        let mut clipboard_selections = Vec::with_capacity(selections.len());
1910        {
1911            let buffer = self.buffer.read(cx).read(cx);
1912            let max_point = buffer.max_point();
1913            for selection in selections.iter() {
1914                let mut start = selection.start;
1915                let mut end = selection.end;
1916                let is_entire_line = selection.is_empty();
1917                if is_entire_line {
1918                    start = Point::new(start.row, 0);
1919                    end = cmp::min(max_point, Point::new(start.row + 1, 0));
1920                }
1921                let mut len = 0;
1922                for chunk in buffer.text_for_range(start..end) {
1923                    text.push_str(chunk);
1924                    len += chunk.len();
1925                }
1926                clipboard_selections.push(ClipboardSelection {
1927                    len,
1928                    is_entire_line,
1929                });
1930            }
1931        }
1932
1933        cx.as_mut()
1934            .write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
1935    }
1936
1937    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
1938        if let Some(item) = cx.as_mut().read_from_clipboard() {
1939            let clipboard_text = item.text();
1940            if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
1941                let mut selections = self.local_selections::<usize>(cx);
1942                let all_selections_were_entire_line =
1943                    clipboard_selections.iter().all(|s| s.is_entire_line);
1944                if clipboard_selections.len() != selections.len() {
1945                    clipboard_selections.clear();
1946                }
1947
1948                let mut delta = 0_isize;
1949                let mut start_offset = 0;
1950                for (i, selection) in selections.iter_mut().enumerate() {
1951                    let to_insert;
1952                    let entire_line;
1953                    if let Some(clipboard_selection) = clipboard_selections.get(i) {
1954                        let end_offset = start_offset + clipboard_selection.len;
1955                        to_insert = &clipboard_text[start_offset..end_offset];
1956                        entire_line = clipboard_selection.is_entire_line;
1957                        start_offset = end_offset
1958                    } else {
1959                        to_insert = clipboard_text.as_str();
1960                        entire_line = all_selections_were_entire_line;
1961                    }
1962
1963                    selection.start = (selection.start as isize + delta) as usize;
1964                    selection.end = (selection.end as isize + delta) as usize;
1965
1966                    self.buffer.update(cx, |buffer, cx| {
1967                        // If the corresponding selection was empty when this slice of the
1968                        // clipboard text was written, then the entire line containing the
1969                        // selection was copied. If this selection is also currently empty,
1970                        // then paste the line before the current line of the buffer.
1971                        let range = if selection.is_empty() && entire_line {
1972                            let column = selection.start.to_point(&buffer.read(cx)).column as usize;
1973                            let line_start = selection.start - column;
1974                            line_start..line_start
1975                        } else {
1976                            selection.start..selection.end
1977                        };
1978
1979                        delta += to_insert.len() as isize - range.len() as isize;
1980                        buffer.edit([range], to_insert, cx);
1981                        selection.start += to_insert.len();
1982                        selection.end = selection.start;
1983                    });
1984                }
1985                self.update_selections(selections, Some(Autoscroll::Fit), cx);
1986            } else {
1987                self.insert(clipboard_text, cx);
1988            }
1989        }
1990    }
1991
1992    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
1993        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
1994            if let Some((selections, _)) = self.selection_history.get(&tx_id).cloned() {
1995                self.set_selections(selections, cx);
1996            }
1997            self.request_autoscroll(Autoscroll::Fit, cx);
1998        }
1999    }
2000
2001    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
2002        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
2003            if let Some((_, Some(selections))) = self.selection_history.get(&tx_id).cloned() {
2004                self.set_selections(selections, cx);
2005            }
2006            self.request_autoscroll(Autoscroll::Fit, cx);
2007        }
2008    }
2009
2010    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
2011        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2012        let mut selections = self.local_selections::<Point>(cx);
2013        for selection in &mut selections {
2014            let start = selection.start.to_display_point(&display_map);
2015            let end = selection.end.to_display_point(&display_map);
2016
2017            if start != end {
2018                selection.end = selection.start.clone();
2019            } else {
2020                let cursor = movement::left(&display_map, start)
2021                    .unwrap()
2022                    .to_point(&display_map);
2023                selection.start = cursor.clone();
2024                selection.end = cursor;
2025            }
2026            selection.reversed = false;
2027            selection.goal = SelectionGoal::None;
2028        }
2029        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2030    }
2031
2032    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
2033        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2034        let mut selections = self.local_selections::<Point>(cx);
2035        for selection in &mut selections {
2036            let head = selection.head().to_display_point(&display_map);
2037            let cursor = movement::left(&display_map, head)
2038                .unwrap()
2039                .to_point(&display_map);
2040            selection.set_head(cursor);
2041            selection.goal = SelectionGoal::None;
2042        }
2043        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2044    }
2045
2046    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
2047        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2048        let mut selections = self.local_selections::<Point>(cx);
2049        for selection in &mut selections {
2050            let start = selection.start.to_display_point(&display_map);
2051            let end = selection.end.to_display_point(&display_map);
2052
2053            if start != end {
2054                selection.start = selection.end.clone();
2055            } else {
2056                let cursor = movement::right(&display_map, end)
2057                    .unwrap()
2058                    .to_point(&display_map);
2059                selection.start = cursor;
2060                selection.end = cursor;
2061            }
2062            selection.reversed = false;
2063            selection.goal = SelectionGoal::None;
2064        }
2065        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2066    }
2067
2068    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
2069        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2070        let mut selections = self.local_selections::<Point>(cx);
2071        for selection in &mut selections {
2072            let head = selection.head().to_display_point(&display_map);
2073            let cursor = movement::right(&display_map, head)
2074                .unwrap()
2075                .to_point(&display_map);
2076            selection.set_head(cursor);
2077            selection.goal = SelectionGoal::None;
2078        }
2079        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2080    }
2081
2082    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
2083        if matches!(self.mode, EditorMode::SingleLine) {
2084            cx.propagate_action();
2085            return;
2086        }
2087
2088        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2089        let mut selections = self.local_selections::<Point>(cx);
2090        for selection in &mut selections {
2091            let start = selection.start.to_display_point(&display_map);
2092            let end = selection.end.to_display_point(&display_map);
2093            if start != end {
2094                selection.goal = SelectionGoal::None;
2095            }
2096
2097            let (start, goal) = movement::up(&display_map, start, selection.goal).unwrap();
2098            let cursor = start.to_point(&display_map);
2099            selection.start = cursor;
2100            selection.end = cursor;
2101            selection.goal = goal;
2102            selection.reversed = false;
2103        }
2104        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2105    }
2106
2107    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
2108        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2109        let mut selections = self.local_selections::<Point>(cx);
2110        for selection in &mut selections {
2111            let head = selection.head().to_display_point(&display_map);
2112            let (head, goal) = movement::up(&display_map, head, selection.goal).unwrap();
2113            let cursor = head.to_point(&display_map);
2114            selection.set_head(cursor);
2115            selection.goal = goal;
2116        }
2117        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2118    }
2119
2120    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
2121        if matches!(self.mode, EditorMode::SingleLine) {
2122            cx.propagate_action();
2123            return;
2124        }
2125
2126        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2127        let mut selections = self.local_selections::<Point>(cx);
2128        for selection in &mut selections {
2129            let start = selection.start.to_display_point(&display_map);
2130            let end = selection.end.to_display_point(&display_map);
2131            if start != end {
2132                selection.goal = SelectionGoal::None;
2133            }
2134
2135            let (start, goal) = movement::down(&display_map, end, selection.goal).unwrap();
2136            let cursor = start.to_point(&display_map);
2137            selection.start = cursor;
2138            selection.end = cursor;
2139            selection.goal = goal;
2140            selection.reversed = false;
2141        }
2142        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2143    }
2144
2145    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
2146        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2147        let mut selections = self.local_selections::<Point>(cx);
2148        for selection in &mut selections {
2149            let head = selection.head().to_display_point(&display_map);
2150            let (head, goal) = movement::down(&display_map, head, selection.goal).unwrap();
2151            let cursor = head.to_point(&display_map);
2152            selection.set_head(cursor);
2153            selection.goal = goal;
2154        }
2155        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2156    }
2157
2158    pub fn move_to_previous_word_boundary(
2159        &mut self,
2160        _: &MoveToPreviousWordBoundary,
2161        cx: &mut ViewContext<Self>,
2162    ) {
2163        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2164        let mut selections = self.local_selections::<Point>(cx);
2165        for selection in &mut selections {
2166            let head = selection.head().to_display_point(&display_map);
2167            let cursor = movement::prev_word_boundary(&display_map, head).to_point(&display_map);
2168            selection.start = cursor.clone();
2169            selection.end = cursor;
2170            selection.reversed = false;
2171            selection.goal = SelectionGoal::None;
2172        }
2173        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2174    }
2175
2176    pub fn select_to_previous_word_boundary(
2177        &mut self,
2178        _: &SelectToPreviousWordBoundary,
2179        cx: &mut ViewContext<Self>,
2180    ) {
2181        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2182        let mut selections = self.local_selections::<Point>(cx);
2183        for selection in &mut selections {
2184            let head = selection.head().to_display_point(&display_map);
2185            let cursor = movement::prev_word_boundary(&display_map, head).to_point(&display_map);
2186            selection.set_head(cursor);
2187            selection.goal = SelectionGoal::None;
2188        }
2189        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2190    }
2191
2192    pub fn delete_to_previous_word_boundary(
2193        &mut self,
2194        _: &DeleteToPreviousWordBoundary,
2195        cx: &mut ViewContext<Self>,
2196    ) {
2197        self.start_transaction(cx);
2198        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2199        let mut selections = self.local_selections::<Point>(cx);
2200        for selection in &mut selections {
2201            if selection.is_empty() {
2202                let head = selection.head().to_display_point(&display_map);
2203                let cursor =
2204                    movement::prev_word_boundary(&display_map, head).to_point(&display_map);
2205                selection.set_head(cursor);
2206                selection.goal = SelectionGoal::None;
2207            }
2208        }
2209        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2210        self.insert("", cx);
2211        self.end_transaction(cx);
2212    }
2213
2214    pub fn move_to_next_word_boundary(
2215        &mut self,
2216        _: &MoveToNextWordBoundary,
2217        cx: &mut ViewContext<Self>,
2218    ) {
2219        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2220        let mut selections = self.local_selections::<Point>(cx);
2221        for selection in &mut selections {
2222            let head = selection.head().to_display_point(&display_map);
2223            let cursor = movement::next_word_boundary(&display_map, head).to_point(&display_map);
2224            selection.start = cursor;
2225            selection.end = cursor;
2226            selection.reversed = false;
2227            selection.goal = SelectionGoal::None;
2228        }
2229        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2230    }
2231
2232    pub fn select_to_next_word_boundary(
2233        &mut self,
2234        _: &SelectToNextWordBoundary,
2235        cx: &mut ViewContext<Self>,
2236    ) {
2237        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2238        let mut selections = self.local_selections::<Point>(cx);
2239        for selection in &mut selections {
2240            let head = selection.head().to_display_point(&display_map);
2241            let cursor = movement::next_word_boundary(&display_map, head).to_point(&display_map);
2242            selection.set_head(cursor);
2243            selection.goal = SelectionGoal::None;
2244        }
2245        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2246    }
2247
2248    pub fn delete_to_next_word_boundary(
2249        &mut self,
2250        _: &DeleteToNextWordBoundary,
2251        cx: &mut ViewContext<Self>,
2252    ) {
2253        self.start_transaction(cx);
2254        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2255        let mut selections = self.local_selections::<Point>(cx);
2256        for selection in &mut selections {
2257            if selection.is_empty() {
2258                let head = selection.head().to_display_point(&display_map);
2259                let cursor =
2260                    movement::next_word_boundary(&display_map, head).to_point(&display_map);
2261                selection.set_head(cursor);
2262                selection.goal = SelectionGoal::None;
2263            }
2264        }
2265        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2266        self.insert("", cx);
2267        self.end_transaction(cx);
2268    }
2269
2270    pub fn move_to_beginning_of_line(
2271        &mut self,
2272        _: &MoveToBeginningOfLine,
2273        cx: &mut ViewContext<Self>,
2274    ) {
2275        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2276        let mut selections = self.local_selections::<Point>(cx);
2277        for selection in &mut selections {
2278            let head = selection.head().to_display_point(&display_map);
2279            let new_head = movement::line_beginning(&display_map, head, true);
2280            let cursor = new_head.to_point(&display_map);
2281            selection.start = cursor;
2282            selection.end = cursor;
2283            selection.reversed = false;
2284            selection.goal = SelectionGoal::None;
2285        }
2286        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2287    }
2288
2289    pub fn select_to_beginning_of_line(
2290        &mut self,
2291        SelectToBeginningOfLine(toggle_indent): &SelectToBeginningOfLine,
2292        cx: &mut ViewContext<Self>,
2293    ) {
2294        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2295        let mut selections = self.local_selections::<Point>(cx);
2296        for selection in &mut selections {
2297            let head = selection.head().to_display_point(&display_map);
2298            let new_head = movement::line_beginning(&display_map, head, *toggle_indent);
2299            selection.set_head(new_head.to_point(&display_map));
2300            selection.goal = SelectionGoal::None;
2301        }
2302        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2303    }
2304
2305    pub fn delete_to_beginning_of_line(
2306        &mut self,
2307        _: &DeleteToBeginningOfLine,
2308        cx: &mut ViewContext<Self>,
2309    ) {
2310        self.start_transaction(cx);
2311        self.select_to_beginning_of_line(&SelectToBeginningOfLine(false), cx);
2312        self.backspace(&Backspace, cx);
2313        self.end_transaction(cx);
2314    }
2315
2316    pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
2317        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2318        let mut selections = self.local_selections::<Point>(cx);
2319        {
2320            for selection in &mut selections {
2321                let head = selection.head().to_display_point(&display_map);
2322                let new_head = movement::line_end(&display_map, head);
2323                let anchor = new_head.to_point(&display_map);
2324                selection.start = anchor.clone();
2325                selection.end = anchor;
2326                selection.reversed = false;
2327                selection.goal = SelectionGoal::None;
2328            }
2329        }
2330        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2331    }
2332
2333    pub fn select_to_end_of_line(&mut self, _: &SelectToEndOfLine, cx: &mut ViewContext<Self>) {
2334        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2335        let mut selections = self.local_selections::<Point>(cx);
2336        for selection in &mut selections {
2337            let head = selection.head().to_display_point(&display_map);
2338            let new_head = movement::line_end(&display_map, head);
2339            selection.set_head(new_head.to_point(&display_map));
2340            selection.goal = SelectionGoal::None;
2341        }
2342        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2343    }
2344
2345    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
2346        self.start_transaction(cx);
2347        self.select_to_end_of_line(&SelectToEndOfLine, cx);
2348        self.delete(&Delete, cx);
2349        self.end_transaction(cx);
2350    }
2351
2352    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
2353        self.start_transaction(cx);
2354        self.select_to_end_of_line(&SelectToEndOfLine, cx);
2355        self.cut(&Cut, cx);
2356        self.end_transaction(cx);
2357    }
2358
2359    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
2360        let selection = Selection {
2361            id: post_inc(&mut self.next_selection_id),
2362            start: 0,
2363            end: 0,
2364            reversed: false,
2365            goal: SelectionGoal::None,
2366        };
2367        self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2368    }
2369
2370    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
2371        let mut selection = self.local_selections::<Point>(cx).last().unwrap().clone();
2372        selection.set_head(Point::zero());
2373        self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2374    }
2375
2376    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
2377        let cursor = self.buffer.read(cx).read(cx).len();
2378        let selection = Selection {
2379            id: post_inc(&mut self.next_selection_id),
2380            start: cursor,
2381            end: cursor,
2382            reversed: false,
2383            goal: SelectionGoal::None,
2384        };
2385        self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2386    }
2387
2388    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
2389        let mut selection = self.local_selections::<usize>(cx).first().unwrap().clone();
2390        selection.set_head(self.buffer.read(cx).read(cx).len());
2391        self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2392    }
2393
2394    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
2395        let selection = Selection {
2396            id: post_inc(&mut self.next_selection_id),
2397            start: 0,
2398            end: self.buffer.read(cx).read(cx).len(),
2399            reversed: false,
2400            goal: SelectionGoal::None,
2401        };
2402        self.update_selections(vec![selection], None, cx);
2403    }
2404
2405    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
2406        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2407        let mut selections = self.local_selections::<Point>(cx);
2408        let max_point = display_map.buffer_snapshot.max_point();
2409        for selection in &mut selections {
2410            let rows = selection.spanned_rows(true, &display_map).buffer_rows;
2411            selection.start = Point::new(rows.start, 0);
2412            selection.end = cmp::min(max_point, Point::new(rows.end, 0));
2413            selection.reversed = false;
2414        }
2415        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2416    }
2417
2418    pub fn split_selection_into_lines(
2419        &mut self,
2420        _: &SplitSelectionIntoLines,
2421        cx: &mut ViewContext<Self>,
2422    ) {
2423        let mut to_unfold = Vec::new();
2424        let mut new_selections = Vec::new();
2425        {
2426            let selections = self.local_selections::<Point>(cx);
2427            let buffer = self.buffer.read(cx).read(cx);
2428            for selection in selections {
2429                for row in selection.start.row..selection.end.row {
2430                    let cursor = Point::new(row, buffer.line_len(row));
2431                    new_selections.push(Selection {
2432                        id: post_inc(&mut self.next_selection_id),
2433                        start: cursor,
2434                        end: cursor,
2435                        reversed: false,
2436                        goal: SelectionGoal::None,
2437                    });
2438                }
2439                new_selections.push(Selection {
2440                    id: selection.id,
2441                    start: selection.end,
2442                    end: selection.end,
2443                    reversed: false,
2444                    goal: SelectionGoal::None,
2445                });
2446                to_unfold.push(selection.start..selection.end);
2447            }
2448        }
2449        self.unfold_ranges(to_unfold, cx);
2450        self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2451    }
2452
2453    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
2454        self.add_selection(true, cx);
2455    }
2456
2457    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
2458        self.add_selection(false, cx);
2459    }
2460
2461    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
2462        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2463        let mut selections = self.local_selections::<Point>(cx);
2464        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
2465            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
2466            let range = oldest_selection.display_range(&display_map).sorted();
2467            let columns = cmp::min(range.start.column(), range.end.column())
2468                ..cmp::max(range.start.column(), range.end.column());
2469
2470            selections.clear();
2471            let mut stack = Vec::new();
2472            for row in range.start.row()..=range.end.row() {
2473                if let Some(selection) = self.build_columnar_selection(
2474                    &display_map,
2475                    row,
2476                    &columns,
2477                    oldest_selection.reversed,
2478                ) {
2479                    stack.push(selection.id);
2480                    selections.push(selection);
2481                }
2482            }
2483
2484            if above {
2485                stack.reverse();
2486            }
2487
2488            AddSelectionsState { above, stack }
2489        });
2490
2491        let last_added_selection = *state.stack.last().unwrap();
2492        let mut new_selections = Vec::new();
2493        if above == state.above {
2494            let end_row = if above {
2495                0
2496            } else {
2497                display_map.max_point().row()
2498            };
2499
2500            'outer: for selection in selections {
2501                if selection.id == last_added_selection {
2502                    let range = selection.display_range(&display_map).sorted();
2503                    debug_assert_eq!(range.start.row(), range.end.row());
2504                    let mut row = range.start.row();
2505                    let columns = if let SelectionGoal::ColumnRange { start, end } = selection.goal
2506                    {
2507                        start..end
2508                    } else {
2509                        cmp::min(range.start.column(), range.end.column())
2510                            ..cmp::max(range.start.column(), range.end.column())
2511                    };
2512
2513                    while row != end_row {
2514                        if above {
2515                            row -= 1;
2516                        } else {
2517                            row += 1;
2518                        }
2519
2520                        if let Some(new_selection) = self.build_columnar_selection(
2521                            &display_map,
2522                            row,
2523                            &columns,
2524                            selection.reversed,
2525                        ) {
2526                            state.stack.push(new_selection.id);
2527                            if above {
2528                                new_selections.push(new_selection);
2529                                new_selections.push(selection);
2530                            } else {
2531                                new_selections.push(selection);
2532                                new_selections.push(new_selection);
2533                            }
2534
2535                            continue 'outer;
2536                        }
2537                    }
2538                }
2539
2540                new_selections.push(selection);
2541            }
2542        } else {
2543            new_selections = selections;
2544            new_selections.retain(|s| s.id != last_added_selection);
2545            state.stack.pop();
2546        }
2547
2548        self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2549        if state.stack.len() > 1 {
2550            self.add_selections_state = Some(state);
2551        }
2552    }
2553
2554    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) {
2555        let replace_newest = action.0;
2556        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2557        let buffer = &display_map.buffer_snapshot;
2558        let mut selections = self.local_selections::<usize>(cx);
2559        if let Some(mut select_next_state) = self.select_next_state.take() {
2560            let query = &select_next_state.query;
2561            if !select_next_state.done {
2562                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
2563                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
2564                let mut next_selected_range = None;
2565
2566                let bytes_after_last_selection =
2567                    buffer.bytes_in_range(last_selection.end..buffer.len());
2568                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
2569                let query_matches = query
2570                    .stream_find_iter(bytes_after_last_selection)
2571                    .map(|result| (last_selection.end, result))
2572                    .chain(
2573                        query
2574                            .stream_find_iter(bytes_before_first_selection)
2575                            .map(|result| (0, result)),
2576                    );
2577                for (start_offset, query_match) in query_matches {
2578                    let query_match = query_match.unwrap(); // can only fail due to I/O
2579                    let offset_range =
2580                        start_offset + query_match.start()..start_offset + query_match.end();
2581                    let display_range = offset_range.start.to_display_point(&display_map)
2582                        ..offset_range.end.to_display_point(&display_map);
2583
2584                    if !select_next_state.wordwise
2585                        || (!movement::is_inside_word(&display_map, display_range.start)
2586                            && !movement::is_inside_word(&display_map, display_range.end))
2587                    {
2588                        next_selected_range = Some(offset_range);
2589                        break;
2590                    }
2591                }
2592
2593                if let Some(next_selected_range) = next_selected_range {
2594                    if replace_newest {
2595                        if let Some(newest_id) =
2596                            selections.iter().max_by_key(|s| s.id).map(|s| s.id)
2597                        {
2598                            selections.retain(|s| s.id != newest_id);
2599                        }
2600                    }
2601                    selections.push(Selection {
2602                        id: post_inc(&mut self.next_selection_id),
2603                        start: next_selected_range.start,
2604                        end: next_selected_range.end,
2605                        reversed: false,
2606                        goal: SelectionGoal::None,
2607                    });
2608                    selections.sort_unstable_by_key(|s| s.start);
2609                    self.update_selections(selections, Some(Autoscroll::Newest), cx);
2610                } else {
2611                    select_next_state.done = true;
2612                }
2613            }
2614
2615            self.select_next_state = Some(select_next_state);
2616        } else if selections.len() == 1 {
2617            let selection = selections.last_mut().unwrap();
2618            if selection.start == selection.end {
2619                let word_range = movement::surrounding_word(
2620                    &display_map,
2621                    selection.start.to_display_point(&display_map),
2622                );
2623                selection.start = word_range.start.to_offset(&display_map, Bias::Left);
2624                selection.end = word_range.end.to_offset(&display_map, Bias::Left);
2625                selection.goal = SelectionGoal::None;
2626                selection.reversed = false;
2627
2628                let query = buffer
2629                    .text_for_range(selection.start..selection.end)
2630                    .collect::<String>();
2631                let select_state = SelectNextState {
2632                    query: AhoCorasick::new_auto_configured(&[query]),
2633                    wordwise: true,
2634                    done: false,
2635                };
2636                self.update_selections(selections, Some(Autoscroll::Newest), cx);
2637                self.select_next_state = Some(select_state);
2638            } else {
2639                let query = buffer
2640                    .text_for_range(selection.start..selection.end)
2641                    .collect::<String>();
2642                self.select_next_state = Some(SelectNextState {
2643                    query: AhoCorasick::new_auto_configured(&[query]),
2644                    wordwise: false,
2645                    done: false,
2646                });
2647                self.select_next(action, cx);
2648            }
2649        }
2650    }
2651
2652    pub fn toggle_comments(&mut self, _: &ToggleComments, cx: &mut ViewContext<Self>) {
2653        // Get the line comment prefix. Split its trailing whitespace into a separate string,
2654        // as that portion won't be used for detecting if a line is a comment.
2655        let full_comment_prefix =
2656            if let Some(prefix) = self.language(cx).and_then(|l| l.line_comment_prefix()) {
2657                prefix.to_string()
2658            } else {
2659                return;
2660            };
2661        let comment_prefix = full_comment_prefix.trim_end_matches(' ');
2662        let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
2663
2664        self.start_transaction(cx);
2665        let mut selections = self.local_selections::<Point>(cx);
2666        let mut all_selection_lines_are_comments = true;
2667        let mut edit_ranges = Vec::new();
2668        let mut last_toggled_row = None;
2669        self.buffer.update(cx, |buffer, cx| {
2670            for selection in &mut selections {
2671                edit_ranges.clear();
2672                let snapshot = buffer.snapshot(cx);
2673
2674                let end_row =
2675                    if selection.end.row > selection.start.row && selection.end.column == 0 {
2676                        selection.end.row
2677                    } else {
2678                        selection.end.row + 1
2679                    };
2680
2681                for row in selection.start.row..end_row {
2682                    // If multiple selections contain a given row, avoid processing that
2683                    // row more than once.
2684                    if last_toggled_row == Some(row) {
2685                        continue;
2686                    } else {
2687                        last_toggled_row = Some(row);
2688                    }
2689
2690                    if snapshot.is_line_blank(row) {
2691                        continue;
2692                    }
2693
2694                    let start = Point::new(row, snapshot.indent_column_for_line(row));
2695                    let mut line_bytes = snapshot
2696                        .bytes_in_range(start..snapshot.max_point())
2697                        .flatten()
2698                        .copied();
2699
2700                    // If this line currently begins with the line comment prefix, then record
2701                    // the range containing the prefix.
2702                    if all_selection_lines_are_comments
2703                        && line_bytes
2704                            .by_ref()
2705                            .take(comment_prefix.len())
2706                            .eq(comment_prefix.bytes())
2707                    {
2708                        // Include any whitespace that matches the comment prefix.
2709                        let matching_whitespace_len = line_bytes
2710                            .zip(comment_prefix_whitespace.bytes())
2711                            .take_while(|(a, b)| a == b)
2712                            .count() as u32;
2713                        let end = Point::new(
2714                            row,
2715                            start.column + comment_prefix.len() as u32 + matching_whitespace_len,
2716                        );
2717                        edit_ranges.push(start..end);
2718                    }
2719                    // If this line does not begin with the line comment prefix, then record
2720                    // the position where the prefix should be inserted.
2721                    else {
2722                        all_selection_lines_are_comments = false;
2723                        edit_ranges.push(start..start);
2724                    }
2725                }
2726
2727                if !edit_ranges.is_empty() {
2728                    if all_selection_lines_are_comments {
2729                        buffer.edit(edit_ranges.iter().cloned(), "", cx);
2730                    } else {
2731                        let min_column = edit_ranges.iter().map(|r| r.start.column).min().unwrap();
2732                        let edit_ranges = edit_ranges.iter().map(|range| {
2733                            let position = Point::new(range.start.row, min_column);
2734                            position..position
2735                        });
2736                        buffer.edit(edit_ranges, &full_comment_prefix, cx);
2737                    }
2738                }
2739            }
2740        });
2741
2742        self.update_selections(
2743            self.local_selections::<usize>(cx),
2744            Some(Autoscroll::Fit),
2745            cx,
2746        );
2747        self.end_transaction(cx);
2748    }
2749
2750    pub fn select_larger_syntax_node(
2751        &mut self,
2752        _: &SelectLargerSyntaxNode,
2753        cx: &mut ViewContext<Self>,
2754    ) {
2755        let old_selections = self.local_selections::<usize>(cx).into_boxed_slice();
2756        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2757        let buffer = self.buffer.read(cx).snapshot(cx);
2758
2759        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
2760        let mut selected_larger_node = false;
2761        let mut new_selections = old_selections
2762            .iter()
2763            .map(|selection| {
2764                let old_range = selection.start..selection.end;
2765                let mut new_range = old_range.clone();
2766                while let Some(containing_range) =
2767                    buffer.range_for_syntax_ancestor(new_range.clone())
2768                {
2769                    new_range = containing_range;
2770                    if !display_map.intersects_fold(new_range.start)
2771                        && !display_map.intersects_fold(new_range.end)
2772                    {
2773                        break;
2774                    }
2775                }
2776
2777                selected_larger_node |= new_range != old_range;
2778                Selection {
2779                    id: selection.id,
2780                    start: new_range.start,
2781                    end: new_range.end,
2782                    goal: SelectionGoal::None,
2783                    reversed: selection.reversed,
2784                }
2785            })
2786            .collect::<Vec<_>>();
2787
2788        if selected_larger_node {
2789            stack.push(old_selections);
2790            new_selections.sort_unstable_by_key(|selection| selection.start);
2791            self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2792        }
2793        self.select_larger_syntax_node_stack = stack;
2794    }
2795
2796    pub fn select_smaller_syntax_node(
2797        &mut self,
2798        _: &SelectSmallerSyntaxNode,
2799        cx: &mut ViewContext<Self>,
2800    ) {
2801        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
2802        if let Some(selections) = stack.pop() {
2803            self.update_selections(selections.to_vec(), Some(Autoscroll::Fit), cx);
2804        }
2805        self.select_larger_syntax_node_stack = stack;
2806    }
2807
2808    pub fn move_to_enclosing_bracket(
2809        &mut self,
2810        _: &MoveToEnclosingBracket,
2811        cx: &mut ViewContext<Self>,
2812    ) {
2813        let mut selections = self.local_selections::<usize>(cx);
2814        let buffer = self.buffer.read(cx).snapshot(cx);
2815        for selection in &mut selections {
2816            if let Some((open_range, close_range)) =
2817                buffer.enclosing_bracket_ranges(selection.start..selection.end)
2818            {
2819                let close_range = close_range.to_inclusive();
2820                let destination = if close_range.contains(&selection.start)
2821                    && close_range.contains(&selection.end)
2822                {
2823                    open_range.end
2824                } else {
2825                    *close_range.start()
2826                };
2827                selection.start = destination;
2828                selection.end = destination;
2829            }
2830        }
2831
2832        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2833    }
2834
2835    pub fn show_next_diagnostic(&mut self, _: &ShowNextDiagnostic, cx: &mut ViewContext<Self>) {
2836        let buffer = self.buffer.read(cx).snapshot(cx);
2837        let selection = self.newest_selection::<usize>(&buffer);
2838        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
2839            active_diagnostics
2840                .primary_range
2841                .to_offset(&buffer)
2842                .to_inclusive()
2843        });
2844        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
2845            if active_primary_range.contains(&selection.head()) {
2846                *active_primary_range.end()
2847            } else {
2848                selection.head()
2849            }
2850        } else {
2851            selection.head()
2852        };
2853
2854        loop {
2855            let next_group = buffer
2856                .diagnostics_in_range::<_, usize>(search_start..buffer.len())
2857                .find_map(|entry| {
2858                    if entry.diagnostic.is_primary
2859                        && !entry.range.is_empty()
2860                        && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
2861                    {
2862                        Some((entry.range, entry.diagnostic.group_id))
2863                    } else {
2864                        None
2865                    }
2866                });
2867
2868            if let Some((primary_range, group_id)) = next_group {
2869                self.activate_diagnostics(group_id, cx);
2870                self.update_selections(
2871                    vec![Selection {
2872                        id: selection.id,
2873                        start: primary_range.start,
2874                        end: primary_range.start,
2875                        reversed: false,
2876                        goal: SelectionGoal::None,
2877                    }],
2878                    Some(Autoscroll::Center),
2879                    cx,
2880                );
2881                break;
2882            } else if search_start == 0 {
2883                break;
2884            } else {
2885                // Cycle around to the start of the buffer.
2886                search_start = 0;
2887            }
2888        }
2889    }
2890
2891    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
2892        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
2893            let buffer = self.buffer.read(cx).snapshot(cx);
2894            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
2895            let is_valid = buffer
2896                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
2897                .any(|entry| {
2898                    entry.diagnostic.is_primary
2899                        && !entry.range.is_empty()
2900                        && entry.range.start == primary_range_start
2901                        && entry.diagnostic.message == active_diagnostics.primary_message
2902                });
2903
2904            if is_valid != active_diagnostics.is_valid {
2905                active_diagnostics.is_valid = is_valid;
2906                let mut new_styles = HashMap::new();
2907                for (block_id, diagnostic) in &active_diagnostics.blocks {
2908                    let build_settings = self.build_settings.clone();
2909                    let diagnostic = diagnostic.clone();
2910                    new_styles.insert(*block_id, move |cx: &BlockContext| {
2911                        let diagnostic = diagnostic.clone();
2912                        let settings = build_settings.borrow()(cx.cx);
2913                        render_diagnostic(diagnostic, &settings.style, is_valid, cx.anchor_x)
2914                    });
2915                }
2916                self.display_map
2917                    .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
2918            }
2919        }
2920    }
2921
2922    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
2923        self.dismiss_diagnostics(cx);
2924        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
2925            let buffer = self.buffer.read(cx).snapshot(cx);
2926
2927            let mut primary_range = None;
2928            let mut primary_message = None;
2929            let mut group_end = Point::zero();
2930            let diagnostic_group = buffer
2931                .diagnostic_group::<Point>(group_id)
2932                .map(|entry| {
2933                    if entry.range.end > group_end {
2934                        group_end = entry.range.end;
2935                    }
2936                    if entry.diagnostic.is_primary {
2937                        primary_range = Some(entry.range.clone());
2938                        primary_message = Some(entry.diagnostic.message.clone());
2939                    }
2940                    entry
2941                })
2942                .collect::<Vec<_>>();
2943            let primary_range = primary_range.unwrap();
2944            let primary_message = primary_message.unwrap();
2945            let primary_range =
2946                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
2947
2948            let blocks = display_map
2949                .insert_blocks(
2950                    diagnostic_group.iter().map(|entry| {
2951                        let build_settings = self.build_settings.clone();
2952                        let diagnostic = entry.diagnostic.clone();
2953                        let message_height = diagnostic.message.lines().count() as u8;
2954
2955                        BlockProperties {
2956                            position: entry.range.start,
2957                            height: message_height,
2958                            render: Arc::new(move |cx| {
2959                                let settings = build_settings.borrow()(cx.cx);
2960                                let diagnostic = diagnostic.clone();
2961                                render_diagnostic(diagnostic, &settings.style, true, cx.anchor_x)
2962                            }),
2963                            disposition: BlockDisposition::Below,
2964                        }
2965                    }),
2966                    cx,
2967                )
2968                .into_iter()
2969                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
2970                .collect();
2971
2972            Some(ActiveDiagnosticGroup {
2973                primary_range,
2974                primary_message,
2975                blocks,
2976                is_valid: true,
2977            })
2978        });
2979    }
2980
2981    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
2982        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
2983            self.display_map.update(cx, |display_map, cx| {
2984                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
2985            });
2986            cx.notify();
2987        }
2988    }
2989
2990    fn build_columnar_selection(
2991        &mut self,
2992        display_map: &DisplaySnapshot,
2993        row: u32,
2994        columns: &Range<u32>,
2995        reversed: bool,
2996    ) -> Option<Selection<Point>> {
2997        let is_empty = columns.start == columns.end;
2998        let line_len = display_map.line_len(row);
2999        if columns.start < line_len || (is_empty && columns.start == line_len) {
3000            let start = DisplayPoint::new(row, columns.start);
3001            let end = DisplayPoint::new(row, cmp::min(columns.end, line_len));
3002            Some(Selection {
3003                id: post_inc(&mut self.next_selection_id),
3004                start: start.to_point(display_map),
3005                end: end.to_point(display_map),
3006                reversed,
3007                goal: SelectionGoal::ColumnRange {
3008                    start: columns.start,
3009                    end: columns.end,
3010                },
3011            })
3012        } else {
3013            None
3014        }
3015    }
3016
3017    pub fn visible_selections<'a>(
3018        &'a self,
3019        display_rows: Range<u32>,
3020        cx: &'a mut MutableAppContext,
3021    ) -> HashMap<ReplicaId, Vec<Selection<DisplayPoint>>> {
3022        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3023        let buffer = &display_map.buffer_snapshot;
3024
3025        let start = if display_rows.start == 0 {
3026            Anchor::min()
3027        } else {
3028            buffer.anchor_before(
3029                DisplayPoint::new(display_rows.start, 0).to_offset(&display_map, Bias::Left),
3030            )
3031        };
3032        let end = if display_rows.end > display_map.max_point().row() {
3033            Anchor::max()
3034        } else {
3035            buffer.anchor_before(
3036                DisplayPoint::new(display_rows.end, 0).to_offset(&display_map, Bias::Right),
3037            )
3038        };
3039
3040        let start_ix = match self
3041            .selections
3042            .binary_search_by(|probe| probe.end.cmp(&start, &buffer).unwrap())
3043        {
3044            Ok(ix) | Err(ix) => ix,
3045        };
3046        let end_ix = match self
3047            .selections
3048            .binary_search_by(|probe| probe.start.cmp(&end, &buffer).unwrap())
3049        {
3050            Ok(ix) => ix + 1,
3051            Err(ix) => ix,
3052        };
3053
3054        fn display_selection(
3055            selection: &Selection<Anchor>,
3056            display_map: &DisplaySnapshot,
3057        ) -> Selection<DisplayPoint> {
3058            Selection {
3059                id: selection.id,
3060                start: selection.start.to_display_point(&display_map),
3061                end: selection.end.to_display_point(&display_map),
3062                reversed: selection.reversed,
3063                goal: selection.goal,
3064            }
3065        }
3066
3067        let mut result = HashMap::new();
3068
3069        result.insert(
3070            self.replica_id(cx),
3071            self.selections[start_ix..end_ix]
3072                .iter()
3073                .chain(
3074                    self.pending_selection
3075                        .as_ref()
3076                        .map(|pending| &pending.selection),
3077                )
3078                .map(|s| display_selection(s, &display_map))
3079                .collect(),
3080        );
3081
3082        for (replica_id, selections) in display_map
3083            .buffer_snapshot
3084            .remote_selections_in_range(start..end)
3085        {
3086            result.insert(
3087                replica_id,
3088                selections
3089                    .map(|s| display_selection(&s, &display_map))
3090                    .collect(),
3091            );
3092        }
3093
3094        result
3095    }
3096
3097    pub fn local_selections<'a, D>(&self, cx: &'a AppContext) -> Vec<Selection<D>>
3098    where
3099        D: 'a + TextDimension + Ord + Sub<D, Output = D>,
3100    {
3101        let buffer = self.buffer.read(cx).snapshot(cx);
3102
3103        let mut summaries = buffer
3104            .summaries_for_anchors::<D, _>(self.selections.iter().flat_map(|s| [&s.start, &s.end]))
3105            .into_iter();
3106
3107        let mut selections = self
3108            .selections
3109            .iter()
3110            .map(|s| Selection {
3111                id: s.id,
3112                start: summaries.next().unwrap(),
3113                end: summaries.next().unwrap(),
3114                reversed: s.reversed,
3115                goal: s.goal,
3116            })
3117            .peekable();
3118
3119        let mut pending_selection = self.pending_selection::<D>(&buffer);
3120
3121        iter::from_fn(move || {
3122            if let Some(pending) = pending_selection.as_mut() {
3123                while let Some(next_selection) = selections.peek() {
3124                    if pending.start <= next_selection.end && pending.end >= next_selection.start {
3125                        let next_selection = selections.next().unwrap();
3126                        if next_selection.start < pending.start {
3127                            pending.start = next_selection.start;
3128                        }
3129                        if next_selection.end > pending.end {
3130                            pending.end = next_selection.end;
3131                        }
3132                    } else if next_selection.end < pending.start {
3133                        return selections.next();
3134                    } else {
3135                        break;
3136                    }
3137                }
3138
3139                pending_selection.take()
3140            } else {
3141                selections.next()
3142            }
3143        })
3144        .collect()
3145    }
3146
3147    fn pending_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3148        &self,
3149        snapshot: &MultiBufferSnapshot,
3150    ) -> Option<Selection<D>> {
3151        self.pending_selection
3152            .as_ref()
3153            .map(|pending| self.resolve_selection(&pending.selection, &snapshot))
3154    }
3155
3156    fn resolve_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3157        &self,
3158        selection: &Selection<Anchor>,
3159        buffer: &MultiBufferSnapshot,
3160    ) -> Selection<D> {
3161        Selection {
3162            id: selection.id,
3163            start: selection.start.summary::<D>(&buffer),
3164            end: selection.end.summary::<D>(&buffer),
3165            reversed: selection.reversed,
3166            goal: selection.goal,
3167        }
3168    }
3169
3170    fn selection_count<'a>(&self) -> usize {
3171        let mut count = self.selections.len();
3172        if self.pending_selection.is_some() {
3173            count += 1;
3174        }
3175        count
3176    }
3177
3178    pub fn oldest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3179        &self,
3180        snapshot: &MultiBufferSnapshot,
3181    ) -> Selection<D> {
3182        self.selections
3183            .iter()
3184            .min_by_key(|s| s.id)
3185            .map(|selection| self.resolve_selection(selection, snapshot))
3186            .or_else(|| self.pending_selection(snapshot))
3187            .unwrap()
3188    }
3189
3190    pub fn newest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3191        &self,
3192        snapshot: &MultiBufferSnapshot,
3193    ) -> Selection<D> {
3194        self.pending_selection(snapshot)
3195            .or_else(|| {
3196                self.selections
3197                    .iter()
3198                    .min_by_key(|s| s.id)
3199                    .map(|selection| self.resolve_selection(selection, snapshot))
3200            })
3201            .unwrap()
3202    }
3203
3204    pub fn update_selections<T>(
3205        &mut self,
3206        mut selections: Vec<Selection<T>>,
3207        autoscroll: Option<Autoscroll>,
3208        cx: &mut ViewContext<Self>,
3209    ) where
3210        T: ToOffset + ToPoint + Ord + std::marker::Copy + std::fmt::Debug,
3211    {
3212        // Merge overlapping selections.
3213        let buffer = self.buffer.read(cx).snapshot(cx);
3214        let mut i = 1;
3215        while i < selections.len() {
3216            if selections[i - 1].end >= selections[i].start {
3217                let removed = selections.remove(i);
3218                if removed.start < selections[i - 1].start {
3219                    selections[i - 1].start = removed.start;
3220                }
3221                if removed.end > selections[i - 1].end {
3222                    selections[i - 1].end = removed.end;
3223                }
3224            } else {
3225                i += 1;
3226            }
3227        }
3228
3229        self.pending_selection = None;
3230        self.add_selections_state = None;
3231        self.select_next_state = None;
3232        self.select_larger_syntax_node_stack.clear();
3233        while let Some(autoclose_pair) = self.autoclose_stack.last() {
3234            let all_selections_inside_autoclose_ranges =
3235                if selections.len() == autoclose_pair.ranges.len() {
3236                    selections
3237                        .iter()
3238                        .zip(autoclose_pair.ranges.iter().map(|r| r.to_point(&buffer)))
3239                        .all(|(selection, autoclose_range)| {
3240                            let head = selection.head().to_point(&buffer);
3241                            autoclose_range.start <= head && autoclose_range.end >= head
3242                        })
3243                } else {
3244                    false
3245                };
3246
3247            if all_selections_inside_autoclose_ranges {
3248                break;
3249            } else {
3250                self.autoclose_stack.pop();
3251            }
3252        }
3253
3254        if let Some(autoscroll) = autoscroll {
3255            self.request_autoscroll(autoscroll, cx);
3256        }
3257        self.pause_cursor_blinking(cx);
3258
3259        self.set_selections(
3260            Arc::from_iter(selections.into_iter().map(|selection| Selection {
3261                id: selection.id,
3262                start: buffer.anchor_before(selection.start),
3263                end: buffer.anchor_before(selection.end),
3264                reversed: selection.reversed,
3265                goal: selection.goal,
3266            })),
3267            cx,
3268        );
3269    }
3270
3271    fn set_selections(&mut self, selections: Arc<[Selection<Anchor>]>, cx: &mut ViewContext<Self>) {
3272        self.selections = selections;
3273        self.buffer.update(cx, |buffer, cx| {
3274            buffer.set_active_selections(&self.selections, cx)
3275        });
3276    }
3277
3278    fn request_autoscroll(&mut self, autoscroll: Autoscroll, cx: &mut ViewContext<Self>) {
3279        self.autoscroll_request = Some(autoscroll);
3280        cx.notify();
3281    }
3282
3283    fn start_transaction(&mut self, cx: &mut ViewContext<Self>) {
3284        self.start_transaction_at(Instant::now(), cx);
3285    }
3286
3287    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
3288        self.end_selection(cx);
3289        if let Some(tx_id) = self
3290            .buffer
3291            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
3292        {
3293            self.selection_history
3294                .insert(tx_id, (self.selections.clone(), None));
3295        }
3296    }
3297
3298    fn end_transaction(&mut self, cx: &mut ViewContext<Self>) {
3299        self.end_transaction_at(Instant::now(), cx);
3300    }
3301
3302    fn end_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
3303        if let Some(tx_id) = self
3304            .buffer
3305            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
3306        {
3307            self.selection_history.get_mut(&tx_id).unwrap().1 = Some(self.selections.clone());
3308        }
3309    }
3310
3311    pub fn page_up(&mut self, _: &PageUp, _: &mut ViewContext<Self>) {
3312        log::info!("Editor::page_up");
3313    }
3314
3315    pub fn page_down(&mut self, _: &PageDown, _: &mut ViewContext<Self>) {
3316        log::info!("Editor::page_down");
3317    }
3318
3319    pub fn fold(&mut self, _: &Fold, cx: &mut ViewContext<Self>) {
3320        let mut fold_ranges = Vec::new();
3321
3322        let selections = self.local_selections::<Point>(cx);
3323        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3324        for selection in selections {
3325            let range = selection.display_range(&display_map).sorted();
3326            let buffer_start_row = range.start.to_point(&display_map).row;
3327
3328            for row in (0..=range.end.row()).rev() {
3329                if self.is_line_foldable(&display_map, row) && !display_map.is_line_folded(row) {
3330                    let fold_range = self.foldable_range_for_line(&display_map, row);
3331                    if fold_range.end.row >= buffer_start_row {
3332                        fold_ranges.push(fold_range);
3333                        if row <= range.start.row() {
3334                            break;
3335                        }
3336                    }
3337                }
3338            }
3339        }
3340
3341        self.fold_ranges(fold_ranges, cx);
3342    }
3343
3344    pub fn unfold(&mut self, _: &Unfold, cx: &mut ViewContext<Self>) {
3345        let selections = self.local_selections::<Point>(cx);
3346        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3347        let buffer = &display_map.buffer_snapshot;
3348        let ranges = selections
3349            .iter()
3350            .map(|s| {
3351                let range = s.display_range(&display_map).sorted();
3352                let mut start = range.start.to_point(&display_map);
3353                let mut end = range.end.to_point(&display_map);
3354                start.column = 0;
3355                end.column = buffer.line_len(end.row);
3356                start..end
3357            })
3358            .collect::<Vec<_>>();
3359        self.unfold_ranges(ranges, cx);
3360    }
3361
3362    fn is_line_foldable(&self, display_map: &DisplaySnapshot, display_row: u32) -> bool {
3363        let max_point = display_map.max_point();
3364        if display_row >= max_point.row() {
3365            false
3366        } else {
3367            let (start_indent, is_blank) = display_map.line_indent(display_row);
3368            if is_blank {
3369                false
3370            } else {
3371                for display_row in display_row + 1..=max_point.row() {
3372                    let (indent, is_blank) = display_map.line_indent(display_row);
3373                    if !is_blank {
3374                        return indent > start_indent;
3375                    }
3376                }
3377                false
3378            }
3379        }
3380    }
3381
3382    fn foldable_range_for_line(
3383        &self,
3384        display_map: &DisplaySnapshot,
3385        start_row: u32,
3386    ) -> Range<Point> {
3387        let max_point = display_map.max_point();
3388
3389        let (start_indent, _) = display_map.line_indent(start_row);
3390        let start = DisplayPoint::new(start_row, display_map.line_len(start_row));
3391        let mut end = None;
3392        for row in start_row + 1..=max_point.row() {
3393            let (indent, is_blank) = display_map.line_indent(row);
3394            if !is_blank && indent <= start_indent {
3395                end = Some(DisplayPoint::new(row - 1, display_map.line_len(row - 1)));
3396                break;
3397            }
3398        }
3399
3400        let end = end.unwrap_or(max_point);
3401        return start.to_point(display_map)..end.to_point(display_map);
3402    }
3403
3404    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
3405        let selections = self.local_selections::<Point>(cx);
3406        let ranges = selections.into_iter().map(|s| s.start..s.end);
3407        self.fold_ranges(ranges, cx);
3408    }
3409
3410    fn fold_ranges<T: ToOffset>(
3411        &mut self,
3412        ranges: impl IntoIterator<Item = Range<T>>,
3413        cx: &mut ViewContext<Self>,
3414    ) {
3415        let mut ranges = ranges.into_iter().peekable();
3416        if ranges.peek().is_some() {
3417            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
3418            self.request_autoscroll(Autoscroll::Fit, cx);
3419            cx.notify();
3420        }
3421    }
3422
3423    fn unfold_ranges<T: ToOffset>(&mut self, ranges: Vec<Range<T>>, cx: &mut ViewContext<Self>) {
3424        if !ranges.is_empty() {
3425            self.display_map
3426                .update(cx, |map, cx| map.unfold(ranges, cx));
3427            self.request_autoscroll(Autoscroll::Fit, cx);
3428            cx.notify();
3429        }
3430    }
3431
3432    pub fn longest_row(&self, cx: &mut MutableAppContext) -> u32 {
3433        self.display_map
3434            .update(cx, |map, cx| map.snapshot(cx))
3435            .longest_row()
3436    }
3437
3438    pub fn max_point(&self, cx: &mut MutableAppContext) -> DisplayPoint {
3439        self.display_map
3440            .update(cx, |map, cx| map.snapshot(cx))
3441            .max_point()
3442    }
3443
3444    pub fn text(&self, cx: &AppContext) -> String {
3445        self.buffer.read(cx).read(cx).text()
3446    }
3447
3448    pub fn display_text(&self, cx: &mut MutableAppContext) -> String {
3449        self.display_map
3450            .update(cx, |map, cx| map.snapshot(cx))
3451            .text()
3452    }
3453
3454    pub fn set_wrap_width(&self, width: Option<f32>, cx: &mut MutableAppContext) -> bool {
3455        self.display_map
3456            .update(cx, |map, cx| map.set_wrap_width(width, cx))
3457    }
3458
3459    pub fn set_highlighted_row(&mut self, row: Option<u32>) {
3460        self.highlighted_row = row;
3461    }
3462
3463    pub fn highlighted_row(&mut self) -> Option<u32> {
3464        self.highlighted_row
3465    }
3466
3467    fn next_blink_epoch(&mut self) -> usize {
3468        self.blink_epoch += 1;
3469        self.blink_epoch
3470    }
3471
3472    fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
3473        self.show_local_cursors = true;
3474        cx.notify();
3475
3476        let epoch = self.next_blink_epoch();
3477        cx.spawn(|this, mut cx| {
3478            let this = this.downgrade();
3479            async move {
3480                Timer::after(CURSOR_BLINK_INTERVAL).await;
3481                if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
3482                    this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
3483                }
3484            }
3485        })
3486        .detach();
3487    }
3488
3489    fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
3490        if epoch == self.blink_epoch {
3491            self.blinking_paused = false;
3492            self.blink_cursors(epoch, cx);
3493        }
3494    }
3495
3496    fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
3497        if epoch == self.blink_epoch && self.focused && !self.blinking_paused {
3498            self.show_local_cursors = !self.show_local_cursors;
3499            cx.notify();
3500
3501            let epoch = self.next_blink_epoch();
3502            cx.spawn(|this, mut cx| {
3503                let this = this.downgrade();
3504                async move {
3505                    Timer::after(CURSOR_BLINK_INTERVAL).await;
3506                    if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
3507                        this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx));
3508                    }
3509                }
3510            })
3511            .detach();
3512        }
3513    }
3514
3515    pub fn show_local_cursors(&self) -> bool {
3516        self.show_local_cursors
3517    }
3518
3519    fn on_buffer_changed(&mut self, _: ModelHandle<MultiBuffer>, cx: &mut ViewContext<Self>) {
3520        self.refresh_active_diagnostics(cx);
3521        cx.notify();
3522    }
3523
3524    fn on_buffer_event(
3525        &mut self,
3526        _: ModelHandle<MultiBuffer>,
3527        event: &language::Event,
3528        cx: &mut ViewContext<Self>,
3529    ) {
3530        match event {
3531            language::Event::Edited => cx.emit(Event::Edited),
3532            language::Event::Dirtied => cx.emit(Event::Dirtied),
3533            language::Event::Saved => cx.emit(Event::Saved),
3534            language::Event::FileHandleChanged => cx.emit(Event::FileHandleChanged),
3535            language::Event::Reloaded => cx.emit(Event::FileHandleChanged),
3536            language::Event::Closed => cx.emit(Event::Closed),
3537            _ => {}
3538        }
3539    }
3540
3541    fn on_display_map_changed(&mut self, _: ModelHandle<DisplayMap>, cx: &mut ViewContext<Self>) {
3542        cx.notify();
3543    }
3544}
3545
3546impl EditorSnapshot {
3547    pub fn is_focused(&self) -> bool {
3548        self.is_focused
3549    }
3550
3551    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
3552        self.placeholder_text.as_ref()
3553    }
3554
3555    pub fn scroll_position(&self) -> Vector2F {
3556        compute_scroll_position(
3557            &self.display_snapshot,
3558            self.scroll_position,
3559            &self.scroll_top_anchor,
3560        )
3561    }
3562}
3563
3564impl Deref for EditorSnapshot {
3565    type Target = DisplaySnapshot;
3566
3567    fn deref(&self) -> &Self::Target {
3568        &self.display_snapshot
3569    }
3570}
3571
3572impl EditorSettings {
3573    #[cfg(any(test, feature = "test-support"))]
3574    pub fn test(cx: &AppContext) -> Self {
3575        Self {
3576            tab_size: 4,
3577            soft_wrap: SoftWrap::None,
3578            style: {
3579                let font_cache: &gpui::FontCache = cx.font_cache();
3580                let font_family_name = Arc::from("Monaco");
3581                let font_properties = Default::default();
3582                let font_family_id = font_cache.load_family(&[&font_family_name]).unwrap();
3583                let font_id = font_cache
3584                    .select_font(font_family_id, &font_properties)
3585                    .unwrap();
3586                EditorStyle {
3587                    text: gpui::fonts::TextStyle {
3588                        font_family_name,
3589                        font_family_id,
3590                        font_id,
3591                        font_size: 14.,
3592                        color: gpui::color::Color::from_u32(0xff0000ff),
3593                        font_properties,
3594                        underline: None,
3595                    },
3596                    placeholder_text: None,
3597                    background: Default::default(),
3598                    gutter_background: Default::default(),
3599                    active_line_background: Default::default(),
3600                    highlighted_line_background: Default::default(),
3601                    line_number: Default::default(),
3602                    line_number_active: Default::default(),
3603                    selection: Default::default(),
3604                    guest_selections: Default::default(),
3605                    syntax: Default::default(),
3606                    error_diagnostic: Default::default(),
3607                    invalid_error_diagnostic: Default::default(),
3608                    warning_diagnostic: Default::default(),
3609                    invalid_warning_diagnostic: Default::default(),
3610                    information_diagnostic: Default::default(),
3611                    invalid_information_diagnostic: Default::default(),
3612                    hint_diagnostic: Default::default(),
3613                    invalid_hint_diagnostic: Default::default(),
3614                }
3615            },
3616        }
3617    }
3618}
3619
3620fn compute_scroll_position(
3621    snapshot: &DisplaySnapshot,
3622    mut scroll_position: Vector2F,
3623    scroll_top_anchor: &Anchor,
3624) -> Vector2F {
3625    let scroll_top = scroll_top_anchor.to_display_point(snapshot).row() as f32;
3626    scroll_position.set_y(scroll_top + scroll_position.y());
3627    scroll_position
3628}
3629
3630pub enum Event {
3631    Activate,
3632    Edited,
3633    Blurred,
3634    Dirtied,
3635    Saved,
3636    FileHandleChanged,
3637    Closed,
3638}
3639
3640impl Entity for Editor {
3641    type Event = Event;
3642}
3643
3644impl View for Editor {
3645    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
3646        let settings = self.build_settings.borrow_mut()(cx);
3647        self.display_map.update(cx, |map, cx| {
3648            map.set_font(
3649                settings.style.text.font_id,
3650                settings.style.text.font_size,
3651                cx,
3652            )
3653        });
3654        EditorElement::new(self.handle.clone(), settings).boxed()
3655    }
3656
3657    fn ui_name() -> &'static str {
3658        "Editor"
3659    }
3660
3661    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
3662        self.focused = true;
3663        self.blink_cursors(self.blink_epoch, cx);
3664        self.buffer.update(cx, |buffer, cx| {
3665            buffer.set_active_selections(&self.selections, cx)
3666        });
3667    }
3668
3669    fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
3670        self.focused = false;
3671        self.show_local_cursors = false;
3672        self.buffer
3673            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
3674        cx.emit(Event::Blurred);
3675        cx.notify();
3676    }
3677
3678    fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
3679        let mut cx = Self::default_keymap_context();
3680        let mode = match self.mode {
3681            EditorMode::SingleLine => "single_line",
3682            EditorMode::AutoHeight { .. } => "auto_height",
3683            EditorMode::Full => "full",
3684        };
3685        cx.map.insert("mode".into(), mode.into());
3686        cx
3687    }
3688}
3689
3690impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
3691    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
3692        let start = self.start.to_point(buffer);
3693        let end = self.end.to_point(buffer);
3694        if self.reversed {
3695            end..start
3696        } else {
3697            start..end
3698        }
3699    }
3700
3701    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
3702        let start = self.start.to_offset(buffer);
3703        let end = self.end.to_offset(buffer);
3704        if self.reversed {
3705            end..start
3706        } else {
3707            start..end
3708        }
3709    }
3710
3711    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
3712        let start = self
3713            .start
3714            .to_point(&map.buffer_snapshot)
3715            .to_display_point(map);
3716        let end = self
3717            .end
3718            .to_point(&map.buffer_snapshot)
3719            .to_display_point(map);
3720        if self.reversed {
3721            end..start
3722        } else {
3723            start..end
3724        }
3725    }
3726
3727    fn spanned_rows(
3728        &self,
3729        include_end_if_at_line_start: bool,
3730        map: &DisplaySnapshot,
3731    ) -> SpannedRows {
3732        let display_start = self
3733            .start
3734            .to_point(&map.buffer_snapshot)
3735            .to_display_point(map);
3736        let mut display_end = self
3737            .end
3738            .to_point(&map.buffer_snapshot)
3739            .to_display_point(map);
3740        if !include_end_if_at_line_start
3741            && display_end.row() != map.max_point().row()
3742            && display_start.row() != display_end.row()
3743            && display_end.column() == 0
3744        {
3745            *display_end.row_mut() -= 1;
3746        }
3747
3748        let (display_start, buffer_start) = map.prev_row_boundary(display_start);
3749        let (display_end, buffer_end) = map.next_row_boundary(display_end);
3750
3751        SpannedRows {
3752            buffer_rows: buffer_start.row..buffer_end.row + 1,
3753            display_rows: display_start.row()..display_end.row() + 1,
3754        }
3755    }
3756}
3757
3758fn render_diagnostic(
3759    diagnostic: Diagnostic,
3760    style: &EditorStyle,
3761    valid: bool,
3762    anchor_x: f32,
3763) -> ElementBox {
3764    let mut text_style = style.text.clone();
3765    text_style.color = diagnostic_style(diagnostic.severity, valid, &style).text;
3766    Text::new(diagnostic.message, text_style)
3767        .contained()
3768        .with_margin_left(anchor_x)
3769        .boxed()
3770}
3771
3772pub fn diagnostic_style(
3773    severity: DiagnosticSeverity,
3774    valid: bool,
3775    style: &EditorStyle,
3776) -> DiagnosticStyle {
3777    match (severity, valid) {
3778        (DiagnosticSeverity::ERROR, true) => style.error_diagnostic,
3779        (DiagnosticSeverity::ERROR, false) => style.invalid_error_diagnostic,
3780        (DiagnosticSeverity::WARNING, true) => style.warning_diagnostic,
3781        (DiagnosticSeverity::WARNING, false) => style.invalid_warning_diagnostic,
3782        (DiagnosticSeverity::INFORMATION, true) => style.information_diagnostic,
3783        (DiagnosticSeverity::INFORMATION, false) => style.invalid_information_diagnostic,
3784        (DiagnosticSeverity::HINT, true) => style.hint_diagnostic,
3785        (DiagnosticSeverity::HINT, false) => style.invalid_hint_diagnostic,
3786        _ => Default::default(),
3787    }
3788}
3789
3790#[cfg(test)]
3791mod tests {
3792    use super::*;
3793    use language::LanguageConfig;
3794    use std::time::Instant;
3795    use text::Point;
3796    use unindent::Unindent;
3797    use util::test::sample_text;
3798
3799    #[gpui::test]
3800    fn test_undo_redo_with_selection_restoration(cx: &mut MutableAppContext) {
3801        let mut now = Instant::now();
3802        let buffer = MultiBuffer::build_simple("123456", cx);
3803        let settings = EditorSettings::test(cx);
3804        let (_, editor) = cx.add_window(Default::default(), |cx| {
3805            build_editor(buffer.clone(), settings, cx)
3806        });
3807
3808        editor.update(cx, |editor, cx| {
3809            editor.start_transaction_at(now, cx);
3810            editor.select_ranges([2..4], None, cx);
3811            editor.insert("cd", cx);
3812            editor.end_transaction_at(now, cx);
3813            assert_eq!(editor.text(cx), "12cd56");
3814            assert_eq!(editor.selected_ranges(cx), vec![4..4]);
3815
3816            editor.start_transaction_at(now, cx);
3817            editor.select_ranges([4..5], None, cx);
3818            editor.insert("e", cx);
3819            editor.end_transaction_at(now, cx);
3820            assert_eq!(editor.text(cx), "12cde6");
3821            assert_eq!(editor.selected_ranges(cx), vec![5..5]);
3822
3823            now += buffer.read(cx).transaction_group_interval(cx) + Duration::from_millis(1);
3824            editor.select_ranges([2..2], None, cx);
3825
3826            // Simulate an edit in another editor
3827            buffer.update(cx, |buffer, cx| {
3828                buffer.start_transaction_at(now, cx);
3829                buffer.edit([0..1], "a", cx);
3830                buffer.edit([1..1], "b", cx);
3831                buffer.end_transaction_at(now, cx);
3832            });
3833
3834            assert_eq!(editor.text(cx), "ab2cde6");
3835            assert_eq!(editor.selected_ranges(cx), vec![3..3]);
3836
3837            // Last transaction happened past the group interval in a different editor.
3838            // Undo it individually and don't restore selections.
3839            editor.undo(&Undo, cx);
3840            assert_eq!(editor.text(cx), "12cde6");
3841            assert_eq!(editor.selected_ranges(cx), vec![2..2]);
3842
3843            // First two transactions happened within the group interval in this editor.
3844            // Undo them together and restore selections.
3845            editor.undo(&Undo, cx);
3846            editor.undo(&Undo, cx); // Undo stack is empty here, so this is a no-op.
3847            assert_eq!(editor.text(cx), "123456");
3848            assert_eq!(editor.selected_ranges(cx), vec![0..0]);
3849
3850            // Redo the first two transactions together.
3851            editor.redo(&Redo, cx);
3852            assert_eq!(editor.text(cx), "12cde6");
3853            assert_eq!(editor.selected_ranges(cx), vec![4..4]);
3854
3855            // Redo the last transaction on its own.
3856            editor.redo(&Redo, cx);
3857            assert_eq!(editor.text(cx), "ab2cde6");
3858            assert_eq!(editor.selected_ranges(cx), vec![5..5]);
3859
3860            // Test empty transactions.
3861            editor.start_transaction_at(now, cx);
3862            editor.end_transaction_at(now, cx);
3863            editor.undo(&Undo, cx);
3864            assert_eq!(editor.text(cx), "12cde6");
3865        });
3866    }
3867
3868    #[gpui::test]
3869    fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
3870        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
3871        let settings = EditorSettings::test(cx);
3872        let (_, editor) =
3873            cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3874
3875        editor.update(cx, |view, cx| {
3876            view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
3877        });
3878
3879        assert_eq!(
3880            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
3881            [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
3882        );
3883
3884        editor.update(cx, |view, cx| {
3885            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
3886        });
3887
3888        assert_eq!(
3889            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
3890            [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
3891        );
3892
3893        editor.update(cx, |view, cx| {
3894            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
3895        });
3896
3897        assert_eq!(
3898            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
3899            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
3900        );
3901
3902        editor.update(cx, |view, cx| {
3903            view.end_selection(cx);
3904            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
3905        });
3906
3907        assert_eq!(
3908            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
3909            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
3910        );
3911
3912        editor.update(cx, |view, cx| {
3913            view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
3914            view.update_selection(DisplayPoint::new(0, 0), 0, Vector2F::zero(), cx);
3915        });
3916
3917        eprintln!(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
3918        assert_eq!(
3919            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
3920            [
3921                DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
3922                DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
3923            ]
3924        );
3925
3926        editor.update(cx, |view, cx| {
3927            view.end_selection(cx);
3928        });
3929
3930        assert_eq!(
3931            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
3932            [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
3933        );
3934    }
3935
3936    #[gpui::test]
3937    fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
3938        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
3939        let settings = EditorSettings::test(cx);
3940        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3941
3942        view.update(cx, |view, cx| {
3943            view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
3944            assert_eq!(
3945                view.selected_display_ranges(cx),
3946                [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
3947            );
3948        });
3949
3950        view.update(cx, |view, cx| {
3951            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
3952            assert_eq!(
3953                view.selected_display_ranges(cx),
3954                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
3955            );
3956        });
3957
3958        view.update(cx, |view, cx| {
3959            view.cancel(&Cancel, cx);
3960            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
3961            assert_eq!(
3962                view.selected_display_ranges(cx),
3963                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
3964            );
3965        });
3966    }
3967
3968    #[gpui::test]
3969    fn test_cancel(cx: &mut gpui::MutableAppContext) {
3970        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
3971        let settings = EditorSettings::test(cx);
3972        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3973
3974        view.update(cx, |view, cx| {
3975            view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
3976            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
3977            view.end_selection(cx);
3978
3979            view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
3980            view.update_selection(DisplayPoint::new(0, 3), 0, Vector2F::zero(), cx);
3981            view.end_selection(cx);
3982            assert_eq!(
3983                view.selected_display_ranges(cx),
3984                [
3985                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
3986                    DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
3987                ]
3988            );
3989        });
3990
3991        view.update(cx, |view, cx| {
3992            view.cancel(&Cancel, cx);
3993            assert_eq!(
3994                view.selected_display_ranges(cx),
3995                [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
3996            );
3997        });
3998
3999        view.update(cx, |view, cx| {
4000            view.cancel(&Cancel, cx);
4001            assert_eq!(
4002                view.selected_display_ranges(cx),
4003                [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
4004            );
4005        });
4006    }
4007
4008    #[gpui::test]
4009    fn test_fold(cx: &mut gpui::MutableAppContext) {
4010        let buffer = MultiBuffer::build_simple(
4011            &"
4012                impl Foo {
4013                    // Hello!
4014
4015                    fn a() {
4016                        1
4017                    }
4018
4019                    fn b() {
4020                        2
4021                    }
4022
4023                    fn c() {
4024                        3
4025                    }
4026                }
4027            "
4028            .unindent(),
4029            cx,
4030        );
4031        let settings = EditorSettings::test(&cx);
4032        let (_, view) = cx.add_window(Default::default(), |cx| {
4033            build_editor(buffer.clone(), settings, cx)
4034        });
4035
4036        view.update(cx, |view, cx| {
4037            view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx)
4038                .unwrap();
4039            view.fold(&Fold, cx);
4040            assert_eq!(
4041                view.display_text(cx),
4042                "
4043                    impl Foo {
4044                        // Hello!
4045
4046                        fn a() {
4047                            1
4048                        }
4049
4050                        fn b() {…
4051                        }
4052
4053                        fn c() {…
4054                        }
4055                    }
4056                "
4057                .unindent(),
4058            );
4059
4060            view.fold(&Fold, cx);
4061            assert_eq!(
4062                view.display_text(cx),
4063                "
4064                    impl Foo {…
4065                    }
4066                "
4067                .unindent(),
4068            );
4069
4070            view.unfold(&Unfold, cx);
4071            assert_eq!(
4072                view.display_text(cx),
4073                "
4074                    impl Foo {
4075                        // Hello!
4076
4077                        fn a() {
4078                            1
4079                        }
4080
4081                        fn b() {…
4082                        }
4083
4084                        fn c() {…
4085                        }
4086                    }
4087                "
4088                .unindent(),
4089            );
4090
4091            view.unfold(&Unfold, cx);
4092            assert_eq!(view.display_text(cx), buffer.read(cx).read(cx).text());
4093        });
4094    }
4095
4096    #[gpui::test]
4097    fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
4098        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
4099        let settings = EditorSettings::test(&cx);
4100        let (_, view) = cx.add_window(Default::default(), |cx| {
4101            build_editor(buffer.clone(), settings, cx)
4102        });
4103
4104        buffer.update(cx, |buffer, cx| {
4105            buffer.edit(
4106                vec![
4107                    Point::new(1, 0)..Point::new(1, 0),
4108                    Point::new(1, 1)..Point::new(1, 1),
4109                ],
4110                "\t",
4111                cx,
4112            );
4113        });
4114
4115        view.update(cx, |view, cx| {
4116            assert_eq!(
4117                view.selected_display_ranges(cx),
4118                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4119            );
4120
4121            view.move_down(&MoveDown, cx);
4122            assert_eq!(
4123                view.selected_display_ranges(cx),
4124                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
4125            );
4126
4127            view.move_right(&MoveRight, cx);
4128            assert_eq!(
4129                view.selected_display_ranges(cx),
4130                &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
4131            );
4132
4133            view.move_left(&MoveLeft, cx);
4134            assert_eq!(
4135                view.selected_display_ranges(cx),
4136                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
4137            );
4138
4139            view.move_up(&MoveUp, cx);
4140            assert_eq!(
4141                view.selected_display_ranges(cx),
4142                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4143            );
4144
4145            view.move_to_end(&MoveToEnd, cx);
4146            assert_eq!(
4147                view.selected_display_ranges(cx),
4148                &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
4149            );
4150
4151            view.move_to_beginning(&MoveToBeginning, cx);
4152            assert_eq!(
4153                view.selected_display_ranges(cx),
4154                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4155            );
4156
4157            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx)
4158                .unwrap();
4159            view.select_to_beginning(&SelectToBeginning, cx);
4160            assert_eq!(
4161                view.selected_display_ranges(cx),
4162                &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
4163            );
4164
4165            view.select_to_end(&SelectToEnd, cx);
4166            assert_eq!(
4167                view.selected_display_ranges(cx),
4168                &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
4169            );
4170        });
4171    }
4172
4173    #[gpui::test]
4174    fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
4175        let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx);
4176        let settings = EditorSettings::test(&cx);
4177        let (_, view) = cx.add_window(Default::default(), |cx| {
4178            build_editor(buffer.clone(), settings, cx)
4179        });
4180
4181        assert_eq!('ⓐ'.len_utf8(), 3);
4182        assert_eq!('α'.len_utf8(), 2);
4183
4184        view.update(cx, |view, cx| {
4185            view.fold_ranges(
4186                vec![
4187                    Point::new(0, 6)..Point::new(0, 12),
4188                    Point::new(1, 2)..Point::new(1, 4),
4189                    Point::new(2, 4)..Point::new(2, 8),
4190                ],
4191                cx,
4192            );
4193            assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
4194
4195            view.move_right(&MoveRight, cx);
4196            assert_eq!(
4197                view.selected_display_ranges(cx),
4198                &[empty_range(0, "".len())]
4199            );
4200            view.move_right(&MoveRight, cx);
4201            assert_eq!(
4202                view.selected_display_ranges(cx),
4203                &[empty_range(0, "ⓐⓑ".len())]
4204            );
4205            view.move_right(&MoveRight, cx);
4206            assert_eq!(
4207                view.selected_display_ranges(cx),
4208                &[empty_range(0, "ⓐⓑ…".len())]
4209            );
4210
4211            view.move_down(&MoveDown, cx);
4212            assert_eq!(
4213                view.selected_display_ranges(cx),
4214                &[empty_range(1, "ab…".len())]
4215            );
4216            view.move_left(&MoveLeft, cx);
4217            assert_eq!(
4218                view.selected_display_ranges(cx),
4219                &[empty_range(1, "ab".len())]
4220            );
4221            view.move_left(&MoveLeft, cx);
4222            assert_eq!(
4223                view.selected_display_ranges(cx),
4224                &[empty_range(1, "a".len())]
4225            );
4226
4227            view.move_down(&MoveDown, cx);
4228            assert_eq!(
4229                view.selected_display_ranges(cx),
4230                &[empty_range(2, "α".len())]
4231            );
4232            view.move_right(&MoveRight, cx);
4233            assert_eq!(
4234                view.selected_display_ranges(cx),
4235                &[empty_range(2, "αβ".len())]
4236            );
4237            view.move_right(&MoveRight, cx);
4238            assert_eq!(
4239                view.selected_display_ranges(cx),
4240                &[empty_range(2, "αβ…".len())]
4241            );
4242            view.move_right(&MoveRight, cx);
4243            assert_eq!(
4244                view.selected_display_ranges(cx),
4245                &[empty_range(2, "αβ…ε".len())]
4246            );
4247
4248            view.move_up(&MoveUp, cx);
4249            assert_eq!(
4250                view.selected_display_ranges(cx),
4251                &[empty_range(1, "ab…e".len())]
4252            );
4253            view.move_up(&MoveUp, cx);
4254            assert_eq!(
4255                view.selected_display_ranges(cx),
4256                &[empty_range(0, "ⓐⓑ…ⓔ".len())]
4257            );
4258            view.move_left(&MoveLeft, cx);
4259            assert_eq!(
4260                view.selected_display_ranges(cx),
4261                &[empty_range(0, "ⓐⓑ…".len())]
4262            );
4263            view.move_left(&MoveLeft, cx);
4264            assert_eq!(
4265                view.selected_display_ranges(cx),
4266                &[empty_range(0, "ⓐⓑ".len())]
4267            );
4268            view.move_left(&MoveLeft, cx);
4269            assert_eq!(
4270                view.selected_display_ranges(cx),
4271                &[empty_range(0, "".len())]
4272            );
4273        });
4274    }
4275
4276    #[gpui::test]
4277    fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
4278        let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
4279        let settings = EditorSettings::test(&cx);
4280        let (_, view) = cx.add_window(Default::default(), |cx| {
4281            build_editor(buffer.clone(), settings, cx)
4282        });
4283        view.update(cx, |view, cx| {
4284            view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx)
4285                .unwrap();
4286
4287            view.move_down(&MoveDown, cx);
4288            assert_eq!(
4289                view.selected_display_ranges(cx),
4290                &[empty_range(1, "abcd".len())]
4291            );
4292
4293            view.move_down(&MoveDown, cx);
4294            assert_eq!(
4295                view.selected_display_ranges(cx),
4296                &[empty_range(2, "αβγ".len())]
4297            );
4298
4299            view.move_down(&MoveDown, cx);
4300            assert_eq!(
4301                view.selected_display_ranges(cx),
4302                &[empty_range(3, "abcd".len())]
4303            );
4304
4305            view.move_down(&MoveDown, cx);
4306            assert_eq!(
4307                view.selected_display_ranges(cx),
4308                &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
4309            );
4310
4311            view.move_up(&MoveUp, cx);
4312            assert_eq!(
4313                view.selected_display_ranges(cx),
4314                &[empty_range(3, "abcd".len())]
4315            );
4316
4317            view.move_up(&MoveUp, cx);
4318            assert_eq!(
4319                view.selected_display_ranges(cx),
4320                &[empty_range(2, "αβγ".len())]
4321            );
4322        });
4323    }
4324
4325    #[gpui::test]
4326    fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
4327        let buffer = MultiBuffer::build_simple("abc\n  def", cx);
4328        let settings = EditorSettings::test(&cx);
4329        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4330        view.update(cx, |view, cx| {
4331            view.select_display_ranges(
4332                &[
4333                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4334                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
4335                ],
4336                cx,
4337            )
4338            .unwrap();
4339        });
4340
4341        view.update(cx, |view, cx| {
4342            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4343            assert_eq!(
4344                view.selected_display_ranges(cx),
4345                &[
4346                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4347                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4348                ]
4349            );
4350        });
4351
4352        view.update(cx, |view, cx| {
4353            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4354            assert_eq!(
4355                view.selected_display_ranges(cx),
4356                &[
4357                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4358                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4359                ]
4360            );
4361        });
4362
4363        view.update(cx, |view, cx| {
4364            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4365            assert_eq!(
4366                view.selected_display_ranges(cx),
4367                &[
4368                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4369                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4370                ]
4371            );
4372        });
4373
4374        view.update(cx, |view, cx| {
4375            view.move_to_end_of_line(&MoveToEndOfLine, cx);
4376            assert_eq!(
4377                view.selected_display_ranges(cx),
4378                &[
4379                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4380                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4381                ]
4382            );
4383        });
4384
4385        // Moving to the end of line again is a no-op.
4386        view.update(cx, |view, cx| {
4387            view.move_to_end_of_line(&MoveToEndOfLine, cx);
4388            assert_eq!(
4389                view.selected_display_ranges(cx),
4390                &[
4391                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4392                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4393                ]
4394            );
4395        });
4396
4397        view.update(cx, |view, cx| {
4398            view.move_left(&MoveLeft, cx);
4399            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4400            assert_eq!(
4401                view.selected_display_ranges(cx),
4402                &[
4403                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4404                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
4405                ]
4406            );
4407        });
4408
4409        view.update(cx, |view, cx| {
4410            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4411            assert_eq!(
4412                view.selected_display_ranges(cx),
4413                &[
4414                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4415                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
4416                ]
4417            );
4418        });
4419
4420        view.update(cx, |view, cx| {
4421            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4422            assert_eq!(
4423                view.selected_display_ranges(cx),
4424                &[
4425                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4426                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
4427                ]
4428            );
4429        });
4430
4431        view.update(cx, |view, cx| {
4432            view.select_to_end_of_line(&SelectToEndOfLine, cx);
4433            assert_eq!(
4434                view.selected_display_ranges(cx),
4435                &[
4436                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
4437                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
4438                ]
4439            );
4440        });
4441
4442        view.update(cx, |view, cx| {
4443            view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
4444            assert_eq!(view.display_text(cx), "ab\n  de");
4445            assert_eq!(
4446                view.selected_display_ranges(cx),
4447                &[
4448                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4449                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
4450                ]
4451            );
4452        });
4453
4454        view.update(cx, |view, cx| {
4455            view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
4456            assert_eq!(view.display_text(cx), "\n");
4457            assert_eq!(
4458                view.selected_display_ranges(cx),
4459                &[
4460                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4461                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4462                ]
4463            );
4464        });
4465    }
4466
4467    #[gpui::test]
4468    fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
4469        let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n  {baz.qux()}", cx);
4470        let settings = EditorSettings::test(&cx);
4471        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4472        view.update(cx, |view, cx| {
4473            view.select_display_ranges(
4474                &[
4475                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
4476                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
4477                ],
4478                cx,
4479            )
4480            .unwrap();
4481        });
4482
4483        view.update(cx, |view, cx| {
4484            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4485            assert_eq!(
4486                view.selected_display_ranges(cx),
4487                &[
4488                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
4489                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
4490                ]
4491            );
4492        });
4493
4494        view.update(cx, |view, cx| {
4495            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4496            assert_eq!(
4497                view.selected_display_ranges(cx),
4498                &[
4499                    DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
4500                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
4501                ]
4502            );
4503        });
4504
4505        view.update(cx, |view, cx| {
4506            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4507            assert_eq!(
4508                view.selected_display_ranges(cx),
4509                &[
4510                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
4511                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
4512                ]
4513            );
4514        });
4515
4516        view.update(cx, |view, cx| {
4517            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4518            assert_eq!(
4519                view.selected_display_ranges(cx),
4520                &[
4521                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4522                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4523                ]
4524            );
4525        });
4526
4527        view.update(cx, |view, cx| {
4528            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4529            assert_eq!(
4530                view.selected_display_ranges(cx),
4531                &[
4532                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4533                    DisplayPoint::new(0, 23)..DisplayPoint::new(0, 23),
4534                ]
4535            );
4536        });
4537
4538        view.update(cx, |view, cx| {
4539            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4540            assert_eq!(
4541                view.selected_display_ranges(cx),
4542                &[
4543                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4544                    DisplayPoint::new(0, 24)..DisplayPoint::new(0, 24),
4545                ]
4546            );
4547        });
4548
4549        view.update(cx, |view, cx| {
4550            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4551            assert_eq!(
4552                view.selected_display_ranges(cx),
4553                &[
4554                    DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
4555                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4556                ]
4557            );
4558        });
4559
4560        view.update(cx, |view, cx| {
4561            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4562            assert_eq!(
4563                view.selected_display_ranges(cx),
4564                &[
4565                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
4566                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
4567                ]
4568            );
4569        });
4570
4571        view.update(cx, |view, cx| {
4572            view.move_right(&MoveRight, cx);
4573            view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
4574            assert_eq!(
4575                view.selected_display_ranges(cx),
4576                &[
4577                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
4578                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
4579                ]
4580            );
4581        });
4582
4583        view.update(cx, |view, cx| {
4584            view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
4585            assert_eq!(
4586                view.selected_display_ranges(cx),
4587                &[
4588                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 7),
4589                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 2),
4590                ]
4591            );
4592        });
4593
4594        view.update(cx, |view, cx| {
4595            view.select_to_next_word_boundary(&SelectToNextWordBoundary, cx);
4596            assert_eq!(
4597                view.selected_display_ranges(cx),
4598                &[
4599                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
4600                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
4601                ]
4602            );
4603        });
4604    }
4605
4606    #[gpui::test]
4607    fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
4608        let buffer = MultiBuffer::build_simple("use one::{\n    two::three::four::five\n};", cx);
4609        let settings = EditorSettings::test(&cx);
4610        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4611
4612        view.update(cx, |view, cx| {
4613            view.set_wrap_width(Some(140.), cx);
4614            assert_eq!(
4615                view.display_text(cx),
4616                "use one::{\n    two::three::\n    four::five\n};"
4617            );
4618
4619            view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx)
4620                .unwrap();
4621
4622            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4623            assert_eq!(
4624                view.selected_display_ranges(cx),
4625                &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
4626            );
4627
4628            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4629            assert_eq!(
4630                view.selected_display_ranges(cx),
4631                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
4632            );
4633
4634            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4635            assert_eq!(
4636                view.selected_display_ranges(cx),
4637                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
4638            );
4639
4640            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4641            assert_eq!(
4642                view.selected_display_ranges(cx),
4643                &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
4644            );
4645
4646            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4647            assert_eq!(
4648                view.selected_display_ranges(cx),
4649                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
4650            );
4651
4652            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4653            assert_eq!(
4654                view.selected_display_ranges(cx),
4655                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
4656            );
4657        });
4658    }
4659
4660    #[gpui::test]
4661    fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
4662        let buffer = MultiBuffer::build_simple("one two three four", cx);
4663        let settings = EditorSettings::test(&cx);
4664        let (_, view) = cx.add_window(Default::default(), |cx| {
4665            build_editor(buffer.clone(), settings, cx)
4666        });
4667
4668        view.update(cx, |view, cx| {
4669            view.select_display_ranges(
4670                &[
4671                    // an empty selection - the preceding word fragment is deleted
4672                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4673                    // characters selected - they are deleted
4674                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
4675                ],
4676                cx,
4677            )
4678            .unwrap();
4679            view.delete_to_previous_word_boundary(&DeleteToPreviousWordBoundary, cx);
4680        });
4681
4682        assert_eq!(buffer.read(cx).read(cx).text(), "e two te four");
4683
4684        view.update(cx, |view, cx| {
4685            view.select_display_ranges(
4686                &[
4687                    // an empty selection - the following word fragment is deleted
4688                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4689                    // characters selected - they are deleted
4690                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
4691                ],
4692                cx,
4693            )
4694            .unwrap();
4695            view.delete_to_next_word_boundary(&DeleteToNextWordBoundary, cx);
4696        });
4697
4698        assert_eq!(buffer.read(cx).read(cx).text(), "e t te our");
4699    }
4700
4701    #[gpui::test]
4702    fn test_newline(cx: &mut gpui::MutableAppContext) {
4703        let buffer = MultiBuffer::build_simple("aaaa\n    bbbb\n", cx);
4704        let settings = EditorSettings::test(&cx);
4705        let (_, view) = cx.add_window(Default::default(), |cx| {
4706            build_editor(buffer.clone(), settings, cx)
4707        });
4708
4709        view.update(cx, |view, cx| {
4710            view.select_display_ranges(
4711                &[
4712                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4713                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4714                    DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
4715                ],
4716                cx,
4717            )
4718            .unwrap();
4719
4720            view.newline(&Newline, cx);
4721            assert_eq!(view.text(cx), "aa\naa\n  \n    bb\n    bb\n");
4722        });
4723    }
4724
4725    #[gpui::test]
4726    fn test_indent_outdent(cx: &mut gpui::MutableAppContext) {
4727        let buffer = MultiBuffer::build_simple("  one two\nthree\n four", cx);
4728        let settings = EditorSettings::test(&cx);
4729        let (_, view) = cx.add_window(Default::default(), |cx| {
4730            build_editor(buffer.clone(), settings, cx)
4731        });
4732
4733        view.update(cx, |view, cx| {
4734            // two selections on the same line
4735            view.select_display_ranges(
4736                &[
4737                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 5),
4738                    DisplayPoint::new(0, 6)..DisplayPoint::new(0, 9),
4739                ],
4740                cx,
4741            )
4742            .unwrap();
4743
4744            // indent from mid-tabstop to full tabstop
4745            view.tab(&Tab, cx);
4746            assert_eq!(view.text(cx), "    one two\nthree\n four");
4747            assert_eq!(
4748                view.selected_display_ranges(cx),
4749                &[
4750                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
4751                    DisplayPoint::new(0, 8)..DisplayPoint::new(0, 11),
4752                ]
4753            );
4754
4755            // outdent from 1 tabstop to 0 tabstops
4756            view.outdent(&Outdent, cx);
4757            assert_eq!(view.text(cx), "one two\nthree\n four");
4758            assert_eq!(
4759                view.selected_display_ranges(cx),
4760                &[
4761                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 3),
4762                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
4763                ]
4764            );
4765
4766            // select across line ending
4767            view.select_display_ranges(&[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)], cx)
4768                .unwrap();
4769
4770            // indent and outdent affect only the preceding line
4771            view.tab(&Tab, cx);
4772            assert_eq!(view.text(cx), "one two\n    three\n four");
4773            assert_eq!(
4774                view.selected_display_ranges(cx),
4775                &[DisplayPoint::new(1, 5)..DisplayPoint::new(2, 0)]
4776            );
4777            view.outdent(&Outdent, cx);
4778            assert_eq!(view.text(cx), "one two\nthree\n four");
4779            assert_eq!(
4780                view.selected_display_ranges(cx),
4781                &[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)]
4782            );
4783        });
4784    }
4785
4786    #[gpui::test]
4787    fn test_backspace(cx: &mut gpui::MutableAppContext) {
4788        let buffer =
4789            MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
4790        let settings = EditorSettings::test(&cx);
4791        let (_, view) = cx.add_window(Default::default(), |cx| {
4792            build_editor(buffer.clone(), settings, cx)
4793        });
4794
4795        view.update(cx, |view, cx| {
4796            view.select_display_ranges(
4797                &[
4798                    // an empty selection - the preceding character is deleted
4799                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4800                    // one character selected - it is deleted
4801                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4802                    // a line suffix selected - it is deleted
4803                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
4804                ],
4805                cx,
4806            )
4807            .unwrap();
4808            view.backspace(&Backspace, cx);
4809        });
4810
4811        assert_eq!(
4812            buffer.read(cx).read(cx).text(),
4813            "oe two three\nfou five six\nseven ten\n"
4814        );
4815    }
4816
4817    #[gpui::test]
4818    fn test_delete(cx: &mut gpui::MutableAppContext) {
4819        let buffer =
4820            MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
4821        let settings = EditorSettings::test(&cx);
4822        let (_, view) = cx.add_window(Default::default(), |cx| {
4823            build_editor(buffer.clone(), settings, cx)
4824        });
4825
4826        view.update(cx, |view, cx| {
4827            view.select_display_ranges(
4828                &[
4829                    // an empty selection - the following character is deleted
4830                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4831                    // one character selected - it is deleted
4832                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4833                    // a line suffix selected - it is deleted
4834                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
4835                ],
4836                cx,
4837            )
4838            .unwrap();
4839            view.delete(&Delete, cx);
4840        });
4841
4842        assert_eq!(
4843            buffer.read(cx).read(cx).text(),
4844            "on two three\nfou five six\nseven ten\n"
4845        );
4846    }
4847
4848    #[gpui::test]
4849    fn test_delete_line(cx: &mut gpui::MutableAppContext) {
4850        let settings = EditorSettings::test(&cx);
4851        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
4852        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4853        view.update(cx, |view, cx| {
4854            view.select_display_ranges(
4855                &[
4856                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4857                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
4858                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4859                ],
4860                cx,
4861            )
4862            .unwrap();
4863            view.delete_line(&DeleteLine, cx);
4864            assert_eq!(view.display_text(cx), "ghi");
4865            assert_eq!(
4866                view.selected_display_ranges(cx),
4867                vec![
4868                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4869                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
4870                ]
4871            );
4872        });
4873
4874        let settings = EditorSettings::test(&cx);
4875        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
4876        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4877        view.update(cx, |view, cx| {
4878            view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx)
4879                .unwrap();
4880            view.delete_line(&DeleteLine, cx);
4881            assert_eq!(view.display_text(cx), "ghi\n");
4882            assert_eq!(
4883                view.selected_display_ranges(cx),
4884                vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
4885            );
4886        });
4887    }
4888
4889    #[gpui::test]
4890    fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
4891        let settings = EditorSettings::test(&cx);
4892        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
4893        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4894        view.update(cx, |view, cx| {
4895            view.select_display_ranges(
4896                &[
4897                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
4898                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4899                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4900                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4901                ],
4902                cx,
4903            )
4904            .unwrap();
4905            view.duplicate_line(&DuplicateLine, cx);
4906            assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
4907            assert_eq!(
4908                view.selected_display_ranges(cx),
4909                vec![
4910                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
4911                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4912                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4913                    DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
4914                ]
4915            );
4916        });
4917
4918        let settings = EditorSettings::test(&cx);
4919        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
4920        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4921        view.update(cx, |view, cx| {
4922            view.select_display_ranges(
4923                &[
4924                    DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
4925                    DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
4926                ],
4927                cx,
4928            )
4929            .unwrap();
4930            view.duplicate_line(&DuplicateLine, cx);
4931            assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
4932            assert_eq!(
4933                view.selected_display_ranges(cx),
4934                vec![
4935                    DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
4936                    DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
4937                ]
4938            );
4939        });
4940    }
4941
4942    #[gpui::test]
4943    fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
4944        let settings = EditorSettings::test(&cx);
4945        let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
4946        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4947        view.update(cx, |view, cx| {
4948            view.fold_ranges(
4949                vec![
4950                    Point::new(0, 2)..Point::new(1, 2),
4951                    Point::new(2, 3)..Point::new(4, 1),
4952                    Point::new(7, 0)..Point::new(8, 4),
4953                ],
4954                cx,
4955            );
4956            view.select_display_ranges(
4957                &[
4958                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4959                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
4960                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
4961                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
4962                ],
4963                cx,
4964            )
4965            .unwrap();
4966            assert_eq!(
4967                view.display_text(cx),
4968                "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
4969            );
4970
4971            view.move_line_up(&MoveLineUp, cx);
4972            assert_eq!(
4973                view.display_text(cx),
4974                "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
4975            );
4976            assert_eq!(
4977                view.selected_display_ranges(cx),
4978                vec![
4979                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4980                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4981                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
4982                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
4983                ]
4984            );
4985        });
4986
4987        view.update(cx, |view, cx| {
4988            view.move_line_down(&MoveLineDown, cx);
4989            assert_eq!(
4990                view.display_text(cx),
4991                "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
4992            );
4993            assert_eq!(
4994                view.selected_display_ranges(cx),
4995                vec![
4996                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4997                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
4998                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
4999                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
5000                ]
5001            );
5002        });
5003
5004        view.update(cx, |view, cx| {
5005            view.move_line_down(&MoveLineDown, cx);
5006            assert_eq!(
5007                view.display_text(cx),
5008                "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
5009            );
5010            assert_eq!(
5011                view.selected_display_ranges(cx),
5012                vec![
5013                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5014                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
5015                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
5016                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
5017                ]
5018            );
5019        });
5020
5021        view.update(cx, |view, cx| {
5022            view.move_line_up(&MoveLineUp, cx);
5023            assert_eq!(
5024                view.display_text(cx),
5025                "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
5026            );
5027            assert_eq!(
5028                view.selected_display_ranges(cx),
5029                vec![
5030                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5031                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5032                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
5033                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
5034                ]
5035            );
5036        });
5037    }
5038
5039    #[gpui::test]
5040    fn test_clipboard(cx: &mut gpui::MutableAppContext) {
5041        let buffer = MultiBuffer::build_simple("one✅ two three four five six ", cx);
5042        let settings = EditorSettings::test(&cx);
5043        let view = cx
5044            .add_window(Default::default(), |cx| {
5045                build_editor(buffer.clone(), settings, cx)
5046            })
5047            .1;
5048
5049        // Cut with three selections. Clipboard text is divided into three slices.
5050        view.update(cx, |view, cx| {
5051            view.select_ranges(vec![0..7, 11..17, 22..27], None, cx);
5052            view.cut(&Cut, cx);
5053            assert_eq!(view.display_text(cx), "two four six ");
5054        });
5055
5056        // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
5057        view.update(cx, |view, cx| {
5058            view.select_ranges(vec![4..4, 9..9, 13..13], None, cx);
5059            view.paste(&Paste, cx);
5060            assert_eq!(view.display_text(cx), "two one✅ four three six five ");
5061            assert_eq!(
5062                view.selected_display_ranges(cx),
5063                &[
5064                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
5065                    DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
5066                    DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
5067                ]
5068            );
5069        });
5070
5071        // Paste again but with only two cursors. Since the number of cursors doesn't
5072        // match the number of slices in the clipboard, the entire clipboard text
5073        // is pasted at each cursor.
5074        view.update(cx, |view, cx| {
5075            view.select_ranges(vec![0..0, 31..31], None, cx);
5076            view.handle_input(&Input("( ".into()), cx);
5077            view.paste(&Paste, cx);
5078            view.handle_input(&Input(") ".into()), cx);
5079            assert_eq!(
5080                view.display_text(cx),
5081                "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
5082            );
5083        });
5084
5085        view.update(cx, |view, cx| {
5086            view.select_ranges(vec![0..0], None, cx);
5087            view.handle_input(&Input("123\n4567\n89\n".into()), cx);
5088            assert_eq!(
5089                view.display_text(cx),
5090                "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
5091            );
5092        });
5093
5094        // Cut with three selections, one of which is full-line.
5095        view.update(cx, |view, cx| {
5096            view.select_display_ranges(
5097                &[
5098                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
5099                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5100                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
5101                ],
5102                cx,
5103            )
5104            .unwrap();
5105            view.cut(&Cut, cx);
5106            assert_eq!(
5107                view.display_text(cx),
5108                "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
5109            );
5110        });
5111
5112        // Paste with three selections, noticing how the copied selection that was full-line
5113        // gets inserted before the second cursor.
5114        view.update(cx, |view, cx| {
5115            view.select_display_ranges(
5116                &[
5117                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5118                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5119                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
5120                ],
5121                cx,
5122            )
5123            .unwrap();
5124            view.paste(&Paste, cx);
5125            assert_eq!(
5126                view.display_text(cx),
5127                "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
5128            );
5129            assert_eq!(
5130                view.selected_display_ranges(cx),
5131                &[
5132                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5133                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5134                    DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
5135                ]
5136            );
5137        });
5138
5139        // Copy with a single cursor only, which writes the whole line into the clipboard.
5140        view.update(cx, |view, cx| {
5141            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx)
5142                .unwrap();
5143            view.copy(&Copy, cx);
5144        });
5145
5146        // Paste with three selections, noticing how the copied full-line selection is inserted
5147        // before the empty selections but replaces the selection that is non-empty.
5148        view.update(cx, |view, cx| {
5149            view.select_display_ranges(
5150                &[
5151                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5152                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
5153                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5154                ],
5155                cx,
5156            )
5157            .unwrap();
5158            view.paste(&Paste, cx);
5159            assert_eq!(
5160                view.display_text(cx),
5161                "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
5162            );
5163            assert_eq!(
5164                view.selected_display_ranges(cx),
5165                &[
5166                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5167                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5168                    DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
5169                ]
5170            );
5171        });
5172    }
5173
5174    #[gpui::test]
5175    fn test_select_all(cx: &mut gpui::MutableAppContext) {
5176        let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
5177        let settings = EditorSettings::test(&cx);
5178        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5179        view.update(cx, |view, cx| {
5180            view.select_all(&SelectAll, cx);
5181            assert_eq!(
5182                view.selected_display_ranges(cx),
5183                &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
5184            );
5185        });
5186    }
5187
5188    #[gpui::test]
5189    fn test_select_line(cx: &mut gpui::MutableAppContext) {
5190        let settings = EditorSettings::test(&cx);
5191        let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
5192        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5193        view.update(cx, |view, cx| {
5194            view.select_display_ranges(
5195                &[
5196                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5197                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5198                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5199                    DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
5200                ],
5201                cx,
5202            )
5203            .unwrap();
5204            view.select_line(&SelectLine, cx);
5205            assert_eq!(
5206                view.selected_display_ranges(cx),
5207                vec![
5208                    DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
5209                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
5210                ]
5211            );
5212        });
5213
5214        view.update(cx, |view, cx| {
5215            view.select_line(&SelectLine, cx);
5216            assert_eq!(
5217                view.selected_display_ranges(cx),
5218                vec![
5219                    DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
5220                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
5221                ]
5222            );
5223        });
5224
5225        view.update(cx, |view, cx| {
5226            view.select_line(&SelectLine, cx);
5227            assert_eq!(
5228                view.selected_display_ranges(cx),
5229                vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
5230            );
5231        });
5232    }
5233
5234    #[gpui::test]
5235    fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
5236        let settings = EditorSettings::test(&cx);
5237        let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
5238        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5239        view.update(cx, |view, cx| {
5240            view.fold_ranges(
5241                vec![
5242                    Point::new(0, 2)..Point::new(1, 2),
5243                    Point::new(2, 3)..Point::new(4, 1),
5244                    Point::new(7, 0)..Point::new(8, 4),
5245                ],
5246                cx,
5247            );
5248            view.select_display_ranges(
5249                &[
5250                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5251                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5252                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5253                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
5254                ],
5255                cx,
5256            )
5257            .unwrap();
5258            assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
5259        });
5260
5261        view.update(cx, |view, cx| {
5262            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
5263            assert_eq!(
5264                view.display_text(cx),
5265                "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
5266            );
5267            assert_eq!(
5268                view.selected_display_ranges(cx),
5269                [
5270                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5271                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5272                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
5273                    DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
5274                ]
5275            );
5276        });
5277
5278        view.update(cx, |view, cx| {
5279            view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx)
5280                .unwrap();
5281            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
5282            assert_eq!(
5283                view.display_text(cx),
5284                "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
5285            );
5286            assert_eq!(
5287                view.selected_display_ranges(cx),
5288                [
5289                    DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
5290                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
5291                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
5292                    DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
5293                    DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
5294                    DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
5295                    DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
5296                    DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
5297                ]
5298            );
5299        });
5300    }
5301
5302    #[gpui::test]
5303    fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
5304        let settings = EditorSettings::test(&cx);
5305        let buffer = MultiBuffer::build_simple("abc\ndefghi\n\njk\nlmno\n", cx);
5306        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5307
5308        view.update(cx, |view, cx| {
5309            view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx)
5310                .unwrap();
5311        });
5312        view.update(cx, |view, cx| {
5313            view.add_selection_above(&AddSelectionAbove, cx);
5314            assert_eq!(
5315                view.selected_display_ranges(cx),
5316                vec![
5317                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5318                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
5319                ]
5320            );
5321        });
5322
5323        view.update(cx, |view, cx| {
5324            view.add_selection_above(&AddSelectionAbove, cx);
5325            assert_eq!(
5326                view.selected_display_ranges(cx),
5327                vec![
5328                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5329                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
5330                ]
5331            );
5332        });
5333
5334        view.update(cx, |view, cx| {
5335            view.add_selection_below(&AddSelectionBelow, cx);
5336            assert_eq!(
5337                view.selected_display_ranges(cx),
5338                vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
5339            );
5340        });
5341
5342        view.update(cx, |view, cx| {
5343            view.add_selection_below(&AddSelectionBelow, cx);
5344            assert_eq!(
5345                view.selected_display_ranges(cx),
5346                vec![
5347                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
5348                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
5349                ]
5350            );
5351        });
5352
5353        view.update(cx, |view, cx| {
5354            view.add_selection_below(&AddSelectionBelow, cx);
5355            assert_eq!(
5356                view.selected_display_ranges(cx),
5357                vec![
5358                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
5359                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
5360                ]
5361            );
5362        });
5363
5364        view.update(cx, |view, cx| {
5365            view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx)
5366                .unwrap();
5367        });
5368        view.update(cx, |view, cx| {
5369            view.add_selection_below(&AddSelectionBelow, cx);
5370            assert_eq!(
5371                view.selected_display_ranges(cx),
5372                vec![
5373                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5374                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
5375                ]
5376            );
5377        });
5378
5379        view.update(cx, |view, cx| {
5380            view.add_selection_below(&AddSelectionBelow, cx);
5381            assert_eq!(
5382                view.selected_display_ranges(cx),
5383                vec![
5384                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5385                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
5386                ]
5387            );
5388        });
5389
5390        view.update(cx, |view, cx| {
5391            view.add_selection_above(&AddSelectionAbove, cx);
5392            assert_eq!(
5393                view.selected_display_ranges(cx),
5394                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
5395            );
5396        });
5397
5398        view.update(cx, |view, cx| {
5399            view.add_selection_above(&AddSelectionAbove, cx);
5400            assert_eq!(
5401                view.selected_display_ranges(cx),
5402                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
5403            );
5404        });
5405
5406        view.update(cx, |view, cx| {
5407            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx)
5408                .unwrap();
5409            view.add_selection_below(&AddSelectionBelow, cx);
5410            assert_eq!(
5411                view.selected_display_ranges(cx),
5412                vec![
5413                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5414                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5415                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5416                ]
5417            );
5418        });
5419
5420        view.update(cx, |view, cx| {
5421            view.add_selection_below(&AddSelectionBelow, cx);
5422            assert_eq!(
5423                view.selected_display_ranges(cx),
5424                vec![
5425                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5426                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5427                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5428                    DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
5429                ]
5430            );
5431        });
5432
5433        view.update(cx, |view, cx| {
5434            view.add_selection_above(&AddSelectionAbove, cx);
5435            assert_eq!(
5436                view.selected_display_ranges(cx),
5437                vec![
5438                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5439                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5440                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5441                ]
5442            );
5443        });
5444
5445        view.update(cx, |view, cx| {
5446            view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx)
5447                .unwrap();
5448        });
5449        view.update(cx, |view, cx| {
5450            view.add_selection_above(&AddSelectionAbove, cx);
5451            assert_eq!(
5452                view.selected_display_ranges(cx),
5453                vec![
5454                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
5455                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
5456                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
5457                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
5458                ]
5459            );
5460        });
5461
5462        view.update(cx, |view, cx| {
5463            view.add_selection_below(&AddSelectionBelow, cx);
5464            assert_eq!(
5465                view.selected_display_ranges(cx),
5466                vec![
5467                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
5468                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
5469                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
5470                ]
5471            );
5472        });
5473    }
5474
5475    #[gpui::test]
5476    async fn test_select_larger_smaller_syntax_node(mut cx: gpui::TestAppContext) {
5477        let settings = cx.read(EditorSettings::test);
5478        let language = Some(Arc::new(Language::new(
5479            LanguageConfig::default(),
5480            Some(tree_sitter_rust::language()),
5481        )));
5482
5483        let text = r#"
5484            use mod1::mod2::{mod3, mod4};
5485
5486            fn fn_1(param1: bool, param2: &str) {
5487                let var1 = "text";
5488            }
5489        "#
5490        .unindent();
5491
5492        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5493        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5494        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5495        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
5496            .await;
5497
5498        view.update(&mut cx, |view, cx| {
5499            view.select_display_ranges(
5500                &[
5501                    DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5502                    DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5503                    DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5504                ],
5505                cx,
5506            )
5507            .unwrap();
5508            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5509        });
5510        assert_eq!(
5511            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5512            &[
5513                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
5514                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5515                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
5516            ]
5517        );
5518
5519        view.update(&mut cx, |view, cx| {
5520            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5521        });
5522        assert_eq!(
5523            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5524            &[
5525                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5526                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
5527            ]
5528        );
5529
5530        view.update(&mut cx, |view, cx| {
5531            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5532        });
5533        assert_eq!(
5534            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5535            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
5536        );
5537
5538        // Trying to expand the selected syntax node one more time has no effect.
5539        view.update(&mut cx, |view, cx| {
5540            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5541        });
5542        assert_eq!(
5543            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5544            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
5545        );
5546
5547        view.update(&mut cx, |view, cx| {
5548            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5549        });
5550        assert_eq!(
5551            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5552            &[
5553                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5554                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
5555            ]
5556        );
5557
5558        view.update(&mut cx, |view, cx| {
5559            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5560        });
5561        assert_eq!(
5562            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5563            &[
5564                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
5565                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5566                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
5567            ]
5568        );
5569
5570        view.update(&mut cx, |view, cx| {
5571            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5572        });
5573        assert_eq!(
5574            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5575            &[
5576                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5577                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5578                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5579            ]
5580        );
5581
5582        // Trying to shrink the selected syntax node one more time has no effect.
5583        view.update(&mut cx, |view, cx| {
5584            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5585        });
5586        assert_eq!(
5587            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5588            &[
5589                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5590                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5591                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5592            ]
5593        );
5594
5595        // Ensure that we keep expanding the selection if the larger selection starts or ends within
5596        // a fold.
5597        view.update(&mut cx, |view, cx| {
5598            view.fold_ranges(
5599                vec![
5600                    Point::new(0, 21)..Point::new(0, 24),
5601                    Point::new(3, 20)..Point::new(3, 22),
5602                ],
5603                cx,
5604            );
5605            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5606        });
5607        assert_eq!(
5608            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5609            &[
5610                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5611                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5612                DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
5613            ]
5614        );
5615    }
5616
5617    #[gpui::test]
5618    async fn test_autoclose_pairs(mut cx: gpui::TestAppContext) {
5619        let settings = cx.read(EditorSettings::test);
5620        let language = Some(Arc::new(Language::new(
5621            LanguageConfig {
5622                brackets: vec![
5623                    BracketPair {
5624                        start: "{".to_string(),
5625                        end: "}".to_string(),
5626                        close: true,
5627                        newline: true,
5628                    },
5629                    BracketPair {
5630                        start: "/*".to_string(),
5631                        end: " */".to_string(),
5632                        close: true,
5633                        newline: true,
5634                    },
5635                ],
5636                ..Default::default()
5637            },
5638            Some(tree_sitter_rust::language()),
5639        )));
5640
5641        let text = r#"
5642            a
5643
5644            /
5645
5646        "#
5647        .unindent();
5648
5649        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5650        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5651        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5652        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
5653            .await;
5654
5655        view.update(&mut cx, |view, cx| {
5656            view.select_display_ranges(
5657                &[
5658                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5659                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5660                ],
5661                cx,
5662            )
5663            .unwrap();
5664            view.handle_input(&Input("{".to_string()), cx);
5665            view.handle_input(&Input("{".to_string()), cx);
5666            view.handle_input(&Input("{".to_string()), cx);
5667            assert_eq!(
5668                view.text(cx),
5669                "
5670                {{{}}}
5671                {{{}}}
5672                /
5673
5674                "
5675                .unindent()
5676            );
5677
5678            view.move_right(&MoveRight, cx);
5679            view.handle_input(&Input("}".to_string()), cx);
5680            view.handle_input(&Input("}".to_string()), cx);
5681            view.handle_input(&Input("}".to_string()), cx);
5682            assert_eq!(
5683                view.text(cx),
5684                "
5685                {{{}}}}
5686                {{{}}}}
5687                /
5688
5689                "
5690                .unindent()
5691            );
5692
5693            view.undo(&Undo, cx);
5694            view.handle_input(&Input("/".to_string()), cx);
5695            view.handle_input(&Input("*".to_string()), cx);
5696            assert_eq!(
5697                view.text(cx),
5698                "
5699                /* */
5700                /* */
5701                /
5702
5703                "
5704                .unindent()
5705            );
5706
5707            view.undo(&Undo, cx);
5708            view.select_display_ranges(
5709                &[
5710                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5711                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5712                ],
5713                cx,
5714            )
5715            .unwrap();
5716            view.handle_input(&Input("*".to_string()), cx);
5717            assert_eq!(
5718                view.text(cx),
5719                "
5720                a
5721
5722                /*
5723                *
5724                "
5725                .unindent()
5726            );
5727        });
5728    }
5729
5730    #[gpui::test]
5731    async fn test_toggle_comment(mut cx: gpui::TestAppContext) {
5732        let settings = cx.read(EditorSettings::test);
5733        let language = Some(Arc::new(Language::new(
5734            LanguageConfig {
5735                line_comment: Some("// ".to_string()),
5736                ..Default::default()
5737            },
5738            Some(tree_sitter_rust::language()),
5739        )));
5740
5741        let text = "
5742            fn a() {
5743                //b();
5744                // c();
5745                //  d();
5746            }
5747        "
5748        .unindent();
5749
5750        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5751        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5752        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5753
5754        view.update(&mut cx, |editor, cx| {
5755            // If multiple selections intersect a line, the line is only
5756            // toggled once.
5757            editor
5758                .select_display_ranges(
5759                    &[
5760                        DisplayPoint::new(1, 3)..DisplayPoint::new(2, 3),
5761                        DisplayPoint::new(3, 5)..DisplayPoint::new(3, 6),
5762                    ],
5763                    cx,
5764                )
5765                .unwrap();
5766            editor.toggle_comments(&ToggleComments, cx);
5767            assert_eq!(
5768                editor.text(cx),
5769                "
5770                    fn a() {
5771                        b();
5772                        c();
5773                         d();
5774                    }
5775                "
5776                .unindent()
5777            );
5778
5779            // The comment prefix is inserted at the same column for every line
5780            // in a selection.
5781            editor
5782                .select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(3, 6)], cx)
5783                .unwrap();
5784            editor.toggle_comments(&ToggleComments, cx);
5785            assert_eq!(
5786                editor.text(cx),
5787                "
5788                    fn a() {
5789                        // b();
5790                        // c();
5791                        //  d();
5792                    }
5793                "
5794                .unindent()
5795            );
5796
5797            // If a selection ends at the beginning of a line, that line is not toggled.
5798            editor
5799                .select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(3, 0)], cx)
5800                .unwrap();
5801            editor.toggle_comments(&ToggleComments, cx);
5802            assert_eq!(
5803                editor.text(cx),
5804                "
5805                        fn a() {
5806                            // b();
5807                            c();
5808                            //  d();
5809                        }
5810                    "
5811                .unindent()
5812            );
5813        });
5814    }
5815
5816    #[gpui::test]
5817    async fn test_extra_newline_insertion(mut cx: gpui::TestAppContext) {
5818        let settings = cx.read(EditorSettings::test);
5819        let language = Some(Arc::new(Language::new(
5820            LanguageConfig {
5821                brackets: vec![
5822                    BracketPair {
5823                        start: "{".to_string(),
5824                        end: "}".to_string(),
5825                        close: true,
5826                        newline: true,
5827                    },
5828                    BracketPair {
5829                        start: "/* ".to_string(),
5830                        end: " */".to_string(),
5831                        close: true,
5832                        newline: true,
5833                    },
5834                ],
5835                ..Default::default()
5836            },
5837            Some(tree_sitter_rust::language()),
5838        )));
5839
5840        let text = concat!(
5841            "{   }\n",     // Suppress rustfmt
5842            "  x\n",       //
5843            "  /*   */\n", //
5844            "x\n",         //
5845            "{{} }\n",     //
5846        );
5847
5848        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5849        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5850        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5851        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
5852            .await;
5853
5854        view.update(&mut cx, |view, cx| {
5855            view.select_display_ranges(
5856                &[
5857                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
5858                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
5859                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
5860                ],
5861                cx,
5862            )
5863            .unwrap();
5864            view.newline(&Newline, cx);
5865
5866            assert_eq!(
5867                view.buffer().read(cx).read(cx).text(),
5868                concat!(
5869                    "{ \n",    // Suppress rustfmt
5870                    "\n",      //
5871                    "}\n",     //
5872                    "  x\n",   //
5873                    "  /* \n", //
5874                    "  \n",    //
5875                    "  */\n",  //
5876                    "x\n",     //
5877                    "{{} \n",  //
5878                    "}\n",     //
5879                )
5880            );
5881        });
5882    }
5883
5884    impl Editor {
5885        fn selected_ranges<D: TextDimension + Ord + Sub<D, Output = D>>(
5886            &self,
5887            cx: &mut MutableAppContext,
5888        ) -> Vec<Range<D>> {
5889            self.local_selections::<D>(cx)
5890                .iter()
5891                .map(|s| {
5892                    if s.reversed {
5893                        s.end.clone()..s.start.clone()
5894                    } else {
5895                        s.start.clone()..s.end.clone()
5896                    }
5897                })
5898                .collect()
5899        }
5900
5901        fn selected_display_ranges(&self, cx: &mut MutableAppContext) -> Vec<Range<DisplayPoint>> {
5902            let display_map = self
5903                .display_map
5904                .update(cx, |display_map, cx| display_map.snapshot(cx));
5905            self.selections
5906                .iter()
5907                .map(|s| {
5908                    if s.reversed {
5909                        s.end.to_display_point(&display_map)..s.start.to_display_point(&display_map)
5910                    } else {
5911                        s.start.to_display_point(&display_map)..s.end.to_display_point(&display_map)
5912                    }
5913                })
5914                .collect()
5915        }
5916    }
5917
5918    fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
5919        let point = DisplayPoint::new(row as u32, column as u32);
5920        point..point
5921    }
5922
5923    fn build_editor(
5924        buffer: ModelHandle<MultiBuffer>,
5925        settings: EditorSettings,
5926        cx: &mut ViewContext<Editor>,
5927    ) -> Editor {
5928        Editor::for_buffer(buffer, move |_| settings.clone(), cx)
5929    }
5930}
5931
5932trait RangeExt<T> {
5933    fn sorted(&self) -> Range<T>;
5934    fn to_inclusive(&self) -> RangeInclusive<T>;
5935}
5936
5937impl<T: Ord + Clone> RangeExt<T> for Range<T> {
5938    fn sorted(&self) -> Self {
5939        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
5940    }
5941
5942    fn to_inclusive(&self) -> RangeInclusive<T> {
5943        self.start.clone()..=self.end.clone()
5944    }
5945}