lib.rs

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