lib.rs

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