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