editor.rs

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