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