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