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