lib.rs

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