lib.rs

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