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