lib.rs

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