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