lib.rs

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