lib.rs

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