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            .selection_set(cx)
2462            .selections::<Point, _>(buffer)
2463            .collect::<Vec<_>>();
2464        let start = range.start.to_point(&display_map);
2465        let start_index = self.selection_insertion_index(&selections, start);
2466        let pending_selection = if set_id.replica_id == self.buffer.read(cx).replica_id() {
2467            self.pending_selection.as_ref().and_then(|pending| {
2468                let mut selection_start = pending.start.to_display_point(&display_map);
2469                let mut selection_end = pending.end.to_display_point(&display_map);
2470                if pending.reversed {
2471                    mem::swap(&mut selection_start, &mut selection_end);
2472                }
2473                if selection_start <= range.end || selection_end <= range.end {
2474                    Some(selection_start..selection_end)
2475                } else {
2476                    None
2477                }
2478            })
2479        } else {
2480            None
2481        };
2482        selections
2483            .into_iter()
2484            .skip(start_index)
2485            .map(move |s| s.display_range(&display_map))
2486            .take_while(move |r| r.start <= range.end || r.end <= range.end)
2487            .chain(pending_selection)
2488    }
2489
2490    fn selection_insertion_index(&self, selections: &[Selection<Point>], start: Point) -> usize {
2491        match selections.binary_search_by_key(&start, |probe| probe.start) {
2492            Ok(index) => index,
2493            Err(index) => {
2494                if index > 0 && selections[index - 1].end > start {
2495                    index - 1
2496                } else {
2497                    index
2498                }
2499            }
2500        }
2501    }
2502
2503    pub fn selections<'a, D>(&self, cx: &'a AppContext) -> impl 'a + Iterator<Item = Selection<D>>
2504    where
2505        D: 'a + TextDimension<'a> + Ord,
2506    {
2507        let buffer = self.buffer.read(cx);
2508        let mut selections = self.selection_set(cx).selections::<D, _>(buffer).peekable();
2509        let mut pending_selection = self.pending_selection(cx);
2510        iter::from_fn(move || {
2511            if let Some(pending) = pending_selection.as_mut() {
2512                while let Some(next_selection) = selections.peek() {
2513                    if pending.start <= next_selection.end && pending.end >= next_selection.start {
2514                        let next_selection = selections.next().unwrap();
2515                        if next_selection.start < pending.start {
2516                            pending.start = next_selection.start;
2517                        }
2518                        if next_selection.end > pending.end {
2519                            pending.end = next_selection.end;
2520                        }
2521                    } else if next_selection.end < pending.start {
2522                        return selections.next();
2523                    } else {
2524                        break;
2525                    }
2526                }
2527
2528                pending_selection.take()
2529            } else {
2530                selections.next()
2531            }
2532        })
2533    }
2534
2535    fn pending_selection<'a, D>(&self, cx: &'a AppContext) -> Option<Selection<D>>
2536    where
2537        D: 'a + TextDimension<'a>,
2538    {
2539        let buffer = self.buffer.read(cx);
2540        self.pending_selection.as_ref().map(|selection| Selection {
2541            id: selection.id,
2542            start: selection.start.summary::<D, _>(buffer),
2543            end: selection.end.summary::<D, _>(buffer),
2544            reversed: selection.reversed,
2545            goal: selection.goal,
2546        })
2547    }
2548
2549    fn selection_count<'a>(&self, cx: &'a AppContext) -> usize {
2550        let mut selection_count = self.selection_set(cx).len();
2551        if self.pending_selection.is_some() {
2552            selection_count += 1;
2553        }
2554        selection_count
2555    }
2556
2557    pub fn oldest_selection<'a, T>(&self, cx: &'a AppContext) -> Selection<T>
2558    where
2559        T: 'a + TextDimension<'a>,
2560    {
2561        let buffer = self.buffer.read(cx);
2562        self.selection_set(cx)
2563            .oldest_selection(buffer)
2564            .or_else(|| self.pending_selection(cx))
2565            .unwrap()
2566    }
2567
2568    pub fn newest_selection<'a, T>(&self, cx: &'a AppContext) -> Selection<T>
2569    where
2570        T: 'a + TextDimension<'a>,
2571    {
2572        let buffer = self.buffer.read(cx);
2573        self.pending_selection(cx)
2574            .or_else(|| self.selection_set(cx).newest_selection(buffer))
2575            .unwrap()
2576    }
2577
2578    fn selection_set<'a>(&self, cx: &'a AppContext) -> &'a SelectionSet {
2579        self.buffer
2580            .read(cx)
2581            .selection_set(self.selection_set_id)
2582            .unwrap()
2583    }
2584
2585    fn update_selections<T>(
2586        &mut self,
2587        mut selections: Vec<Selection<T>>,
2588        autoscroll: bool,
2589        cx: &mut ViewContext<Self>,
2590    ) where
2591        T: ToOffset + ToPoint + Ord + std::marker::Copy + std::fmt::Debug,
2592    {
2593        // Merge overlapping selections.
2594        let buffer = self.buffer.read(cx);
2595        let mut i = 1;
2596        while i < selections.len() {
2597            if selections[i - 1].end >= selections[i].start {
2598                let removed = selections.remove(i);
2599                if removed.start < selections[i - 1].start {
2600                    selections[i - 1].start = removed.start;
2601                }
2602                if removed.end > selections[i - 1].end {
2603                    selections[i - 1].end = removed.end;
2604                }
2605            } else {
2606                i += 1;
2607            }
2608        }
2609
2610        self.pending_selection = None;
2611        self.add_selections_state = None;
2612        self.select_larger_syntax_node_stack.clear();
2613        while let Some(autoclose_pair_state) = self.autoclose_stack.last() {
2614            let all_selections_inside_autoclose_ranges =
2615                if selections.len() == autoclose_pair_state.ranges.len() {
2616                    selections
2617                        .iter()
2618                        .zip(autoclose_pair_state.ranges.ranges::<Point, _>(buffer))
2619                        .all(|(selection, autoclose_range)| {
2620                            let head = selection.head().to_point(&*buffer);
2621                            autoclose_range.start <= head && autoclose_range.end >= head
2622                        })
2623                } else {
2624                    false
2625                };
2626
2627            if all_selections_inside_autoclose_ranges {
2628                break;
2629            } else {
2630                self.autoclose_stack.pop();
2631            }
2632        }
2633
2634        if autoscroll {
2635            self.request_autoscroll(cx);
2636        }
2637        self.pause_cursor_blinking(cx);
2638
2639        self.buffer.update(cx, |buffer, cx| {
2640            buffer
2641                .update_selection_set(self.selection_set_id, &selections, cx)
2642                .unwrap();
2643        });
2644    }
2645
2646    fn request_autoscroll(&mut self, cx: &mut ViewContext<Self>) {
2647        self.autoscroll_requested = true;
2648        cx.notify();
2649    }
2650
2651    fn start_transaction(&mut self, cx: &mut ViewContext<Self>) {
2652        self.end_selection(cx);
2653        self.buffer.update(cx, |buffer, _| {
2654            buffer
2655                .start_transaction(Some(self.selection_set_id))
2656                .unwrap()
2657        });
2658    }
2659
2660    fn end_transaction(&self, cx: &mut ViewContext<Self>) {
2661        self.buffer.update(cx, |buffer, cx| {
2662            buffer
2663                .end_transaction(Some(self.selection_set_id), cx)
2664                .unwrap()
2665        });
2666    }
2667
2668    pub fn page_up(&mut self, _: &PageUp, _: &mut ViewContext<Self>) {
2669        log::info!("Editor::page_up");
2670    }
2671
2672    pub fn page_down(&mut self, _: &PageDown, _: &mut ViewContext<Self>) {
2673        log::info!("Editor::page_down");
2674    }
2675
2676    pub fn fold(&mut self, _: &Fold, cx: &mut ViewContext<Self>) {
2677        let mut fold_ranges = Vec::new();
2678
2679        let selections = self.selections::<Point>(cx).collect::<Vec<_>>();
2680        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2681        for selection in selections {
2682            let range = selection.display_range(&display_map).sorted();
2683            let buffer_start_row = range.start.to_point(&display_map).row;
2684
2685            for row in (0..=range.end.row()).rev() {
2686                if self.is_line_foldable(&display_map, row) && !display_map.is_line_folded(row) {
2687                    let fold_range = self.foldable_range_for_line(&display_map, row);
2688                    if fold_range.end.row >= buffer_start_row {
2689                        fold_ranges.push(fold_range);
2690                        if row <= range.start.row() {
2691                            break;
2692                        }
2693                    }
2694                }
2695            }
2696        }
2697
2698        self.fold_ranges(fold_ranges, cx);
2699    }
2700
2701    pub fn unfold(&mut self, _: &Unfold, cx: &mut ViewContext<Self>) {
2702        let selections = self.selections::<Point>(cx).collect::<Vec<_>>();
2703        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2704        let buffer = self.buffer.read(cx);
2705        let ranges = selections
2706            .iter()
2707            .map(|s| {
2708                let range = s.display_range(&display_map).sorted();
2709                let mut start = range.start.to_point(&display_map);
2710                let mut end = range.end.to_point(&display_map);
2711                start.column = 0;
2712                end.column = buffer.line_len(end.row);
2713                start..end
2714            })
2715            .collect::<Vec<_>>();
2716        self.unfold_ranges(ranges, cx);
2717    }
2718
2719    fn is_line_foldable(&self, display_map: &DisplayMapSnapshot, display_row: u32) -> bool {
2720        let max_point = display_map.max_point();
2721        if display_row >= max_point.row() {
2722            false
2723        } else {
2724            let (start_indent, is_blank) = display_map.line_indent(display_row);
2725            if is_blank {
2726                false
2727            } else {
2728                for display_row in display_row + 1..=max_point.row() {
2729                    let (indent, is_blank) = display_map.line_indent(display_row);
2730                    if !is_blank {
2731                        return indent > start_indent;
2732                    }
2733                }
2734                false
2735            }
2736        }
2737    }
2738
2739    fn foldable_range_for_line(
2740        &self,
2741        display_map: &DisplayMapSnapshot,
2742        start_row: u32,
2743    ) -> Range<Point> {
2744        let max_point = display_map.max_point();
2745
2746        let (start_indent, _) = display_map.line_indent(start_row);
2747        let start = DisplayPoint::new(start_row, display_map.line_len(start_row));
2748        let mut end = None;
2749        for row in start_row + 1..=max_point.row() {
2750            let (indent, is_blank) = display_map.line_indent(row);
2751            if !is_blank && indent <= start_indent {
2752                end = Some(DisplayPoint::new(row - 1, display_map.line_len(row - 1)));
2753                break;
2754            }
2755        }
2756
2757        let end = end.unwrap_or(max_point);
2758        return start.to_point(display_map)..end.to_point(display_map);
2759    }
2760
2761    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
2762        let selections = self.selections::<Point>(cx);
2763        let ranges = selections.map(|s| s.start..s.end).collect();
2764        self.fold_ranges(ranges, cx);
2765    }
2766
2767    fn fold_ranges<T: ToOffset>(&mut self, ranges: Vec<Range<T>>, cx: &mut ViewContext<Self>) {
2768        if !ranges.is_empty() {
2769            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
2770            self.autoscroll_requested = true;
2771            cx.notify();
2772        }
2773    }
2774
2775    fn unfold_ranges<T: ToOffset>(&mut self, ranges: Vec<Range<T>>, cx: &mut ViewContext<Self>) {
2776        if !ranges.is_empty() {
2777            self.display_map
2778                .update(cx, |map, cx| map.unfold(ranges, cx));
2779            self.autoscroll_requested = true;
2780            cx.notify();
2781        }
2782    }
2783
2784    pub fn longest_row(&self, cx: &mut MutableAppContext) -> u32 {
2785        self.display_map
2786            .update(cx, |map, cx| map.snapshot(cx))
2787            .longest_row()
2788    }
2789
2790    pub fn max_point(&self, cx: &mut MutableAppContext) -> DisplayPoint {
2791        self.display_map
2792            .update(cx, |map, cx| map.snapshot(cx))
2793            .max_point()
2794    }
2795
2796    pub fn text(&self, cx: &AppContext) -> String {
2797        self.buffer.read(cx).text()
2798    }
2799
2800    pub fn display_text(&self, cx: &mut MutableAppContext) -> String {
2801        self.display_map
2802            .update(cx, |map, cx| map.snapshot(cx))
2803            .text()
2804    }
2805
2806    // pub fn font_size(&self) -> f32 {
2807    //     self.settings.font_size
2808    // }
2809
2810    pub fn set_wrap_width(&self, width: f32, cx: &mut MutableAppContext) -> bool {
2811        self.display_map
2812            .update(cx, |map, cx| map.set_wrap_width(Some(width), cx))
2813    }
2814
2815    fn next_blink_epoch(&mut self) -> usize {
2816        self.blink_epoch += 1;
2817        self.blink_epoch
2818    }
2819
2820    fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
2821        self.show_local_cursors = true;
2822        cx.notify();
2823
2824        let epoch = self.next_blink_epoch();
2825        cx.spawn(|this, mut cx| {
2826            let this = this.downgrade();
2827            async move {
2828                Timer::after(CURSOR_BLINK_INTERVAL).await;
2829                if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
2830                    this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
2831                }
2832            }
2833        })
2834        .detach();
2835    }
2836
2837    fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
2838        if epoch == self.blink_epoch {
2839            self.blinking_paused = false;
2840            self.blink_cursors(epoch, cx);
2841        }
2842    }
2843
2844    fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
2845        if epoch == self.blink_epoch && self.focused && !self.blinking_paused {
2846            self.show_local_cursors = !self.show_local_cursors;
2847            cx.notify();
2848
2849            let epoch = self.next_blink_epoch();
2850            cx.spawn(|this, mut cx| {
2851                let this = this.downgrade();
2852                async move {
2853                    Timer::after(CURSOR_BLINK_INTERVAL).await;
2854                    if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
2855                        this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx));
2856                    }
2857                }
2858            })
2859            .detach();
2860        }
2861    }
2862
2863    pub fn show_local_cursors(&self) -> bool {
2864        self.show_local_cursors
2865    }
2866
2867    fn on_buffer_changed(&mut self, _: ModelHandle<Buffer>, cx: &mut ViewContext<Self>) {
2868        self.refresh_active_diagnostics(cx);
2869        cx.notify();
2870    }
2871
2872    fn on_buffer_event(
2873        &mut self,
2874        _: ModelHandle<Buffer>,
2875        event: &language::Event,
2876        cx: &mut ViewContext<Self>,
2877    ) {
2878        match event {
2879            language::Event::Edited => cx.emit(Event::Edited),
2880            language::Event::Dirtied => cx.emit(Event::Dirtied),
2881            language::Event::Saved => cx.emit(Event::Saved),
2882            language::Event::FileHandleChanged => cx.emit(Event::FileHandleChanged),
2883            language::Event::Reloaded => cx.emit(Event::FileHandleChanged),
2884            language::Event::Closed => cx.emit(Event::Closed),
2885            language::Event::Reparsed => {}
2886        }
2887    }
2888
2889    fn on_display_map_changed(&mut self, _: ModelHandle<DisplayMap>, cx: &mut ViewContext<Self>) {
2890        cx.notify();
2891    }
2892}
2893
2894impl Snapshot {
2895    pub fn is_empty(&self) -> bool {
2896        self.display_snapshot.is_empty()
2897    }
2898
2899    pub fn is_focused(&self) -> bool {
2900        self.is_focused
2901    }
2902
2903    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
2904        self.placeholder_text.as_ref()
2905    }
2906
2907    pub fn buffer_row_count(&self) -> u32 {
2908        self.display_snapshot.buffer_row_count()
2909    }
2910
2911    pub fn buffer_rows<'a>(&'a self, start_row: u32, cx: &'a AppContext) -> BufferRows<'a> {
2912        self.display_snapshot.buffer_rows(start_row, Some(cx))
2913    }
2914
2915    pub fn chunks<'a>(
2916        &'a self,
2917        display_rows: Range<u32>,
2918        theme: Option<&'a SyntaxTheme>,
2919        cx: &'a AppContext,
2920    ) -> display_map::Chunks<'a> {
2921        self.display_snapshot.chunks(display_rows, theme, cx)
2922    }
2923
2924    pub fn scroll_position(&self) -> Vector2F {
2925        compute_scroll_position(
2926            &self.display_snapshot,
2927            self.scroll_position,
2928            &self.scroll_top_anchor,
2929        )
2930    }
2931
2932    pub fn max_point(&self) -> DisplayPoint {
2933        self.display_snapshot.max_point()
2934    }
2935
2936    pub fn longest_row(&self) -> u32 {
2937        self.display_snapshot.longest_row()
2938    }
2939
2940    pub fn line_len(&self, display_row: u32) -> u32 {
2941        self.display_snapshot.line_len(display_row)
2942    }
2943
2944    pub fn line(&self, display_row: u32) -> String {
2945        self.display_snapshot.line(display_row)
2946    }
2947
2948    pub fn prev_row_boundary(&self, point: DisplayPoint) -> (DisplayPoint, Point) {
2949        self.display_snapshot.prev_row_boundary(point)
2950    }
2951
2952    pub fn next_row_boundary(&self, point: DisplayPoint) -> (DisplayPoint, Point) {
2953        self.display_snapshot.next_row_boundary(point)
2954    }
2955}
2956
2957impl EditorSettings {
2958    #[cfg(any(test, feature = "test-support"))]
2959    pub fn test(cx: &AppContext) -> Self {
2960        Self {
2961            tab_size: 4,
2962            style: {
2963                let font_cache: &gpui::FontCache = cx.font_cache();
2964                let font_family_name = Arc::from("Monaco");
2965                let font_properties = Default::default();
2966                let font_family_id = font_cache.load_family(&[&font_family_name]).unwrap();
2967                let font_id = font_cache
2968                    .select_font(font_family_id, &font_properties)
2969                    .unwrap();
2970                EditorStyle {
2971                    text: gpui::fonts::TextStyle {
2972                        font_family_name,
2973                        font_family_id,
2974                        font_id,
2975                        font_size: 14.,
2976                        color: gpui::color::Color::from_u32(0xff0000ff),
2977                        font_properties,
2978                        underline: None,
2979                    },
2980                    placeholder_text: None,
2981                    background: Default::default(),
2982                    gutter_background: Default::default(),
2983                    active_line_background: Default::default(),
2984                    line_number: Default::default(),
2985                    line_number_active: Default::default(),
2986                    selection: Default::default(),
2987                    guest_selections: Default::default(),
2988                    syntax: Default::default(),
2989                    error_diagnostic: Default::default(),
2990                    invalid_error_diagnostic: Default::default(),
2991                    warning_diagnostic: Default::default(),
2992                    invalid_warning_diagnostic: Default::default(),
2993                    information_diagnostic: Default::default(),
2994                    invalid_information_diagnostic: Default::default(),
2995                    hint_diagnostic: Default::default(),
2996                    invalid_hint_diagnostic: Default::default(),
2997                }
2998            },
2999        }
3000    }
3001}
3002
3003fn compute_scroll_position(
3004    snapshot: &DisplayMapSnapshot,
3005    mut scroll_position: Vector2F,
3006    scroll_top_anchor: &Anchor,
3007) -> Vector2F {
3008    let scroll_top = scroll_top_anchor.to_display_point(snapshot).row() as f32;
3009    scroll_position.set_y(scroll_top + scroll_position.y());
3010    scroll_position
3011}
3012
3013pub enum Event {
3014    Activate,
3015    Edited,
3016    Blurred,
3017    Dirtied,
3018    Saved,
3019    FileHandleChanged,
3020    Closed,
3021}
3022
3023impl Entity for Editor {
3024    type Event = Event;
3025
3026    fn release(&mut self, cx: &mut MutableAppContext) {
3027        self.buffer.update(cx, |buffer, cx| {
3028            buffer
3029                .remove_selection_set(self.selection_set_id, cx)
3030                .unwrap();
3031        });
3032    }
3033}
3034
3035impl View for Editor {
3036    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
3037        let settings = self.build_settings.borrow_mut()(cx);
3038        self.display_map.update(cx, |map, cx| {
3039            map.set_font(
3040                settings.style.text.font_id,
3041                settings.style.text.font_size,
3042                cx,
3043            )
3044        });
3045        EditorElement::new(self.handle.clone(), settings).boxed()
3046    }
3047
3048    fn ui_name() -> &'static str {
3049        "Editor"
3050    }
3051
3052    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
3053        self.focused = true;
3054        self.blink_cursors(self.blink_epoch, cx);
3055        self.buffer.update(cx, |buffer, cx| {
3056            buffer
3057                .set_active_selection_set(Some(self.selection_set_id), cx)
3058                .unwrap();
3059        });
3060    }
3061
3062    fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
3063        self.focused = false;
3064        self.show_local_cursors = false;
3065        self.buffer.update(cx, |buffer, cx| {
3066            buffer.set_active_selection_set(None, cx).unwrap();
3067        });
3068        cx.emit(Event::Blurred);
3069        cx.notify();
3070    }
3071
3072    fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
3073        let mut cx = Self::default_keymap_context();
3074        let mode = match self.mode {
3075            EditorMode::SingleLine => "single_line",
3076            EditorMode::AutoHeight { .. } => "auto_height",
3077            EditorMode::Full => "full",
3078        };
3079        cx.map.insert("mode".into(), mode.into());
3080        cx
3081    }
3082}
3083
3084impl SelectionExt for Selection<Point> {
3085    fn display_range(&self, map: &DisplayMapSnapshot) -> Range<DisplayPoint> {
3086        let start = self.start.to_display_point(map);
3087        let end = self.end.to_display_point(map);
3088        if self.reversed {
3089            end..start
3090        } else {
3091            start..end
3092        }
3093    }
3094
3095    fn spanned_rows(
3096        &self,
3097        include_end_if_at_line_start: bool,
3098        map: &DisplayMapSnapshot,
3099    ) -> SpannedRows {
3100        let display_start = self.start.to_display_point(map);
3101        let mut display_end = self.end.to_display_point(map);
3102        if !include_end_if_at_line_start
3103            && display_end.row() != map.max_point().row()
3104            && display_start.row() != display_end.row()
3105            && display_end.column() == 0
3106        {
3107            *display_end.row_mut() -= 1;
3108        }
3109
3110        let (display_start, buffer_start) = map.prev_row_boundary(display_start);
3111        let (display_end, buffer_end) = map.next_row_boundary(display_end);
3112
3113        SpannedRows {
3114            buffer_rows: buffer_start.row..buffer_end.row + 1,
3115            display_rows: display_start.row()..display_end.row() + 1,
3116        }
3117    }
3118}
3119
3120pub fn diagnostic_style(
3121    severity: DiagnosticSeverity,
3122    valid: bool,
3123    style: &EditorStyle,
3124) -> DiagnosticStyle {
3125    match (severity, valid) {
3126        (DiagnosticSeverity::ERROR, true) => style.error_diagnostic,
3127        (DiagnosticSeverity::ERROR, false) => style.invalid_error_diagnostic,
3128        (DiagnosticSeverity::WARNING, true) => style.warning_diagnostic,
3129        (DiagnosticSeverity::WARNING, false) => style.invalid_warning_diagnostic,
3130        (DiagnosticSeverity::INFORMATION, true) => style.information_diagnostic,
3131        (DiagnosticSeverity::INFORMATION, false) => style.invalid_information_diagnostic,
3132        (DiagnosticSeverity::HINT, true) => style.hint_diagnostic,
3133        (DiagnosticSeverity::HINT, false) => style.invalid_hint_diagnostic,
3134        _ => Default::default(),
3135    }
3136}
3137
3138#[cfg(test)]
3139mod tests {
3140    use super::*;
3141    use crate::test::sample_text;
3142    use buffer::Point;
3143    use unindent::Unindent;
3144
3145    #[gpui::test]
3146    fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
3147        let buffer = cx.add_model(|cx| Buffer::new(0, "aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx));
3148        let settings = EditorSettings::test(cx);
3149        let (_, editor) =
3150            cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3151
3152        editor.update(cx, |view, cx| {
3153            view.begin_selection(DisplayPoint::new(2, 2), false, cx);
3154        });
3155
3156        assert_eq!(
3157            editor.update(cx, |view, cx| view.selection_ranges(cx)),
3158            [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
3159        );
3160
3161        editor.update(cx, |view, cx| {
3162            view.update_selection(DisplayPoint::new(3, 3), Vector2F::zero(), cx);
3163        });
3164
3165        assert_eq!(
3166            editor.update(cx, |view, cx| view.selection_ranges(cx)),
3167            [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
3168        );
3169
3170        editor.update(cx, |view, cx| {
3171            view.update_selection(DisplayPoint::new(1, 1), Vector2F::zero(), cx);
3172        });
3173
3174        assert_eq!(
3175            editor.update(cx, |view, cx| view.selection_ranges(cx)),
3176            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
3177        );
3178
3179        editor.update(cx, |view, cx| {
3180            view.end_selection(cx);
3181            view.update_selection(DisplayPoint::new(3, 3), Vector2F::zero(), cx);
3182        });
3183
3184        assert_eq!(
3185            editor.update(cx, |view, cx| view.selection_ranges(cx)),
3186            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
3187        );
3188
3189        editor.update(cx, |view, cx| {
3190            view.begin_selection(DisplayPoint::new(3, 3), true, cx);
3191            view.update_selection(DisplayPoint::new(0, 0), Vector2F::zero(), cx);
3192        });
3193
3194        assert_eq!(
3195            editor.update(cx, |view, cx| view.selection_ranges(cx)),
3196            [
3197                DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
3198                DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
3199            ]
3200        );
3201
3202        editor.update(cx, |view, cx| {
3203            view.end_selection(cx);
3204        });
3205
3206        assert_eq!(
3207            editor.update(cx, |view, cx| view.selection_ranges(cx)),
3208            [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
3209        );
3210    }
3211
3212    #[gpui::test]
3213    fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
3214        let buffer = cx.add_model(|cx| Buffer::new(0, "aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx));
3215        let settings = EditorSettings::test(cx);
3216        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3217
3218        view.update(cx, |view, cx| {
3219            view.begin_selection(DisplayPoint::new(2, 2), false, cx);
3220            assert_eq!(
3221                view.selection_ranges(cx),
3222                [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
3223            );
3224        });
3225
3226        view.update(cx, |view, cx| {
3227            view.update_selection(DisplayPoint::new(3, 3), Vector2F::zero(), cx);
3228            assert_eq!(
3229                view.selection_ranges(cx),
3230                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
3231            );
3232        });
3233
3234        view.update(cx, |view, cx| {
3235            view.cancel(&Cancel, cx);
3236            view.update_selection(DisplayPoint::new(1, 1), Vector2F::zero(), cx);
3237            assert_eq!(
3238                view.selection_ranges(cx),
3239                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
3240            );
3241        });
3242    }
3243
3244    #[gpui::test]
3245    fn test_cancel(cx: &mut gpui::MutableAppContext) {
3246        let buffer = cx.add_model(|cx| Buffer::new(0, "aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx));
3247        let settings = EditorSettings::test(cx);
3248        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3249
3250        view.update(cx, |view, cx| {
3251            view.begin_selection(DisplayPoint::new(3, 4), false, cx);
3252            view.update_selection(DisplayPoint::new(1, 1), Vector2F::zero(), cx);
3253            view.end_selection(cx);
3254
3255            view.begin_selection(DisplayPoint::new(0, 1), true, cx);
3256            view.update_selection(DisplayPoint::new(0, 3), Vector2F::zero(), cx);
3257            view.end_selection(cx);
3258            assert_eq!(
3259                view.selection_ranges(cx),
3260                [
3261                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
3262                    DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
3263                ]
3264            );
3265        });
3266
3267        view.update(cx, |view, cx| {
3268            view.cancel(&Cancel, cx);
3269            assert_eq!(
3270                view.selection_ranges(cx),
3271                [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
3272            );
3273        });
3274
3275        view.update(cx, |view, cx| {
3276            view.cancel(&Cancel, cx);
3277            assert_eq!(
3278                view.selection_ranges(cx),
3279                [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
3280            );
3281        });
3282    }
3283
3284    #[gpui::test]
3285    fn test_fold(cx: &mut gpui::MutableAppContext) {
3286        let buffer = cx.add_model(|cx| {
3287            Buffer::new(
3288                0,
3289                "
3290                    impl Foo {
3291                        // Hello!
3292
3293                        fn a() {
3294                            1
3295                        }
3296
3297                        fn b() {
3298                            2
3299                        }
3300
3301                        fn c() {
3302                            3
3303                        }
3304                    }
3305                "
3306                .unindent(),
3307                cx,
3308            )
3309        });
3310        let settings = EditorSettings::test(&cx);
3311        let (_, view) = cx.add_window(Default::default(), |cx| {
3312            build_editor(buffer.clone(), settings, cx)
3313        });
3314
3315        view.update(cx, |view, cx| {
3316            view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx)
3317                .unwrap();
3318            view.fold(&Fold, cx);
3319            assert_eq!(
3320                view.display_text(cx),
3321                "
3322                    impl Foo {
3323                        // Hello!
3324
3325                        fn a() {
3326                            1
3327                        }
3328
3329                        fn b() {…
3330                        }
3331
3332                        fn c() {…
3333                        }
3334                    }
3335                "
3336                .unindent(),
3337            );
3338
3339            view.fold(&Fold, cx);
3340            assert_eq!(
3341                view.display_text(cx),
3342                "
3343                    impl Foo {…
3344                    }
3345                "
3346                .unindent(),
3347            );
3348
3349            view.unfold(&Unfold, cx);
3350            assert_eq!(
3351                view.display_text(cx),
3352                "
3353                    impl Foo {
3354                        // Hello!
3355
3356                        fn a() {
3357                            1
3358                        }
3359
3360                        fn b() {…
3361                        }
3362
3363                        fn c() {…
3364                        }
3365                    }
3366                "
3367                .unindent(),
3368            );
3369
3370            view.unfold(&Unfold, cx);
3371            assert_eq!(view.display_text(cx), buffer.read(cx).text());
3372        });
3373    }
3374
3375    #[gpui::test]
3376    fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
3377        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6), cx));
3378        let settings = EditorSettings::test(&cx);
3379        let (_, view) = cx.add_window(Default::default(), |cx| {
3380            build_editor(buffer.clone(), settings, cx)
3381        });
3382
3383        buffer.update(cx, |buffer, cx| {
3384            buffer.edit(
3385                vec![
3386                    Point::new(1, 0)..Point::new(1, 0),
3387                    Point::new(1, 1)..Point::new(1, 1),
3388                ],
3389                "\t",
3390                cx,
3391            );
3392        });
3393
3394        view.update(cx, |view, cx| {
3395            assert_eq!(
3396                view.selection_ranges(cx),
3397                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
3398            );
3399
3400            view.move_down(&MoveDown, cx);
3401            assert_eq!(
3402                view.selection_ranges(cx),
3403                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
3404            );
3405
3406            view.move_right(&MoveRight, cx);
3407            assert_eq!(
3408                view.selection_ranges(cx),
3409                &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
3410            );
3411
3412            view.move_left(&MoveLeft, cx);
3413            assert_eq!(
3414                view.selection_ranges(cx),
3415                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
3416            );
3417
3418            view.move_up(&MoveUp, cx);
3419            assert_eq!(
3420                view.selection_ranges(cx),
3421                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
3422            );
3423
3424            view.move_to_end(&MoveToEnd, cx);
3425            assert_eq!(
3426                view.selection_ranges(cx),
3427                &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
3428            );
3429
3430            view.move_to_beginning(&MoveToBeginning, cx);
3431            assert_eq!(
3432                view.selection_ranges(cx),
3433                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
3434            );
3435
3436            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx)
3437                .unwrap();
3438            view.select_to_beginning(&SelectToBeginning, cx);
3439            assert_eq!(
3440                view.selection_ranges(cx),
3441                &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
3442            );
3443
3444            view.select_to_end(&SelectToEnd, cx);
3445            assert_eq!(
3446                view.selection_ranges(cx),
3447                &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
3448            );
3449        });
3450    }
3451
3452    #[gpui::test]
3453    fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
3454        let buffer = cx.add_model(|cx| Buffer::new(0, "ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx));
3455        let settings = EditorSettings::test(&cx);
3456        let (_, view) = cx.add_window(Default::default(), |cx| {
3457            build_editor(buffer.clone(), settings, cx)
3458        });
3459
3460        assert_eq!('ⓐ'.len_utf8(), 3);
3461        assert_eq!('α'.len_utf8(), 2);
3462
3463        view.update(cx, |view, cx| {
3464            view.fold_ranges(
3465                vec![
3466                    Point::new(0, 6)..Point::new(0, 12),
3467                    Point::new(1, 2)..Point::new(1, 4),
3468                    Point::new(2, 4)..Point::new(2, 8),
3469                ],
3470                cx,
3471            );
3472            assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
3473
3474            view.move_right(&MoveRight, cx);
3475            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "".len())]);
3476            view.move_right(&MoveRight, cx);
3477            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ".len())]);
3478            view.move_right(&MoveRight, cx);
3479            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…".len())]);
3480
3481            view.move_down(&MoveDown, cx);
3482            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab…".len())]);
3483            view.move_left(&MoveLeft, cx);
3484            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab".len())]);
3485            view.move_left(&MoveLeft, cx);
3486            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "a".len())]);
3487
3488            view.move_down(&MoveDown, cx);
3489            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "α".len())]);
3490            view.move_right(&MoveRight, cx);
3491            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ".len())]);
3492            view.move_right(&MoveRight, cx);
3493            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ…".len())]);
3494            view.move_right(&MoveRight, cx);
3495            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ…ε".len())]);
3496
3497            view.move_up(&MoveUp, cx);
3498            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab…e".len())]);
3499            view.move_up(&MoveUp, cx);
3500            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…ⓔ".len())]);
3501            view.move_left(&MoveLeft, cx);
3502            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…".len())]);
3503            view.move_left(&MoveLeft, cx);
3504            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ".len())]);
3505            view.move_left(&MoveLeft, cx);
3506            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "".len())]);
3507        });
3508    }
3509
3510    #[gpui::test]
3511    fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
3512        let buffer = cx.add_model(|cx| Buffer::new(0, "ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx));
3513        let settings = EditorSettings::test(&cx);
3514        let (_, view) = cx.add_window(Default::default(), |cx| {
3515            build_editor(buffer.clone(), settings, cx)
3516        });
3517        view.update(cx, |view, cx| {
3518            view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx)
3519                .unwrap();
3520
3521            view.move_down(&MoveDown, cx);
3522            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "abcd".len())]);
3523
3524            view.move_down(&MoveDown, cx);
3525            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβγ".len())]);
3526
3527            view.move_down(&MoveDown, cx);
3528            assert_eq!(view.selection_ranges(cx), &[empty_range(3, "abcd".len())]);
3529
3530            view.move_down(&MoveDown, cx);
3531            assert_eq!(view.selection_ranges(cx), &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]);
3532
3533            view.move_up(&MoveUp, cx);
3534            assert_eq!(view.selection_ranges(cx), &[empty_range(3, "abcd".len())]);
3535
3536            view.move_up(&MoveUp, cx);
3537            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβγ".len())]);
3538        });
3539    }
3540
3541    #[gpui::test]
3542    fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
3543        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\n  def", cx));
3544        let settings = EditorSettings::test(&cx);
3545        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3546        view.update(cx, |view, cx| {
3547            view.select_display_ranges(
3548                &[
3549                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
3550                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
3551                ],
3552                cx,
3553            )
3554            .unwrap();
3555        });
3556
3557        view.update(cx, |view, cx| {
3558            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
3559            assert_eq!(
3560                view.selection_ranges(cx),
3561                &[
3562                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3563                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
3564                ]
3565            );
3566        });
3567
3568        view.update(cx, |view, cx| {
3569            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
3570            assert_eq!(
3571                view.selection_ranges(cx),
3572                &[
3573                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3574                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3575                ]
3576            );
3577        });
3578
3579        view.update(cx, |view, cx| {
3580            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
3581            assert_eq!(
3582                view.selection_ranges(cx),
3583                &[
3584                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3585                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
3586                ]
3587            );
3588        });
3589
3590        view.update(cx, |view, cx| {
3591            view.move_to_end_of_line(&MoveToEndOfLine, cx);
3592            assert_eq!(
3593                view.selection_ranges(cx),
3594                &[
3595                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
3596                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
3597                ]
3598            );
3599        });
3600
3601        // Moving to the end of line again is a no-op.
3602        view.update(cx, |view, cx| {
3603            view.move_to_end_of_line(&MoveToEndOfLine, cx);
3604            assert_eq!(
3605                view.selection_ranges(cx),
3606                &[
3607                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
3608                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
3609                ]
3610            );
3611        });
3612
3613        view.update(cx, |view, cx| {
3614            view.move_left(&MoveLeft, cx);
3615            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
3616            assert_eq!(
3617                view.selection_ranges(cx),
3618                &[
3619                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
3620                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
3621                ]
3622            );
3623        });
3624
3625        view.update(cx, |view, cx| {
3626            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
3627            assert_eq!(
3628                view.selection_ranges(cx),
3629                &[
3630                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
3631                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
3632                ]
3633            );
3634        });
3635
3636        view.update(cx, |view, cx| {
3637            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
3638            assert_eq!(
3639                view.selection_ranges(cx),
3640                &[
3641                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
3642                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
3643                ]
3644            );
3645        });
3646
3647        view.update(cx, |view, cx| {
3648            view.select_to_end_of_line(&SelectToEndOfLine, cx);
3649            assert_eq!(
3650                view.selection_ranges(cx),
3651                &[
3652                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
3653                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
3654                ]
3655            );
3656        });
3657
3658        view.update(cx, |view, cx| {
3659            view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
3660            assert_eq!(view.display_text(cx), "ab\n  de");
3661            assert_eq!(
3662                view.selection_ranges(cx),
3663                &[
3664                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3665                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
3666                ]
3667            );
3668        });
3669
3670        view.update(cx, |view, cx| {
3671            view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
3672            assert_eq!(view.display_text(cx), "\n");
3673            assert_eq!(
3674                view.selection_ranges(cx),
3675                &[
3676                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3677                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3678                ]
3679            );
3680        });
3681    }
3682
3683    #[gpui::test]
3684    fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
3685        let buffer =
3686            cx.add_model(|cx| Buffer::new(0, "use std::str::{foo, bar}\n\n  {baz.qux()}", cx));
3687        let settings = EditorSettings::test(&cx);
3688        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3689        view.update(cx, |view, cx| {
3690            view.select_display_ranges(
3691                &[
3692                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
3693                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
3694                ],
3695                cx,
3696            )
3697            .unwrap();
3698        });
3699
3700        view.update(cx, |view, cx| {
3701            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3702            assert_eq!(
3703                view.selection_ranges(cx),
3704                &[
3705                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
3706                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
3707                ]
3708            );
3709        });
3710
3711        view.update(cx, |view, cx| {
3712            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3713            assert_eq!(
3714                view.selection_ranges(cx),
3715                &[
3716                    DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
3717                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
3718                ]
3719            );
3720        });
3721
3722        view.update(cx, |view, cx| {
3723            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3724            assert_eq!(
3725                view.selection_ranges(cx),
3726                &[
3727                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
3728                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
3729                ]
3730            );
3731        });
3732
3733        view.update(cx, |view, cx| {
3734            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3735            assert_eq!(
3736                view.selection_ranges(cx),
3737                &[
3738                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3739                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3740                ]
3741            );
3742        });
3743
3744        view.update(cx, |view, cx| {
3745            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3746            assert_eq!(
3747                view.selection_ranges(cx),
3748                &[
3749                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3750                    DisplayPoint::new(0, 23)..DisplayPoint::new(0, 23),
3751                ]
3752            );
3753        });
3754
3755        view.update(cx, |view, cx| {
3756            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3757            assert_eq!(
3758                view.selection_ranges(cx),
3759                &[
3760                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
3761                    DisplayPoint::new(0, 24)..DisplayPoint::new(0, 24),
3762                ]
3763            );
3764        });
3765
3766        view.update(cx, |view, cx| {
3767            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3768            assert_eq!(
3769                view.selection_ranges(cx),
3770                &[
3771                    DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
3772                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3773                ]
3774            );
3775        });
3776
3777        view.update(cx, |view, cx| {
3778            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3779            assert_eq!(
3780                view.selection_ranges(cx),
3781                &[
3782                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
3783                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
3784                ]
3785            );
3786        });
3787
3788        view.update(cx, |view, cx| {
3789            view.move_right(&MoveRight, cx);
3790            view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
3791            assert_eq!(
3792                view.selection_ranges(cx),
3793                &[
3794                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
3795                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
3796                ]
3797            );
3798        });
3799
3800        view.update(cx, |view, cx| {
3801            view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
3802            assert_eq!(
3803                view.selection_ranges(cx),
3804                &[
3805                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 7),
3806                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 2),
3807                ]
3808            );
3809        });
3810
3811        view.update(cx, |view, cx| {
3812            view.select_to_next_word_boundary(&SelectToNextWordBoundary, cx);
3813            assert_eq!(
3814                view.selection_ranges(cx),
3815                &[
3816                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
3817                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
3818                ]
3819            );
3820        });
3821    }
3822
3823    #[gpui::test]
3824    fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
3825        let buffer =
3826            cx.add_model(|cx| Buffer::new(0, "use one::{\n    two::three::four::five\n};", cx));
3827        let settings = EditorSettings::test(&cx);
3828        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3829
3830        view.update(cx, |view, cx| {
3831            view.set_wrap_width(140., cx);
3832            assert_eq!(
3833                view.display_text(cx),
3834                "use one::{\n    two::three::\n    four::five\n};"
3835            );
3836
3837            view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx)
3838                .unwrap();
3839
3840            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3841            assert_eq!(
3842                view.selection_ranges(cx),
3843                &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
3844            );
3845
3846            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3847            assert_eq!(
3848                view.selection_ranges(cx),
3849                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
3850            );
3851
3852            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3853            assert_eq!(
3854                view.selection_ranges(cx),
3855                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
3856            );
3857
3858            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3859            assert_eq!(
3860                view.selection_ranges(cx),
3861                &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
3862            );
3863
3864            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3865            assert_eq!(
3866                view.selection_ranges(cx),
3867                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
3868            );
3869
3870            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3871            assert_eq!(
3872                view.selection_ranges(cx),
3873                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
3874            );
3875        });
3876    }
3877
3878    #[gpui::test]
3879    fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
3880        let buffer = cx.add_model(|cx| Buffer::new(0, "one two three four", cx));
3881        let settings = EditorSettings::test(&cx);
3882        let (_, view) = cx.add_window(Default::default(), |cx| {
3883            build_editor(buffer.clone(), settings, cx)
3884        });
3885
3886        view.update(cx, |view, cx| {
3887            view.select_display_ranges(
3888                &[
3889                    // an empty selection - the preceding word fragment is deleted
3890                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3891                    // characters selected - they are deleted
3892                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
3893                ],
3894                cx,
3895            )
3896            .unwrap();
3897            view.delete_to_previous_word_boundary(&DeleteToPreviousWordBoundary, cx);
3898        });
3899
3900        assert_eq!(buffer.read(cx).text(), "e two te four");
3901
3902        view.update(cx, |view, cx| {
3903            view.select_display_ranges(
3904                &[
3905                    // an empty selection - the following word fragment is deleted
3906                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
3907                    // characters selected - they are deleted
3908                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
3909                ],
3910                cx,
3911            )
3912            .unwrap();
3913            view.delete_to_next_word_boundary(&DeleteToNextWordBoundary, cx);
3914        });
3915
3916        assert_eq!(buffer.read(cx).text(), "e t te our");
3917    }
3918
3919    #[gpui::test]
3920    fn test_newline(cx: &mut gpui::MutableAppContext) {
3921        let buffer = cx.add_model(|cx| Buffer::new(0, "aaaa\n    bbbb\n", cx));
3922        let settings = EditorSettings::test(&cx);
3923        let (_, view) = cx.add_window(Default::default(), |cx| {
3924            build_editor(buffer.clone(), settings, cx)
3925        });
3926
3927        view.update(cx, |view, cx| {
3928            view.select_display_ranges(
3929                &[
3930                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3931                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
3932                    DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
3933                ],
3934                cx,
3935            )
3936            .unwrap();
3937
3938            view.newline(&Newline, cx);
3939            assert_eq!(view.text(cx), "aa\naa\n  \n    bb\n    bb\n");
3940        });
3941    }
3942
3943    #[gpui::test]
3944    fn test_backspace(cx: &mut gpui::MutableAppContext) {
3945        let buffer = cx.add_model(|cx| {
3946            Buffer::new(
3947                0,
3948                "one two three\nfour five six\nseven eight nine\nten\n",
3949                cx,
3950            )
3951        });
3952        let settings = EditorSettings::test(&cx);
3953        let (_, view) = cx.add_window(Default::default(), |cx| {
3954            build_editor(buffer.clone(), settings, cx)
3955        });
3956
3957        view.update(cx, |view, cx| {
3958            view.select_display_ranges(
3959                &[
3960                    // an empty selection - the preceding character is deleted
3961                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3962                    // one character selected - it is deleted
3963                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
3964                    // a line suffix selected - it is deleted
3965                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
3966                ],
3967                cx,
3968            )
3969            .unwrap();
3970            view.backspace(&Backspace, cx);
3971        });
3972
3973        assert_eq!(
3974            buffer.read(cx).text(),
3975            "oe two three\nfou five six\nseven ten\n"
3976        );
3977    }
3978
3979    #[gpui::test]
3980    fn test_delete(cx: &mut gpui::MutableAppContext) {
3981        let buffer = cx.add_model(|cx| {
3982            Buffer::new(
3983                0,
3984                "one two three\nfour five six\nseven eight nine\nten\n",
3985                cx,
3986            )
3987        });
3988        let settings = EditorSettings::test(&cx);
3989        let (_, view) = cx.add_window(Default::default(), |cx| {
3990            build_editor(buffer.clone(), settings, cx)
3991        });
3992
3993        view.update(cx, |view, cx| {
3994            view.select_display_ranges(
3995                &[
3996                    // an empty selection - the following character is deleted
3997                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3998                    // one character selected - it is deleted
3999                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4000                    // a line suffix selected - it is deleted
4001                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
4002                ],
4003                cx,
4004            )
4005            .unwrap();
4006            view.delete(&Delete, cx);
4007        });
4008
4009        assert_eq!(
4010            buffer.read(cx).text(),
4011            "on two three\nfou five six\nseven ten\n"
4012        );
4013    }
4014
4015    #[gpui::test]
4016    fn test_delete_line(cx: &mut gpui::MutableAppContext) {
4017        let settings = EditorSettings::test(&cx);
4018        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
4019        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4020        view.update(cx, |view, cx| {
4021            view.select_display_ranges(
4022                &[
4023                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4024                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
4025                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4026                ],
4027                cx,
4028            )
4029            .unwrap();
4030            view.delete_line(&DeleteLine, cx);
4031            assert_eq!(view.display_text(cx), "ghi");
4032            assert_eq!(
4033                view.selection_ranges(cx),
4034                vec![
4035                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4036                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
4037                ]
4038            );
4039        });
4040
4041        let settings = EditorSettings::test(&cx);
4042        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
4043        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4044        view.update(cx, |view, cx| {
4045            view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx)
4046                .unwrap();
4047            view.delete_line(&DeleteLine, cx);
4048            assert_eq!(view.display_text(cx), "ghi\n");
4049            assert_eq!(
4050                view.selection_ranges(cx),
4051                vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
4052            );
4053        });
4054    }
4055
4056    #[gpui::test]
4057    fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
4058        let settings = EditorSettings::test(&cx);
4059        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
4060        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4061        view.update(cx, |view, cx| {
4062            view.select_display_ranges(
4063                &[
4064                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
4065                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4066                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4067                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4068                ],
4069                cx,
4070            )
4071            .unwrap();
4072            view.duplicate_line(&DuplicateLine, cx);
4073            assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
4074            assert_eq!(
4075                view.selection_ranges(cx),
4076                vec![
4077                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
4078                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4079                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4080                    DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
4081                ]
4082            );
4083        });
4084
4085        let settings = EditorSettings::test(&cx);
4086        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
4087        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4088        view.update(cx, |view, cx| {
4089            view.select_display_ranges(
4090                &[
4091                    DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
4092                    DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
4093                ],
4094                cx,
4095            )
4096            .unwrap();
4097            view.duplicate_line(&DuplicateLine, cx);
4098            assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
4099            assert_eq!(
4100                view.selection_ranges(cx),
4101                vec![
4102                    DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
4103                    DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
4104                ]
4105            );
4106        });
4107    }
4108
4109    #[gpui::test]
4110    fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
4111        let settings = EditorSettings::test(&cx);
4112        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(10, 5), cx));
4113        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4114        view.update(cx, |view, cx| {
4115            view.fold_ranges(
4116                vec![
4117                    Point::new(0, 2)..Point::new(1, 2),
4118                    Point::new(2, 3)..Point::new(4, 1),
4119                    Point::new(7, 0)..Point::new(8, 4),
4120                ],
4121                cx,
4122            );
4123            view.select_display_ranges(
4124                &[
4125                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4126                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
4127                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
4128                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
4129                ],
4130                cx,
4131            )
4132            .unwrap();
4133            assert_eq!(
4134                view.display_text(cx),
4135                "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
4136            );
4137
4138            view.move_line_up(&MoveLineUp, cx);
4139            assert_eq!(
4140                view.display_text(cx),
4141                "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
4142            );
4143            assert_eq!(
4144                view.selection_ranges(cx),
4145                vec![
4146                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4147                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4148                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
4149                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
4150                ]
4151            );
4152        });
4153
4154        view.update(cx, |view, cx| {
4155            view.move_line_down(&MoveLineDown, cx);
4156            assert_eq!(
4157                view.display_text(cx),
4158                "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
4159            );
4160            assert_eq!(
4161                view.selection_ranges(cx),
4162                vec![
4163                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4164                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
4165                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
4166                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
4167                ]
4168            );
4169        });
4170
4171        view.update(cx, |view, cx| {
4172            view.move_line_down(&MoveLineDown, cx);
4173            assert_eq!(
4174                view.display_text(cx),
4175                "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
4176            );
4177            assert_eq!(
4178                view.selection_ranges(cx),
4179                vec![
4180                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4181                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
4182                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
4183                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
4184                ]
4185            );
4186        });
4187
4188        view.update(cx, |view, cx| {
4189            view.move_line_up(&MoveLineUp, cx);
4190            assert_eq!(
4191                view.display_text(cx),
4192                "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
4193            );
4194            assert_eq!(
4195                view.selection_ranges(cx),
4196                vec![
4197                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4198                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4199                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
4200                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
4201                ]
4202            );
4203        });
4204    }
4205
4206    #[gpui::test]
4207    fn test_clipboard(cx: &mut gpui::MutableAppContext) {
4208        let buffer = cx.add_model(|cx| Buffer::new(0, "one✅ two three four five six ", cx));
4209        let settings = EditorSettings::test(&cx);
4210        let view = cx
4211            .add_window(Default::default(), |cx| {
4212                build_editor(buffer.clone(), settings, cx)
4213            })
4214            .1;
4215
4216        // Cut with three selections. Clipboard text is divided into three slices.
4217        view.update(cx, |view, cx| {
4218            view.select_ranges(vec![0..7, 11..17, 22..27], false, cx);
4219            view.cut(&Cut, cx);
4220            assert_eq!(view.display_text(cx), "two four six ");
4221        });
4222
4223        // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
4224        view.update(cx, |view, cx| {
4225            view.select_ranges(vec![4..4, 9..9, 13..13], false, cx);
4226            view.paste(&Paste, cx);
4227            assert_eq!(view.display_text(cx), "two one✅ four three six five ");
4228            assert_eq!(
4229                view.selection_ranges(cx),
4230                &[
4231                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
4232                    DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
4233                    DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
4234                ]
4235            );
4236        });
4237
4238        // Paste again but with only two cursors. Since the number of cursors doesn't
4239        // match the number of slices in the clipboard, the entire clipboard text
4240        // is pasted at each cursor.
4241        view.update(cx, |view, cx| {
4242            view.select_ranges(vec![0..0, 31..31], false, cx);
4243            view.handle_input(&Input("( ".into()), cx);
4244            view.paste(&Paste, cx);
4245            view.handle_input(&Input(") ".into()), cx);
4246            assert_eq!(
4247                view.display_text(cx),
4248                "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
4249            );
4250        });
4251
4252        view.update(cx, |view, cx| {
4253            view.select_ranges(vec![0..0], false, cx);
4254            view.handle_input(&Input("123\n4567\n89\n".into()), cx);
4255            assert_eq!(
4256                view.display_text(cx),
4257                "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
4258            );
4259        });
4260
4261        // Cut with three selections, one of which is full-line.
4262        view.update(cx, |view, cx| {
4263            view.select_display_ranges(
4264                &[
4265                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
4266                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4267                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
4268                ],
4269                cx,
4270            )
4271            .unwrap();
4272            view.cut(&Cut, cx);
4273            assert_eq!(
4274                view.display_text(cx),
4275                "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
4276            );
4277        });
4278
4279        // Paste with three selections, noticing how the copied selection that was full-line
4280        // gets inserted before the second cursor.
4281        view.update(cx, |view, cx| {
4282            view.select_display_ranges(
4283                &[
4284                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4285                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4286                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
4287                ],
4288                cx,
4289            )
4290            .unwrap();
4291            view.paste(&Paste, cx);
4292            assert_eq!(
4293                view.display_text(cx),
4294                "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
4295            );
4296            assert_eq!(
4297                view.selection_ranges(cx),
4298                &[
4299                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4300                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4301                    DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
4302                ]
4303            );
4304        });
4305
4306        // Copy with a single cursor only, which writes the whole line into the clipboard.
4307        view.update(cx, |view, cx| {
4308            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx)
4309                .unwrap();
4310            view.copy(&Copy, cx);
4311        });
4312
4313        // Paste with three selections, noticing how the copied full-line selection is inserted
4314        // before the empty selections but replaces the selection that is non-empty.
4315        view.update(cx, |view, cx| {
4316            view.select_display_ranges(
4317                &[
4318                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4319                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
4320                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4321                ],
4322                cx,
4323            )
4324            .unwrap();
4325            view.paste(&Paste, cx);
4326            assert_eq!(
4327                view.display_text(cx),
4328                "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
4329            );
4330            assert_eq!(
4331                view.selection_ranges(cx),
4332                &[
4333                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4334                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4335                    DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
4336                ]
4337            );
4338        });
4339    }
4340
4341    #[gpui::test]
4342    fn test_select_all(cx: &mut gpui::MutableAppContext) {
4343        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\nde\nfgh", cx));
4344        let settings = EditorSettings::test(&cx);
4345        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4346        view.update(cx, |view, cx| {
4347            view.select_all(&SelectAll, cx);
4348            assert_eq!(
4349                view.selection_ranges(cx),
4350                &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
4351            );
4352        });
4353    }
4354
4355    #[gpui::test]
4356    fn test_select_line(cx: &mut gpui::MutableAppContext) {
4357        let settings = EditorSettings::test(&cx);
4358        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 5), cx));
4359        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4360        view.update(cx, |view, cx| {
4361            view.select_display_ranges(
4362                &[
4363                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
4364                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4365                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4366                    DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
4367                ],
4368                cx,
4369            )
4370            .unwrap();
4371            view.select_line(&SelectLine, cx);
4372            assert_eq!(
4373                view.selection_ranges(cx),
4374                vec![
4375                    DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
4376                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
4377                ]
4378            );
4379        });
4380
4381        view.update(cx, |view, cx| {
4382            view.select_line(&SelectLine, cx);
4383            assert_eq!(
4384                view.selection_ranges(cx),
4385                vec![
4386                    DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
4387                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
4388                ]
4389            );
4390        });
4391
4392        view.update(cx, |view, cx| {
4393            view.select_line(&SelectLine, cx);
4394            assert_eq!(
4395                view.selection_ranges(cx),
4396                vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
4397            );
4398        });
4399    }
4400
4401    #[gpui::test]
4402    fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
4403        let settings = EditorSettings::test(&cx);
4404        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(9, 5), cx));
4405        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4406        view.update(cx, |view, cx| {
4407            view.fold_ranges(
4408                vec![
4409                    Point::new(0, 2)..Point::new(1, 2),
4410                    Point::new(2, 3)..Point::new(4, 1),
4411                    Point::new(7, 0)..Point::new(8, 4),
4412                ],
4413                cx,
4414            );
4415            view.select_display_ranges(
4416                &[
4417                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
4418                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4419                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4420                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
4421                ],
4422                cx,
4423            )
4424            .unwrap();
4425            assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
4426        });
4427
4428        view.update(cx, |view, cx| {
4429            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
4430            assert_eq!(
4431                view.display_text(cx),
4432                "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
4433            );
4434            assert_eq!(
4435                view.selection_ranges(cx),
4436                [
4437                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4438                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4439                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
4440                    DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
4441                ]
4442            );
4443        });
4444
4445        view.update(cx, |view, cx| {
4446            view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx)
4447                .unwrap();
4448            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
4449            assert_eq!(
4450                view.display_text(cx),
4451                "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
4452            );
4453            assert_eq!(
4454                view.selection_ranges(cx),
4455                [
4456                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4457                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4458                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
4459                    DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
4460                    DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
4461                    DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
4462                    DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
4463                    DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
4464                ]
4465            );
4466        });
4467    }
4468
4469    #[gpui::test]
4470    fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
4471        let settings = EditorSettings::test(&cx);
4472        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndefghi\n\njk\nlmno\n", cx));
4473        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4474
4475        view.update(cx, |view, cx| {
4476            view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx)
4477                .unwrap();
4478        });
4479        view.update(cx, |view, cx| {
4480            view.add_selection_above(&AddSelectionAbove, cx);
4481            assert_eq!(
4482                view.selection_ranges(cx),
4483                vec![
4484                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4485                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
4486                ]
4487            );
4488        });
4489
4490        view.update(cx, |view, cx| {
4491            view.add_selection_above(&AddSelectionAbove, cx);
4492            assert_eq!(
4493                view.selection_ranges(cx),
4494                vec![
4495                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4496                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
4497                ]
4498            );
4499        });
4500
4501        view.update(cx, |view, cx| {
4502            view.add_selection_below(&AddSelectionBelow, cx);
4503            assert_eq!(
4504                view.selection_ranges(cx),
4505                vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
4506            );
4507        });
4508
4509        view.update(cx, |view, cx| {
4510            view.add_selection_below(&AddSelectionBelow, cx);
4511            assert_eq!(
4512                view.selection_ranges(cx),
4513                vec![
4514                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
4515                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
4516                ]
4517            );
4518        });
4519
4520        view.update(cx, |view, cx| {
4521            view.add_selection_below(&AddSelectionBelow, cx);
4522            assert_eq!(
4523                view.selection_ranges(cx),
4524                vec![
4525                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
4526                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
4527                ]
4528            );
4529        });
4530
4531        view.update(cx, |view, cx| {
4532            view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx)
4533                .unwrap();
4534        });
4535        view.update(cx, |view, cx| {
4536            view.add_selection_below(&AddSelectionBelow, cx);
4537            assert_eq!(
4538                view.selection_ranges(cx),
4539                vec![
4540                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4541                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
4542                ]
4543            );
4544        });
4545
4546        view.update(cx, |view, cx| {
4547            view.add_selection_below(&AddSelectionBelow, cx);
4548            assert_eq!(
4549                view.selection_ranges(cx),
4550                vec![
4551                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4552                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
4553                ]
4554            );
4555        });
4556
4557        view.update(cx, |view, cx| {
4558            view.add_selection_above(&AddSelectionAbove, cx);
4559            assert_eq!(
4560                view.selection_ranges(cx),
4561                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
4562            );
4563        });
4564
4565        view.update(cx, |view, cx| {
4566            view.add_selection_above(&AddSelectionAbove, cx);
4567            assert_eq!(
4568                view.selection_ranges(cx),
4569                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
4570            );
4571        });
4572
4573        view.update(cx, |view, cx| {
4574            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx)
4575                .unwrap();
4576            view.add_selection_below(&AddSelectionBelow, cx);
4577            assert_eq!(
4578                view.selection_ranges(cx),
4579                vec![
4580                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
4581                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
4582                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
4583                ]
4584            );
4585        });
4586
4587        view.update(cx, |view, cx| {
4588            view.add_selection_below(&AddSelectionBelow, cx);
4589            assert_eq!(
4590                view.selection_ranges(cx),
4591                vec![
4592                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
4593                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
4594                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
4595                    DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
4596                ]
4597            );
4598        });
4599
4600        view.update(cx, |view, cx| {
4601            view.add_selection_above(&AddSelectionAbove, cx);
4602            assert_eq!(
4603                view.selection_ranges(cx),
4604                vec![
4605                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
4606                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
4607                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
4608                ]
4609            );
4610        });
4611
4612        view.update(cx, |view, cx| {
4613            view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx)
4614                .unwrap();
4615        });
4616        view.update(cx, |view, cx| {
4617            view.add_selection_above(&AddSelectionAbove, cx);
4618            assert_eq!(
4619                view.selection_ranges(cx),
4620                vec![
4621                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
4622                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
4623                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
4624                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
4625                ]
4626            );
4627        });
4628
4629        view.update(cx, |view, cx| {
4630            view.add_selection_below(&AddSelectionBelow, cx);
4631            assert_eq!(
4632                view.selection_ranges(cx),
4633                vec![
4634                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
4635                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
4636                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
4637                ]
4638            );
4639        });
4640    }
4641
4642    #[gpui::test]
4643    async fn test_select_larger_smaller_syntax_node(mut cx: gpui::TestAppContext) {
4644        let settings = cx.read(EditorSettings::test);
4645        let language = Some(Arc::new(Language::new(
4646            LanguageConfig::default(),
4647            tree_sitter_rust::language(),
4648        )));
4649
4650        let text = r#"
4651            use mod1::mod2::{mod3, mod4};
4652
4653            fn fn_1(param1: bool, param2: &str) {
4654                let var1 = "text";
4655            }
4656        "#
4657        .unindent();
4658
4659        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
4660        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
4661        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing())
4662            .await;
4663
4664        view.update(&mut cx, |view, cx| {
4665            view.select_display_ranges(
4666                &[
4667                    DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
4668                    DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
4669                    DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
4670                ],
4671                cx,
4672            )
4673            .unwrap();
4674            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4675        });
4676        assert_eq!(
4677            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4678            &[
4679                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
4680                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
4681                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
4682            ]
4683        );
4684
4685        view.update(&mut cx, |view, cx| {
4686            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4687        });
4688        assert_eq!(
4689            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4690            &[
4691                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
4692                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
4693            ]
4694        );
4695
4696        view.update(&mut cx, |view, cx| {
4697            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4698        });
4699        assert_eq!(
4700            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4701            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
4702        );
4703
4704        // Trying to expand the selected syntax node one more time has no effect.
4705        view.update(&mut cx, |view, cx| {
4706            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4707        });
4708        assert_eq!(
4709            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4710            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
4711        );
4712
4713        view.update(&mut cx, |view, cx| {
4714            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
4715        });
4716        assert_eq!(
4717            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4718            &[
4719                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
4720                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
4721            ]
4722        );
4723
4724        view.update(&mut cx, |view, cx| {
4725            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
4726        });
4727        assert_eq!(
4728            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4729            &[
4730                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
4731                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
4732                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
4733            ]
4734        );
4735
4736        view.update(&mut cx, |view, cx| {
4737            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
4738        });
4739        assert_eq!(
4740            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4741            &[
4742                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
4743                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
4744                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
4745            ]
4746        );
4747
4748        // Trying to shrink the selected syntax node one more time has no effect.
4749        view.update(&mut cx, |view, cx| {
4750            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
4751        });
4752        assert_eq!(
4753            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4754            &[
4755                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
4756                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
4757                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
4758            ]
4759        );
4760
4761        // Ensure that we keep expanding the selection if the larger selection starts or ends within
4762        // a fold.
4763        view.update(&mut cx, |view, cx| {
4764            view.fold_ranges(
4765                vec![
4766                    Point::new(0, 21)..Point::new(0, 24),
4767                    Point::new(3, 20)..Point::new(3, 22),
4768                ],
4769                cx,
4770            );
4771            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4772        });
4773        assert_eq!(
4774            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4775            &[
4776                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
4777                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
4778                DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
4779            ]
4780        );
4781    }
4782
4783    #[gpui::test]
4784    async fn test_autoclose_pairs(mut cx: gpui::TestAppContext) {
4785        let settings = cx.read(EditorSettings::test);
4786        let language = Some(Arc::new(Language::new(
4787            LanguageConfig {
4788                brackets: vec![
4789                    BracketPair {
4790                        start: "{".to_string(),
4791                        end: "}".to_string(),
4792                        close: true,
4793                        newline: true,
4794                    },
4795                    BracketPair {
4796                        start: "/*".to_string(),
4797                        end: " */".to_string(),
4798                        close: true,
4799                        newline: true,
4800                    },
4801                ],
4802                ..Default::default()
4803            },
4804            tree_sitter_rust::language(),
4805        )));
4806
4807        let text = r#"
4808            a
4809
4810            /
4811
4812        "#
4813        .unindent();
4814
4815        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
4816        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
4817        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing())
4818            .await;
4819
4820        view.update(&mut cx, |view, cx| {
4821            view.select_display_ranges(
4822                &[
4823                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
4824                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4825                ],
4826                cx,
4827            )
4828            .unwrap();
4829            view.handle_input(&Input("{".to_string()), cx);
4830            view.handle_input(&Input("{".to_string()), cx);
4831            view.handle_input(&Input("{".to_string()), cx);
4832            assert_eq!(
4833                view.text(cx),
4834                "
4835                {{{}}}
4836                {{{}}}
4837                /
4838
4839                "
4840                .unindent()
4841            );
4842
4843            view.move_right(&MoveRight, cx);
4844            view.handle_input(&Input("}".to_string()), cx);
4845            view.handle_input(&Input("}".to_string()), cx);
4846            view.handle_input(&Input("}".to_string()), cx);
4847            assert_eq!(
4848                view.text(cx),
4849                "
4850                {{{}}}}
4851                {{{}}}}
4852                /
4853
4854                "
4855                .unindent()
4856            );
4857
4858            view.undo(&Undo, cx);
4859            view.handle_input(&Input("/".to_string()), cx);
4860            view.handle_input(&Input("*".to_string()), cx);
4861            assert_eq!(
4862                view.text(cx),
4863                "
4864                /* */
4865                /* */
4866                /
4867
4868                "
4869                .unindent()
4870            );
4871
4872            view.undo(&Undo, cx);
4873            view.select_display_ranges(
4874                &[
4875                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4876                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4877                ],
4878                cx,
4879            )
4880            .unwrap();
4881            view.handle_input(&Input("*".to_string()), cx);
4882            assert_eq!(
4883                view.text(cx),
4884                "
4885                a
4886
4887                /*
4888                *
4889                "
4890                .unindent()
4891            );
4892        });
4893    }
4894
4895    #[gpui::test]
4896    async fn test_extra_newline_insertion(mut cx: gpui::TestAppContext) {
4897        let settings = cx.read(EditorSettings::test);
4898        let language = Some(Arc::new(Language::new(
4899            LanguageConfig {
4900                brackets: vec![
4901                    BracketPair {
4902                        start: "{".to_string(),
4903                        end: "}".to_string(),
4904                        close: true,
4905                        newline: true,
4906                    },
4907                    BracketPair {
4908                        start: "/* ".to_string(),
4909                        end: " */".to_string(),
4910                        close: true,
4911                        newline: true,
4912                    },
4913                ],
4914                ..Default::default()
4915            },
4916            tree_sitter_rust::language(),
4917        )));
4918
4919        let text = concat!(
4920            "{   }\n",     // Suppress rustfmt
4921            "  x\n",       //
4922            "  /*   */\n", //
4923            "x\n",         //
4924            "{{} }\n",     //
4925        );
4926
4927        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
4928        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
4929        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing())
4930            .await;
4931
4932        view.update(&mut cx, |view, cx| {
4933            view.select_display_ranges(
4934                &[
4935                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
4936                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
4937                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
4938                ],
4939                cx,
4940            )
4941            .unwrap();
4942            view.newline(&Newline, cx);
4943
4944            assert_eq!(
4945                view.buffer().read(cx).text(),
4946                concat!(
4947                    "{ \n",    // Suppress rustfmt
4948                    "\n",      //
4949                    "}\n",     //
4950                    "  x\n",   //
4951                    "  /* \n", //
4952                    "  \n",    //
4953                    "  */\n",  //
4954                    "x\n",     //
4955                    "{{} \n",  //
4956                    "}\n",     //
4957                )
4958            );
4959        });
4960    }
4961
4962    impl Editor {
4963        fn selection_ranges(&self, cx: &mut MutableAppContext) -> Vec<Range<DisplayPoint>> {
4964            self.selections_in_range(
4965                self.selection_set_id,
4966                DisplayPoint::zero()..self.max_point(cx),
4967                cx,
4968            )
4969            .collect::<Vec<_>>()
4970        }
4971    }
4972
4973    fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
4974        let point = DisplayPoint::new(row as u32, column as u32);
4975        point..point
4976    }
4977
4978    fn build_editor(
4979        buffer: ModelHandle<Buffer>,
4980        settings: EditorSettings,
4981        cx: &mut ViewContext<Editor>,
4982    ) -> Editor {
4983        Editor::for_buffer(buffer, move |_| settings.clone(), cx)
4984    }
4985}
4986
4987trait RangeExt<T> {
4988    fn sorted(&self) -> Range<T>;
4989    fn to_inclusive(&self) -> RangeInclusive<T>;
4990}
4991
4992impl<T: Ord + Clone> RangeExt<T> for Range<T> {
4993    fn sorted(&self) -> Self {
4994        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
4995    }
4996
4997    fn to_inclusive(&self) -> RangeInclusive<T> {
4998        self.start.clone()..=self.end.clone()
4999    }
5000}