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