lib.rs

   1pub mod display_map;
   2mod element;
   3pub mod movement;
   4
   5#[cfg(test)]
   6mod test;
   7
   8use buffer::*;
   9use clock::ReplicaId;
  10pub use display_map::DisplayPoint;
  11use display_map::*;
  12pub use element::*;
  13use gpui::{
  14    action, color::Color, fonts::TextStyle, geometry::vector::Vector2F, keymap::Binding,
  15    text_layout, AppContext, ClipboardItem, Element, ElementBox, Entity, ModelHandle,
  16    MutableAppContext, RenderContext, View, ViewContext, WeakViewHandle,
  17};
  18use serde::{Deserialize, Serialize};
  19use smallvec::SmallVec;
  20use smol::Timer;
  21use std::{
  22    cell::RefCell,
  23    cmp::{self, Ordering},
  24    iter, mem,
  25    ops::{Range, RangeInclusive},
  26    rc::Rc,
  27    sync::Arc,
  28    time::Duration,
  29};
  30use sum_tree::Bias;
  31use theme::EditorStyle;
  32use util::post_inc;
  33
  34const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  35const MAX_LINE_LEN: usize = 1024;
  36
  37action!(Cancel);
  38action!(Backspace);
  39action!(Delete);
  40action!(Input, String);
  41action!(Newline);
  42action!(Tab);
  43action!(DeleteLine);
  44action!(DeleteToPreviousWordBoundary);
  45action!(DeleteToNextWordBoundary);
  46action!(DeleteToBeginningOfLine);
  47action!(DeleteToEndOfLine);
  48action!(CutToEndOfLine);
  49action!(DuplicateLine);
  50action!(MoveLineUp);
  51action!(MoveLineDown);
  52action!(Cut);
  53action!(Copy);
  54action!(Paste);
  55action!(Undo);
  56action!(Redo);
  57action!(MoveUp);
  58action!(MoveDown);
  59action!(MoveLeft);
  60action!(MoveRight);
  61action!(MoveToPreviousWordBoundary);
  62action!(MoveToNextWordBoundary);
  63action!(MoveToBeginningOfLine);
  64action!(MoveToEndOfLine);
  65action!(MoveToBeginning);
  66action!(MoveToEnd);
  67action!(SelectUp);
  68action!(SelectDown);
  69action!(SelectLeft);
  70action!(SelectRight);
  71action!(SelectToPreviousWordBoundary);
  72action!(SelectToNextWordBoundary);
  73action!(SelectToBeginningOfLine, bool);
  74action!(SelectToEndOfLine);
  75action!(SelectToBeginning);
  76action!(SelectToEnd);
  77action!(SelectAll);
  78action!(SelectLine);
  79action!(SplitSelectionIntoLines);
  80action!(AddSelectionAbove);
  81action!(AddSelectionBelow);
  82action!(SelectLargerSyntaxNode);
  83action!(SelectSmallerSyntaxNode);
  84action!(MoveToEnclosingBracket);
  85action!(PageUp);
  86action!(PageDown);
  87action!(Fold);
  88action!(Unfold);
  89action!(FoldSelectedRanges);
  90action!(Scroll, Vector2F);
  91action!(Select, SelectPhase);
  92
  93pub fn init(cx: &mut MutableAppContext) {
  94    cx.add_bindings(vec![
  95        Binding::new("escape", Cancel, Some("Editor")),
  96        Binding::new("backspace", Backspace, Some("Editor")),
  97        Binding::new("ctrl-h", Backspace, Some("Editor")),
  98        Binding::new("delete", Delete, Some("Editor")),
  99        Binding::new("ctrl-d", Delete, Some("Editor")),
 100        Binding::new("enter", Newline, Some("Editor && mode == full")),
 101        Binding::new(
 102            "alt-enter",
 103            Input("\n".into()),
 104            Some("Editor && mode == auto_height"),
 105        ),
 106        Binding::new("tab", Tab, Some("Editor")),
 107        Binding::new("ctrl-shift-K", DeleteLine, Some("Editor")),
 108        Binding::new(
 109            "alt-backspace",
 110            DeleteToPreviousWordBoundary,
 111            Some("Editor"),
 112        ),
 113        Binding::new("alt-h", DeleteToPreviousWordBoundary, Some("Editor")),
 114        Binding::new("alt-delete", DeleteToNextWordBoundary, Some("Editor")),
 115        Binding::new("alt-d", DeleteToNextWordBoundary, Some("Editor")),
 116        Binding::new("cmd-backspace", DeleteToBeginningOfLine, Some("Editor")),
 117        Binding::new("cmd-delete", DeleteToEndOfLine, Some("Editor")),
 118        Binding::new("ctrl-k", CutToEndOfLine, Some("Editor")),
 119        Binding::new("cmd-shift-D", DuplicateLine, Some("Editor")),
 120        Binding::new("ctrl-cmd-up", MoveLineUp, Some("Editor")),
 121        Binding::new("ctrl-cmd-down", MoveLineDown, Some("Editor")),
 122        Binding::new("cmd-x", Cut, Some("Editor")),
 123        Binding::new("cmd-c", Copy, Some("Editor")),
 124        Binding::new("cmd-v", Paste, Some("Editor")),
 125        Binding::new("cmd-z", Undo, Some("Editor")),
 126        Binding::new("cmd-shift-Z", Redo, Some("Editor")),
 127        Binding::new("up", MoveUp, Some("Editor")),
 128        Binding::new("down", MoveDown, Some("Editor")),
 129        Binding::new("left", MoveLeft, Some("Editor")),
 130        Binding::new("right", MoveRight, Some("Editor")),
 131        Binding::new("ctrl-p", MoveUp, Some("Editor")),
 132        Binding::new("ctrl-n", MoveDown, Some("Editor")),
 133        Binding::new("ctrl-b", MoveLeft, Some("Editor")),
 134        Binding::new("ctrl-f", MoveRight, Some("Editor")),
 135        Binding::new("alt-left", MoveToPreviousWordBoundary, Some("Editor")),
 136        Binding::new("alt-b", MoveToPreviousWordBoundary, Some("Editor")),
 137        Binding::new("alt-right", MoveToNextWordBoundary, Some("Editor")),
 138        Binding::new("alt-f", MoveToNextWordBoundary, Some("Editor")),
 139        Binding::new("cmd-left", MoveToBeginningOfLine, Some("Editor")),
 140        Binding::new("ctrl-a", MoveToBeginningOfLine, Some("Editor")),
 141        Binding::new("cmd-right", MoveToEndOfLine, Some("Editor")),
 142        Binding::new("ctrl-e", MoveToEndOfLine, Some("Editor")),
 143        Binding::new("cmd-up", MoveToBeginning, Some("Editor")),
 144        Binding::new("cmd-down", MoveToEnd, Some("Editor")),
 145        Binding::new("shift-up", SelectUp, Some("Editor")),
 146        Binding::new("ctrl-shift-P", SelectUp, Some("Editor")),
 147        Binding::new("shift-down", SelectDown, Some("Editor")),
 148        Binding::new("ctrl-shift-N", SelectDown, Some("Editor")),
 149        Binding::new("shift-left", SelectLeft, Some("Editor")),
 150        Binding::new("ctrl-shift-B", SelectLeft, Some("Editor")),
 151        Binding::new("shift-right", SelectRight, Some("Editor")),
 152        Binding::new("ctrl-shift-F", SelectRight, Some("Editor")),
 153        Binding::new(
 154            "alt-shift-left",
 155            SelectToPreviousWordBoundary,
 156            Some("Editor"),
 157        ),
 158        Binding::new("alt-shift-B", SelectToPreviousWordBoundary, Some("Editor")),
 159        Binding::new("alt-shift-right", SelectToNextWordBoundary, Some("Editor")),
 160        Binding::new("alt-shift-F", SelectToNextWordBoundary, Some("Editor")),
 161        Binding::new(
 162            "cmd-shift-left",
 163            SelectToBeginningOfLine(true),
 164            Some("Editor"),
 165        ),
 166        Binding::new(
 167            "ctrl-shift-A",
 168            SelectToBeginningOfLine(true),
 169            Some("Editor"),
 170        ),
 171        Binding::new("cmd-shift-right", SelectToEndOfLine, Some("Editor")),
 172        Binding::new("ctrl-shift-E", SelectToEndOfLine, Some("Editor")),
 173        Binding::new("cmd-shift-up", SelectToBeginning, Some("Editor")),
 174        Binding::new("cmd-shift-down", SelectToEnd, Some("Editor")),
 175        Binding::new("cmd-a", SelectAll, Some("Editor")),
 176        Binding::new("cmd-l", SelectLine, Some("Editor")),
 177        Binding::new("cmd-shift-L", SplitSelectionIntoLines, Some("Editor")),
 178        Binding::new("cmd-alt-up", AddSelectionAbove, Some("Editor")),
 179        Binding::new("cmd-ctrl-p", AddSelectionAbove, Some("Editor")),
 180        Binding::new("cmd-alt-down", AddSelectionBelow, Some("Editor")),
 181        Binding::new("cmd-ctrl-n", AddSelectionBelow, Some("Editor")),
 182        Binding::new("alt-up", SelectLargerSyntaxNode, Some("Editor")),
 183        Binding::new("ctrl-w", SelectLargerSyntaxNode, Some("Editor")),
 184        Binding::new("alt-down", SelectSmallerSyntaxNode, Some("Editor")),
 185        Binding::new("ctrl-shift-W", SelectSmallerSyntaxNode, Some("Editor")),
 186        Binding::new("ctrl-m", MoveToEnclosingBracket, Some("Editor")),
 187        Binding::new("pageup", PageUp, Some("Editor")),
 188        Binding::new("pagedown", PageDown, Some("Editor")),
 189        Binding::new("alt-cmd-[", Fold, Some("Editor")),
 190        Binding::new("alt-cmd-]", Unfold, Some("Editor")),
 191        Binding::new("alt-cmd-f", FoldSelectedRanges, Some("Editor")),
 192    ]);
 193
 194    cx.add_action(|this: &mut Editor, action: &Scroll, cx| this.set_scroll_position(action.0, cx));
 195    cx.add_action(Editor::select);
 196    cx.add_action(Editor::cancel);
 197    cx.add_action(Editor::handle_input);
 198    cx.add_action(Editor::newline);
 199    cx.add_action(Editor::backspace);
 200    cx.add_action(Editor::delete);
 201    cx.add_action(Editor::tab);
 202    cx.add_action(Editor::delete_line);
 203    cx.add_action(Editor::delete_to_previous_word_boundary);
 204    cx.add_action(Editor::delete_to_next_word_boundary);
 205    cx.add_action(Editor::delete_to_beginning_of_line);
 206    cx.add_action(Editor::delete_to_end_of_line);
 207    cx.add_action(Editor::cut_to_end_of_line);
 208    cx.add_action(Editor::duplicate_line);
 209    cx.add_action(Editor::move_line_up);
 210    cx.add_action(Editor::move_line_down);
 211    cx.add_action(Editor::cut);
 212    cx.add_action(Editor::copy);
 213    cx.add_action(Editor::paste);
 214    cx.add_action(Editor::undo);
 215    cx.add_action(Editor::redo);
 216    cx.add_action(Editor::move_up);
 217    cx.add_action(Editor::move_down);
 218    cx.add_action(Editor::move_left);
 219    cx.add_action(Editor::move_right);
 220    cx.add_action(Editor::move_to_previous_word_boundary);
 221    cx.add_action(Editor::move_to_next_word_boundary);
 222    cx.add_action(Editor::move_to_beginning_of_line);
 223    cx.add_action(Editor::move_to_end_of_line);
 224    cx.add_action(Editor::move_to_beginning);
 225    cx.add_action(Editor::move_to_end);
 226    cx.add_action(Editor::select_up);
 227    cx.add_action(Editor::select_down);
 228    cx.add_action(Editor::select_left);
 229    cx.add_action(Editor::select_right);
 230    cx.add_action(Editor::select_to_previous_word_boundary);
 231    cx.add_action(Editor::select_to_next_word_boundary);
 232    cx.add_action(Editor::select_to_beginning_of_line);
 233    cx.add_action(Editor::select_to_end_of_line);
 234    cx.add_action(Editor::select_to_beginning);
 235    cx.add_action(Editor::select_to_end);
 236    cx.add_action(Editor::select_all);
 237    cx.add_action(Editor::select_line);
 238    cx.add_action(Editor::split_selection_into_lines);
 239    cx.add_action(Editor::add_selection_above);
 240    cx.add_action(Editor::add_selection_below);
 241    cx.add_action(Editor::select_larger_syntax_node);
 242    cx.add_action(Editor::select_smaller_syntax_node);
 243    cx.add_action(Editor::move_to_enclosing_bracket);
 244    cx.add_action(Editor::page_up);
 245    cx.add_action(Editor::page_down);
 246    cx.add_action(Editor::fold);
 247    cx.add_action(Editor::unfold);
 248    cx.add_action(Editor::fold_selected_ranges);
 249}
 250
 251trait SelectionExt {
 252    fn display_range(&self, map: &DisplayMapSnapshot) -> Range<DisplayPoint>;
 253    fn spanned_rows(
 254        &self,
 255        include_end_if_at_line_start: bool,
 256        map: &DisplayMapSnapshot,
 257    ) -> SpannedRows;
 258}
 259
 260struct SpannedRows {
 261    buffer_rows: Range<u32>,
 262    display_rows: Range<u32>,
 263}
 264
 265#[derive(Clone, Debug)]
 266pub enum SelectPhase {
 267    Begin {
 268        position: DisplayPoint,
 269        add: bool,
 270    },
 271    Update {
 272        position: DisplayPoint,
 273        scroll_position: Vector2F,
 274    },
 275    End,
 276}
 277
 278#[derive(Copy, Clone, PartialEq, Eq)]
 279pub enum EditorMode {
 280    SingleLine,
 281    AutoHeight { max_lines: usize },
 282    Full,
 283}
 284
 285#[derive(Clone)]
 286pub struct EditorSettings {
 287    pub tab_size: usize,
 288    pub style: EditorStyle,
 289}
 290
 291pub struct Editor {
 292    handle: WeakViewHandle<Self>,
 293    buffer: ModelHandle<Buffer>,
 294    display_map: ModelHandle<DisplayMap>,
 295    selection_set_id: SelectionSetId,
 296    pending_selection: Option<Selection>,
 297    next_selection_id: usize,
 298    add_selections_state: Option<AddSelectionsState>,
 299    autoclose_stack: Vec<AutoclosePairState>,
 300    select_larger_syntax_node_stack: Vec<Arc<[Selection]>>,
 301    scroll_position: Vector2F,
 302    scroll_top_anchor: Anchor,
 303    autoscroll_requested: bool,
 304    build_settings: Rc<RefCell<dyn Fn(&AppContext) -> EditorSettings>>,
 305    focused: bool,
 306    show_local_cursors: bool,
 307    blink_epoch: usize,
 308    blinking_paused: bool,
 309    mode: EditorMode,
 310    placeholder_text: Option<Arc<str>>,
 311}
 312
 313pub struct Snapshot {
 314    pub mode: EditorMode,
 315    pub display_snapshot: DisplayMapSnapshot,
 316    pub placeholder_text: Option<Arc<str>>,
 317    is_focused: bool,
 318    scroll_position: Vector2F,
 319    scroll_top_anchor: Anchor,
 320}
 321
 322struct AddSelectionsState {
 323    above: bool,
 324    stack: Vec<usize>,
 325}
 326
 327struct AutoclosePairState {
 328    ranges: SmallVec<[Range<Anchor>; 32]>,
 329    pair: AutoclosePair,
 330}
 331
 332#[derive(Serialize, Deserialize)]
 333struct ClipboardSelection {
 334    len: usize,
 335    is_entire_line: bool,
 336}
 337
 338impl Editor {
 339    pub fn single_line(
 340        build_settings: impl 'static + Fn(&AppContext) -> EditorSettings,
 341        cx: &mut ViewContext<Self>,
 342    ) -> Self {
 343        let buffer = cx.add_model(|cx| Buffer::new(0, String::new(), cx));
 344        let mut view = Self::for_buffer(buffer, build_settings, cx);
 345        view.mode = EditorMode::SingleLine;
 346        view
 347    }
 348
 349    pub fn auto_height(
 350        max_lines: usize,
 351        build_settings: impl 'static + Fn(&AppContext) -> EditorSettings,
 352        cx: &mut ViewContext<Self>,
 353    ) -> Self {
 354        let buffer = cx.add_model(|cx| Buffer::new(0, String::new(), cx));
 355        let mut view = Self::for_buffer(buffer, build_settings, cx);
 356        view.mode = EditorMode::AutoHeight { max_lines };
 357        view
 358    }
 359
 360    pub fn for_buffer(
 361        buffer: ModelHandle<Buffer>,
 362        build_settings: impl 'static + Fn(&AppContext) -> EditorSettings,
 363        cx: &mut ViewContext<Self>,
 364    ) -> Self {
 365        Self::new(buffer, Rc::new(RefCell::new(build_settings)), cx)
 366    }
 367
 368    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 369        let mut clone = Self::new(self.buffer.clone(), self.build_settings.clone(), cx);
 370        clone.scroll_position = self.scroll_position;
 371        clone.scroll_top_anchor = self.scroll_top_anchor.clone();
 372        clone
 373    }
 374
 375    pub fn new(
 376        buffer: ModelHandle<Buffer>,
 377        build_settings: Rc<RefCell<dyn Fn(&AppContext) -> EditorSettings>>,
 378        cx: &mut ViewContext<Self>,
 379    ) -> Self {
 380        let settings = build_settings.borrow_mut()(cx);
 381        let display_map = cx.add_model(|cx| {
 382            DisplayMap::new(
 383                buffer.clone(),
 384                settings.tab_size,
 385                settings.style.text.font_id,
 386                settings.style.text.font_size,
 387                None,
 388                cx,
 389            )
 390        });
 391        cx.observe(&buffer, Self::on_buffer_changed).detach();
 392        cx.subscribe(&buffer, Self::on_buffer_event).detach();
 393        cx.observe(&display_map, Self::on_display_map_changed)
 394            .detach();
 395
 396        let mut next_selection_id = 0;
 397        let selection_set_id = buffer.update(cx, |buffer, cx| {
 398            buffer.add_selection_set(
 399                vec![Selection {
 400                    id: post_inc(&mut next_selection_id),
 401                    start: buffer.anchor_before(0),
 402                    end: buffer.anchor_before(0),
 403                    reversed: false,
 404                    goal: SelectionGoal::None,
 405                }],
 406                cx,
 407            )
 408        });
 409        Self {
 410            handle: cx.handle().downgrade(),
 411            buffer,
 412            display_map,
 413            selection_set_id,
 414            pending_selection: None,
 415            next_selection_id,
 416            add_selections_state: None,
 417            autoclose_stack: Default::default(),
 418            select_larger_syntax_node_stack: Vec::new(),
 419            build_settings,
 420            scroll_position: Vector2F::zero(),
 421            scroll_top_anchor: Anchor::min(),
 422            autoscroll_requested: false,
 423            focused: false,
 424            show_local_cursors: false,
 425            blink_epoch: 0,
 426            blinking_paused: false,
 427            mode: EditorMode::Full,
 428            placeholder_text: None,
 429        }
 430    }
 431
 432    pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
 433        self.buffer.read(cx).replica_id()
 434    }
 435
 436    pub fn buffer(&self) -> &ModelHandle<Buffer> {
 437        &self.buffer
 438    }
 439
 440    pub fn snapshot(&mut self, cx: &mut MutableAppContext) -> Snapshot {
 441        Snapshot {
 442            mode: self.mode,
 443            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 444            scroll_position: self.scroll_position,
 445            scroll_top_anchor: self.scroll_top_anchor.clone(),
 446            placeholder_text: self.placeholder_text.clone(),
 447            is_focused: self
 448                .handle
 449                .upgrade(cx)
 450                .map_or(false, |handle| handle.is_focused(cx)),
 451        }
 452    }
 453
 454    pub fn language<'a>(&self, cx: &'a AppContext) -> Option<&'a Arc<Language>> {
 455        self.buffer.read(cx).language()
 456    }
 457
 458    pub fn set_placeholder_text(
 459        &mut self,
 460        placeholder_text: impl Into<Arc<str>>,
 461        cx: &mut ViewContext<Self>,
 462    ) {
 463        self.placeholder_text = Some(placeholder_text.into());
 464        cx.notify();
 465    }
 466
 467    fn set_scroll_position(&mut self, mut scroll_position: Vector2F, cx: &mut ViewContext<Self>) {
 468        let map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 469        let scroll_top_buffer_offset =
 470            DisplayPoint::new(scroll_position.y() as u32, 0).to_buffer_offset(&map, Bias::Right);
 471        self.scroll_top_anchor = self
 472            .buffer
 473            .read(cx)
 474            .anchor_at(scroll_top_buffer_offset, Bias::Right);
 475        scroll_position.set_y(scroll_position.y().fract());
 476        self.scroll_position = scroll_position;
 477        cx.notify();
 478    }
 479
 480    pub fn clamp_scroll_left(&mut self, max: f32) -> bool {
 481        if max < self.scroll_position.x() {
 482            self.scroll_position.set_x(max);
 483            true
 484        } else {
 485            false
 486        }
 487    }
 488
 489    pub fn autoscroll_vertically(
 490        &mut self,
 491        viewport_height: f32,
 492        line_height: f32,
 493        cx: &mut ViewContext<Self>,
 494    ) -> bool {
 495        let visible_lines = viewport_height / line_height;
 496        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 497        let mut scroll_position =
 498            compute_scroll_position(&display_map, self.scroll_position, &self.scroll_top_anchor);
 499        let max_scroll_top = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
 500            (display_map.max_point().row() as f32 - visible_lines + 1.).max(0.)
 501        } else {
 502            display_map.max_point().row().saturating_sub(1) as f32
 503        };
 504        if scroll_position.y() > max_scroll_top {
 505            scroll_position.set_y(max_scroll_top);
 506            self.set_scroll_position(scroll_position, cx);
 507        }
 508
 509        if self.autoscroll_requested {
 510            self.autoscroll_requested = false;
 511        } else {
 512            return false;
 513        }
 514
 515        let selections = self.selections(cx);
 516        let first_cursor_top = selections
 517            .first()
 518            .unwrap()
 519            .head()
 520            .to_display_point(&display_map, Bias::Left)
 521            .row() as f32;
 522        let last_cursor_bottom = selections
 523            .last()
 524            .unwrap()
 525            .head()
 526            .to_display_point(&display_map, Bias::Right)
 527            .row() as f32
 528            + 1.0;
 529
 530        let margin = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
 531            0.
 532        } else {
 533            ((visible_lines - (last_cursor_bottom - first_cursor_top)) / 2.0)
 534                .floor()
 535                .min(3.0)
 536        };
 537        if margin < 0.0 {
 538            return false;
 539        }
 540
 541        let target_top = (first_cursor_top - margin).max(0.0);
 542        let target_bottom = last_cursor_bottom + margin;
 543        let start_row = scroll_position.y();
 544        let end_row = start_row + visible_lines;
 545
 546        if target_top < start_row {
 547            scroll_position.set_y(target_top);
 548            self.set_scroll_position(scroll_position, cx);
 549        } else if target_bottom >= end_row {
 550            scroll_position.set_y(target_bottom - visible_lines);
 551            self.set_scroll_position(scroll_position, cx);
 552        }
 553
 554        true
 555    }
 556
 557    pub fn autoscroll_horizontally(
 558        &mut self,
 559        start_row: u32,
 560        viewport_width: f32,
 561        scroll_width: f32,
 562        max_glyph_width: f32,
 563        layouts: &[text_layout::Line],
 564        cx: &mut ViewContext<Self>,
 565    ) -> bool {
 566        let selections = self.selections(cx);
 567        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 568        let mut target_left = std::f32::INFINITY;
 569        let mut target_right = 0.0_f32;
 570        for selection in selections.iter() {
 571            let head = selection.head().to_display_point(&display_map, Bias::Left);
 572            let start_column = head.column().saturating_sub(3);
 573            let end_column = cmp::min(display_map.line_len(head.row()), head.column() + 3);
 574            target_left = target_left
 575                .min(layouts[(head.row() - start_row) as usize].x_for_index(start_column as usize));
 576            target_right = target_right.max(
 577                layouts[(head.row() - start_row) as usize].x_for_index(end_column as usize)
 578                    + max_glyph_width,
 579            );
 580        }
 581        target_right = target_right.min(scroll_width);
 582
 583        if target_right - target_left > viewport_width {
 584            return false;
 585        }
 586
 587        let scroll_left = self.scroll_position.x() * max_glyph_width;
 588        let scroll_right = scroll_left + viewport_width;
 589
 590        if target_left < scroll_left {
 591            self.scroll_position.set_x(target_left / max_glyph_width);
 592            true
 593        } else if target_right > scroll_right {
 594            self.scroll_position
 595                .set_x((target_right - viewport_width) / max_glyph_width);
 596            true
 597        } else {
 598            false
 599        }
 600    }
 601
 602    fn select(&mut self, Select(phase): &Select, cx: &mut ViewContext<Self>) {
 603        match phase {
 604            SelectPhase::Begin { position, add } => self.begin_selection(*position, *add, cx),
 605            SelectPhase::Update {
 606                position,
 607                scroll_position,
 608            } => self.update_selection(*position, *scroll_position, cx),
 609            SelectPhase::End => self.end_selection(cx),
 610        }
 611    }
 612
 613    fn begin_selection(&mut self, position: DisplayPoint, add: bool, cx: &mut ViewContext<Self>) {
 614        if !self.focused {
 615            cx.focus_self();
 616            cx.emit(Event::Activate);
 617        }
 618
 619        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 620        let cursor = display_map.anchor_before(position, Bias::Left);
 621        let selection = Selection {
 622            id: post_inc(&mut self.next_selection_id),
 623            start: cursor.clone(),
 624            end: cursor,
 625            reversed: false,
 626            goal: SelectionGoal::None,
 627        };
 628
 629        if !add {
 630            self.update_selections(Vec::new(), false, cx);
 631        }
 632        self.pending_selection = Some(selection);
 633
 634        cx.notify();
 635    }
 636
 637    fn update_selection(
 638        &mut self,
 639        position: DisplayPoint,
 640        scroll_position: Vector2F,
 641        cx: &mut ViewContext<Self>,
 642    ) {
 643        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 644        let buffer = self.buffer.read(cx);
 645        let cursor = display_map.anchor_before(position, Bias::Left);
 646        if let Some(selection) = self.pending_selection.as_mut() {
 647            selection.set_head(buffer, cursor);
 648        } else {
 649            log::error!("update_selection dispatched with no pending selection");
 650            return;
 651        }
 652
 653        self.set_scroll_position(scroll_position, cx);
 654        cx.notify();
 655    }
 656
 657    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 658        if let Some(selection) = self.pending_selection.take() {
 659            let mut selections = self.selections(cx).to_vec();
 660            let ix = self.selection_insertion_index(&selections, &selection.start, cx.as_ref());
 661            selections.insert(ix, selection);
 662            self.update_selections(selections, false, cx);
 663        }
 664    }
 665
 666    pub fn is_selecting(&self) -> bool {
 667        self.pending_selection.is_some()
 668    }
 669
 670    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 671        if let Some(pending_selection) = self.pending_selection.take() {
 672            let selections = self.selections(cx);
 673            if selections.is_empty() {
 674                self.update_selections(vec![pending_selection], true, cx);
 675            }
 676        } else {
 677            let selections = self.selections(cx);
 678            let mut oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 679            if selections.len() == 1 {
 680                oldest_selection.start = oldest_selection.head().clone();
 681                oldest_selection.end = oldest_selection.head().clone();
 682            }
 683            self.update_selections(vec![oldest_selection], true, cx);
 684        }
 685    }
 686
 687    fn select_ranges<I, T>(&mut self, ranges: I, autoscroll: bool, cx: &mut ViewContext<Self>)
 688    where
 689        I: IntoIterator<Item = Range<T>>,
 690        T: ToOffset,
 691    {
 692        let buffer = self.buffer.read(cx);
 693        let mut selections = Vec::new();
 694        for range in ranges {
 695            let mut start = range.start.to_offset(buffer);
 696            let mut end = range.end.to_offset(buffer);
 697            let reversed = if start > end {
 698                mem::swap(&mut start, &mut end);
 699                true
 700            } else {
 701                false
 702            };
 703            selections.push(Selection {
 704                id: post_inc(&mut self.next_selection_id),
 705                start: buffer.anchor_before(start),
 706                end: buffer.anchor_before(end),
 707                reversed,
 708                goal: SelectionGoal::None,
 709            });
 710        }
 711        self.update_selections(selections, autoscroll, cx);
 712    }
 713
 714    #[cfg(test)]
 715    fn select_display_ranges<'a, T>(
 716        &mut self,
 717        ranges: T,
 718        cx: &mut ViewContext<Self>,
 719    ) -> anyhow::Result<()>
 720    where
 721        T: IntoIterator<Item = &'a Range<DisplayPoint>>,
 722    {
 723        let mut selections = Vec::new();
 724        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 725        for range in ranges {
 726            let mut start = range.start;
 727            let mut end = range.end;
 728            let reversed = if start > end {
 729                mem::swap(&mut start, &mut end);
 730                true
 731            } else {
 732                false
 733            };
 734
 735            selections.push(Selection {
 736                id: post_inc(&mut self.next_selection_id),
 737                start: display_map.anchor_before(start, Bias::Left),
 738                end: display_map.anchor_before(end, Bias::Left),
 739                reversed,
 740                goal: SelectionGoal::None,
 741            });
 742        }
 743        self.update_selections(selections, false, cx);
 744        Ok(())
 745    }
 746
 747    pub fn handle_input(&mut self, action: &Input, cx: &mut ViewContext<Self>) {
 748        let text = action.0.as_ref();
 749        if !self.skip_autoclose_end(text, cx) {
 750            self.start_transaction(cx);
 751            self.insert(text, cx);
 752            self.autoclose_pairs(cx);
 753            self.end_transaction(cx);
 754        }
 755    }
 756
 757    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 758        self.start_transaction(cx);
 759        let mut old_selections = SmallVec::<[_; 32]>::new();
 760        {
 761            let selections = self.selections(cx);
 762            let buffer = self.buffer.read(cx);
 763            for selection in selections.iter() {
 764                let start_point = selection.start.to_point(buffer);
 765                let indent = buffer
 766                    .indent_column_for_line(start_point.row)
 767                    .min(start_point.column);
 768                let start = selection.start.to_offset(buffer);
 769                let end = selection.end.to_offset(buffer);
 770                old_selections.push((selection.id, start..end, indent));
 771            }
 772        }
 773
 774        let mut new_selections = Vec::with_capacity(old_selections.len());
 775        self.buffer.update(cx, |buffer, cx| {
 776            let mut delta = 0_isize;
 777            let mut pending_edit: Option<PendingEdit> = None;
 778            for (_, range, indent) in &old_selections {
 779                if pending_edit
 780                    .as_ref()
 781                    .map_or(false, |pending| pending.indent != *indent)
 782                {
 783                    let pending = pending_edit.take().unwrap();
 784                    let mut new_text = String::with_capacity(1 + pending.indent as usize);
 785                    new_text.push('\n');
 786                    new_text.extend(iter::repeat(' ').take(pending.indent as usize));
 787                    buffer.edit_with_autoindent(pending.ranges, new_text, cx);
 788                    delta += pending.delta;
 789                }
 790
 791                let start = (range.start as isize + delta) as usize;
 792                let end = (range.end as isize + delta) as usize;
 793                let text_len = *indent as usize + 1;
 794
 795                let pending = pending_edit.get_or_insert_with(Default::default);
 796                pending.delta += text_len as isize - (end - start) as isize;
 797                pending.indent = *indent;
 798                pending.ranges.push(start..end);
 799            }
 800
 801            let pending = pending_edit.unwrap();
 802            let mut new_text = String::with_capacity(1 + pending.indent as usize);
 803            new_text.push('\n');
 804            new_text.extend(iter::repeat(' ').take(pending.indent as usize));
 805            buffer.edit_with_autoindent(pending.ranges, new_text, cx);
 806
 807            let mut delta = 0_isize;
 808            new_selections.extend(old_selections.into_iter().map(|(id, range, indent)| {
 809                let start = (range.start as isize + delta) as usize;
 810                let end = (range.end as isize + delta) as usize;
 811                let text_len = indent as usize + 1;
 812                let anchor = buffer.anchor_before(start + text_len);
 813                delta += text_len as isize - (end - start) as isize;
 814                Selection {
 815                    id,
 816                    start: anchor.clone(),
 817                    end: anchor,
 818                    reversed: false,
 819                    goal: SelectionGoal::None,
 820                }
 821            }))
 822        });
 823
 824        self.update_selections(new_selections, true, cx);
 825        self.end_transaction(cx);
 826
 827        #[derive(Default)]
 828        struct PendingEdit {
 829            indent: u32,
 830            delta: isize,
 831            ranges: SmallVec<[Range<usize>; 32]>,
 832        }
 833    }
 834
 835    fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 836        self.start_transaction(cx);
 837        let mut old_selections = SmallVec::<[_; 32]>::new();
 838        {
 839            let selections = self.selections(cx);
 840            let buffer = self.buffer.read(cx);
 841            for selection in selections.iter() {
 842                let start = selection.start.to_offset(buffer);
 843                let end = selection.end.to_offset(buffer);
 844                old_selections.push((selection.id, start..end));
 845            }
 846        }
 847
 848        let mut new_selections = Vec::new();
 849        self.buffer.update(cx, |buffer, cx| {
 850            let edit_ranges = old_selections.iter().map(|(_, range)| range.clone());
 851            buffer.edit_with_autoindent(edit_ranges, text, cx);
 852            let text_len = text.len() as isize;
 853            let mut delta = 0_isize;
 854            new_selections = old_selections
 855                .into_iter()
 856                .map(|(id, range)| {
 857                    let start = range.start as isize;
 858                    let end = range.end as isize;
 859                    let anchor = buffer.anchor_before((start + delta + text_len) as usize);
 860                    let deleted_count = end - start;
 861                    delta += text_len - deleted_count;
 862                    Selection {
 863                        id,
 864                        start: anchor.clone(),
 865                        end: anchor,
 866                        reversed: false,
 867                        goal: SelectionGoal::None,
 868                    }
 869                })
 870                .collect();
 871        });
 872
 873        self.update_selections(new_selections, true, cx);
 874        self.end_transaction(cx);
 875    }
 876
 877    fn autoclose_pairs(&mut self, cx: &mut ViewContext<Self>) {
 878        let selections = self.selections(cx);
 879        let new_autoclose_pair_state = self.buffer.update(cx, |buffer, cx| {
 880            let autoclose_pair = buffer.language().and_then(|language| {
 881                let first_selection_start = selections.first().unwrap().start.to_offset(&*buffer);
 882                let pair = language.autoclose_pairs().iter().find(|pair| {
 883                    buffer.contains_str_at(
 884                        first_selection_start.saturating_sub(pair.start.len()),
 885                        &pair.start,
 886                    )
 887                });
 888                pair.and_then(|pair| {
 889                    let should_autoclose = selections[1..].iter().all(|selection| {
 890                        let selection_start = selection.start.to_offset(&*buffer);
 891                        buffer.contains_str_at(
 892                            selection_start.saturating_sub(pair.start.len()),
 893                            &pair.start,
 894                        )
 895                    });
 896
 897                    if should_autoclose {
 898                        Some(pair.clone())
 899                    } else {
 900                        None
 901                    }
 902                })
 903            });
 904
 905            autoclose_pair.and_then(|pair| {
 906                let selection_ranges = selections
 907                    .iter()
 908                    .map(|selection| {
 909                        let start = selection.start.to_offset(&*buffer);
 910                        start..start
 911                    })
 912                    .collect::<SmallVec<[_; 32]>>();
 913
 914                buffer.edit(selection_ranges, &pair.end, cx);
 915
 916                if pair.end.len() == 1 {
 917                    Some(AutoclosePairState {
 918                        ranges: selections
 919                            .iter()
 920                            .map(|selection| {
 921                                selection.start.bias_left(buffer)
 922                                    ..selection.start.bias_right(buffer)
 923                            })
 924                            .collect(),
 925                        pair,
 926                    })
 927                } else {
 928                    None
 929                }
 930            })
 931        });
 932        self.autoclose_stack.extend(new_autoclose_pair_state);
 933    }
 934
 935    fn skip_autoclose_end(&mut self, text: &str, cx: &mut ViewContext<Self>) -> bool {
 936        let old_selections = self.selections(cx);
 937        let autoclose_pair_state = if let Some(autoclose_pair_state) = self.autoclose_stack.last() {
 938            autoclose_pair_state
 939        } else {
 940            return false;
 941        };
 942        if text != autoclose_pair_state.pair.end {
 943            return false;
 944        }
 945
 946        debug_assert_eq!(old_selections.len(), autoclose_pair_state.ranges.len());
 947
 948        let buffer = self.buffer.read(cx);
 949        let old_selection_ranges: SmallVec<[_; 32]> = old_selections
 950            .iter()
 951            .map(|selection| (selection.id, selection.offset_range(buffer)))
 952            .collect();
 953        if old_selection_ranges
 954            .iter()
 955            .zip(&autoclose_pair_state.ranges)
 956            .all(|((_, selection_range), autoclose_range)| {
 957                let autoclose_range_end = autoclose_range.end.to_offset(buffer);
 958                selection_range.is_empty() && selection_range.start == autoclose_range_end
 959            })
 960        {
 961            let new_selections = old_selection_ranges
 962                .into_iter()
 963                .map(|(id, range)| {
 964                    let new_head = buffer.anchor_before(range.start + 1);
 965                    Selection {
 966                        id,
 967                        start: new_head.clone(),
 968                        end: new_head,
 969                        reversed: false,
 970                        goal: SelectionGoal::None,
 971                    }
 972                })
 973                .collect();
 974            self.autoclose_stack.pop();
 975            self.update_selections(new_selections, true, cx);
 976            true
 977        } else {
 978            false
 979        }
 980    }
 981
 982    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 983        self.start_transaction(cx);
 984        self.select_all(&SelectAll, cx);
 985        self.insert("", cx);
 986        self.end_transaction(cx);
 987    }
 988
 989    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 990        self.start_transaction(cx);
 991        let mut selections = self.selections(cx).to_vec();
 992        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 993        {
 994            let buffer = self.buffer.read(cx);
 995            for selection in &mut selections {
 996                let range = selection.point_range(buffer);
 997                if range.start == range.end {
 998                    let head = selection.head().to_display_point(&display_map, Bias::Left);
 999                    let cursor = display_map
1000                        .anchor_before(movement::left(&display_map, head).unwrap(), Bias::Left);
1001                    selection.set_head(&buffer, cursor);
1002                    selection.goal = SelectionGoal::None;
1003                }
1004            }
1005        }
1006
1007        self.update_selections(selections, true, cx);
1008        self.insert("", cx);
1009        self.end_transaction(cx);
1010    }
1011
1012    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
1013        self.start_transaction(cx);
1014        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1015        let mut selections = self.selections(cx).to_vec();
1016        {
1017            let buffer = self.buffer.read(cx);
1018            for selection in &mut selections {
1019                let range = selection.point_range(buffer);
1020                if range.start == range.end {
1021                    let head = selection.head().to_display_point(&display_map, Bias::Left);
1022                    let cursor = display_map
1023                        .anchor_before(movement::right(&display_map, head).unwrap(), Bias::Right);
1024                    selection.set_head(&buffer, cursor);
1025                    selection.goal = SelectionGoal::None;
1026                }
1027            }
1028        }
1029
1030        self.update_selections(selections, true, cx);
1031        self.insert(&"", cx);
1032        self.end_transaction(cx);
1033    }
1034
1035    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
1036        self.start_transaction(cx);
1037        let tab_size = self.build_settings.borrow()(cx).tab_size;
1038        let mut selections = self.selections(cx).to_vec();
1039        self.buffer.update(cx, |buffer, cx| {
1040            let mut last_indented_row = None;
1041            for selection in &mut selections {
1042                let mut range = selection.point_range(buffer);
1043                if range.is_empty() {
1044                    let char_column = buffer
1045                        .chars_for_range(Point::new(range.start.row, 0)..range.start)
1046                        .count();
1047                    let chars_to_next_tab_stop = tab_size - (char_column % tab_size);
1048                    buffer.edit(
1049                        [range.start..range.start],
1050                        " ".repeat(chars_to_next_tab_stop),
1051                        cx,
1052                    );
1053                    range.start.column += chars_to_next_tab_stop as u32;
1054
1055                    let head = buffer.anchor_before(range.start);
1056                    selection.start = head.clone();
1057                    selection.end = head;
1058                } else {
1059                    for row in range.start.row..=range.end.row {
1060                        if last_indented_row != Some(row) {
1061                            let char_column = buffer.indent_column_for_line(row) as usize;
1062                            let chars_to_next_tab_stop = tab_size - (char_column % tab_size);
1063                            let row_start = Point::new(row, 0);
1064                            buffer.edit(
1065                                [row_start..row_start],
1066                                " ".repeat(chars_to_next_tab_stop),
1067                                cx,
1068                            );
1069                            last_indented_row = Some(row);
1070                        }
1071                    }
1072                }
1073            }
1074        });
1075
1076        self.update_selections(selections, true, cx);
1077        self.end_transaction(cx);
1078    }
1079
1080    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
1081        self.start_transaction(cx);
1082
1083        let selections = self.selections(cx);
1084        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1085        let buffer = self.buffer.read(cx);
1086
1087        let mut new_cursors = Vec::new();
1088        let mut edit_ranges = Vec::new();
1089
1090        let mut selections = selections.iter().peekable();
1091        while let Some(selection) = selections.next() {
1092            let mut rows = selection.spanned_rows(false, &display_map).buffer_rows;
1093            let goal_display_column = selection
1094                .head()
1095                .to_display_point(&display_map, Bias::Left)
1096                .column();
1097
1098            // Accumulate contiguous regions of rows that we want to delete.
1099            while let Some(next_selection) = selections.peek() {
1100                let next_rows = next_selection.spanned_rows(false, &display_map).buffer_rows;
1101                if next_rows.start <= rows.end {
1102                    rows.end = next_rows.end;
1103                    selections.next().unwrap();
1104                } else {
1105                    break;
1106                }
1107            }
1108
1109            let mut edit_start = Point::new(rows.start, 0).to_offset(buffer);
1110            let edit_end;
1111            let cursor_buffer_row;
1112            if buffer.max_point().row >= rows.end {
1113                // If there's a line after the range, delete the \n from the end of the row range
1114                // and position the cursor on the next line.
1115                edit_end = Point::new(rows.end, 0).to_offset(buffer);
1116                cursor_buffer_row = rows.end;
1117            } else {
1118                // If there isn't a line after the range, delete the \n from the line before the
1119                // start of the row range and position the cursor there.
1120                edit_start = edit_start.saturating_sub(1);
1121                edit_end = buffer.len();
1122                cursor_buffer_row = rows.start.saturating_sub(1);
1123            }
1124
1125            let mut cursor =
1126                Point::new(cursor_buffer_row, 0).to_display_point(&display_map, Bias::Left);
1127            *cursor.column_mut() =
1128                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
1129
1130            new_cursors.push((
1131                selection.id,
1132                cursor.to_buffer_point(&display_map, Bias::Left),
1133            ));
1134            edit_ranges.push(edit_start..edit_end);
1135        }
1136
1137        new_cursors.sort_unstable_by_key(|(_, range)| range.clone());
1138        let new_selections = new_cursors
1139            .into_iter()
1140            .map(|(id, cursor)| {
1141                let anchor = buffer.anchor_before(cursor);
1142                Selection {
1143                    id,
1144                    start: anchor.clone(),
1145                    end: anchor,
1146                    reversed: false,
1147                    goal: SelectionGoal::None,
1148                }
1149            })
1150            .collect();
1151        self.buffer
1152            .update(cx, |buffer, cx| buffer.edit(edit_ranges, "", cx));
1153        self.update_selections(new_selections, true, cx);
1154        self.end_transaction(cx);
1155    }
1156
1157    pub fn duplicate_line(&mut self, _: &DuplicateLine, cx: &mut ViewContext<Self>) {
1158        self.start_transaction(cx);
1159
1160        let mut selections = self.selections(cx).to_vec();
1161        {
1162            // Temporarily bias selections right to allow newly duplicate lines to push them down
1163            // when the selections are at the beginning of a line.
1164            let buffer = self.buffer.read(cx);
1165            for selection in &mut selections {
1166                selection.start = selection.start.bias_right(buffer);
1167                selection.end = selection.end.bias_right(buffer);
1168            }
1169        }
1170        self.update_selections(selections.clone(), false, cx);
1171
1172        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1173        let buffer = self.buffer.read(cx);
1174
1175        let mut edits = Vec::new();
1176        let mut selections_iter = selections.iter_mut().peekable();
1177        while let Some(selection) = selections_iter.next() {
1178            // Avoid duplicating the same lines twice.
1179            let mut rows = selection.spanned_rows(false, &display_map).buffer_rows;
1180            while let Some(next_selection) = selections_iter.peek() {
1181                let next_rows = next_selection.spanned_rows(false, &display_map).buffer_rows;
1182                if next_rows.start <= rows.end - 1 {
1183                    rows.end = next_rows.end;
1184                    selections_iter.next().unwrap();
1185                } else {
1186                    break;
1187                }
1188            }
1189
1190            // Copy the text from the selected row region and splice it at the start of the region.
1191            let start = Point::new(rows.start, 0);
1192            let end = Point::new(rows.end - 1, buffer.line_len(rows.end - 1));
1193            let text = buffer
1194                .text_for_range(start..end)
1195                .chain(Some("\n"))
1196                .collect::<String>();
1197            edits.push((start, text));
1198        }
1199
1200        self.buffer.update(cx, |buffer, cx| {
1201            for (offset, text) in edits.into_iter().rev() {
1202                buffer.edit(Some(offset..offset), text, cx);
1203            }
1204        });
1205
1206        // Restore bias on selections.
1207        let buffer = self.buffer.read(cx);
1208        for selection in &mut selections {
1209            selection.start = selection.start.bias_left(buffer);
1210            selection.end = selection.end.bias_left(buffer);
1211        }
1212        self.update_selections(selections, true, cx);
1213
1214        self.end_transaction(cx);
1215    }
1216
1217    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
1218        self.start_transaction(cx);
1219
1220        let selections = self.selections(cx);
1221        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1222        let buffer = self.buffer.read(cx);
1223
1224        let mut edits = Vec::new();
1225        let mut new_selection_ranges = Vec::new();
1226        let mut old_folds = Vec::new();
1227        let mut new_folds = Vec::new();
1228
1229        let mut selections = selections.iter().peekable();
1230        let mut contiguous_selections = Vec::new();
1231        while let Some(selection) = selections.next() {
1232            // Accumulate contiguous regions of rows that we want to move.
1233            contiguous_selections.push(selection.point_range(buffer));
1234            let SpannedRows {
1235                mut buffer_rows,
1236                mut display_rows,
1237            } = selection.spanned_rows(false, &display_map);
1238
1239            while let Some(next_selection) = selections.peek() {
1240                let SpannedRows {
1241                    buffer_rows: next_buffer_rows,
1242                    display_rows: next_display_rows,
1243                } = next_selection.spanned_rows(false, &display_map);
1244                if next_buffer_rows.start <= buffer_rows.end {
1245                    buffer_rows.end = next_buffer_rows.end;
1246                    display_rows.end = next_display_rows.end;
1247                    contiguous_selections.push(next_selection.point_range(buffer));
1248                    selections.next().unwrap();
1249                } else {
1250                    break;
1251                }
1252            }
1253
1254            // Cut the text from the selected rows and paste it at the start of the previous line.
1255            if display_rows.start != 0 {
1256                let start = Point::new(buffer_rows.start, 0).to_offset(buffer);
1257                let end = Point::new(buffer_rows.end - 1, buffer.line_len(buffer_rows.end - 1))
1258                    .to_offset(buffer);
1259
1260                let prev_row_display_start = DisplayPoint::new(display_rows.start - 1, 0);
1261                let prev_row_buffer_start = display_map.prev_row_boundary(prev_row_display_start).1;
1262                let prev_row_buffer_start_offset = prev_row_buffer_start.to_offset(buffer);
1263
1264                let mut text = String::new();
1265                text.extend(buffer.text_for_range(start..end));
1266                text.push('\n');
1267                edits.push((
1268                    prev_row_buffer_start_offset..prev_row_buffer_start_offset,
1269                    text,
1270                ));
1271                edits.push((start - 1..end, String::new()));
1272
1273                let row_delta = buffer_rows.start - prev_row_buffer_start.row;
1274
1275                // Move selections up.
1276                for range in &mut contiguous_selections {
1277                    range.start.row -= row_delta;
1278                    range.end.row -= row_delta;
1279                }
1280
1281                // Move folds up.
1282                old_folds.push(start..end);
1283                for fold in display_map.folds_in_range(start..end) {
1284                    let mut start = fold.start.to_point(buffer);
1285                    let mut end = fold.end.to_point(buffer);
1286                    start.row -= row_delta;
1287                    end.row -= row_delta;
1288                    new_folds.push(start..end);
1289                }
1290            }
1291
1292            new_selection_ranges.extend(contiguous_selections.drain(..));
1293        }
1294
1295        self.unfold_ranges(old_folds, cx);
1296        self.buffer.update(cx, |buffer, cx| {
1297            for (range, text) in edits.into_iter().rev() {
1298                buffer.edit(Some(range), text, cx);
1299            }
1300        });
1301        self.fold_ranges(new_folds, cx);
1302        self.select_ranges(new_selection_ranges, true, cx);
1303
1304        self.end_transaction(cx);
1305    }
1306
1307    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
1308        self.start_transaction(cx);
1309
1310        let selections = self.selections(cx);
1311        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1312        let buffer = self.buffer.read(cx);
1313
1314        let mut edits = Vec::new();
1315        let mut new_selection_ranges = Vec::new();
1316        let mut old_folds = Vec::new();
1317        let mut new_folds = Vec::new();
1318
1319        let mut selections = selections.iter().peekable();
1320        let mut contiguous_selections = Vec::new();
1321        while let Some(selection) = selections.next() {
1322            // Accumulate contiguous regions of rows that we want to move.
1323            contiguous_selections.push(selection.point_range(buffer));
1324            let SpannedRows {
1325                mut buffer_rows,
1326                mut display_rows,
1327            } = selection.spanned_rows(false, &display_map);
1328            while let Some(next_selection) = selections.peek() {
1329                let SpannedRows {
1330                    buffer_rows: next_buffer_rows,
1331                    display_rows: next_display_rows,
1332                } = next_selection.spanned_rows(false, &display_map);
1333                if next_buffer_rows.start <= buffer_rows.end {
1334                    buffer_rows.end = next_buffer_rows.end;
1335                    display_rows.end = next_display_rows.end;
1336                    contiguous_selections.push(next_selection.point_range(buffer));
1337                    selections.next().unwrap();
1338                } else {
1339                    break;
1340                }
1341            }
1342
1343            // Cut the text from the selected rows and paste it at the end of the next line.
1344            if display_rows.end <= display_map.max_point().row() {
1345                let start = Point::new(buffer_rows.start, 0).to_offset(buffer);
1346                let end = Point::new(buffer_rows.end - 1, buffer.line_len(buffer_rows.end - 1))
1347                    .to_offset(buffer);
1348
1349                let next_row_display_end =
1350                    DisplayPoint::new(display_rows.end, display_map.line_len(display_rows.end));
1351                let next_row_buffer_end = display_map.next_row_boundary(next_row_display_end).1;
1352                let next_row_buffer_end_offset = next_row_buffer_end.to_offset(buffer);
1353
1354                let mut text = String::new();
1355                text.push('\n');
1356                text.extend(buffer.text_for_range(start..end));
1357                edits.push((start..end + 1, String::new()));
1358                edits.push((next_row_buffer_end_offset..next_row_buffer_end_offset, text));
1359
1360                let row_delta = next_row_buffer_end.row - buffer_rows.end + 1;
1361
1362                // Move selections down.
1363                for range in &mut contiguous_selections {
1364                    range.start.row += row_delta;
1365                    range.end.row += row_delta;
1366                }
1367
1368                // Move folds down.
1369                old_folds.push(start..end);
1370                for fold in display_map.folds_in_range(start..end) {
1371                    let mut start = fold.start.to_point(buffer);
1372                    let mut end = fold.end.to_point(buffer);
1373                    start.row += row_delta;
1374                    end.row += row_delta;
1375                    new_folds.push(start..end);
1376                }
1377            }
1378
1379            new_selection_ranges.extend(contiguous_selections.drain(..));
1380        }
1381
1382        self.unfold_ranges(old_folds, cx);
1383        self.buffer.update(cx, |buffer, cx| {
1384            for (range, text) in edits.into_iter().rev() {
1385                buffer.edit(Some(range), text, cx);
1386            }
1387        });
1388        self.fold_ranges(new_folds, cx);
1389        self.select_ranges(new_selection_ranges, true, cx);
1390
1391        self.end_transaction(cx);
1392    }
1393
1394    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
1395        self.start_transaction(cx);
1396        let mut text = String::new();
1397        let mut selections = self.selections(cx).to_vec();
1398        let mut clipboard_selections = Vec::with_capacity(selections.len());
1399        {
1400            let buffer = self.buffer.read(cx);
1401            let max_point = buffer.max_point();
1402            for selection in &mut selections {
1403                let mut start = selection.start.to_point(buffer);
1404                let mut end = selection.end.to_point(buffer);
1405                let is_entire_line = start == end;
1406                if is_entire_line {
1407                    start = Point::new(start.row, 0);
1408                    end = cmp::min(max_point, Point::new(start.row + 1, 0));
1409                    selection.start = buffer.anchor_before(start);
1410                    selection.end = buffer.anchor_before(end);
1411                }
1412                let mut len = 0;
1413                for chunk in buffer.text_for_range(start..end) {
1414                    text.push_str(chunk);
1415                    len += chunk.len();
1416                }
1417                clipboard_selections.push(ClipboardSelection {
1418                    len,
1419                    is_entire_line,
1420                });
1421            }
1422        }
1423        self.update_selections(selections, true, cx);
1424        self.insert("", cx);
1425        self.end_transaction(cx);
1426
1427        cx.as_mut()
1428            .write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
1429    }
1430
1431    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
1432        let selections = self.selections(cx);
1433        let buffer = self.buffer.read(cx);
1434        let max_point = buffer.max_point();
1435        let mut text = String::new();
1436        let mut clipboard_selections = Vec::with_capacity(selections.len());
1437        for selection in selections.iter() {
1438            let mut start = selection.start.to_point(buffer);
1439            let mut end = selection.end.to_point(buffer);
1440            let is_entire_line = start == end;
1441            if is_entire_line {
1442                start = Point::new(start.row, 0);
1443                end = cmp::min(max_point, Point::new(start.row + 1, 0));
1444            }
1445            let mut len = 0;
1446            for chunk in buffer.text_for_range(start..end) {
1447                text.push_str(chunk);
1448                len += chunk.len();
1449            }
1450            clipboard_selections.push(ClipboardSelection {
1451                len,
1452                is_entire_line,
1453            });
1454        }
1455
1456        cx.as_mut()
1457            .write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
1458    }
1459
1460    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
1461        if let Some(item) = cx.as_mut().read_from_clipboard() {
1462            let clipboard_text = item.text();
1463            if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
1464                let selections = self.selections(cx);
1465                let all_selections_were_entire_line =
1466                    clipboard_selections.iter().all(|s| s.is_entire_line);
1467                if clipboard_selections.len() != selections.len() {
1468                    clipboard_selections.clear();
1469                }
1470
1471                let mut start_offset = 0;
1472                let mut new_selections = Vec::with_capacity(selections.len());
1473                for (i, selection) in selections.iter().enumerate() {
1474                    let to_insert;
1475                    let entire_line;
1476                    if let Some(clipboard_selection) = clipboard_selections.get(i) {
1477                        let end_offset = start_offset + clipboard_selection.len;
1478                        to_insert = &clipboard_text[start_offset..end_offset];
1479                        entire_line = clipboard_selection.is_entire_line;
1480                        start_offset = end_offset
1481                    } else {
1482                        to_insert = clipboard_text.as_str();
1483                        entire_line = all_selections_were_entire_line;
1484                    }
1485
1486                    self.buffer.update(cx, |buffer, cx| {
1487                        let selection_start = selection.start.to_point(&*buffer);
1488                        let selection_end = selection.end.to_point(&*buffer);
1489
1490                        // If the corresponding selection was empty when this slice of the
1491                        // clipboard text was written, then the entire line containing the
1492                        // selection was copied. If this selection is also currently empty,
1493                        // then paste the line before the current line of the buffer.
1494                        let new_selection_start = selection.end.bias_right(buffer);
1495                        if selection_start == selection_end && entire_line {
1496                            let line_start = Point::new(selection_start.row, 0);
1497                            buffer.edit(Some(line_start..line_start), to_insert, cx);
1498                        } else {
1499                            buffer.edit(Some(&selection.start..&selection.end), to_insert, cx);
1500                        };
1501
1502                        let new_selection_start = new_selection_start.bias_left(buffer);
1503                        new_selections.push(Selection {
1504                            id: selection.id,
1505                            start: new_selection_start.clone(),
1506                            end: new_selection_start,
1507                            reversed: false,
1508                            goal: SelectionGoal::None,
1509                        });
1510                    });
1511                }
1512                self.update_selections(new_selections, true, cx);
1513            } else {
1514                self.insert(clipboard_text, cx);
1515            }
1516        }
1517    }
1518
1519    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
1520        self.buffer.update(cx, |buffer, cx| buffer.undo(cx));
1521    }
1522
1523    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
1524        self.buffer.update(cx, |buffer, cx| buffer.redo(cx));
1525    }
1526
1527    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
1528        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1529        let mut selections = self.selections(cx).to_vec();
1530        {
1531            for selection in &mut selections {
1532                let start = selection.start.to_display_point(&display_map, Bias::Left);
1533                let end = selection.end.to_display_point(&display_map, Bias::Left);
1534
1535                if start != end {
1536                    selection.end = selection.start.clone();
1537                } else {
1538                    let cursor = display_map
1539                        .anchor_before(movement::left(&display_map, start).unwrap(), Bias::Left);
1540                    selection.start = cursor.clone();
1541                    selection.end = cursor;
1542                }
1543                selection.reversed = false;
1544                selection.goal = SelectionGoal::None;
1545            }
1546        }
1547        self.update_selections(selections, true, cx);
1548    }
1549
1550    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
1551        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1552        let mut selections = self.selections(cx).to_vec();
1553        {
1554            let buffer = self.buffer.read(cx);
1555            for selection in &mut selections {
1556                let head = selection.head().to_display_point(&display_map, Bias::Left);
1557                let cursor = display_map
1558                    .anchor_before(movement::left(&display_map, head).unwrap(), Bias::Left);
1559                selection.set_head(&buffer, cursor);
1560                selection.goal = SelectionGoal::None;
1561            }
1562        }
1563        self.update_selections(selections, true, cx);
1564    }
1565
1566    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
1567        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1568        let mut selections = self.selections(cx).to_vec();
1569        {
1570            for selection in &mut selections {
1571                let start = selection.start.to_display_point(&display_map, Bias::Left);
1572                let end = selection.end.to_display_point(&display_map, Bias::Left);
1573
1574                if start != end {
1575                    selection.start = selection.end.clone();
1576                } else {
1577                    let cursor = display_map
1578                        .anchor_before(movement::right(&display_map, end).unwrap(), Bias::Right);
1579                    selection.start = cursor.clone();
1580                    selection.end = cursor;
1581                }
1582                selection.reversed = false;
1583                selection.goal = SelectionGoal::None;
1584            }
1585        }
1586        self.update_selections(selections, true, cx);
1587    }
1588
1589    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
1590        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1591        let mut selections = self.selections(cx).to_vec();
1592        {
1593            let app = cx.as_ref();
1594            let buffer = self.buffer.read(app);
1595            for selection in &mut selections {
1596                let head = selection.head().to_display_point(&display_map, Bias::Left);
1597                let cursor = display_map
1598                    .anchor_before(movement::right(&display_map, head).unwrap(), Bias::Right);
1599                selection.set_head(&buffer, cursor);
1600                selection.goal = SelectionGoal::None;
1601            }
1602        }
1603        self.update_selections(selections, true, cx);
1604    }
1605
1606    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
1607        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1608        if matches!(self.mode, EditorMode::SingleLine) {
1609            cx.propagate_action();
1610        } else {
1611            let mut selections = self.selections(cx).to_vec();
1612            {
1613                for selection in &mut selections {
1614                    let start = selection.start.to_display_point(&display_map, Bias::Left);
1615                    let end = selection.end.to_display_point(&display_map, Bias::Left);
1616                    if start != end {
1617                        selection.goal = SelectionGoal::None;
1618                    }
1619
1620                    let (start, goal) = movement::up(&display_map, start, selection.goal).unwrap();
1621                    let cursor = display_map.anchor_before(start, Bias::Left);
1622                    selection.start = cursor.clone();
1623                    selection.end = cursor;
1624                    selection.goal = goal;
1625                    selection.reversed = false;
1626                }
1627            }
1628            self.update_selections(selections, true, cx);
1629        }
1630    }
1631
1632    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
1633        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1634        let mut selections = self.selections(cx).to_vec();
1635        {
1636            let app = cx.as_ref();
1637            let buffer = self.buffer.read(app);
1638            for selection in &mut selections {
1639                let head = selection.head().to_display_point(&display_map, Bias::Left);
1640                let (head, goal) = movement::up(&display_map, head, selection.goal).unwrap();
1641                selection.set_head(&buffer, display_map.anchor_before(head, Bias::Left));
1642                selection.goal = goal;
1643            }
1644        }
1645        self.update_selections(selections, true, cx);
1646    }
1647
1648    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
1649        if matches!(self.mode, EditorMode::SingleLine) {
1650            cx.propagate_action();
1651        } else {
1652            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1653            let mut selections = self.selections(cx).to_vec();
1654            {
1655                for selection in &mut selections {
1656                    let start = selection.start.to_display_point(&display_map, Bias::Left);
1657                    let end = selection.end.to_display_point(&display_map, Bias::Left);
1658                    if start != end {
1659                        selection.goal = SelectionGoal::None;
1660                    }
1661
1662                    let (start, goal) = movement::down(&display_map, end, selection.goal).unwrap();
1663                    let cursor = display_map.anchor_before(start, Bias::Right);
1664                    selection.start = cursor.clone();
1665                    selection.end = cursor;
1666                    selection.goal = goal;
1667                    selection.reversed = false;
1668                }
1669            }
1670            self.update_selections(selections, true, cx);
1671        }
1672    }
1673
1674    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
1675        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1676        let mut selections = self.selections(cx).to_vec();
1677        {
1678            let app = cx.as_ref();
1679            let buffer = self.buffer.read(app);
1680            for selection in &mut selections {
1681                let head = selection.head().to_display_point(&display_map, Bias::Left);
1682                let (head, goal) = movement::down(&display_map, head, selection.goal).unwrap();
1683                selection.set_head(&buffer, display_map.anchor_before(head, Bias::Right));
1684                selection.goal = goal;
1685            }
1686        }
1687        self.update_selections(selections, true, cx);
1688    }
1689
1690    pub fn move_to_previous_word_boundary(
1691        &mut self,
1692        _: &MoveToPreviousWordBoundary,
1693        cx: &mut ViewContext<Self>,
1694    ) {
1695        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1696        let mut selections = self.selections(cx).to_vec();
1697        {
1698            for selection in &mut selections {
1699                let head = selection.head().to_display_point(&display_map, Bias::Left);
1700                let new_head = movement::prev_word_boundary(&display_map, head).unwrap();
1701                let anchor = display_map.anchor_before(new_head, Bias::Left);
1702                selection.start = anchor.clone();
1703                selection.end = anchor;
1704                selection.reversed = false;
1705                selection.goal = SelectionGoal::None;
1706            }
1707        }
1708        self.update_selections(selections, true, cx);
1709    }
1710
1711    pub fn select_to_previous_word_boundary(
1712        &mut self,
1713        _: &SelectToPreviousWordBoundary,
1714        cx: &mut ViewContext<Self>,
1715    ) {
1716        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1717        let mut selections = self.selections(cx).to_vec();
1718        {
1719            let buffer = self.buffer.read(cx);
1720            for selection in &mut selections {
1721                let head = selection.head().to_display_point(&display_map, Bias::Left);
1722                let new_head = movement::prev_word_boundary(&display_map, head).unwrap();
1723                let anchor = display_map.anchor_before(new_head, Bias::Left);
1724                selection.set_head(buffer, anchor);
1725                selection.goal = SelectionGoal::None;
1726            }
1727        }
1728        self.update_selections(selections, true, cx);
1729    }
1730
1731    pub fn delete_to_previous_word_boundary(
1732        &mut self,
1733        _: &DeleteToPreviousWordBoundary,
1734        cx: &mut ViewContext<Self>,
1735    ) {
1736        self.start_transaction(cx);
1737        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1738        let mut selections = self.selections(cx).to_vec();
1739        {
1740            let buffer = self.buffer.read(cx);
1741            for selection in &mut selections {
1742                let range = selection.point_range(buffer);
1743                if range.start == range.end {
1744                    let head = selection.head().to_display_point(&display_map, Bias::Left);
1745                    let cursor = display_map.anchor_before(
1746                        movement::prev_word_boundary(&display_map, head).unwrap(),
1747                        Bias::Right,
1748                    );
1749                    selection.set_head(&buffer, cursor);
1750                    selection.goal = SelectionGoal::None;
1751                }
1752            }
1753        }
1754
1755        self.update_selections(selections, true, cx);
1756        self.insert("", cx);
1757        self.end_transaction(cx);
1758    }
1759
1760    pub fn move_to_next_word_boundary(
1761        &mut self,
1762        _: &MoveToNextWordBoundary,
1763        cx: &mut ViewContext<Self>,
1764    ) {
1765        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1766        let mut selections = self.selections(cx).to_vec();
1767        {
1768            for selection in &mut selections {
1769                let head = selection.head().to_display_point(&display_map, Bias::Left);
1770                let new_head = movement::next_word_boundary(&display_map, head).unwrap();
1771                let anchor = display_map.anchor_before(new_head, Bias::Left);
1772                selection.start = anchor.clone();
1773                selection.end = anchor;
1774                selection.reversed = false;
1775                selection.goal = SelectionGoal::None;
1776            }
1777        }
1778        self.update_selections(selections, true, cx);
1779    }
1780
1781    pub fn select_to_next_word_boundary(
1782        &mut self,
1783        _: &SelectToNextWordBoundary,
1784        cx: &mut ViewContext<Self>,
1785    ) {
1786        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1787        let mut selections = self.selections(cx).to_vec();
1788        {
1789            let buffer = self.buffer.read(cx);
1790            for selection in &mut selections {
1791                let head = selection.head().to_display_point(&display_map, Bias::Left);
1792                let new_head = movement::next_word_boundary(&display_map, head).unwrap();
1793                let anchor = display_map.anchor_before(new_head, Bias::Left);
1794                selection.set_head(buffer, anchor);
1795                selection.goal = SelectionGoal::None;
1796            }
1797        }
1798        self.update_selections(selections, true, cx);
1799    }
1800
1801    pub fn delete_to_next_word_boundary(
1802        &mut self,
1803        _: &DeleteToNextWordBoundary,
1804        cx: &mut ViewContext<Self>,
1805    ) {
1806        self.start_transaction(cx);
1807        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1808        let mut selections = self.selections(cx).to_vec();
1809        {
1810            let buffer = self.buffer.read(cx);
1811            for selection in &mut selections {
1812                let range = selection.point_range(buffer);
1813                if range.start == range.end {
1814                    let head = selection.head().to_display_point(&display_map, Bias::Left);
1815                    let cursor = display_map.anchor_before(
1816                        movement::next_word_boundary(&display_map, head).unwrap(),
1817                        Bias::Right,
1818                    );
1819                    selection.set_head(&buffer, cursor);
1820                    selection.goal = SelectionGoal::None;
1821                }
1822            }
1823        }
1824
1825        self.update_selections(selections, true, cx);
1826        self.insert("", cx);
1827        self.end_transaction(cx);
1828    }
1829
1830    pub fn move_to_beginning_of_line(
1831        &mut self,
1832        _: &MoveToBeginningOfLine,
1833        cx: &mut ViewContext<Self>,
1834    ) {
1835        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1836        let mut selections = self.selections(cx).to_vec();
1837        {
1838            for selection in &mut selections {
1839                let head = selection.head().to_display_point(&display_map, Bias::Left);
1840                let new_head = movement::line_beginning(&display_map, head, true).unwrap();
1841                let anchor = display_map.anchor_before(new_head, Bias::Left);
1842                selection.start = anchor.clone();
1843                selection.end = anchor;
1844                selection.reversed = false;
1845                selection.goal = SelectionGoal::None;
1846            }
1847        }
1848        self.update_selections(selections, true, cx);
1849    }
1850
1851    pub fn select_to_beginning_of_line(
1852        &mut self,
1853        SelectToBeginningOfLine(toggle_indent): &SelectToBeginningOfLine,
1854        cx: &mut ViewContext<Self>,
1855    ) {
1856        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1857        let mut selections = self.selections(cx).to_vec();
1858        {
1859            let buffer = self.buffer.read(cx);
1860            for selection in &mut selections {
1861                let head = selection.head().to_display_point(&display_map, Bias::Left);
1862                let new_head =
1863                    movement::line_beginning(&display_map, head, *toggle_indent).unwrap();
1864                let anchor = display_map.anchor_before(new_head, Bias::Left);
1865                selection.set_head(buffer, anchor);
1866                selection.goal = SelectionGoal::None;
1867            }
1868        }
1869        self.update_selections(selections, true, cx);
1870    }
1871
1872    pub fn delete_to_beginning_of_line(
1873        &mut self,
1874        _: &DeleteToBeginningOfLine,
1875        cx: &mut ViewContext<Self>,
1876    ) {
1877        self.start_transaction(cx);
1878        self.select_to_beginning_of_line(&SelectToBeginningOfLine(false), cx);
1879        self.backspace(&Backspace, cx);
1880        self.end_transaction(cx);
1881    }
1882
1883    pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
1884        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1885        let mut selections = self.selections(cx).to_vec();
1886        {
1887            for selection in &mut selections {
1888                let head = selection.head().to_display_point(&display_map, Bias::Left);
1889                let new_head = movement::line_end(&display_map, head).unwrap();
1890                let anchor = display_map.anchor_before(new_head, Bias::Left);
1891                selection.start = anchor.clone();
1892                selection.end = anchor;
1893                selection.reversed = false;
1894                selection.goal = SelectionGoal::None;
1895            }
1896        }
1897        self.update_selections(selections, true, cx);
1898    }
1899
1900    pub fn select_to_end_of_line(&mut self, _: &SelectToEndOfLine, cx: &mut ViewContext<Self>) {
1901        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1902        let mut selections = self.selections(cx).to_vec();
1903        {
1904            let buffer = self.buffer.read(cx);
1905            for selection in &mut selections {
1906                let head = selection.head().to_display_point(&display_map, Bias::Left);
1907                let new_head = movement::line_end(&display_map, head).unwrap();
1908                let anchor = display_map.anchor_before(new_head, Bias::Left);
1909                selection.set_head(buffer, anchor);
1910                selection.goal = SelectionGoal::None;
1911            }
1912        }
1913        self.update_selections(selections, true, cx);
1914    }
1915
1916    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
1917        self.start_transaction(cx);
1918        self.select_to_end_of_line(&SelectToEndOfLine, cx);
1919        self.delete(&Delete, cx);
1920        self.end_transaction(cx);
1921    }
1922
1923    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
1924        self.start_transaction(cx);
1925        self.select_to_end_of_line(&SelectToEndOfLine, cx);
1926        self.cut(&Cut, cx);
1927        self.end_transaction(cx);
1928    }
1929
1930    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
1931        let buffer = self.buffer.read(cx);
1932        let cursor = buffer.anchor_before(Point::new(0, 0));
1933        let selection = Selection {
1934            id: post_inc(&mut self.next_selection_id),
1935            start: cursor.clone(),
1936            end: cursor,
1937            reversed: false,
1938            goal: SelectionGoal::None,
1939        };
1940        self.update_selections(vec![selection], true, cx);
1941    }
1942
1943    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
1944        let mut selection = self.selections(cx).last().unwrap().clone();
1945        selection.set_head(self.buffer.read(cx), Anchor::min());
1946        self.update_selections(vec![selection], true, cx);
1947    }
1948
1949    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
1950        let buffer = self.buffer.read(cx);
1951        let cursor = buffer.anchor_before(buffer.max_point());
1952        let selection = Selection {
1953            id: post_inc(&mut self.next_selection_id),
1954            start: cursor.clone(),
1955            end: cursor,
1956            reversed: false,
1957            goal: SelectionGoal::None,
1958        };
1959        self.update_selections(vec![selection], true, cx);
1960    }
1961
1962    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
1963        let mut selection = self.selections(cx).last().unwrap().clone();
1964        selection.set_head(self.buffer.read(cx), Anchor::max());
1965        self.update_selections(vec![selection], true, cx);
1966    }
1967
1968    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
1969        let selection = Selection {
1970            id: post_inc(&mut self.next_selection_id),
1971            start: Anchor::min(),
1972            end: Anchor::max(),
1973            reversed: false,
1974            goal: SelectionGoal::None,
1975        };
1976        self.update_selections(vec![selection], false, cx);
1977    }
1978
1979    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
1980        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1981        let mut selections = self.selections(cx).to_vec();
1982        let buffer = self.buffer.read(cx);
1983        let max_point = buffer.max_point();
1984        for selection in &mut selections {
1985            let rows = selection.spanned_rows(true, &display_map).buffer_rows;
1986            selection.start = buffer.anchor_before(Point::new(rows.start, 0));
1987            selection.end = buffer.anchor_before(cmp::min(max_point, Point::new(rows.end, 0)));
1988            selection.reversed = false;
1989        }
1990        self.update_selections(selections, true, cx);
1991    }
1992
1993    pub fn split_selection_into_lines(
1994        &mut self,
1995        _: &SplitSelectionIntoLines,
1996        cx: &mut ViewContext<Self>,
1997    ) {
1998        let selections = self.selections(cx);
1999        let buffer = self.buffer.read(cx);
2000
2001        let mut to_unfold = Vec::new();
2002        let mut new_selections = Vec::new();
2003        for selection in selections.iter() {
2004            let range = selection.point_range(buffer).sorted();
2005            if range.start.row != range.end.row {
2006                new_selections.push(Selection {
2007                    id: post_inc(&mut self.next_selection_id),
2008                    start: selection.start.clone(),
2009                    end: selection.start.clone(),
2010                    reversed: false,
2011                    goal: SelectionGoal::None,
2012                });
2013            }
2014            for row in range.start.row + 1..range.end.row {
2015                let cursor = buffer.anchor_before(Point::new(row, buffer.line_len(row)));
2016                new_selections.push(Selection {
2017                    id: post_inc(&mut self.next_selection_id),
2018                    start: cursor.clone(),
2019                    end: cursor,
2020                    reversed: false,
2021                    goal: SelectionGoal::None,
2022                });
2023            }
2024            new_selections.push(Selection {
2025                id: selection.id,
2026                start: selection.end.clone(),
2027                end: selection.end.clone(),
2028                reversed: false,
2029                goal: SelectionGoal::None,
2030            });
2031            to_unfold.push(range);
2032        }
2033        self.unfold_ranges(to_unfold, cx);
2034        self.update_selections(new_selections, true, cx);
2035    }
2036
2037    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
2038        self.add_selection(true, cx);
2039    }
2040
2041    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
2042        self.add_selection(false, cx);
2043    }
2044
2045    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
2046        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2047        let mut selections = self.selections(cx).to_vec();
2048        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
2049            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
2050            let range = oldest_selection.display_range(&display_map).sorted();
2051            let columns = cmp::min(range.start.column(), range.end.column())
2052                ..cmp::max(range.start.column(), range.end.column());
2053
2054            selections.clear();
2055            let mut stack = Vec::new();
2056            for row in range.start.row()..=range.end.row() {
2057                if let Some(selection) = self.build_columnar_selection(
2058                    &display_map,
2059                    row,
2060                    &columns,
2061                    oldest_selection.reversed,
2062                ) {
2063                    stack.push(selection.id);
2064                    selections.push(selection);
2065                }
2066            }
2067
2068            if above {
2069                stack.reverse();
2070            }
2071
2072            AddSelectionsState { above, stack }
2073        });
2074
2075        let last_added_selection = *state.stack.last().unwrap();
2076        let mut new_selections = Vec::new();
2077        if above == state.above {
2078            let end_row = if above {
2079                0
2080            } else {
2081                display_map.max_point().row()
2082            };
2083
2084            'outer: for selection in selections {
2085                if selection.id == last_added_selection {
2086                    let range = selection.display_range(&display_map).sorted();
2087                    debug_assert_eq!(range.start.row(), range.end.row());
2088                    let mut row = range.start.row();
2089                    let columns = if let SelectionGoal::ColumnRange { start, end } = selection.goal
2090                    {
2091                        start..end
2092                    } else {
2093                        cmp::min(range.start.column(), range.end.column())
2094                            ..cmp::max(range.start.column(), range.end.column())
2095                    };
2096
2097                    while row != end_row {
2098                        if above {
2099                            row -= 1;
2100                        } else {
2101                            row += 1;
2102                        }
2103
2104                        if let Some(new_selection) = self.build_columnar_selection(
2105                            &display_map,
2106                            row,
2107                            &columns,
2108                            selection.reversed,
2109                        ) {
2110                            state.stack.push(new_selection.id);
2111                            if above {
2112                                new_selections.push(new_selection);
2113                                new_selections.push(selection);
2114                            } else {
2115                                new_selections.push(selection);
2116                                new_selections.push(new_selection);
2117                            }
2118
2119                            continue 'outer;
2120                        }
2121                    }
2122                }
2123
2124                new_selections.push(selection);
2125            }
2126        } else {
2127            new_selections = selections;
2128            new_selections.retain(|s| s.id != last_added_selection);
2129            state.stack.pop();
2130        }
2131
2132        self.update_selections(new_selections, true, cx);
2133        if state.stack.len() > 1 {
2134            self.add_selections_state = Some(state);
2135        }
2136    }
2137
2138    pub fn select_larger_syntax_node(
2139        &mut self,
2140        _: &SelectLargerSyntaxNode,
2141        cx: &mut ViewContext<Self>,
2142    ) {
2143        let old_selections = self.selections(cx);
2144        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2145        let buffer = self.buffer.read(cx);
2146
2147        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
2148        let mut selected_larger_node = false;
2149        let mut new_selection_ranges = Vec::new();
2150        for selection in old_selections.iter() {
2151            let old_range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
2152            let mut new_range = old_range.clone();
2153            while let Some(containing_range) = buffer.range_for_syntax_ancestor(new_range.clone()) {
2154                new_range = containing_range;
2155                if !display_map.intersects_fold(new_range.start)
2156                    && !display_map.intersects_fold(new_range.end)
2157                {
2158                    break;
2159                }
2160            }
2161
2162            selected_larger_node |= new_range != old_range;
2163            new_selection_ranges.push((selection.id, new_range, selection.reversed));
2164        }
2165
2166        if selected_larger_node {
2167            stack.push(old_selections);
2168            new_selection_ranges.sort_unstable_by_key(|(_, range, _)| range.start.clone());
2169            let new_selections = new_selection_ranges
2170                .into_iter()
2171                .map(|(id, range, reversed)| Selection {
2172                    id,
2173                    start: buffer.anchor_before(range.start),
2174                    end: buffer.anchor_before(range.end),
2175                    reversed,
2176                    goal: SelectionGoal::None,
2177                })
2178                .collect();
2179            self.update_selections(new_selections, true, cx);
2180        }
2181        self.select_larger_syntax_node_stack = stack;
2182    }
2183
2184    pub fn select_smaller_syntax_node(
2185        &mut self,
2186        _: &SelectSmallerSyntaxNode,
2187        cx: &mut ViewContext<Self>,
2188    ) {
2189        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
2190        if let Some(selections) = stack.pop() {
2191            self.update_selections(selections.to_vec(), true, cx);
2192        }
2193        self.select_larger_syntax_node_stack = stack;
2194    }
2195
2196    pub fn move_to_enclosing_bracket(
2197        &mut self,
2198        _: &MoveToEnclosingBracket,
2199        cx: &mut ViewContext<Self>,
2200    ) {
2201        let mut selections = self.selections(cx).to_vec();
2202        let buffer = self.buffer.read(cx.as_ref());
2203        for selection in &mut selections {
2204            let selection_range = selection.offset_range(buffer);
2205            if let Some((open_range, close_range)) =
2206                buffer.enclosing_bracket_ranges(selection_range.clone())
2207            {
2208                let close_range = close_range.to_inclusive();
2209                let destination = if close_range.contains(&selection_range.start)
2210                    && close_range.contains(&selection_range.end)
2211                {
2212                    open_range.end
2213                } else {
2214                    *close_range.start()
2215                };
2216                selection.start = buffer.anchor_before(destination);
2217                selection.end = selection.start.clone();
2218            }
2219        }
2220
2221        self.update_selections(selections, true, cx);
2222    }
2223
2224    fn build_columnar_selection(
2225        &mut self,
2226        display_map: &DisplayMapSnapshot,
2227        row: u32,
2228        columns: &Range<u32>,
2229        reversed: bool,
2230    ) -> Option<Selection> {
2231        let is_empty = columns.start == columns.end;
2232        let line_len = display_map.line_len(row);
2233        if columns.start < line_len || (is_empty && columns.start == line_len) {
2234            let start = DisplayPoint::new(row, columns.start);
2235            let end = DisplayPoint::new(row, cmp::min(columns.end, line_len));
2236            Some(Selection {
2237                id: post_inc(&mut self.next_selection_id),
2238                start: display_map.anchor_before(start, Bias::Left),
2239                end: display_map.anchor_before(end, Bias::Left),
2240                reversed,
2241                goal: SelectionGoal::ColumnRange {
2242                    start: columns.start,
2243                    end: columns.end,
2244                },
2245            })
2246        } else {
2247            None
2248        }
2249    }
2250
2251    pub fn active_selection_sets<'a>(
2252        &'a self,
2253        cx: &'a AppContext,
2254    ) -> impl 'a + Iterator<Item = SelectionSetId> {
2255        let buffer = self.buffer.read(cx);
2256        let replica_id = buffer.replica_id();
2257        buffer
2258            .selection_sets()
2259            .filter(move |(set_id, set)| {
2260                set.active && (set_id.replica_id != replica_id || **set_id == self.selection_set_id)
2261            })
2262            .map(|(set_id, _)| *set_id)
2263    }
2264
2265    pub fn selections_in_range<'a>(
2266        &'a self,
2267        set_id: SelectionSetId,
2268        range: Range<DisplayPoint>,
2269        cx: &'a mut MutableAppContext,
2270    ) -> impl 'a + Iterator<Item = Range<DisplayPoint>> {
2271        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2272        let buffer = self.buffer.read(cx);
2273        let selections = &buffer.selection_set(set_id).unwrap().selections;
2274        let start = display_map.anchor_before(range.start, Bias::Left);
2275        let start_index = self.selection_insertion_index(selections, &start, cx);
2276        let pending_selection = if set_id.replica_id == self.buffer.read(cx).replica_id() {
2277            self.pending_selection.as_ref().and_then(|s| {
2278                let selection_range = s.display_range(&display_map);
2279                if selection_range.start <= range.end || selection_range.end <= range.end {
2280                    Some(selection_range)
2281                } else {
2282                    None
2283                }
2284            })
2285        } else {
2286            None
2287        };
2288        selections[start_index..]
2289            .iter()
2290            .map(move |s| s.display_range(&display_map))
2291            .take_while(move |r| r.start <= range.end || r.end <= range.end)
2292            .chain(pending_selection)
2293    }
2294
2295    fn selection_insertion_index(
2296        &self,
2297        selections: &[Selection],
2298        start: &Anchor,
2299        cx: &AppContext,
2300    ) -> usize {
2301        let buffer = self.buffer.read(cx);
2302        match selections.binary_search_by(|probe| probe.start.cmp(&start, buffer).unwrap()) {
2303            Ok(index) => index,
2304            Err(index) => {
2305                if index > 0
2306                    && selections[index - 1].end.cmp(&start, buffer).unwrap() == Ordering::Greater
2307                {
2308                    index - 1
2309                } else {
2310                    index
2311                }
2312            }
2313        }
2314    }
2315
2316    fn selections(&mut self, cx: &mut ViewContext<Self>) -> Arc<[Selection]> {
2317        self.end_selection(cx);
2318        let buffer = self.buffer.read(cx);
2319        buffer
2320            .selection_set(self.selection_set_id)
2321            .unwrap()
2322            .selections
2323            .clone()
2324    }
2325
2326    fn update_selections(
2327        &mut self,
2328        mut selections: Vec<Selection>,
2329        autoscroll: bool,
2330        cx: &mut ViewContext<Self>,
2331    ) {
2332        // Merge overlapping selections.
2333        let buffer = self.buffer.read(cx);
2334        let mut i = 1;
2335        while i < selections.len() {
2336            if selections[i - 1]
2337                .end
2338                .cmp(&selections[i].start, buffer)
2339                .unwrap()
2340                >= Ordering::Equal
2341            {
2342                let removed = selections.remove(i);
2343                if removed.start.cmp(&selections[i - 1].start, buffer).unwrap() < Ordering::Equal {
2344                    selections[i - 1].start = removed.start;
2345                }
2346                if removed.end.cmp(&selections[i - 1].end, buffer).unwrap() > Ordering::Equal {
2347                    selections[i - 1].end = removed.end;
2348                }
2349            } else {
2350                i += 1;
2351            }
2352        }
2353
2354        self.add_selections_state = None;
2355        self.select_larger_syntax_node_stack.clear();
2356        while let Some(autoclose_pair_state) = self.autoclose_stack.last() {
2357            let all_selections_inside_autoclose_ranges =
2358                if selections.len() == autoclose_pair_state.ranges.len() {
2359                    selections.iter().zip(&autoclose_pair_state.ranges).all(
2360                        |(selection, autoclose_range)| {
2361                            let head = selection.head();
2362                            autoclose_range.start.cmp(head, buffer).unwrap() <= Ordering::Equal
2363                                && autoclose_range.end.cmp(head, buffer).unwrap() >= Ordering::Equal
2364                        },
2365                    )
2366                } else {
2367                    false
2368                };
2369
2370            if all_selections_inside_autoclose_ranges {
2371                break;
2372            } else {
2373                self.autoclose_stack.pop();
2374            }
2375        }
2376
2377        if autoscroll {
2378            self.autoscroll_requested = true;
2379            cx.notify();
2380        }
2381
2382        self.pause_cursor_blinking(cx);
2383
2384        self.buffer.update(cx, |buffer, cx| {
2385            buffer
2386                .update_selection_set(self.selection_set_id, selections, cx)
2387                .unwrap();
2388        });
2389    }
2390
2391    fn start_transaction(&self, cx: &mut ViewContext<Self>) {
2392        self.buffer.update(cx, |buffer, _| {
2393            buffer
2394                .start_transaction(Some(self.selection_set_id))
2395                .unwrap()
2396        });
2397    }
2398
2399    fn end_transaction(&self, cx: &mut ViewContext<Self>) {
2400        self.buffer.update(cx, |buffer, cx| {
2401            buffer
2402                .end_transaction(Some(self.selection_set_id), cx)
2403                .unwrap()
2404        });
2405    }
2406
2407    pub fn page_up(&mut self, _: &PageUp, _: &mut ViewContext<Self>) {
2408        log::info!("Editor::page_up");
2409    }
2410
2411    pub fn page_down(&mut self, _: &PageDown, _: &mut ViewContext<Self>) {
2412        log::info!("Editor::page_down");
2413    }
2414
2415    pub fn fold(&mut self, _: &Fold, cx: &mut ViewContext<Self>) {
2416        let mut fold_ranges = Vec::new();
2417
2418        let selections = self.selections(cx);
2419        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2420        for selection in selections.iter() {
2421            let range = selection.display_range(&display_map).sorted();
2422            let buffer_start_row = range.start.to_buffer_point(&display_map, Bias::Left).row;
2423
2424            for row in (0..=range.end.row()).rev() {
2425                if self.is_line_foldable(&display_map, row) && !display_map.is_line_folded(row) {
2426                    let fold_range = self.foldable_range_for_line(&display_map, row);
2427                    if fold_range.end.row >= buffer_start_row {
2428                        fold_ranges.push(fold_range);
2429                        if row <= range.start.row() {
2430                            break;
2431                        }
2432                    }
2433                }
2434            }
2435        }
2436
2437        self.fold_ranges(fold_ranges, cx);
2438    }
2439
2440    pub fn unfold(&mut self, _: &Unfold, cx: &mut ViewContext<Self>) {
2441        let selections = self.selections(cx);
2442        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2443        let buffer = self.buffer.read(cx);
2444        let ranges = selections
2445            .iter()
2446            .map(|s| {
2447                let range = s.display_range(&display_map).sorted();
2448                let mut start = range.start.to_buffer_point(&display_map, Bias::Left);
2449                let mut end = range.end.to_buffer_point(&display_map, Bias::Left);
2450                start.column = 0;
2451                end.column = buffer.line_len(end.row);
2452                start..end
2453            })
2454            .collect::<Vec<_>>();
2455        self.unfold_ranges(ranges, cx);
2456    }
2457
2458    fn is_line_foldable(&self, display_map: &DisplayMapSnapshot, display_row: u32) -> bool {
2459        let max_point = display_map.max_point();
2460        if display_row >= max_point.row() {
2461            false
2462        } else {
2463            let (start_indent, is_blank) = display_map.line_indent(display_row);
2464            if is_blank {
2465                false
2466            } else {
2467                for display_row in display_row + 1..=max_point.row() {
2468                    let (indent, is_blank) = display_map.line_indent(display_row);
2469                    if !is_blank {
2470                        return indent > start_indent;
2471                    }
2472                }
2473                false
2474            }
2475        }
2476    }
2477
2478    fn foldable_range_for_line(
2479        &self,
2480        display_map: &DisplayMapSnapshot,
2481        start_row: u32,
2482    ) -> Range<Point> {
2483        let max_point = display_map.max_point();
2484
2485        let (start_indent, _) = display_map.line_indent(start_row);
2486        let start = DisplayPoint::new(start_row, display_map.line_len(start_row));
2487        let mut end = None;
2488        for row in start_row + 1..=max_point.row() {
2489            let (indent, is_blank) = display_map.line_indent(row);
2490            if !is_blank && indent <= start_indent {
2491                end = Some(DisplayPoint::new(row - 1, display_map.line_len(row - 1)));
2492                break;
2493            }
2494        }
2495
2496        let end = end.unwrap_or(max_point);
2497        return start.to_buffer_point(display_map, Bias::Left)
2498            ..end.to_buffer_point(display_map, Bias::Left);
2499    }
2500
2501    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
2502        let selections = self.selections(cx);
2503        let buffer = self.buffer.read(cx);
2504        let ranges = selections
2505            .iter()
2506            .map(|s| s.point_range(buffer).sorted())
2507            .collect();
2508        self.fold_ranges(ranges, cx);
2509    }
2510
2511    fn fold_ranges<T: ToOffset>(&mut self, ranges: Vec<Range<T>>, cx: &mut ViewContext<Self>) {
2512        if !ranges.is_empty() {
2513            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
2514            self.autoscroll_requested = true;
2515            cx.notify();
2516        }
2517    }
2518
2519    fn unfold_ranges<T: ToOffset>(&mut self, ranges: Vec<Range<T>>, cx: &mut ViewContext<Self>) {
2520        if !ranges.is_empty() {
2521            self.display_map
2522                .update(cx, |map, cx| map.unfold(ranges, cx));
2523            self.autoscroll_requested = true;
2524            cx.notify();
2525        }
2526    }
2527
2528    pub fn longest_row(&self, cx: &mut MutableAppContext) -> u32 {
2529        self.display_map
2530            .update(cx, |map, cx| map.snapshot(cx))
2531            .longest_row()
2532    }
2533
2534    pub fn max_point(&self, cx: &mut MutableAppContext) -> DisplayPoint {
2535        self.display_map
2536            .update(cx, |map, cx| map.snapshot(cx))
2537            .max_point()
2538    }
2539
2540    pub fn text(&self, cx: &AppContext) -> String {
2541        self.buffer.read(cx).text()
2542    }
2543
2544    pub fn display_text(&self, cx: &mut MutableAppContext) -> String {
2545        self.display_map
2546            .update(cx, |map, cx| map.snapshot(cx))
2547            .text()
2548    }
2549
2550    // pub fn font_size(&self) -> f32 {
2551    //     self.settings.font_size
2552    // }
2553
2554    pub fn set_wrap_width(&self, width: f32, cx: &mut MutableAppContext) -> bool {
2555        self.display_map
2556            .update(cx, |map, cx| map.set_wrap_width(Some(width), cx))
2557    }
2558
2559    fn next_blink_epoch(&mut self) -> usize {
2560        self.blink_epoch += 1;
2561        self.blink_epoch
2562    }
2563
2564    fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
2565        self.show_local_cursors = true;
2566        cx.notify();
2567
2568        let epoch = self.next_blink_epoch();
2569        cx.spawn(|this, mut cx| {
2570            let this = this.downgrade();
2571            async move {
2572                Timer::after(CURSOR_BLINK_INTERVAL).await;
2573                if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
2574                    this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
2575                }
2576            }
2577        })
2578        .detach();
2579    }
2580
2581    fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
2582        if epoch == self.blink_epoch {
2583            self.blinking_paused = false;
2584            self.blink_cursors(epoch, cx);
2585        }
2586    }
2587
2588    fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
2589        if epoch == self.blink_epoch && self.focused && !self.blinking_paused {
2590            self.show_local_cursors = !self.show_local_cursors;
2591            cx.notify();
2592
2593            let epoch = self.next_blink_epoch();
2594            cx.spawn(|this, mut cx| {
2595                let this = this.downgrade();
2596                async move {
2597                    Timer::after(CURSOR_BLINK_INTERVAL).await;
2598                    if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
2599                        this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx));
2600                    }
2601                }
2602            })
2603            .detach();
2604        }
2605    }
2606
2607    pub fn show_local_cursors(&self) -> bool {
2608        self.show_local_cursors
2609    }
2610
2611    fn on_buffer_changed(&mut self, _: ModelHandle<Buffer>, cx: &mut ViewContext<Self>) {
2612        cx.notify();
2613    }
2614
2615    fn on_buffer_event(
2616        &mut self,
2617        _: ModelHandle<Buffer>,
2618        event: &buffer::Event,
2619        cx: &mut ViewContext<Self>,
2620    ) {
2621        match event {
2622            buffer::Event::Edited => cx.emit(Event::Edited),
2623            buffer::Event::Dirtied => cx.emit(Event::Dirtied),
2624            buffer::Event::Saved => cx.emit(Event::Saved),
2625            buffer::Event::FileHandleChanged => cx.emit(Event::FileHandleChanged),
2626            buffer::Event::Reloaded => cx.emit(Event::FileHandleChanged),
2627            buffer::Event::Closed => cx.emit(Event::Closed),
2628            buffer::Event::Reparsed => {}
2629        }
2630    }
2631
2632    fn on_display_map_changed(&mut self, _: ModelHandle<DisplayMap>, cx: &mut ViewContext<Self>) {
2633        cx.notify();
2634    }
2635}
2636
2637impl Snapshot {
2638    pub fn is_empty(&self) -> bool {
2639        self.display_snapshot.is_empty()
2640    }
2641
2642    pub fn is_focused(&self) -> bool {
2643        self.is_focused
2644    }
2645
2646    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
2647        self.placeholder_text.as_ref()
2648    }
2649
2650    pub fn buffer_row_count(&self) -> u32 {
2651        self.display_snapshot.buffer_row_count()
2652    }
2653
2654    pub fn buffer_rows(&self, start_row: u32) -> BufferRows {
2655        self.display_snapshot.buffer_rows(start_row)
2656    }
2657
2658    pub fn highlighted_chunks_for_rows(
2659        &mut self,
2660        display_rows: Range<u32>,
2661    ) -> display_map::HighlightedChunks {
2662        self.display_snapshot
2663            .highlighted_chunks_for_rows(display_rows)
2664    }
2665
2666    pub fn scroll_position(&self) -> Vector2F {
2667        compute_scroll_position(
2668            &self.display_snapshot,
2669            self.scroll_position,
2670            &self.scroll_top_anchor,
2671        )
2672    }
2673
2674    pub fn max_point(&self) -> DisplayPoint {
2675        self.display_snapshot.max_point()
2676    }
2677
2678    pub fn longest_row(&self) -> u32 {
2679        self.display_snapshot.longest_row()
2680    }
2681
2682    pub fn line_len(&self, display_row: u32) -> u32 {
2683        self.display_snapshot.line_len(display_row)
2684    }
2685
2686    pub fn line(&self, display_row: u32) -> String {
2687        self.display_snapshot.line(display_row)
2688    }
2689
2690    pub fn prev_row_boundary(&self, point: DisplayPoint) -> (DisplayPoint, Point) {
2691        self.display_snapshot.prev_row_boundary(point)
2692    }
2693
2694    pub fn next_row_boundary(&self, point: DisplayPoint) -> (DisplayPoint, Point) {
2695        self.display_snapshot.next_row_boundary(point)
2696    }
2697}
2698
2699impl EditorSettings {
2700    #[cfg(any(test, feature = "test-support"))]
2701    pub fn test(cx: &AppContext) -> Self {
2702        Self {
2703            tab_size: 4,
2704            style: {
2705                let font_cache: &gpui::FontCache = cx.font_cache();
2706                let font_family_name = Arc::from("Monaco");
2707                let font_properties = Default::default();
2708                let font_family_id = font_cache.load_family(&[&font_family_name]).unwrap();
2709                let font_id = font_cache
2710                    .select_font(font_family_id, &font_properties)
2711                    .unwrap();
2712                EditorStyle {
2713                    text: TextStyle {
2714                        font_family_name,
2715                        font_family_id,
2716                        font_id,
2717                        font_size: 14.,
2718                        color: Color::from_u32(0xff0000ff),
2719                        font_properties,
2720                        underline: false,
2721                    },
2722                    placeholder_text: None,
2723                    background: Default::default(),
2724                    gutter_background: Default::default(),
2725                    active_line_background: Default::default(),
2726                    line_number: Default::default(),
2727                    line_number_active: Default::default(),
2728                    selection: Default::default(),
2729                    guest_selections: Default::default(),
2730                    syntax: Default::default(),
2731                }
2732            },
2733        }
2734    }
2735}
2736
2737fn compute_scroll_position(
2738    snapshot: &DisplayMapSnapshot,
2739    mut scroll_position: Vector2F,
2740    scroll_top_anchor: &Anchor,
2741) -> Vector2F {
2742    let scroll_top = scroll_top_anchor
2743        .to_display_point(snapshot, Bias::Left)
2744        .row() as f32;
2745    scroll_position.set_y(scroll_top + scroll_position.y());
2746    scroll_position
2747}
2748
2749pub enum Event {
2750    Activate,
2751    Edited,
2752    Blurred,
2753    Dirtied,
2754    Saved,
2755    FileHandleChanged,
2756    Closed,
2757}
2758
2759impl Entity for Editor {
2760    type Event = Event;
2761
2762    fn release(&mut self, cx: &mut MutableAppContext) {
2763        self.buffer.update(cx, |buffer, cx| {
2764            buffer
2765                .remove_selection_set(self.selection_set_id, cx)
2766                .unwrap();
2767        });
2768    }
2769}
2770
2771impl View for Editor {
2772    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
2773        let settings = self.build_settings.borrow_mut()(cx);
2774        self.display_map.update(cx, |map, cx| {
2775            map.set_font(
2776                settings.style.text.font_id,
2777                settings.style.text.font_size,
2778                cx,
2779            )
2780        });
2781        EditorElement::new(self.handle.clone(), settings).boxed()
2782    }
2783
2784    fn ui_name() -> &'static str {
2785        "Editor"
2786    }
2787
2788    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
2789        self.focused = true;
2790        self.blink_cursors(self.blink_epoch, cx);
2791        self.buffer.update(cx, |buffer, cx| {
2792            buffer
2793                .set_active_selection_set(Some(self.selection_set_id), cx)
2794                .unwrap();
2795        });
2796    }
2797
2798    fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
2799        self.focused = false;
2800        self.show_local_cursors = false;
2801        self.buffer.update(cx, |buffer, cx| {
2802            buffer.set_active_selection_set(None, cx).unwrap();
2803        });
2804        cx.emit(Event::Blurred);
2805        cx.notify();
2806    }
2807
2808    fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
2809        let mut cx = Self::default_keymap_context();
2810        let mode = match self.mode {
2811            EditorMode::SingleLine => "single_line",
2812            EditorMode::AutoHeight { .. } => "auto_height",
2813            EditorMode::Full => "full",
2814        };
2815        cx.map.insert("mode".into(), mode.into());
2816        cx
2817    }
2818}
2819
2820impl SelectionExt for Selection {
2821    fn display_range(&self, map: &DisplayMapSnapshot) -> Range<DisplayPoint> {
2822        let start = self.start.to_display_point(map, Bias::Left);
2823        let end = self.end.to_display_point(map, Bias::Left);
2824        if self.reversed {
2825            end..start
2826        } else {
2827            start..end
2828        }
2829    }
2830
2831    fn spanned_rows(
2832        &self,
2833        include_end_if_at_line_start: bool,
2834        map: &DisplayMapSnapshot,
2835    ) -> SpannedRows {
2836        let display_start = self.start.to_display_point(map, Bias::Left);
2837        let mut display_end = self.end.to_display_point(map, Bias::Right);
2838        if !include_end_if_at_line_start
2839            && display_end.row() != map.max_point().row()
2840            && display_start.row() != display_end.row()
2841            && display_end.column() == 0
2842        {
2843            *display_end.row_mut() -= 1;
2844        }
2845
2846        let (display_start, buffer_start) = map.prev_row_boundary(display_start);
2847        let (display_end, buffer_end) = map.next_row_boundary(display_end);
2848
2849        SpannedRows {
2850            buffer_rows: buffer_start.row..buffer_end.row + 1,
2851            display_rows: display_start.row()..display_end.row() + 1,
2852        }
2853    }
2854}
2855
2856#[cfg(test)]
2857mod tests {
2858    use super::*;
2859    use crate::test::sample_text;
2860    use buffer::{History, Point};
2861    use unindent::Unindent;
2862
2863    #[gpui::test]
2864    fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
2865        let buffer = cx.add_model(|cx| Buffer::new(0, "aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx));
2866        let settings = EditorSettings::test(cx);
2867        let (_, editor) =
2868            cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
2869
2870        editor.update(cx, |view, cx| {
2871            view.begin_selection(DisplayPoint::new(2, 2), false, cx);
2872        });
2873
2874        assert_eq!(
2875            editor.update(cx, |view, cx| view.selection_ranges(cx)),
2876            [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
2877        );
2878
2879        editor.update(cx, |view, cx| {
2880            view.update_selection(DisplayPoint::new(3, 3), Vector2F::zero(), cx);
2881        });
2882
2883        assert_eq!(
2884            editor.update(cx, |view, cx| view.selection_ranges(cx)),
2885            [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
2886        );
2887
2888        editor.update(cx, |view, cx| {
2889            view.update_selection(DisplayPoint::new(1, 1), Vector2F::zero(), cx);
2890        });
2891
2892        assert_eq!(
2893            editor.update(cx, |view, cx| view.selection_ranges(cx)),
2894            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
2895        );
2896
2897        editor.update(cx, |view, cx| {
2898            view.end_selection(cx);
2899            view.update_selection(DisplayPoint::new(3, 3), Vector2F::zero(), cx);
2900        });
2901
2902        assert_eq!(
2903            editor.update(cx, |view, cx| view.selection_ranges(cx)),
2904            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
2905        );
2906
2907        editor.update(cx, |view, cx| {
2908            view.begin_selection(DisplayPoint::new(3, 3), true, cx);
2909            view.update_selection(DisplayPoint::new(0, 0), Vector2F::zero(), cx);
2910        });
2911
2912        assert_eq!(
2913            editor.update(cx, |view, cx| view.selection_ranges(cx)),
2914            [
2915                DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
2916                DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
2917            ]
2918        );
2919
2920        editor.update(cx, |view, cx| {
2921            view.end_selection(cx);
2922        });
2923
2924        assert_eq!(
2925            editor.update(cx, |view, cx| view.selection_ranges(cx)),
2926            [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
2927        );
2928    }
2929
2930    #[gpui::test]
2931    fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
2932        let buffer = cx.add_model(|cx| Buffer::new(0, "aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx));
2933        let settings = EditorSettings::test(cx);
2934        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
2935
2936        view.update(cx, |view, cx| {
2937            view.begin_selection(DisplayPoint::new(2, 2), false, cx);
2938            assert_eq!(
2939                view.selection_ranges(cx),
2940                [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
2941            );
2942        });
2943
2944        view.update(cx, |view, cx| {
2945            view.update_selection(DisplayPoint::new(3, 3), Vector2F::zero(), cx);
2946            assert_eq!(
2947                view.selection_ranges(cx),
2948                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
2949            );
2950        });
2951
2952        view.update(cx, |view, cx| {
2953            view.cancel(&Cancel, cx);
2954            view.update_selection(DisplayPoint::new(1, 1), Vector2F::zero(), cx);
2955            assert_eq!(
2956                view.selection_ranges(cx),
2957                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
2958            );
2959        });
2960    }
2961
2962    #[gpui::test]
2963    fn test_cancel(cx: &mut gpui::MutableAppContext) {
2964        let buffer = cx.add_model(|cx| Buffer::new(0, "aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx));
2965        let settings = EditorSettings::test(cx);
2966        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
2967
2968        view.update(cx, |view, cx| {
2969            view.begin_selection(DisplayPoint::new(3, 4), false, cx);
2970            view.update_selection(DisplayPoint::new(1, 1), Vector2F::zero(), cx);
2971            view.end_selection(cx);
2972
2973            view.begin_selection(DisplayPoint::new(0, 1), true, cx);
2974            view.update_selection(DisplayPoint::new(0, 3), Vector2F::zero(), cx);
2975            view.end_selection(cx);
2976            assert_eq!(
2977                view.selection_ranges(cx),
2978                [
2979                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
2980                    DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
2981                ]
2982            );
2983        });
2984
2985        view.update(cx, |view, cx| {
2986            view.cancel(&Cancel, cx);
2987            assert_eq!(
2988                view.selection_ranges(cx),
2989                [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
2990            );
2991        });
2992
2993        view.update(cx, |view, cx| {
2994            view.cancel(&Cancel, cx);
2995            assert_eq!(
2996                view.selection_ranges(cx),
2997                [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
2998            );
2999        });
3000    }
3001
3002    #[gpui::test]
3003    fn test_fold(cx: &mut gpui::MutableAppContext) {
3004        let buffer = cx.add_model(|cx| {
3005            Buffer::new(
3006                0,
3007                "
3008                    impl Foo {
3009                        // Hello!
3010
3011                        fn a() {
3012                            1
3013                        }
3014
3015                        fn b() {
3016                            2
3017                        }
3018
3019                        fn c() {
3020                            3
3021                        }
3022                    }
3023                "
3024                .unindent(),
3025                cx,
3026            )
3027        });
3028        let settings = EditorSettings::test(&cx);
3029        let (_, view) = cx.add_window(Default::default(), |cx| {
3030            build_editor(buffer.clone(), settings, cx)
3031        });
3032
3033        view.update(cx, |view, cx| {
3034            view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx)
3035                .unwrap();
3036            view.fold(&Fold, cx);
3037            assert_eq!(
3038                view.display_text(cx),
3039                "
3040                    impl Foo {
3041                        // Hello!
3042
3043                        fn a() {
3044                            1
3045                        }
3046
3047                        fn b() {…
3048                        }
3049
3050                        fn c() {…
3051                        }
3052                    }
3053                "
3054                .unindent(),
3055            );
3056
3057            view.fold(&Fold, cx);
3058            assert_eq!(
3059                view.display_text(cx),
3060                "
3061                    impl Foo {…
3062                    }
3063                "
3064                .unindent(),
3065            );
3066
3067            view.unfold(&Unfold, cx);
3068            assert_eq!(
3069                view.display_text(cx),
3070                "
3071                    impl Foo {
3072                        // Hello!
3073
3074                        fn a() {
3075                            1
3076                        }
3077
3078                        fn b() {…
3079                        }
3080
3081                        fn c() {…
3082                        }
3083                    }
3084                "
3085                .unindent(),
3086            );
3087
3088            view.unfold(&Unfold, cx);
3089            assert_eq!(view.display_text(cx), buffer.read(cx).text());
3090        });
3091    }
3092
3093    #[gpui::test]
3094    fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
3095        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6), cx));
3096        let settings = EditorSettings::test(&cx);
3097        let (_, view) = cx.add_window(Default::default(), |cx| {
3098            build_editor(buffer.clone(), settings, cx)
3099        });
3100
3101        buffer.update(cx, |buffer, cx| {
3102            buffer.edit(
3103                vec![
3104                    Point::new(1, 0)..Point::new(1, 0),
3105                    Point::new(1, 1)..Point::new(1, 1),
3106                ],
3107                "\t",
3108                cx,
3109            );
3110        });
3111
3112        view.update(cx, |view, cx| {
3113            assert_eq!(
3114                view.selection_ranges(cx),
3115                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
3116            );
3117
3118            view.move_down(&MoveDown, cx);
3119            assert_eq!(
3120                view.selection_ranges(cx),
3121                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
3122            );
3123
3124            view.move_right(&MoveRight, cx);
3125            assert_eq!(
3126                view.selection_ranges(cx),
3127                &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
3128            );
3129
3130            view.move_left(&MoveLeft, cx);
3131            assert_eq!(
3132                view.selection_ranges(cx),
3133                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
3134            );
3135
3136            view.move_up(&MoveUp, cx);
3137            assert_eq!(
3138                view.selection_ranges(cx),
3139                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
3140            );
3141
3142            view.move_to_end(&MoveToEnd, cx);
3143            assert_eq!(
3144                view.selection_ranges(cx),
3145                &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
3146            );
3147
3148            view.move_to_beginning(&MoveToBeginning, cx);
3149            assert_eq!(
3150                view.selection_ranges(cx),
3151                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
3152            );
3153
3154            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx)
3155                .unwrap();
3156            view.select_to_beginning(&SelectToBeginning, cx);
3157            assert_eq!(
3158                view.selection_ranges(cx),
3159                &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
3160            );
3161
3162            view.select_to_end(&SelectToEnd, cx);
3163            assert_eq!(
3164                view.selection_ranges(cx),
3165                &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
3166            );
3167        });
3168    }
3169
3170    #[gpui::test]
3171    fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
3172        let buffer = cx.add_model(|cx| Buffer::new(0, "ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx));
3173        let settings = EditorSettings::test(&cx);
3174        let (_, view) = cx.add_window(Default::default(), |cx| {
3175            build_editor(buffer.clone(), settings, cx)
3176        });
3177
3178        assert_eq!('ⓐ'.len_utf8(), 3);
3179        assert_eq!('α'.len_utf8(), 2);
3180
3181        view.update(cx, |view, cx| {
3182            view.fold_ranges(
3183                vec![
3184                    Point::new(0, 6)..Point::new(0, 12),
3185                    Point::new(1, 2)..Point::new(1, 4),
3186                    Point::new(2, 4)..Point::new(2, 8),
3187                ],
3188                cx,
3189            );
3190            assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
3191
3192            view.move_right(&MoveRight, cx);
3193            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "".len())]);
3194            view.move_right(&MoveRight, cx);
3195            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ".len())]);
3196            view.move_right(&MoveRight, cx);
3197            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…".len())]);
3198
3199            view.move_down(&MoveDown, cx);
3200            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab…".len())]);
3201            view.move_left(&MoveLeft, cx);
3202            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab".len())]);
3203            view.move_left(&MoveLeft, cx);
3204            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "a".len())]);
3205
3206            view.move_down(&MoveDown, cx);
3207            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "α".len())]);
3208            view.move_right(&MoveRight, cx);
3209            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ".len())]);
3210            view.move_right(&MoveRight, cx);
3211            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ…".len())]);
3212            view.move_right(&MoveRight, cx);
3213            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ…ε".len())]);
3214
3215            view.move_up(&MoveUp, cx);
3216            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab…e".len())]);
3217            view.move_up(&MoveUp, cx);
3218            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…ⓔ".len())]);
3219            view.move_left(&MoveLeft, cx);
3220            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…".len())]);
3221            view.move_left(&MoveLeft, cx);
3222            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ".len())]);
3223            view.move_left(&MoveLeft, cx);
3224            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "".len())]);
3225        });
3226    }
3227
3228    #[gpui::test]
3229    fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
3230        let buffer = cx.add_model(|cx| Buffer::new(0, "ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx));
3231        let settings = EditorSettings::test(&cx);
3232        let (_, view) = cx.add_window(Default::default(), |cx| {
3233            build_editor(buffer.clone(), settings, cx)
3234        });
3235        view.update(cx, |view, cx| {
3236            view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx)
3237                .unwrap();
3238
3239            view.move_down(&MoveDown, cx);
3240            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "abcd".len())]);
3241
3242            view.move_down(&MoveDown, cx);
3243            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβγ".len())]);
3244
3245            view.move_down(&MoveDown, cx);
3246            assert_eq!(view.selection_ranges(cx), &[empty_range(3, "abcd".len())]);
3247
3248            view.move_down(&MoveDown, cx);
3249            assert_eq!(view.selection_ranges(cx), &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]);
3250
3251            view.move_up(&MoveUp, cx);
3252            assert_eq!(view.selection_ranges(cx), &[empty_range(3, "abcd".len())]);
3253
3254            view.move_up(&MoveUp, cx);
3255            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβγ".len())]);
3256        });
3257    }
3258
3259    #[gpui::test]
3260    fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
3261        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\n  def", cx));
3262        let settings = EditorSettings::test(&cx);
3263        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3264        view.update(cx, |view, cx| {
3265            view.select_display_ranges(
3266                &[
3267                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
3268                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
3269                ],
3270                cx,
3271            )
3272            .unwrap();
3273        });
3274
3275        view.update(cx, |view, cx| {
3276            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
3277            assert_eq!(
3278                view.selection_ranges(cx),
3279                &[
3280                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3281                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
3282                ]
3283            );
3284        });
3285
3286        view.update(cx, |view, cx| {
3287            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
3288            assert_eq!(
3289                view.selection_ranges(cx),
3290                &[
3291                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3292                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3293                ]
3294            );
3295        });
3296
3297        view.update(cx, |view, cx| {
3298            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
3299            assert_eq!(
3300                view.selection_ranges(cx),
3301                &[
3302                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3303                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
3304                ]
3305            );
3306        });
3307
3308        view.update(cx, |view, cx| {
3309            view.move_to_end_of_line(&MoveToEndOfLine, cx);
3310            assert_eq!(
3311                view.selection_ranges(cx),
3312                &[
3313                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
3314                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
3315                ]
3316            );
3317        });
3318
3319        // Moving to the end of line again is a no-op.
3320        view.update(cx, |view, cx| {
3321            view.move_to_end_of_line(&MoveToEndOfLine, cx);
3322            assert_eq!(
3323                view.selection_ranges(cx),
3324                &[
3325                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
3326                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
3327                ]
3328            );
3329        });
3330
3331        view.update(cx, |view, cx| {
3332            view.move_left(&MoveLeft, cx);
3333            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
3334            assert_eq!(
3335                view.selection_ranges(cx),
3336                &[
3337                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
3338                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
3339                ]
3340            );
3341        });
3342
3343        view.update(cx, |view, cx| {
3344            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
3345            assert_eq!(
3346                view.selection_ranges(cx),
3347                &[
3348                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
3349                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
3350                ]
3351            );
3352        });
3353
3354        view.update(cx, |view, cx| {
3355            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
3356            assert_eq!(
3357                view.selection_ranges(cx),
3358                &[
3359                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
3360                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
3361                ]
3362            );
3363        });
3364
3365        view.update(cx, |view, cx| {
3366            view.select_to_end_of_line(&SelectToEndOfLine, cx);
3367            assert_eq!(
3368                view.selection_ranges(cx),
3369                &[
3370                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
3371                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
3372                ]
3373            );
3374        });
3375
3376        view.update(cx, |view, cx| {
3377            view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
3378            assert_eq!(view.display_text(cx), "ab\n  de");
3379            assert_eq!(
3380                view.selection_ranges(cx),
3381                &[
3382                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3383                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
3384                ]
3385            );
3386        });
3387
3388        view.update(cx, |view, cx| {
3389            view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
3390            assert_eq!(view.display_text(cx), "\n");
3391            assert_eq!(
3392                view.selection_ranges(cx),
3393                &[
3394                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3395                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3396                ]
3397            );
3398        });
3399    }
3400
3401    #[gpui::test]
3402    fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
3403        let buffer =
3404            cx.add_model(|cx| Buffer::new(0, "use std::str::{foo, bar}\n\n  {baz.qux()}", cx));
3405        let settings = EditorSettings::test(&cx);
3406        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3407        view.update(cx, |view, cx| {
3408            view.select_display_ranges(
3409                &[
3410                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
3411                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
3412                ],
3413                cx,
3414            )
3415            .unwrap();
3416        });
3417
3418        view.update(cx, |view, cx| {
3419            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3420            assert_eq!(
3421                view.selection_ranges(cx),
3422                &[
3423                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
3424                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
3425                ]
3426            );
3427        });
3428
3429        view.update(cx, |view, cx| {
3430            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3431            assert_eq!(
3432                view.selection_ranges(cx),
3433                &[
3434                    DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
3435                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
3436                ]
3437            );
3438        });
3439
3440        view.update(cx, |view, cx| {
3441            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3442            assert_eq!(
3443                view.selection_ranges(cx),
3444                &[
3445                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
3446                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
3447                ]
3448            );
3449        });
3450
3451        view.update(cx, |view, cx| {
3452            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3453            assert_eq!(
3454                view.selection_ranges(cx),
3455                &[
3456                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3457                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3458                ]
3459            );
3460        });
3461
3462        view.update(cx, |view, cx| {
3463            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3464            assert_eq!(
3465                view.selection_ranges(cx),
3466                &[
3467                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3468                    DisplayPoint::new(0, 23)..DisplayPoint::new(0, 23),
3469                ]
3470            );
3471        });
3472
3473        view.update(cx, |view, cx| {
3474            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3475            assert_eq!(
3476                view.selection_ranges(cx),
3477                &[
3478                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
3479                    DisplayPoint::new(0, 24)..DisplayPoint::new(0, 24),
3480                ]
3481            );
3482        });
3483
3484        view.update(cx, |view, cx| {
3485            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3486            assert_eq!(
3487                view.selection_ranges(cx),
3488                &[
3489                    DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
3490                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3491                ]
3492            );
3493        });
3494
3495        view.update(cx, |view, cx| {
3496            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3497            assert_eq!(
3498                view.selection_ranges(cx),
3499                &[
3500                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
3501                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
3502                ]
3503            );
3504        });
3505
3506        view.update(cx, |view, cx| {
3507            view.move_right(&MoveRight, cx);
3508            view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
3509            assert_eq!(
3510                view.selection_ranges(cx),
3511                &[
3512                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
3513                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
3514                ]
3515            );
3516        });
3517
3518        view.update(cx, |view, cx| {
3519            view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
3520            assert_eq!(
3521                view.selection_ranges(cx),
3522                &[
3523                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 7),
3524                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 2),
3525                ]
3526            );
3527        });
3528
3529        view.update(cx, |view, cx| {
3530            view.select_to_next_word_boundary(&SelectToNextWordBoundary, cx);
3531            assert_eq!(
3532                view.selection_ranges(cx),
3533                &[
3534                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
3535                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
3536                ]
3537            );
3538        });
3539    }
3540
3541    #[gpui::test]
3542    fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
3543        let buffer =
3544            cx.add_model(|cx| Buffer::new(0, "use one::{\n    two::three::four::five\n};", cx));
3545        let settings = EditorSettings::test(&cx);
3546        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3547
3548        view.update(cx, |view, cx| {
3549            view.set_wrap_width(140., cx);
3550            assert_eq!(
3551                view.display_text(cx),
3552                "use one::{\n    two::three::\n    four::five\n};"
3553            );
3554
3555            view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx)
3556                .unwrap();
3557
3558            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3559            assert_eq!(
3560                view.selection_ranges(cx),
3561                &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
3562            );
3563
3564            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3565            assert_eq!(
3566                view.selection_ranges(cx),
3567                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
3568            );
3569
3570            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3571            assert_eq!(
3572                view.selection_ranges(cx),
3573                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
3574            );
3575
3576            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3577            assert_eq!(
3578                view.selection_ranges(cx),
3579                &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
3580            );
3581
3582            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3583            assert_eq!(
3584                view.selection_ranges(cx),
3585                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
3586            );
3587
3588            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3589            assert_eq!(
3590                view.selection_ranges(cx),
3591                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
3592            );
3593        });
3594    }
3595
3596    #[gpui::test]
3597    fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
3598        let buffer = cx.add_model(|cx| Buffer::new(0, "one two three four", cx));
3599        let settings = EditorSettings::test(&cx);
3600        let (_, view) = cx.add_window(Default::default(), |cx| {
3601            build_editor(buffer.clone(), settings, cx)
3602        });
3603
3604        view.update(cx, |view, cx| {
3605            view.select_display_ranges(
3606                &[
3607                    // an empty selection - the preceding word fragment is deleted
3608                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3609                    // characters selected - they are deleted
3610                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
3611                ],
3612                cx,
3613            )
3614            .unwrap();
3615            view.delete_to_previous_word_boundary(&DeleteToPreviousWordBoundary, cx);
3616        });
3617
3618        assert_eq!(buffer.read(cx).text(), "e two te four");
3619
3620        view.update(cx, |view, cx| {
3621            view.select_display_ranges(
3622                &[
3623                    // an empty selection - the following word fragment is deleted
3624                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
3625                    // characters selected - they are deleted
3626                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
3627                ],
3628                cx,
3629            )
3630            .unwrap();
3631            view.delete_to_next_word_boundary(&DeleteToNextWordBoundary, cx);
3632        });
3633
3634        assert_eq!(buffer.read(cx).text(), "e t te our");
3635    }
3636
3637    #[gpui::test]
3638    fn test_newline(cx: &mut gpui::MutableAppContext) {
3639        let buffer = cx.add_model(|cx| Buffer::new(0, "aaaa\n    bbbb\n", cx));
3640        let settings = EditorSettings::test(&cx);
3641        let (_, view) = cx.add_window(Default::default(), |cx| {
3642            build_editor(buffer.clone(), settings, cx)
3643        });
3644
3645        view.update(cx, |view, cx| {
3646            view.select_display_ranges(
3647                &[
3648                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3649                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
3650                    DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
3651                ],
3652                cx,
3653            )
3654            .unwrap();
3655
3656            view.newline(&Newline, cx);
3657            assert_eq!(view.text(cx), "aa\naa\n  \n    bb\n    bb\n");
3658        });
3659    }
3660
3661    #[gpui::test]
3662    fn test_backspace(cx: &mut gpui::MutableAppContext) {
3663        let buffer = cx.add_model(|cx| {
3664            Buffer::new(
3665                0,
3666                "one two three\nfour five six\nseven eight nine\nten\n",
3667                cx,
3668            )
3669        });
3670        let settings = EditorSettings::test(&cx);
3671        let (_, view) = cx.add_window(Default::default(), |cx| {
3672            build_editor(buffer.clone(), settings, cx)
3673        });
3674
3675        view.update(cx, |view, cx| {
3676            view.select_display_ranges(
3677                &[
3678                    // an empty selection - the preceding character is deleted
3679                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3680                    // one character selected - it is deleted
3681                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
3682                    // a line suffix selected - it is deleted
3683                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
3684                ],
3685                cx,
3686            )
3687            .unwrap();
3688            view.backspace(&Backspace, cx);
3689        });
3690
3691        assert_eq!(
3692            buffer.read(cx).text(),
3693            "oe two three\nfou five six\nseven ten\n"
3694        );
3695    }
3696
3697    #[gpui::test]
3698    fn test_delete(cx: &mut gpui::MutableAppContext) {
3699        let buffer = cx.add_model(|cx| {
3700            Buffer::new(
3701                0,
3702                "one two three\nfour five six\nseven eight nine\nten\n",
3703                cx,
3704            )
3705        });
3706        let settings = EditorSettings::test(&cx);
3707        let (_, view) = cx.add_window(Default::default(), |cx| {
3708            build_editor(buffer.clone(), settings, cx)
3709        });
3710
3711        view.update(cx, |view, cx| {
3712            view.select_display_ranges(
3713                &[
3714                    // an empty selection - the following character is deleted
3715                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3716                    // one character selected - it is deleted
3717                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
3718                    // a line suffix selected - it is deleted
3719                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
3720                ],
3721                cx,
3722            )
3723            .unwrap();
3724            view.delete(&Delete, cx);
3725        });
3726
3727        assert_eq!(
3728            buffer.read(cx).text(),
3729            "on two three\nfou five six\nseven ten\n"
3730        );
3731    }
3732
3733    #[gpui::test]
3734    fn test_delete_line(cx: &mut gpui::MutableAppContext) {
3735        let settings = EditorSettings::test(&cx);
3736        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
3737        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3738        view.update(cx, |view, cx| {
3739            view.select_display_ranges(
3740                &[
3741                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
3742                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
3743                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
3744                ],
3745                cx,
3746            )
3747            .unwrap();
3748            view.delete_line(&DeleteLine, cx);
3749            assert_eq!(view.display_text(cx), "ghi");
3750            assert_eq!(
3751                view.selection_ranges(cx),
3752                vec![
3753                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3754                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
3755                ]
3756            );
3757        });
3758
3759        let settings = EditorSettings::test(&cx);
3760        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
3761        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3762        view.update(cx, |view, cx| {
3763            view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx)
3764                .unwrap();
3765            view.delete_line(&DeleteLine, cx);
3766            assert_eq!(view.display_text(cx), "ghi\n");
3767            assert_eq!(
3768                view.selection_ranges(cx),
3769                vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
3770            );
3771        });
3772    }
3773
3774    #[gpui::test]
3775    fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
3776        let settings = EditorSettings::test(&cx);
3777        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
3778        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3779        view.update(cx, |view, cx| {
3780            view.select_display_ranges(
3781                &[
3782                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
3783                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3784                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3785                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
3786                ],
3787                cx,
3788            )
3789            .unwrap();
3790            view.duplicate_line(&DuplicateLine, cx);
3791            assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
3792            assert_eq!(
3793                view.selection_ranges(cx),
3794                vec![
3795                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
3796                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
3797                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
3798                    DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
3799                ]
3800            );
3801        });
3802
3803        let settings = EditorSettings::test(&cx);
3804        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
3805        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3806        view.update(cx, |view, cx| {
3807            view.select_display_ranges(
3808                &[
3809                    DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
3810                    DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
3811                ],
3812                cx,
3813            )
3814            .unwrap();
3815            view.duplicate_line(&DuplicateLine, cx);
3816            assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
3817            assert_eq!(
3818                view.selection_ranges(cx),
3819                vec![
3820                    DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
3821                    DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
3822                ]
3823            );
3824        });
3825    }
3826
3827    #[gpui::test]
3828    fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
3829        let settings = EditorSettings::test(&cx);
3830        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(10, 5), cx));
3831        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3832        view.update(cx, |view, cx| {
3833            view.fold_ranges(
3834                vec![
3835                    Point::new(0, 2)..Point::new(1, 2),
3836                    Point::new(2, 3)..Point::new(4, 1),
3837                    Point::new(7, 0)..Point::new(8, 4),
3838                ],
3839                cx,
3840            );
3841            view.select_display_ranges(
3842                &[
3843                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
3844                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
3845                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
3846                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
3847                ],
3848                cx,
3849            )
3850            .unwrap();
3851            assert_eq!(
3852                view.display_text(cx),
3853                "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
3854            );
3855
3856            view.move_line_up(&MoveLineUp, cx);
3857            assert_eq!(
3858                view.display_text(cx),
3859                "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
3860            );
3861            assert_eq!(
3862                view.selection_ranges(cx),
3863                vec![
3864                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
3865                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
3866                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
3867                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
3868                ]
3869            );
3870        });
3871
3872        view.update(cx, |view, cx| {
3873            view.move_line_down(&MoveLineDown, cx);
3874            assert_eq!(
3875                view.display_text(cx),
3876                "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
3877            );
3878            assert_eq!(
3879                view.selection_ranges(cx),
3880                vec![
3881                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
3882                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
3883                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
3884                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
3885                ]
3886            );
3887        });
3888
3889        view.update(cx, |view, cx| {
3890            view.move_line_down(&MoveLineDown, cx);
3891            assert_eq!(
3892                view.display_text(cx),
3893                "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
3894            );
3895            assert_eq!(
3896                view.selection_ranges(cx),
3897                vec![
3898                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
3899                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
3900                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
3901                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
3902                ]
3903            );
3904        });
3905
3906        view.update(cx, |view, cx| {
3907            view.move_line_up(&MoveLineUp, cx);
3908            assert_eq!(
3909                view.display_text(cx),
3910                "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
3911            );
3912            assert_eq!(
3913                view.selection_ranges(cx),
3914                vec![
3915                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
3916                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
3917                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
3918                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
3919                ]
3920            );
3921        });
3922    }
3923
3924    #[gpui::test]
3925    fn test_clipboard(cx: &mut gpui::MutableAppContext) {
3926        let buffer = cx.add_model(|cx| Buffer::new(0, "one✅ two three four five six ", cx));
3927        let settings = EditorSettings::test(&cx);
3928        let view = cx
3929            .add_window(Default::default(), |cx| {
3930                build_editor(buffer.clone(), settings, cx)
3931            })
3932            .1;
3933
3934        // Cut with three selections. Clipboard text is divided into three slices.
3935        view.update(cx, |view, cx| {
3936            view.select_ranges(vec![0..7, 11..17, 22..27], false, cx);
3937            view.cut(&Cut, cx);
3938            assert_eq!(view.display_text(cx), "two four six ");
3939        });
3940
3941        // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
3942        view.update(cx, |view, cx| {
3943            view.select_ranges(vec![4..4, 9..9, 13..13], false, cx);
3944            view.paste(&Paste, cx);
3945            assert_eq!(view.display_text(cx), "two one✅ four three six five ");
3946            assert_eq!(
3947                view.selection_ranges(cx),
3948                &[
3949                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
3950                    DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
3951                    DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
3952                ]
3953            );
3954        });
3955
3956        // Paste again but with only two cursors. Since the number of cursors doesn't
3957        // match the number of slices in the clipboard, the entire clipboard text
3958        // is pasted at each cursor.
3959        view.update(cx, |view, cx| {
3960            view.select_ranges(vec![0..0, 31..31], false, cx);
3961            view.handle_input(&Input("( ".into()), cx);
3962            view.paste(&Paste, cx);
3963            view.handle_input(&Input(") ".into()), cx);
3964            assert_eq!(
3965                view.display_text(cx),
3966                "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
3967            );
3968        });
3969
3970        view.update(cx, |view, cx| {
3971            view.select_ranges(vec![0..0], false, cx);
3972            view.handle_input(&Input("123\n4567\n89\n".into()), cx);
3973            assert_eq!(
3974                view.display_text(cx),
3975                "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
3976            );
3977        });
3978
3979        // Cut with three selections, one of which is full-line.
3980        view.update(cx, |view, cx| {
3981            view.select_display_ranges(
3982                &[
3983                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
3984                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
3985                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
3986                ],
3987                cx,
3988            )
3989            .unwrap();
3990            view.cut(&Cut, cx);
3991            assert_eq!(
3992                view.display_text(cx),
3993                "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
3994            );
3995        });
3996
3997        // Paste with three selections, noticing how the copied selection that was full-line
3998        // gets inserted before the second cursor.
3999        view.update(cx, |view, cx| {
4000            view.select_display_ranges(
4001                &[
4002                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4003                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4004                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
4005                ],
4006                cx,
4007            )
4008            .unwrap();
4009            view.paste(&Paste, cx);
4010            assert_eq!(
4011                view.display_text(cx),
4012                "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
4013            );
4014            assert_eq!(
4015                view.selection_ranges(cx),
4016                &[
4017                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4018                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4019                    DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
4020                ]
4021            );
4022        });
4023
4024        // Copy with a single cursor only, which writes the whole line into the clipboard.
4025        view.update(cx, |view, cx| {
4026            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx)
4027                .unwrap();
4028            view.copy(&Copy, cx);
4029        });
4030
4031        // Paste with three selections, noticing how the copied full-line selection is inserted
4032        // before the empty selections but replaces the selection that is non-empty.
4033        view.update(cx, |view, cx| {
4034            view.select_display_ranges(
4035                &[
4036                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4037                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
4038                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4039                ],
4040                cx,
4041            )
4042            .unwrap();
4043            view.paste(&Paste, cx);
4044            assert_eq!(
4045                view.display_text(cx),
4046                "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
4047            );
4048            assert_eq!(
4049                view.selection_ranges(cx),
4050                &[
4051                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4052                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4053                    DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
4054                ]
4055            );
4056        });
4057    }
4058
4059    #[gpui::test]
4060    fn test_select_all(cx: &mut gpui::MutableAppContext) {
4061        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\nde\nfgh", cx));
4062        let settings = EditorSettings::test(&cx);
4063        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4064        view.update(cx, |view, cx| {
4065            view.select_all(&SelectAll, cx);
4066            assert_eq!(
4067                view.selection_ranges(cx),
4068                &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
4069            );
4070        });
4071    }
4072
4073    #[gpui::test]
4074    fn test_select_line(cx: &mut gpui::MutableAppContext) {
4075        let settings = EditorSettings::test(&cx);
4076        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 5), cx));
4077        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4078        view.update(cx, |view, cx| {
4079            view.select_display_ranges(
4080                &[
4081                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
4082                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4083                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4084                    DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
4085                ],
4086                cx,
4087            )
4088            .unwrap();
4089            view.select_line(&SelectLine, cx);
4090            assert_eq!(
4091                view.selection_ranges(cx),
4092                vec![
4093                    DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
4094                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
4095                ]
4096            );
4097        });
4098
4099        view.update(cx, |view, cx| {
4100            view.select_line(&SelectLine, cx);
4101            assert_eq!(
4102                view.selection_ranges(cx),
4103                vec![
4104                    DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
4105                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
4106                ]
4107            );
4108        });
4109
4110        view.update(cx, |view, cx| {
4111            view.select_line(&SelectLine, cx);
4112            assert_eq!(
4113                view.selection_ranges(cx),
4114                vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
4115            );
4116        });
4117    }
4118
4119    #[gpui::test]
4120    fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
4121        let settings = EditorSettings::test(&cx);
4122        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(9, 5), cx));
4123        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4124        view.update(cx, |view, cx| {
4125            view.fold_ranges(
4126                vec![
4127                    Point::new(0, 2)..Point::new(1, 2),
4128                    Point::new(2, 3)..Point::new(4, 1),
4129                    Point::new(7, 0)..Point::new(8, 4),
4130                ],
4131                cx,
4132            );
4133            view.select_display_ranges(
4134                &[
4135                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
4136                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4137                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4138                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
4139                ],
4140                cx,
4141            )
4142            .unwrap();
4143            assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
4144        });
4145
4146        view.update(cx, |view, cx| {
4147            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
4148            assert_eq!(
4149                view.display_text(cx),
4150                "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
4151            );
4152            assert_eq!(
4153                view.selection_ranges(cx),
4154                [
4155                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4156                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4157                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
4158                    DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
4159                ]
4160            );
4161        });
4162
4163        view.update(cx, |view, cx| {
4164            view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx)
4165                .unwrap();
4166            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
4167            assert_eq!(
4168                view.display_text(cx),
4169                "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
4170            );
4171            assert_eq!(
4172                view.selection_ranges(cx),
4173                [
4174                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4175                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4176                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
4177                    DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
4178                    DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
4179                    DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
4180                    DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
4181                    DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
4182                ]
4183            );
4184        });
4185    }
4186
4187    #[gpui::test]
4188    fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
4189        let settings = EditorSettings::test(&cx);
4190        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndefghi\n\njk\nlmno\n", cx));
4191        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4192
4193        view.update(cx, |view, cx| {
4194            view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx)
4195                .unwrap();
4196        });
4197        view.update(cx, |view, cx| {
4198            view.add_selection_above(&AddSelectionAbove, cx);
4199            assert_eq!(
4200                view.selection_ranges(cx),
4201                vec![
4202                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4203                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
4204                ]
4205            );
4206        });
4207
4208        view.update(cx, |view, cx| {
4209            view.add_selection_above(&AddSelectionAbove, cx);
4210            assert_eq!(
4211                view.selection_ranges(cx),
4212                vec![
4213                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4214                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
4215                ]
4216            );
4217        });
4218
4219        view.update(cx, |view, cx| {
4220            view.add_selection_below(&AddSelectionBelow, cx);
4221            assert_eq!(
4222                view.selection_ranges(cx),
4223                vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
4224            );
4225        });
4226
4227        view.update(cx, |view, cx| {
4228            view.add_selection_below(&AddSelectionBelow, cx);
4229            assert_eq!(
4230                view.selection_ranges(cx),
4231                vec![
4232                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
4233                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
4234                ]
4235            );
4236        });
4237
4238        view.update(cx, |view, cx| {
4239            view.add_selection_below(&AddSelectionBelow, cx);
4240            assert_eq!(
4241                view.selection_ranges(cx),
4242                vec![
4243                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
4244                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
4245                ]
4246            );
4247        });
4248
4249        view.update(cx, |view, cx| {
4250            view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx)
4251                .unwrap();
4252        });
4253        view.update(cx, |view, cx| {
4254            view.add_selection_below(&AddSelectionBelow, cx);
4255            assert_eq!(
4256                view.selection_ranges(cx),
4257                vec![
4258                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4259                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
4260                ]
4261            );
4262        });
4263
4264        view.update(cx, |view, cx| {
4265            view.add_selection_below(&AddSelectionBelow, cx);
4266            assert_eq!(
4267                view.selection_ranges(cx),
4268                vec![
4269                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4270                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
4271                ]
4272            );
4273        });
4274
4275        view.update(cx, |view, cx| {
4276            view.add_selection_above(&AddSelectionAbove, cx);
4277            assert_eq!(
4278                view.selection_ranges(cx),
4279                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
4280            );
4281        });
4282
4283        view.update(cx, |view, cx| {
4284            view.add_selection_above(&AddSelectionAbove, cx);
4285            assert_eq!(
4286                view.selection_ranges(cx),
4287                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
4288            );
4289        });
4290
4291        view.update(cx, |view, cx| {
4292            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx)
4293                .unwrap();
4294            view.add_selection_below(&AddSelectionBelow, cx);
4295            assert_eq!(
4296                view.selection_ranges(cx),
4297                vec![
4298                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
4299                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
4300                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
4301                ]
4302            );
4303        });
4304
4305        view.update(cx, |view, cx| {
4306            view.add_selection_below(&AddSelectionBelow, cx);
4307            assert_eq!(
4308                view.selection_ranges(cx),
4309                vec![
4310                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
4311                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
4312                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
4313                    DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
4314                ]
4315            );
4316        });
4317
4318        view.update(cx, |view, cx| {
4319            view.add_selection_above(&AddSelectionAbove, cx);
4320            assert_eq!(
4321                view.selection_ranges(cx),
4322                vec![
4323                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
4324                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
4325                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
4326                ]
4327            );
4328        });
4329
4330        view.update(cx, |view, cx| {
4331            view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx)
4332                .unwrap();
4333        });
4334        view.update(cx, |view, cx| {
4335            view.add_selection_above(&AddSelectionAbove, cx);
4336            assert_eq!(
4337                view.selection_ranges(cx),
4338                vec![
4339                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
4340                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
4341                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
4342                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
4343                ]
4344            );
4345        });
4346
4347        view.update(cx, |view, cx| {
4348            view.add_selection_below(&AddSelectionBelow, cx);
4349            assert_eq!(
4350                view.selection_ranges(cx),
4351                vec![
4352                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
4353                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
4354                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
4355                ]
4356            );
4357        });
4358    }
4359
4360    #[gpui::test]
4361    async fn test_select_larger_smaller_syntax_node(mut cx: gpui::TestAppContext) {
4362        let settings = cx.read(EditorSettings::test);
4363        let language = Arc::new(Language::new(
4364            LanguageConfig::default(),
4365            tree_sitter_rust::language(),
4366        ));
4367
4368        let text = r#"
4369            use mod1::mod2::{mod3, mod4};
4370
4371            fn fn_1(param1: bool, param2: &str) {
4372                let var1 = "text";
4373            }
4374        "#
4375        .unindent();
4376
4377        let buffer = cx.add_model(|cx| {
4378            let history = History::new(text.into());
4379            Buffer::from_history(0, history, None, Some(language), cx)
4380        });
4381        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
4382        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing())
4383            .await;
4384
4385        view.update(&mut cx, |view, cx| {
4386            view.select_display_ranges(
4387                &[
4388                    DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
4389                    DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
4390                    DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
4391                ],
4392                cx,
4393            )
4394            .unwrap();
4395            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4396        });
4397        assert_eq!(
4398            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4399            &[
4400                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
4401                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
4402                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
4403            ]
4404        );
4405
4406        view.update(&mut cx, |view, cx| {
4407            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4408        });
4409        assert_eq!(
4410            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4411            &[
4412                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
4413                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
4414            ]
4415        );
4416
4417        view.update(&mut cx, |view, cx| {
4418            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4419        });
4420        assert_eq!(
4421            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4422            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
4423        );
4424
4425        // Trying to expand the selected syntax node one more time has no effect.
4426        view.update(&mut cx, |view, cx| {
4427            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4428        });
4429        assert_eq!(
4430            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4431            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
4432        );
4433
4434        view.update(&mut cx, |view, cx| {
4435            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
4436        });
4437        assert_eq!(
4438            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4439            &[
4440                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
4441                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
4442            ]
4443        );
4444
4445        view.update(&mut cx, |view, cx| {
4446            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
4447        });
4448        assert_eq!(
4449            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4450            &[
4451                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
4452                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
4453                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
4454            ]
4455        );
4456
4457        view.update(&mut cx, |view, cx| {
4458            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
4459        });
4460        assert_eq!(
4461            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4462            &[
4463                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
4464                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
4465                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
4466            ]
4467        );
4468
4469        // Trying to shrink the selected syntax node one more time has no effect.
4470        view.update(&mut cx, |view, cx| {
4471            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
4472        });
4473        assert_eq!(
4474            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4475            &[
4476                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
4477                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
4478                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
4479            ]
4480        );
4481
4482        // Ensure that we keep expanding the selection if the larger selection starts or ends within
4483        // a fold.
4484        view.update(&mut cx, |view, cx| {
4485            view.fold_ranges(
4486                vec![
4487                    Point::new(0, 21)..Point::new(0, 24),
4488                    Point::new(3, 20)..Point::new(3, 22),
4489                ],
4490                cx,
4491            );
4492            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4493        });
4494        assert_eq!(
4495            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4496            &[
4497                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
4498                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
4499                DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
4500            ]
4501        );
4502    }
4503
4504    #[gpui::test]
4505    async fn test_autoclose_pairs(mut cx: gpui::TestAppContext) {
4506        let settings = cx.read(EditorSettings::test);
4507        let language = Arc::new(Language::new(
4508            LanguageConfig {
4509                autoclose_pairs: vec![
4510                    AutoclosePair {
4511                        start: "{".to_string(),
4512                        end: "}".to_string(),
4513                    },
4514                    AutoclosePair {
4515                        start: "/*".to_string(),
4516                        end: " */".to_string(),
4517                    },
4518                ],
4519                ..Default::default()
4520            },
4521            tree_sitter_rust::language(),
4522        ));
4523
4524        let text = r#"
4525            a
4526
4527            /
4528
4529        "#
4530        .unindent();
4531
4532        let buffer = cx.add_model(|cx| {
4533            let history = History::new(text.into());
4534            Buffer::from_history(0, history, None, Some(language), cx)
4535        });
4536        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
4537        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing())
4538            .await;
4539
4540        view.update(&mut cx, |view, cx| {
4541            view.select_display_ranges(
4542                &[
4543                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
4544                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4545                ],
4546                cx,
4547            )
4548            .unwrap();
4549            view.handle_input(&Input("{".to_string()), cx);
4550            view.handle_input(&Input("{".to_string()), cx);
4551            view.handle_input(&Input("{".to_string()), cx);
4552            assert_eq!(
4553                view.text(cx),
4554                "
4555                {{{}}}
4556                {{{}}}
4557                /
4558
4559                "
4560                .unindent()
4561            );
4562
4563            view.move_right(&MoveRight, cx);
4564            view.handle_input(&Input("}".to_string()), cx);
4565            view.handle_input(&Input("}".to_string()), cx);
4566            view.handle_input(&Input("}".to_string()), cx);
4567            assert_eq!(
4568                view.text(cx),
4569                "
4570                {{{}}}}
4571                {{{}}}}
4572                /
4573
4574                "
4575                .unindent()
4576            );
4577
4578            view.undo(&Undo, cx);
4579            view.handle_input(&Input("/".to_string()), cx);
4580            view.handle_input(&Input("*".to_string()), cx);
4581            assert_eq!(
4582                view.text(cx),
4583                "
4584                /* */
4585                /* */
4586                /
4587
4588                "
4589                .unindent()
4590            );
4591
4592            view.undo(&Undo, cx);
4593            view.select_display_ranges(
4594                &[
4595                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4596                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4597                ],
4598                cx,
4599            )
4600            .unwrap();
4601            view.handle_input(&Input("*".to_string()), cx);
4602            assert_eq!(
4603                view.text(cx),
4604                "
4605                a
4606
4607                /*
4608                *
4609                "
4610                .unindent()
4611            );
4612        });
4613    }
4614
4615    impl Editor {
4616        fn selection_ranges(&self, cx: &mut MutableAppContext) -> Vec<Range<DisplayPoint>> {
4617            self.selections_in_range(
4618                self.selection_set_id,
4619                DisplayPoint::zero()..self.max_point(cx),
4620                cx,
4621            )
4622            .collect::<Vec<_>>()
4623        }
4624    }
4625
4626    fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
4627        let point = DisplayPoint::new(row as u32, column as u32);
4628        point..point
4629    }
4630
4631    fn build_editor(
4632        buffer: ModelHandle<Buffer>,
4633        settings: EditorSettings,
4634        cx: &mut ViewContext<Editor>,
4635    ) -> Editor {
4636        Editor::for_buffer(buffer, move |_| settings.clone(), cx)
4637    }
4638}
4639
4640trait RangeExt<T> {
4641    fn sorted(&self) -> Range<T>;
4642    fn to_inclusive(&self) -> RangeInclusive<T>;
4643}
4644
4645impl<T: Ord + Clone> RangeExt<T> for Range<T> {
4646    fn sorted(&self) -> Self {
4647        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
4648    }
4649
4650    fn to_inclusive(&self) -> RangeInclusive<T> {
4651        self.start.clone()..=self.end.clone()
4652    }
4653}