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 selections = self.local_selections::<Point>(cx);
1787        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1788        let buffer = self.buffer.read(cx).snapshot(cx);
1789
1790        let mut edits = Vec::new();
1791        let mut new_selection_ranges = Vec::new();
1792        let mut old_folds = Vec::new();
1793        let mut new_folds = Vec::new();
1794
1795        let mut selections = selections.iter().peekable();
1796        let mut contiguous_selections = Vec::new();
1797        while let Some(selection) = selections.next() {
1798            // Accumulate contiguous regions of rows that we want to move.
1799            contiguous_selections.push(selection.point_range(&buffer));
1800
1801            let SpannedRows {
1802                mut buffer_rows,
1803                mut display_rows,
1804            } = selection.spanned_rows(false, &display_map);
1805
1806            while let Some(next_selection) = selections.peek() {
1807                let SpannedRows {
1808                    buffer_rows: next_buffer_rows,
1809                    display_rows: next_display_rows,
1810                } = next_selection.spanned_rows(false, &display_map);
1811                if next_buffer_rows.start <= buffer_rows.end {
1812                    buffer_rows.end = next_buffer_rows.end;
1813                    display_rows.end = next_display_rows.end;
1814                    contiguous_selections.push(next_selection.point_range(&buffer));
1815                    selections.next().unwrap();
1816                } else {
1817                    break;
1818                }
1819            }
1820
1821            // Cut the text from the selected rows and paste it at the end of the next line.
1822            if display_rows.end <= display_map.max_point().row() {
1823                let start = Point::new(buffer_rows.start, 0).to_offset(&buffer);
1824                let end = Point::new(buffer_rows.end - 1, buffer.line_len(buffer_rows.end - 1))
1825                    .to_offset(&buffer);
1826
1827                let next_row_display_end =
1828                    DisplayPoint::new(display_rows.end, display_map.line_len(display_rows.end));
1829
1830                let next_row_buffer_end = display_map.next_row_boundary(next_row_display_end).1;
1831                let next_row_buffer_end_offset = next_row_buffer_end.to_offset(&buffer);
1832
1833                if buffer.range_contains_excerpt_boundary(start..next_row_buffer_end_offset) {
1834                    new_selection_ranges.extend(contiguous_selections.drain(..));
1835                    continue;
1836                }
1837
1838                let mut text = String::new();
1839                text.push('\n');
1840                text.extend(buffer.text_for_range(start..end));
1841                edits.push((start..end + 1, String::new()));
1842                edits.push((next_row_buffer_end_offset..next_row_buffer_end_offset, text));
1843
1844                // Move selections down.
1845                let display_row_delta = next_row_display_end.row() - display_rows.end + 1;
1846                for range in &mut contiguous_selections {
1847                    range.start.row += display_row_delta;
1848                    range.end.row += display_row_delta;
1849                }
1850
1851                // Move folds down.
1852                old_folds.push(start..end);
1853                let buffer_row_delta = next_row_buffer_end.row - buffer_rows.end + 1;
1854                for fold in display_map.folds_in_range(start..end) {
1855                    let mut start = fold.start.to_point(&buffer);
1856                    let mut end = fold.end.to_point(&buffer);
1857                    start.row += buffer_row_delta;
1858                    end.row += buffer_row_delta;
1859                    new_folds.push(start..end);
1860                }
1861            }
1862
1863            new_selection_ranges.extend(contiguous_selections.drain(..));
1864        }
1865
1866        self.start_transaction(cx);
1867        self.unfold_ranges(old_folds, cx);
1868        self.buffer.update(cx, |buffer, cx| {
1869            for (range, text) in edits.into_iter().rev() {
1870                buffer.edit(Some(range), text, cx);
1871            }
1872        });
1873        self.fold_ranges(new_folds, cx);
1874        self.select_ranges(new_selection_ranges, Some(Autoscroll::Fit), cx);
1875        self.end_transaction(cx);
1876    }
1877
1878    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
1879        self.start_transaction(cx);
1880        let mut text = String::new();
1881        let mut selections = self.local_selections::<Point>(cx);
1882        let mut clipboard_selections = Vec::with_capacity(selections.len());
1883        {
1884            let buffer = self.buffer.read(cx).read(cx);
1885            let max_point = buffer.max_point();
1886            for selection in &mut selections {
1887                let is_entire_line = selection.is_empty();
1888                if is_entire_line {
1889                    selection.start = Point::new(selection.start.row, 0);
1890                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
1891                }
1892                let mut len = 0;
1893                for chunk in buffer.text_for_range(selection.start..selection.end) {
1894                    text.push_str(chunk);
1895                    len += chunk.len();
1896                }
1897                clipboard_selections.push(ClipboardSelection {
1898                    len,
1899                    is_entire_line,
1900                });
1901            }
1902        }
1903        self.update_selections(selections, Some(Autoscroll::Fit), cx);
1904        self.insert("", cx);
1905        self.end_transaction(cx);
1906
1907        cx.as_mut()
1908            .write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
1909    }
1910
1911    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
1912        let selections = self.local_selections::<Point>(cx);
1913        let mut text = String::new();
1914        let mut clipboard_selections = Vec::with_capacity(selections.len());
1915        {
1916            let buffer = self.buffer.read(cx).read(cx);
1917            let max_point = buffer.max_point();
1918            for selection in selections.iter() {
1919                let mut start = selection.start;
1920                let mut end = selection.end;
1921                let is_entire_line = selection.is_empty();
1922                if is_entire_line {
1923                    start = Point::new(start.row, 0);
1924                    end = cmp::min(max_point, Point::new(start.row + 1, 0));
1925                }
1926                let mut len = 0;
1927                for chunk in buffer.text_for_range(start..end) {
1928                    text.push_str(chunk);
1929                    len += chunk.len();
1930                }
1931                clipboard_selections.push(ClipboardSelection {
1932                    len,
1933                    is_entire_line,
1934                });
1935            }
1936        }
1937
1938        cx.as_mut()
1939            .write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
1940    }
1941
1942    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
1943        if let Some(item) = cx.as_mut().read_from_clipboard() {
1944            let clipboard_text = item.text();
1945            if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
1946                let mut selections = self.local_selections::<usize>(cx);
1947                let all_selections_were_entire_line =
1948                    clipboard_selections.iter().all(|s| s.is_entire_line);
1949                if clipboard_selections.len() != selections.len() {
1950                    clipboard_selections.clear();
1951                }
1952
1953                let mut delta = 0_isize;
1954                let mut start_offset = 0;
1955                for (i, selection) in selections.iter_mut().enumerate() {
1956                    let to_insert;
1957                    let entire_line;
1958                    if let Some(clipboard_selection) = clipboard_selections.get(i) {
1959                        let end_offset = start_offset + clipboard_selection.len;
1960                        to_insert = &clipboard_text[start_offset..end_offset];
1961                        entire_line = clipboard_selection.is_entire_line;
1962                        start_offset = end_offset
1963                    } else {
1964                        to_insert = clipboard_text.as_str();
1965                        entire_line = all_selections_were_entire_line;
1966                    }
1967
1968                    selection.start = (selection.start as isize + delta) as usize;
1969                    selection.end = (selection.end as isize + delta) as usize;
1970
1971                    self.buffer.update(cx, |buffer, cx| {
1972                        // If the corresponding selection was empty when this slice of the
1973                        // clipboard text was written, then the entire line containing the
1974                        // selection was copied. If this selection is also currently empty,
1975                        // then paste the line before the current line of the buffer.
1976                        let range = if selection.is_empty() && entire_line {
1977                            let column = selection.start.to_point(&buffer.read(cx)).column as usize;
1978                            let line_start = selection.start - column;
1979                            line_start..line_start
1980                        } else {
1981                            selection.start..selection.end
1982                        };
1983
1984                        delta += to_insert.len() as isize - range.len() as isize;
1985                        buffer.edit([range], to_insert, cx);
1986                        selection.start += to_insert.len();
1987                        selection.end = selection.start;
1988                    });
1989                }
1990                self.update_selections(selections, Some(Autoscroll::Fit), cx);
1991            } else {
1992                self.insert(clipboard_text, cx);
1993            }
1994        }
1995    }
1996
1997    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
1998        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
1999            if let Some((selections, _)) = self.selection_history.get(&tx_id).cloned() {
2000                self.set_selections(selections, cx);
2001            }
2002            self.request_autoscroll(Autoscroll::Fit, cx);
2003        }
2004    }
2005
2006    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
2007        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
2008            if let Some((_, Some(selections))) = self.selection_history.get(&tx_id).cloned() {
2009                self.set_selections(selections, cx);
2010            }
2011            self.request_autoscroll(Autoscroll::Fit, cx);
2012        }
2013    }
2014
2015    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
2016        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2017        let mut selections = self.local_selections::<Point>(cx);
2018        for selection in &mut selections {
2019            let start = selection.start.to_display_point(&display_map);
2020            let end = selection.end.to_display_point(&display_map);
2021
2022            if start != end {
2023                selection.end = selection.start.clone();
2024            } else {
2025                let cursor = movement::left(&display_map, start)
2026                    .unwrap()
2027                    .to_point(&display_map);
2028                selection.start = cursor.clone();
2029                selection.end = cursor;
2030            }
2031            selection.reversed = false;
2032            selection.goal = SelectionGoal::None;
2033        }
2034        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2035    }
2036
2037    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
2038        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2039        let mut selections = self.local_selections::<Point>(cx);
2040        for selection in &mut selections {
2041            let head = selection.head().to_display_point(&display_map);
2042            let cursor = movement::left(&display_map, head)
2043                .unwrap()
2044                .to_point(&display_map);
2045            selection.set_head(cursor);
2046            selection.goal = SelectionGoal::None;
2047        }
2048        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2049    }
2050
2051    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
2052        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2053        let mut selections = self.local_selections::<Point>(cx);
2054        for selection in &mut selections {
2055            let start = selection.start.to_display_point(&display_map);
2056            let end = selection.end.to_display_point(&display_map);
2057
2058            if start != end {
2059                selection.start = selection.end.clone();
2060            } else {
2061                let cursor = movement::right(&display_map, end)
2062                    .unwrap()
2063                    .to_point(&display_map);
2064                selection.start = cursor;
2065                selection.end = cursor;
2066            }
2067            selection.reversed = false;
2068            selection.goal = SelectionGoal::None;
2069        }
2070        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2071    }
2072
2073    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
2074        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2075        let mut selections = self.local_selections::<Point>(cx);
2076        for selection in &mut selections {
2077            let head = selection.head().to_display_point(&display_map);
2078            let cursor = movement::right(&display_map, head)
2079                .unwrap()
2080                .to_point(&display_map);
2081            selection.set_head(cursor);
2082            selection.goal = SelectionGoal::None;
2083        }
2084        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2085    }
2086
2087    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
2088        if matches!(self.mode, EditorMode::SingleLine) {
2089            cx.propagate_action();
2090            return;
2091        }
2092
2093        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2094        let mut selections = self.local_selections::<Point>(cx);
2095        for selection in &mut selections {
2096            let start = selection.start.to_display_point(&display_map);
2097            let end = selection.end.to_display_point(&display_map);
2098            if start != end {
2099                selection.goal = SelectionGoal::None;
2100            }
2101
2102            let (start, goal) = movement::up(&display_map, start, selection.goal).unwrap();
2103            let cursor = start.to_point(&display_map);
2104            selection.start = cursor;
2105            selection.end = cursor;
2106            selection.goal = goal;
2107            selection.reversed = false;
2108        }
2109        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2110    }
2111
2112    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
2113        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2114        let mut selections = self.local_selections::<Point>(cx);
2115        for selection in &mut selections {
2116            let head = selection.head().to_display_point(&display_map);
2117            let (head, goal) = movement::up(&display_map, head, selection.goal).unwrap();
2118            let cursor = head.to_point(&display_map);
2119            selection.set_head(cursor);
2120            selection.goal = goal;
2121        }
2122        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2123    }
2124
2125    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
2126        if matches!(self.mode, EditorMode::SingleLine) {
2127            cx.propagate_action();
2128            return;
2129        }
2130
2131        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2132        let mut selections = self.local_selections::<Point>(cx);
2133        for selection in &mut selections {
2134            let start = selection.start.to_display_point(&display_map);
2135            let end = selection.end.to_display_point(&display_map);
2136            if start != end {
2137                selection.goal = SelectionGoal::None;
2138            }
2139
2140            let (start, goal) = movement::down(&display_map, end, selection.goal).unwrap();
2141            let cursor = start.to_point(&display_map);
2142            selection.start = cursor;
2143            selection.end = cursor;
2144            selection.goal = goal;
2145            selection.reversed = false;
2146        }
2147        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2148    }
2149
2150    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
2151        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2152        let mut selections = self.local_selections::<Point>(cx);
2153        for selection in &mut selections {
2154            let head = selection.head().to_display_point(&display_map);
2155            let (head, goal) = movement::down(&display_map, head, selection.goal).unwrap();
2156            let cursor = head.to_point(&display_map);
2157            selection.set_head(cursor);
2158            selection.goal = goal;
2159        }
2160        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2161    }
2162
2163    pub fn move_to_previous_word_boundary(
2164        &mut self,
2165        _: &MoveToPreviousWordBoundary,
2166        cx: &mut ViewContext<Self>,
2167    ) {
2168        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2169        let mut selections = self.local_selections::<Point>(cx);
2170        for selection in &mut selections {
2171            let head = selection.head().to_display_point(&display_map);
2172            let cursor = movement::prev_word_boundary(&display_map, head).to_point(&display_map);
2173            selection.start = cursor.clone();
2174            selection.end = cursor;
2175            selection.reversed = false;
2176            selection.goal = SelectionGoal::None;
2177        }
2178        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2179    }
2180
2181    pub fn select_to_previous_word_boundary(
2182        &mut self,
2183        _: &SelectToPreviousWordBoundary,
2184        cx: &mut ViewContext<Self>,
2185    ) {
2186        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2187        let mut selections = self.local_selections::<Point>(cx);
2188        for selection in &mut selections {
2189            let head = selection.head().to_display_point(&display_map);
2190            let cursor = movement::prev_word_boundary(&display_map, head).to_point(&display_map);
2191            selection.set_head(cursor);
2192            selection.goal = SelectionGoal::None;
2193        }
2194        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2195    }
2196
2197    pub fn delete_to_previous_word_boundary(
2198        &mut self,
2199        _: &DeleteToPreviousWordBoundary,
2200        cx: &mut ViewContext<Self>,
2201    ) {
2202        self.start_transaction(cx);
2203        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2204        let mut selections = self.local_selections::<Point>(cx);
2205        for selection in &mut selections {
2206            if selection.is_empty() {
2207                let head = selection.head().to_display_point(&display_map);
2208                let cursor =
2209                    movement::prev_word_boundary(&display_map, head).to_point(&display_map);
2210                selection.set_head(cursor);
2211                selection.goal = SelectionGoal::None;
2212            }
2213        }
2214        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2215        self.insert("", cx);
2216        self.end_transaction(cx);
2217    }
2218
2219    pub fn move_to_next_word_boundary(
2220        &mut self,
2221        _: &MoveToNextWordBoundary,
2222        cx: &mut ViewContext<Self>,
2223    ) {
2224        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2225        let mut selections = self.local_selections::<Point>(cx);
2226        for selection in &mut selections {
2227            let head = selection.head().to_display_point(&display_map);
2228            let cursor = movement::next_word_boundary(&display_map, head).to_point(&display_map);
2229            selection.start = cursor;
2230            selection.end = cursor;
2231            selection.reversed = false;
2232            selection.goal = SelectionGoal::None;
2233        }
2234        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2235    }
2236
2237    pub fn select_to_next_word_boundary(
2238        &mut self,
2239        _: &SelectToNextWordBoundary,
2240        cx: &mut ViewContext<Self>,
2241    ) {
2242        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2243        let mut selections = self.local_selections::<Point>(cx);
2244        for selection in &mut selections {
2245            let head = selection.head().to_display_point(&display_map);
2246            let cursor = movement::next_word_boundary(&display_map, head).to_point(&display_map);
2247            selection.set_head(cursor);
2248            selection.goal = SelectionGoal::None;
2249        }
2250        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2251    }
2252
2253    pub fn delete_to_next_word_boundary(
2254        &mut self,
2255        _: &DeleteToNextWordBoundary,
2256        cx: &mut ViewContext<Self>,
2257    ) {
2258        self.start_transaction(cx);
2259        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2260        let mut selections = self.local_selections::<Point>(cx);
2261        for selection in &mut selections {
2262            if selection.is_empty() {
2263                let head = selection.head().to_display_point(&display_map);
2264                let cursor =
2265                    movement::next_word_boundary(&display_map, head).to_point(&display_map);
2266                selection.set_head(cursor);
2267                selection.goal = SelectionGoal::None;
2268            }
2269        }
2270        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2271        self.insert("", cx);
2272        self.end_transaction(cx);
2273    }
2274
2275    pub fn move_to_beginning_of_line(
2276        &mut self,
2277        _: &MoveToBeginningOfLine,
2278        cx: &mut ViewContext<Self>,
2279    ) {
2280        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2281        let mut selections = self.local_selections::<Point>(cx);
2282        for selection in &mut selections {
2283            let head = selection.head().to_display_point(&display_map);
2284            let new_head = movement::line_beginning(&display_map, head, true);
2285            let cursor = new_head.to_point(&display_map);
2286            selection.start = cursor;
2287            selection.end = cursor;
2288            selection.reversed = false;
2289            selection.goal = SelectionGoal::None;
2290        }
2291        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2292    }
2293
2294    pub fn select_to_beginning_of_line(
2295        &mut self,
2296        SelectToBeginningOfLine(toggle_indent): &SelectToBeginningOfLine,
2297        cx: &mut ViewContext<Self>,
2298    ) {
2299        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2300        let mut selections = self.local_selections::<Point>(cx);
2301        for selection in &mut selections {
2302            let head = selection.head().to_display_point(&display_map);
2303            let new_head = movement::line_beginning(&display_map, head, *toggle_indent);
2304            selection.set_head(new_head.to_point(&display_map));
2305            selection.goal = SelectionGoal::None;
2306        }
2307        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2308    }
2309
2310    pub fn delete_to_beginning_of_line(
2311        &mut self,
2312        _: &DeleteToBeginningOfLine,
2313        cx: &mut ViewContext<Self>,
2314    ) {
2315        self.start_transaction(cx);
2316        self.select_to_beginning_of_line(&SelectToBeginningOfLine(false), cx);
2317        self.backspace(&Backspace, cx);
2318        self.end_transaction(cx);
2319    }
2320
2321    pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
2322        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2323        let mut selections = self.local_selections::<Point>(cx);
2324        {
2325            for selection in &mut selections {
2326                let head = selection.head().to_display_point(&display_map);
2327                let new_head = movement::line_end(&display_map, head);
2328                let anchor = new_head.to_point(&display_map);
2329                selection.start = anchor.clone();
2330                selection.end = anchor;
2331                selection.reversed = false;
2332                selection.goal = SelectionGoal::None;
2333            }
2334        }
2335        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2336    }
2337
2338    pub fn select_to_end_of_line(&mut self, _: &SelectToEndOfLine, cx: &mut ViewContext<Self>) {
2339        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2340        let mut selections = self.local_selections::<Point>(cx);
2341        for selection in &mut selections {
2342            let head = selection.head().to_display_point(&display_map);
2343            let new_head = movement::line_end(&display_map, head);
2344            selection.set_head(new_head.to_point(&display_map));
2345            selection.goal = SelectionGoal::None;
2346        }
2347        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2348    }
2349
2350    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
2351        self.start_transaction(cx);
2352        self.select_to_end_of_line(&SelectToEndOfLine, cx);
2353        self.delete(&Delete, cx);
2354        self.end_transaction(cx);
2355    }
2356
2357    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
2358        self.start_transaction(cx);
2359        self.select_to_end_of_line(&SelectToEndOfLine, cx);
2360        self.cut(&Cut, cx);
2361        self.end_transaction(cx);
2362    }
2363
2364    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
2365        let selection = Selection {
2366            id: post_inc(&mut self.next_selection_id),
2367            start: 0,
2368            end: 0,
2369            reversed: false,
2370            goal: SelectionGoal::None,
2371        };
2372        self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2373    }
2374
2375    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
2376        let mut selection = self.local_selections::<Point>(cx).last().unwrap().clone();
2377        selection.set_head(Point::zero());
2378        self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2379    }
2380
2381    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
2382        let cursor = self.buffer.read(cx).read(cx).len();
2383        let selection = Selection {
2384            id: post_inc(&mut self.next_selection_id),
2385            start: cursor,
2386            end: cursor,
2387            reversed: false,
2388            goal: SelectionGoal::None,
2389        };
2390        self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2391    }
2392
2393    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
2394        let mut selection = self.local_selections::<usize>(cx).first().unwrap().clone();
2395        selection.set_head(self.buffer.read(cx).read(cx).len());
2396        self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2397    }
2398
2399    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
2400        let selection = Selection {
2401            id: post_inc(&mut self.next_selection_id),
2402            start: 0,
2403            end: self.buffer.read(cx).read(cx).len(),
2404            reversed: false,
2405            goal: SelectionGoal::None,
2406        };
2407        self.update_selections(vec![selection], None, cx);
2408    }
2409
2410    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
2411        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2412        let mut selections = self.local_selections::<Point>(cx);
2413        let max_point = display_map.buffer_snapshot.max_point();
2414        for selection in &mut selections {
2415            let rows = selection.spanned_rows(true, &display_map).buffer_rows;
2416            selection.start = Point::new(rows.start, 0);
2417            selection.end = cmp::min(max_point, Point::new(rows.end, 0));
2418            selection.reversed = false;
2419        }
2420        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2421    }
2422
2423    pub fn split_selection_into_lines(
2424        &mut self,
2425        _: &SplitSelectionIntoLines,
2426        cx: &mut ViewContext<Self>,
2427    ) {
2428        let mut to_unfold = Vec::new();
2429        let mut new_selections = Vec::new();
2430        {
2431            let selections = self.local_selections::<Point>(cx);
2432            let buffer = self.buffer.read(cx).read(cx);
2433            for selection in selections {
2434                for row in selection.start.row..selection.end.row {
2435                    let cursor = Point::new(row, buffer.line_len(row));
2436                    new_selections.push(Selection {
2437                        id: post_inc(&mut self.next_selection_id),
2438                        start: cursor,
2439                        end: cursor,
2440                        reversed: false,
2441                        goal: SelectionGoal::None,
2442                    });
2443                }
2444                new_selections.push(Selection {
2445                    id: selection.id,
2446                    start: selection.end,
2447                    end: selection.end,
2448                    reversed: false,
2449                    goal: SelectionGoal::None,
2450                });
2451                to_unfold.push(selection.start..selection.end);
2452            }
2453        }
2454        self.unfold_ranges(to_unfold, cx);
2455        self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2456    }
2457
2458    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
2459        self.add_selection(true, cx);
2460    }
2461
2462    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
2463        self.add_selection(false, cx);
2464    }
2465
2466    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
2467        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2468        let mut selections = self.local_selections::<Point>(cx);
2469        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
2470            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
2471            let range = oldest_selection.display_range(&display_map).sorted();
2472            let columns = cmp::min(range.start.column(), range.end.column())
2473                ..cmp::max(range.start.column(), range.end.column());
2474
2475            selections.clear();
2476            let mut stack = Vec::new();
2477            for row in range.start.row()..=range.end.row() {
2478                if let Some(selection) = self.build_columnar_selection(
2479                    &display_map,
2480                    row,
2481                    &columns,
2482                    oldest_selection.reversed,
2483                ) {
2484                    stack.push(selection.id);
2485                    selections.push(selection);
2486                }
2487            }
2488
2489            if above {
2490                stack.reverse();
2491            }
2492
2493            AddSelectionsState { above, stack }
2494        });
2495
2496        let last_added_selection = *state.stack.last().unwrap();
2497        let mut new_selections = Vec::new();
2498        if above == state.above {
2499            let end_row = if above {
2500                0
2501            } else {
2502                display_map.max_point().row()
2503            };
2504
2505            'outer: for selection in selections {
2506                if selection.id == last_added_selection {
2507                    let range = selection.display_range(&display_map).sorted();
2508                    debug_assert_eq!(range.start.row(), range.end.row());
2509                    let mut row = range.start.row();
2510                    let columns = if let SelectionGoal::ColumnRange { start, end } = selection.goal
2511                    {
2512                        start..end
2513                    } else {
2514                        cmp::min(range.start.column(), range.end.column())
2515                            ..cmp::max(range.start.column(), range.end.column())
2516                    };
2517
2518                    while row != end_row {
2519                        if above {
2520                            row -= 1;
2521                        } else {
2522                            row += 1;
2523                        }
2524
2525                        if let Some(new_selection) = self.build_columnar_selection(
2526                            &display_map,
2527                            row,
2528                            &columns,
2529                            selection.reversed,
2530                        ) {
2531                            state.stack.push(new_selection.id);
2532                            if above {
2533                                new_selections.push(new_selection);
2534                                new_selections.push(selection);
2535                            } else {
2536                                new_selections.push(selection);
2537                                new_selections.push(new_selection);
2538                            }
2539
2540                            continue 'outer;
2541                        }
2542                    }
2543                }
2544
2545                new_selections.push(selection);
2546            }
2547        } else {
2548            new_selections = selections;
2549            new_selections.retain(|s| s.id != last_added_selection);
2550            state.stack.pop();
2551        }
2552
2553        self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2554        if state.stack.len() > 1 {
2555            self.add_selections_state = Some(state);
2556        }
2557    }
2558
2559    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) {
2560        let replace_newest = action.0;
2561        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2562        let buffer = &display_map.buffer_snapshot;
2563        let mut selections = self.local_selections::<usize>(cx);
2564        if let Some(mut select_next_state) = self.select_next_state.take() {
2565            let query = &select_next_state.query;
2566            if !select_next_state.done {
2567                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
2568                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
2569                let mut next_selected_range = None;
2570
2571                let bytes_after_last_selection =
2572                    buffer.bytes_in_range(last_selection.end..buffer.len());
2573                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
2574                let query_matches = query
2575                    .stream_find_iter(bytes_after_last_selection)
2576                    .map(|result| (last_selection.end, result))
2577                    .chain(
2578                        query
2579                            .stream_find_iter(bytes_before_first_selection)
2580                            .map(|result| (0, result)),
2581                    );
2582                for (start_offset, query_match) in query_matches {
2583                    let query_match = query_match.unwrap(); // can only fail due to I/O
2584                    let offset_range =
2585                        start_offset + query_match.start()..start_offset + query_match.end();
2586                    let display_range = offset_range.start.to_display_point(&display_map)
2587                        ..offset_range.end.to_display_point(&display_map);
2588
2589                    if !select_next_state.wordwise
2590                        || (!movement::is_inside_word(&display_map, display_range.start)
2591                            && !movement::is_inside_word(&display_map, display_range.end))
2592                    {
2593                        next_selected_range = Some(offset_range);
2594                        break;
2595                    }
2596                }
2597
2598                if let Some(next_selected_range) = next_selected_range {
2599                    if replace_newest {
2600                        if let Some(newest_id) =
2601                            selections.iter().max_by_key(|s| s.id).map(|s| s.id)
2602                        {
2603                            selections.retain(|s| s.id != newest_id);
2604                        }
2605                    }
2606                    selections.push(Selection {
2607                        id: post_inc(&mut self.next_selection_id),
2608                        start: next_selected_range.start,
2609                        end: next_selected_range.end,
2610                        reversed: false,
2611                        goal: SelectionGoal::None,
2612                    });
2613                    selections.sort_unstable_by_key(|s| s.start);
2614                    self.update_selections(selections, Some(Autoscroll::Newest), cx);
2615                } else {
2616                    select_next_state.done = true;
2617                }
2618            }
2619
2620            self.select_next_state = Some(select_next_state);
2621        } else if selections.len() == 1 {
2622            let selection = selections.last_mut().unwrap();
2623            if selection.start == selection.end {
2624                let word_range = movement::surrounding_word(
2625                    &display_map,
2626                    selection.start.to_display_point(&display_map),
2627                );
2628                selection.start = word_range.start.to_offset(&display_map, Bias::Left);
2629                selection.end = word_range.end.to_offset(&display_map, Bias::Left);
2630                selection.goal = SelectionGoal::None;
2631                selection.reversed = false;
2632
2633                let query = buffer
2634                    .text_for_range(selection.start..selection.end)
2635                    .collect::<String>();
2636                let select_state = SelectNextState {
2637                    query: AhoCorasick::new_auto_configured(&[query]),
2638                    wordwise: true,
2639                    done: false,
2640                };
2641                self.update_selections(selections, Some(Autoscroll::Newest), cx);
2642                self.select_next_state = Some(select_state);
2643            } else {
2644                let query = buffer
2645                    .text_for_range(selection.start..selection.end)
2646                    .collect::<String>();
2647                self.select_next_state = Some(SelectNextState {
2648                    query: AhoCorasick::new_auto_configured(&[query]),
2649                    wordwise: false,
2650                    done: false,
2651                });
2652                self.select_next(action, cx);
2653            }
2654        }
2655    }
2656
2657    pub fn toggle_comments(&mut self, _: &ToggleComments, cx: &mut ViewContext<Self>) {
2658        // Get the line comment prefix. Split its trailing whitespace into a separate string,
2659        // as that portion won't be used for detecting if a line is a comment.
2660        let full_comment_prefix =
2661            if let Some(prefix) = self.language(cx).and_then(|l| l.line_comment_prefix()) {
2662                prefix.to_string()
2663            } else {
2664                return;
2665            };
2666        let comment_prefix = full_comment_prefix.trim_end_matches(' ');
2667        let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
2668
2669        self.start_transaction(cx);
2670        let mut selections = self.local_selections::<Point>(cx);
2671        let mut all_selection_lines_are_comments = true;
2672        let mut edit_ranges = Vec::new();
2673        let mut last_toggled_row = None;
2674        self.buffer.update(cx, |buffer, cx| {
2675            for selection in &mut selections {
2676                edit_ranges.clear();
2677                let snapshot = buffer.snapshot(cx);
2678
2679                let end_row =
2680                    if selection.end.row > selection.start.row && selection.end.column == 0 {
2681                        selection.end.row
2682                    } else {
2683                        selection.end.row + 1
2684                    };
2685
2686                for row in selection.start.row..end_row {
2687                    // If multiple selections contain a given row, avoid processing that
2688                    // row more than once.
2689                    if last_toggled_row == Some(row) {
2690                        continue;
2691                    } else {
2692                        last_toggled_row = Some(row);
2693                    }
2694
2695                    if snapshot.is_line_blank(row) {
2696                        continue;
2697                    }
2698
2699                    let start = Point::new(row, snapshot.indent_column_for_line(row));
2700                    let mut line_bytes = snapshot
2701                        .bytes_in_range(start..snapshot.max_point())
2702                        .flatten()
2703                        .copied();
2704
2705                    // If this line currently begins with the line comment prefix, then record
2706                    // the range containing the prefix.
2707                    if all_selection_lines_are_comments
2708                        && line_bytes
2709                            .by_ref()
2710                            .take(comment_prefix.len())
2711                            .eq(comment_prefix.bytes())
2712                    {
2713                        // Include any whitespace that matches the comment prefix.
2714                        let matching_whitespace_len = line_bytes
2715                            .zip(comment_prefix_whitespace.bytes())
2716                            .take_while(|(a, b)| a == b)
2717                            .count() as u32;
2718                        let end = Point::new(
2719                            row,
2720                            start.column + comment_prefix.len() as u32 + matching_whitespace_len,
2721                        );
2722                        edit_ranges.push(start..end);
2723                    }
2724                    // If this line does not begin with the line comment prefix, then record
2725                    // the position where the prefix should be inserted.
2726                    else {
2727                        all_selection_lines_are_comments = false;
2728                        edit_ranges.push(start..start);
2729                    }
2730                }
2731
2732                if !edit_ranges.is_empty() {
2733                    if all_selection_lines_are_comments {
2734                        buffer.edit(edit_ranges.iter().cloned(), "", cx);
2735                    } else {
2736                        let min_column = edit_ranges.iter().map(|r| r.start.column).min().unwrap();
2737                        let edit_ranges = edit_ranges.iter().map(|range| {
2738                            let position = Point::new(range.start.row, min_column);
2739                            position..position
2740                        });
2741                        buffer.edit(edit_ranges, &full_comment_prefix, cx);
2742                    }
2743                }
2744            }
2745        });
2746
2747        self.update_selections(
2748            self.local_selections::<usize>(cx),
2749            Some(Autoscroll::Fit),
2750            cx,
2751        );
2752        self.end_transaction(cx);
2753    }
2754
2755    pub fn select_larger_syntax_node(
2756        &mut self,
2757        _: &SelectLargerSyntaxNode,
2758        cx: &mut ViewContext<Self>,
2759    ) {
2760        let old_selections = self.local_selections::<usize>(cx).into_boxed_slice();
2761        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2762        let buffer = self.buffer.read(cx).snapshot(cx);
2763
2764        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
2765        let mut selected_larger_node = false;
2766        let mut new_selections = old_selections
2767            .iter()
2768            .map(|selection| {
2769                let old_range = selection.start..selection.end;
2770                let mut new_range = old_range.clone();
2771                while let Some(containing_range) =
2772                    buffer.range_for_syntax_ancestor(new_range.clone())
2773                {
2774                    new_range = containing_range;
2775                    if !display_map.intersects_fold(new_range.start)
2776                        && !display_map.intersects_fold(new_range.end)
2777                    {
2778                        break;
2779                    }
2780                }
2781
2782                selected_larger_node |= new_range != old_range;
2783                Selection {
2784                    id: selection.id,
2785                    start: new_range.start,
2786                    end: new_range.end,
2787                    goal: SelectionGoal::None,
2788                    reversed: selection.reversed,
2789                }
2790            })
2791            .collect::<Vec<_>>();
2792
2793        if selected_larger_node {
2794            stack.push(old_selections);
2795            new_selections.sort_unstable_by_key(|selection| selection.start);
2796            self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2797        }
2798        self.select_larger_syntax_node_stack = stack;
2799    }
2800
2801    pub fn select_smaller_syntax_node(
2802        &mut self,
2803        _: &SelectSmallerSyntaxNode,
2804        cx: &mut ViewContext<Self>,
2805    ) {
2806        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
2807        if let Some(selections) = stack.pop() {
2808            self.update_selections(selections.to_vec(), Some(Autoscroll::Fit), cx);
2809        }
2810        self.select_larger_syntax_node_stack = stack;
2811    }
2812
2813    pub fn move_to_enclosing_bracket(
2814        &mut self,
2815        _: &MoveToEnclosingBracket,
2816        cx: &mut ViewContext<Self>,
2817    ) {
2818        let mut selections = self.local_selections::<usize>(cx);
2819        let buffer = self.buffer.read(cx).snapshot(cx);
2820        for selection in &mut selections {
2821            if let Some((open_range, close_range)) =
2822                buffer.enclosing_bracket_ranges(selection.start..selection.end)
2823            {
2824                let close_range = close_range.to_inclusive();
2825                let destination = if close_range.contains(&selection.start)
2826                    && close_range.contains(&selection.end)
2827                {
2828                    open_range.end
2829                } else {
2830                    *close_range.start()
2831                };
2832                selection.start = destination;
2833                selection.end = destination;
2834            }
2835        }
2836
2837        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2838    }
2839
2840    pub fn show_next_diagnostic(&mut self, _: &ShowNextDiagnostic, cx: &mut ViewContext<Self>) {
2841        let buffer = self.buffer.read(cx).snapshot(cx);
2842        let selection = self.newest_selection::<usize>(&buffer);
2843        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
2844            active_diagnostics
2845                .primary_range
2846                .to_offset(&buffer)
2847                .to_inclusive()
2848        });
2849        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
2850            if active_primary_range.contains(&selection.head()) {
2851                *active_primary_range.end()
2852            } else {
2853                selection.head()
2854            }
2855        } else {
2856            selection.head()
2857        };
2858
2859        loop {
2860            let next_group = buffer
2861                .diagnostics_in_range::<_, usize>(search_start..buffer.len())
2862                .find_map(|(provider_name, entry)| {
2863                    if entry.diagnostic.is_primary
2864                        && !entry.range.is_empty()
2865                        && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
2866                    {
2867                        Some((provider_name, entry.range, entry.diagnostic.group_id))
2868                    } else {
2869                        None
2870                    }
2871                });
2872
2873            if let Some((provider_name, primary_range, group_id)) = next_group {
2874                self.activate_diagnostics(provider_name, group_id, cx);
2875                self.update_selections(
2876                    vec![Selection {
2877                        id: selection.id,
2878                        start: primary_range.start,
2879                        end: primary_range.start,
2880                        reversed: false,
2881                        goal: SelectionGoal::None,
2882                    }],
2883                    Some(Autoscroll::Center),
2884                    cx,
2885                );
2886                break;
2887            } else if search_start == 0 {
2888                break;
2889            } else {
2890                // Cycle around to the start of the buffer.
2891                search_start = 0;
2892            }
2893        }
2894    }
2895
2896    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
2897        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
2898            let buffer = self.buffer.read(cx).snapshot(cx);
2899            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
2900            let is_valid = buffer
2901                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
2902                .any(|(_, entry)| {
2903                    entry.diagnostic.is_primary
2904                        && !entry.range.is_empty()
2905                        && entry.range.start == primary_range_start
2906                        && entry.diagnostic.message == active_diagnostics.primary_message
2907                });
2908
2909            if is_valid != active_diagnostics.is_valid {
2910                active_diagnostics.is_valid = is_valid;
2911                let mut new_styles = HashMap::default();
2912                for (block_id, diagnostic) in &active_diagnostics.blocks {
2913                    new_styles.insert(
2914                        *block_id,
2915                        diagnostic_block_renderer(
2916                            diagnostic.clone(),
2917                            is_valid,
2918                            self.build_settings.clone(),
2919                        ),
2920                    );
2921                }
2922                self.display_map
2923                    .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
2924            }
2925        }
2926    }
2927
2928    fn activate_diagnostics(
2929        &mut self,
2930        provider_name: &str,
2931        group_id: usize,
2932        cx: &mut ViewContext<Self>,
2933    ) {
2934        self.dismiss_diagnostics(cx);
2935        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
2936            let buffer = self.buffer.read(cx).snapshot(cx);
2937
2938            let mut primary_range = None;
2939            let mut primary_message = None;
2940            let mut group_end = Point::zero();
2941            let diagnostic_group = buffer
2942                .diagnostic_group::<Point>(provider_name, group_id)
2943                .map(|entry| {
2944                    if entry.range.end > group_end {
2945                        group_end = entry.range.end;
2946                    }
2947                    if entry.diagnostic.is_primary {
2948                        primary_range = Some(entry.range.clone());
2949                        primary_message = Some(entry.diagnostic.message.clone());
2950                    }
2951                    entry
2952                })
2953                .collect::<Vec<_>>();
2954            let primary_range = primary_range.unwrap();
2955            let primary_message = primary_message.unwrap();
2956            let primary_range =
2957                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
2958
2959            let blocks = display_map
2960                .insert_blocks(
2961                    diagnostic_group.iter().map(|entry| {
2962                        let build_settings = self.build_settings.clone();
2963                        let diagnostic = entry.diagnostic.clone();
2964                        let message_height = diagnostic.message.lines().count() as u8;
2965
2966                        BlockProperties {
2967                            position: entry.range.start,
2968                            height: message_height,
2969                            render: diagnostic_block_renderer(diagnostic, true, build_settings),
2970                            disposition: BlockDisposition::Below,
2971                        }
2972                    }),
2973                    cx,
2974                )
2975                .into_iter()
2976                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
2977                .collect();
2978
2979            Some(ActiveDiagnosticGroup {
2980                primary_range,
2981                primary_message,
2982                blocks,
2983                is_valid: true,
2984            })
2985        });
2986    }
2987
2988    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
2989        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
2990            self.display_map.update(cx, |display_map, cx| {
2991                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
2992            });
2993            cx.notify();
2994        }
2995    }
2996
2997    fn build_columnar_selection(
2998        &mut self,
2999        display_map: &DisplaySnapshot,
3000        row: u32,
3001        columns: &Range<u32>,
3002        reversed: bool,
3003    ) -> Option<Selection<Point>> {
3004        let is_empty = columns.start == columns.end;
3005        let line_len = display_map.line_len(row);
3006        if columns.start < line_len || (is_empty && columns.start == line_len) {
3007            let start = DisplayPoint::new(row, columns.start);
3008            let end = DisplayPoint::new(row, cmp::min(columns.end, line_len));
3009            Some(Selection {
3010                id: post_inc(&mut self.next_selection_id),
3011                start: start.to_point(display_map),
3012                end: end.to_point(display_map),
3013                reversed,
3014                goal: SelectionGoal::ColumnRange {
3015                    start: columns.start,
3016                    end: columns.end,
3017                },
3018            })
3019        } else {
3020            None
3021        }
3022    }
3023
3024    pub fn visible_selections<'a>(
3025        &'a self,
3026        display_rows: Range<u32>,
3027        cx: &'a mut MutableAppContext,
3028    ) -> HashMap<ReplicaId, Vec<Selection<DisplayPoint>>> {
3029        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3030        let buffer = &display_map.buffer_snapshot;
3031
3032        let start = if display_rows.start == 0 {
3033            Anchor::min()
3034        } else {
3035            buffer.anchor_before(
3036                DisplayPoint::new(display_rows.start, 0).to_offset(&display_map, Bias::Left),
3037            )
3038        };
3039        let end = if display_rows.end > display_map.max_point().row() {
3040            Anchor::max()
3041        } else {
3042            buffer.anchor_before(
3043                DisplayPoint::new(display_rows.end, 0).to_offset(&display_map, Bias::Right),
3044            )
3045        };
3046
3047        let start_ix = match self
3048            .selections
3049            .binary_search_by(|probe| probe.end.cmp(&start, &buffer).unwrap())
3050        {
3051            Ok(ix) | Err(ix) => ix,
3052        };
3053        let end_ix = match self
3054            .selections
3055            .binary_search_by(|probe| probe.start.cmp(&end, &buffer).unwrap())
3056        {
3057            Ok(ix) => ix + 1,
3058            Err(ix) => ix,
3059        };
3060
3061        fn display_selection(
3062            selection: &Selection<Anchor>,
3063            display_map: &DisplaySnapshot,
3064        ) -> Selection<DisplayPoint> {
3065            Selection {
3066                id: selection.id,
3067                start: selection.start.to_display_point(&display_map),
3068                end: selection.end.to_display_point(&display_map),
3069                reversed: selection.reversed,
3070                goal: selection.goal,
3071            }
3072        }
3073
3074        let mut result = HashMap::default();
3075
3076        result.insert(
3077            self.replica_id(cx),
3078            self.selections[start_ix..end_ix]
3079                .iter()
3080                .chain(
3081                    self.pending_selection
3082                        .as_ref()
3083                        .map(|pending| &pending.selection),
3084                )
3085                .map(|s| display_selection(s, &display_map))
3086                .collect(),
3087        );
3088
3089        for (replica_id, selection) in display_map
3090            .buffer_snapshot
3091            .remote_selections_in_range(&(start..end))
3092        {
3093            result
3094                .entry(replica_id)
3095                .or_insert(Vec::new())
3096                .push(display_selection(&selection, &display_map));
3097        }
3098
3099        result
3100    }
3101
3102    pub fn local_selections<'a, D>(&self, cx: &'a AppContext) -> Vec<Selection<D>>
3103    where
3104        D: 'a + TextDimension + Ord + Sub<D, Output = D>,
3105    {
3106        let buffer = self.buffer.read(cx).snapshot(cx);
3107        let mut selections = self
3108            .resolve_selections::<D, _>(self.selections.iter(), &buffer)
3109            .peekable();
3110
3111        let mut pending_selection = self.pending_selection::<D>(&buffer);
3112
3113        iter::from_fn(move || {
3114            if let Some(pending) = pending_selection.as_mut() {
3115                while let Some(next_selection) = selections.peek() {
3116                    if pending.start <= next_selection.end && pending.end >= next_selection.start {
3117                        let next_selection = selections.next().unwrap();
3118                        if next_selection.start < pending.start {
3119                            pending.start = next_selection.start;
3120                        }
3121                        if next_selection.end > pending.end {
3122                            pending.end = next_selection.end;
3123                        }
3124                    } else if next_selection.end < pending.start {
3125                        return selections.next();
3126                    } else {
3127                        break;
3128                    }
3129                }
3130
3131                pending_selection.take()
3132            } else {
3133                selections.next()
3134            }
3135        })
3136        .collect()
3137    }
3138
3139    pub fn local_anchor_selections(&self) -> &Arc<[Selection<Anchor>]> {
3140        &self.selections
3141    }
3142
3143    fn resolve_selections<'a, D, I>(
3144        &self,
3145        selections: I,
3146        snapshot: &MultiBufferSnapshot,
3147    ) -> impl 'a + Iterator<Item = Selection<D>>
3148    where
3149        D: TextDimension + Ord + Sub<D, Output = D>,
3150        I: 'a + IntoIterator<Item = &'a Selection<Anchor>>,
3151    {
3152        let (to_summarize, selections) = selections.into_iter().tee();
3153        let mut summaries = snapshot
3154            .summaries_for_anchors::<D, _>(to_summarize.flat_map(|s| [&s.start, &s.end]))
3155            .into_iter();
3156        selections.map(move |s| Selection {
3157            id: s.id,
3158            start: summaries.next().unwrap(),
3159            end: summaries.next().unwrap(),
3160            reversed: s.reversed,
3161            goal: s.goal,
3162        })
3163    }
3164
3165    fn pending_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3166        &self,
3167        snapshot: &MultiBufferSnapshot,
3168    ) -> Option<Selection<D>> {
3169        self.pending_selection
3170            .as_ref()
3171            .map(|pending| self.resolve_selection(&pending.selection, &snapshot))
3172    }
3173
3174    fn resolve_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3175        &self,
3176        selection: &Selection<Anchor>,
3177        buffer: &MultiBufferSnapshot,
3178    ) -> Selection<D> {
3179        Selection {
3180            id: selection.id,
3181            start: selection.start.summary::<D>(&buffer),
3182            end: selection.end.summary::<D>(&buffer),
3183            reversed: selection.reversed,
3184            goal: selection.goal,
3185        }
3186    }
3187
3188    fn selection_count<'a>(&self) -> usize {
3189        let mut count = self.selections.len();
3190        if self.pending_selection.is_some() {
3191            count += 1;
3192        }
3193        count
3194    }
3195
3196    pub fn oldest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3197        &self,
3198        snapshot: &MultiBufferSnapshot,
3199    ) -> Selection<D> {
3200        self.selections
3201            .iter()
3202            .min_by_key(|s| s.id)
3203            .map(|selection| self.resolve_selection(selection, snapshot))
3204            .or_else(|| self.pending_selection(snapshot))
3205            .unwrap()
3206    }
3207
3208    pub fn newest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3209        &self,
3210        snapshot: &MultiBufferSnapshot,
3211    ) -> Selection<D> {
3212        self.pending_selection(snapshot)
3213            .or_else(|| {
3214                self.selections
3215                    .iter()
3216                    .max_by_key(|s| s.id)
3217                    .map(|selection| self.resolve_selection(selection, snapshot))
3218            })
3219            .unwrap()
3220    }
3221
3222    pub fn update_selections<T>(
3223        &mut self,
3224        mut selections: Vec<Selection<T>>,
3225        autoscroll: Option<Autoscroll>,
3226        cx: &mut ViewContext<Self>,
3227    ) where
3228        T: ToOffset + ToPoint + Ord + std::marker::Copy + std::fmt::Debug,
3229    {
3230        // Merge overlapping selections.
3231        let buffer = self.buffer.read(cx).snapshot(cx);
3232        let mut i = 1;
3233        while i < selections.len() {
3234            if selections[i - 1].end >= selections[i].start {
3235                let removed = selections.remove(i);
3236                if removed.start < selections[i - 1].start {
3237                    selections[i - 1].start = removed.start;
3238                }
3239                if removed.end > selections[i - 1].end {
3240                    selections[i - 1].end = removed.end;
3241                }
3242            } else {
3243                i += 1;
3244            }
3245        }
3246
3247        self.pending_selection = None;
3248        self.add_selections_state = None;
3249        self.select_next_state = None;
3250        self.select_larger_syntax_node_stack.clear();
3251        while let Some(autoclose_pair) = self.autoclose_stack.last() {
3252            let all_selections_inside_autoclose_ranges =
3253                if selections.len() == autoclose_pair.ranges.len() {
3254                    selections
3255                        .iter()
3256                        .zip(autoclose_pair.ranges.iter().map(|r| r.to_point(&buffer)))
3257                        .all(|(selection, autoclose_range)| {
3258                            let head = selection.head().to_point(&buffer);
3259                            autoclose_range.start <= head && autoclose_range.end >= head
3260                        })
3261                } else {
3262                    false
3263                };
3264
3265            if all_selections_inside_autoclose_ranges {
3266                break;
3267            } else {
3268                self.autoclose_stack.pop();
3269            }
3270        }
3271
3272        if let Some(autoscroll) = autoscroll {
3273            self.request_autoscroll(autoscroll, cx);
3274        }
3275        self.pause_cursor_blinking(cx);
3276
3277        self.set_selections(
3278            Arc::from_iter(selections.into_iter().map(|selection| {
3279                let end_bias = if selection.end > selection.start {
3280                    Bias::Left
3281                } else {
3282                    Bias::Right
3283                };
3284                Selection {
3285                    id: selection.id,
3286                    start: buffer.anchor_after(selection.start),
3287                    end: buffer.anchor_at(selection.end, end_bias),
3288                    reversed: selection.reversed,
3289                    goal: selection.goal,
3290                }
3291            })),
3292            cx,
3293        );
3294    }
3295
3296    fn set_selections(&mut self, selections: Arc<[Selection<Anchor>]>, cx: &mut ViewContext<Self>) {
3297        self.selections = selections;
3298        self.buffer.update(cx, |buffer, cx| {
3299            buffer.set_active_selections(&self.selections, cx)
3300        });
3301    }
3302
3303    fn request_autoscroll(&mut self, autoscroll: Autoscroll, cx: &mut ViewContext<Self>) {
3304        self.autoscroll_request = Some(autoscroll);
3305        cx.notify();
3306    }
3307
3308    fn start_transaction(&mut self, cx: &mut ViewContext<Self>) {
3309        self.start_transaction_at(Instant::now(), cx);
3310    }
3311
3312    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
3313        self.end_selection(cx);
3314        if let Some(tx_id) = self
3315            .buffer
3316            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
3317        {
3318            self.selection_history
3319                .insert(tx_id, (self.selections.clone(), None));
3320        }
3321    }
3322
3323    fn end_transaction(&mut self, cx: &mut ViewContext<Self>) {
3324        self.end_transaction_at(Instant::now(), cx);
3325    }
3326
3327    fn end_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
3328        if let Some(tx_id) = self
3329            .buffer
3330            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
3331        {
3332            self.selection_history.get_mut(&tx_id).unwrap().1 = Some(self.selections.clone());
3333        }
3334    }
3335
3336    pub fn page_up(&mut self, _: &PageUp, _: &mut ViewContext<Self>) {
3337        log::info!("Editor::page_up");
3338    }
3339
3340    pub fn page_down(&mut self, _: &PageDown, _: &mut ViewContext<Self>) {
3341        log::info!("Editor::page_down");
3342    }
3343
3344    pub fn fold(&mut self, _: &Fold, cx: &mut ViewContext<Self>) {
3345        let mut fold_ranges = Vec::new();
3346
3347        let selections = self.local_selections::<Point>(cx);
3348        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3349        for selection in selections {
3350            let range = selection.display_range(&display_map).sorted();
3351            let buffer_start_row = range.start.to_point(&display_map).row;
3352
3353            for row in (0..=range.end.row()).rev() {
3354                if self.is_line_foldable(&display_map, row) && !display_map.is_line_folded(row) {
3355                    let fold_range = self.foldable_range_for_line(&display_map, row);
3356                    if fold_range.end.row >= buffer_start_row {
3357                        fold_ranges.push(fold_range);
3358                        if row <= range.start.row() {
3359                            break;
3360                        }
3361                    }
3362                }
3363            }
3364        }
3365
3366        self.fold_ranges(fold_ranges, cx);
3367    }
3368
3369    pub fn unfold(&mut self, _: &Unfold, cx: &mut ViewContext<Self>) {
3370        let selections = self.local_selections::<Point>(cx);
3371        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3372        let buffer = &display_map.buffer_snapshot;
3373        let ranges = selections
3374            .iter()
3375            .map(|s| {
3376                let range = s.display_range(&display_map).sorted();
3377                let mut start = range.start.to_point(&display_map);
3378                let mut end = range.end.to_point(&display_map);
3379                start.column = 0;
3380                end.column = buffer.line_len(end.row);
3381                start..end
3382            })
3383            .collect::<Vec<_>>();
3384        self.unfold_ranges(ranges, cx);
3385    }
3386
3387    fn is_line_foldable(&self, display_map: &DisplaySnapshot, display_row: u32) -> bool {
3388        let max_point = display_map.max_point();
3389        if display_row >= max_point.row() {
3390            false
3391        } else {
3392            let (start_indent, is_blank) = display_map.line_indent(display_row);
3393            if is_blank {
3394                false
3395            } else {
3396                for display_row in display_row + 1..=max_point.row() {
3397                    let (indent, is_blank) = display_map.line_indent(display_row);
3398                    if !is_blank {
3399                        return indent > start_indent;
3400                    }
3401                }
3402                false
3403            }
3404        }
3405    }
3406
3407    fn foldable_range_for_line(
3408        &self,
3409        display_map: &DisplaySnapshot,
3410        start_row: u32,
3411    ) -> Range<Point> {
3412        let max_point = display_map.max_point();
3413
3414        let (start_indent, _) = display_map.line_indent(start_row);
3415        let start = DisplayPoint::new(start_row, display_map.line_len(start_row));
3416        let mut end = None;
3417        for row in start_row + 1..=max_point.row() {
3418            let (indent, is_blank) = display_map.line_indent(row);
3419            if !is_blank && indent <= start_indent {
3420                end = Some(DisplayPoint::new(row - 1, display_map.line_len(row - 1)));
3421                break;
3422            }
3423        }
3424
3425        let end = end.unwrap_or(max_point);
3426        return start.to_point(display_map)..end.to_point(display_map);
3427    }
3428
3429    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
3430        let selections = self.local_selections::<Point>(cx);
3431        let ranges = selections.into_iter().map(|s| s.start..s.end);
3432        self.fold_ranges(ranges, cx);
3433    }
3434
3435    fn fold_ranges<T: ToOffset>(
3436        &mut self,
3437        ranges: impl IntoIterator<Item = Range<T>>,
3438        cx: &mut ViewContext<Self>,
3439    ) {
3440        let mut ranges = ranges.into_iter().peekable();
3441        if ranges.peek().is_some() {
3442            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
3443            self.request_autoscroll(Autoscroll::Fit, cx);
3444            cx.notify();
3445        }
3446    }
3447
3448    fn unfold_ranges<T: ToOffset>(&mut self, ranges: Vec<Range<T>>, cx: &mut ViewContext<Self>) {
3449        if !ranges.is_empty() {
3450            self.display_map
3451                .update(cx, |map, cx| map.unfold(ranges, cx));
3452            self.request_autoscroll(Autoscroll::Fit, cx);
3453            cx.notify();
3454        }
3455    }
3456
3457    pub fn insert_blocks<P>(
3458        &mut self,
3459        blocks: impl IntoIterator<Item = BlockProperties<P>>,
3460        cx: &mut ViewContext<Self>,
3461    ) -> Vec<BlockId>
3462    where
3463        P: ToOffset + Clone,
3464    {
3465        let blocks = self
3466            .display_map
3467            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
3468        self.request_autoscroll(Autoscroll::Fit, cx);
3469        blocks
3470    }
3471
3472    pub fn replace_blocks(
3473        &mut self,
3474        blocks: HashMap<BlockId, RenderBlock>,
3475        cx: &mut ViewContext<Self>,
3476    ) {
3477        self.display_map
3478            .update(cx, |display_map, _| display_map.replace_blocks(blocks));
3479        self.request_autoscroll(Autoscroll::Fit, cx);
3480    }
3481
3482    pub fn remove_blocks(&mut self, block_ids: HashSet<BlockId>, cx: &mut ViewContext<Self>) {
3483        self.display_map.update(cx, |display_map, cx| {
3484            display_map.remove_blocks(block_ids, cx)
3485        });
3486    }
3487
3488    pub fn longest_row(&self, cx: &mut MutableAppContext) -> u32 {
3489        self.display_map
3490            .update(cx, |map, cx| map.snapshot(cx))
3491            .longest_row()
3492    }
3493
3494    pub fn max_point(&self, cx: &mut MutableAppContext) -> DisplayPoint {
3495        self.display_map
3496            .update(cx, |map, cx| map.snapshot(cx))
3497            .max_point()
3498    }
3499
3500    pub fn text(&self, cx: &AppContext) -> String {
3501        self.buffer.read(cx).read(cx).text()
3502    }
3503
3504    pub fn display_text(&self, cx: &mut MutableAppContext) -> String {
3505        self.display_map
3506            .update(cx, |map, cx| map.snapshot(cx))
3507            .text()
3508    }
3509
3510    pub fn set_wrap_width(&self, width: Option<f32>, cx: &mut MutableAppContext) -> bool {
3511        self.display_map
3512            .update(cx, |map, cx| map.set_wrap_width(width, cx))
3513    }
3514
3515    pub fn set_highlighted_row(&mut self, row: Option<u32>) {
3516        self.highlighted_row = row;
3517    }
3518
3519    pub fn highlighted_row(&mut self) -> Option<u32> {
3520        self.highlighted_row
3521    }
3522
3523    fn next_blink_epoch(&mut self) -> usize {
3524        self.blink_epoch += 1;
3525        self.blink_epoch
3526    }
3527
3528    fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
3529        self.show_local_cursors = true;
3530        cx.notify();
3531
3532        let epoch = self.next_blink_epoch();
3533        cx.spawn(|this, mut cx| {
3534            let this = this.downgrade();
3535            async move {
3536                Timer::after(CURSOR_BLINK_INTERVAL).await;
3537                if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
3538                    this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
3539                }
3540            }
3541        })
3542        .detach();
3543    }
3544
3545    fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
3546        if epoch == self.blink_epoch {
3547            self.blinking_paused = false;
3548            self.blink_cursors(epoch, cx);
3549        }
3550    }
3551
3552    fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
3553        if epoch == self.blink_epoch && self.focused && !self.blinking_paused {
3554            self.show_local_cursors = !self.show_local_cursors;
3555            cx.notify();
3556
3557            let epoch = self.next_blink_epoch();
3558            cx.spawn(|this, mut cx| {
3559                let this = this.downgrade();
3560                async move {
3561                    Timer::after(CURSOR_BLINK_INTERVAL).await;
3562                    if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
3563                        this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx));
3564                    }
3565                }
3566            })
3567            .detach();
3568        }
3569    }
3570
3571    pub fn show_local_cursors(&self) -> bool {
3572        self.show_local_cursors
3573    }
3574
3575    fn on_buffer_changed(&mut self, _: ModelHandle<MultiBuffer>, cx: &mut ViewContext<Self>) {
3576        self.refresh_active_diagnostics(cx);
3577        cx.notify();
3578    }
3579
3580    fn on_buffer_event(
3581        &mut self,
3582        _: ModelHandle<MultiBuffer>,
3583        event: &language::Event,
3584        cx: &mut ViewContext<Self>,
3585    ) {
3586        match event {
3587            language::Event::Edited => cx.emit(Event::Edited),
3588            language::Event::Dirtied => cx.emit(Event::Dirtied),
3589            language::Event::Saved => cx.emit(Event::Saved),
3590            language::Event::FileHandleChanged => cx.emit(Event::FileHandleChanged),
3591            language::Event::Reloaded => cx.emit(Event::FileHandleChanged),
3592            language::Event::Closed => cx.emit(Event::Closed),
3593            _ => {}
3594        }
3595    }
3596
3597    fn on_display_map_changed(&mut self, _: ModelHandle<DisplayMap>, cx: &mut ViewContext<Self>) {
3598        cx.notify();
3599    }
3600}
3601
3602impl EditorSnapshot {
3603    pub fn is_focused(&self) -> bool {
3604        self.is_focused
3605    }
3606
3607    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
3608        self.placeholder_text.as_ref()
3609    }
3610
3611    pub fn scroll_position(&self) -> Vector2F {
3612        compute_scroll_position(
3613            &self.display_snapshot,
3614            self.scroll_position,
3615            &self.scroll_top_anchor,
3616        )
3617    }
3618}
3619
3620impl Deref for EditorSnapshot {
3621    type Target = DisplaySnapshot;
3622
3623    fn deref(&self) -> &Self::Target {
3624        &self.display_snapshot
3625    }
3626}
3627
3628impl EditorSettings {
3629    #[cfg(any(test, feature = "test-support"))]
3630    pub fn test(cx: &AppContext) -> Self {
3631        Self {
3632            tab_size: 4,
3633            soft_wrap: SoftWrap::None,
3634            style: {
3635                let font_cache: &gpui::FontCache = cx.font_cache();
3636                let font_family_name = Arc::from("Monaco");
3637                let font_properties = Default::default();
3638                let font_family_id = font_cache.load_family(&[&font_family_name]).unwrap();
3639                let font_id = font_cache
3640                    .select_font(font_family_id, &font_properties)
3641                    .unwrap();
3642                EditorStyle {
3643                    text: gpui::fonts::TextStyle {
3644                        font_family_name,
3645                        font_family_id,
3646                        font_id,
3647                        font_size: 14.,
3648                        color: gpui::color::Color::from_u32(0xff0000ff),
3649                        font_properties,
3650                        underline: None,
3651                    },
3652                    placeholder_text: None,
3653                    background: Default::default(),
3654                    gutter_background: Default::default(),
3655                    active_line_background: Default::default(),
3656                    highlighted_line_background: Default::default(),
3657                    line_number: Default::default(),
3658                    line_number_active: Default::default(),
3659                    selection: Default::default(),
3660                    guest_selections: Default::default(),
3661                    syntax: Default::default(),
3662                    error_diagnostic: Default::default(),
3663                    invalid_error_diagnostic: Default::default(),
3664                    warning_diagnostic: Default::default(),
3665                    invalid_warning_diagnostic: Default::default(),
3666                    information_diagnostic: Default::default(),
3667                    invalid_information_diagnostic: Default::default(),
3668                    hint_diagnostic: Default::default(),
3669                    invalid_hint_diagnostic: Default::default(),
3670                }
3671            },
3672        }
3673    }
3674}
3675
3676fn compute_scroll_position(
3677    snapshot: &DisplaySnapshot,
3678    mut scroll_position: Vector2F,
3679    scroll_top_anchor: &Anchor,
3680) -> Vector2F {
3681    let scroll_top = scroll_top_anchor.to_display_point(snapshot).row() as f32;
3682    scroll_position.set_y(scroll_top + scroll_position.y());
3683    scroll_position
3684}
3685
3686#[derive(Copy, Clone)]
3687pub enum Event {
3688    Activate,
3689    Edited,
3690    Blurred,
3691    Dirtied,
3692    Saved,
3693    FileHandleChanged,
3694    Closed,
3695}
3696
3697impl Entity for Editor {
3698    type Event = Event;
3699}
3700
3701impl View for Editor {
3702    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
3703        let settings = (self.build_settings)(cx);
3704        self.display_map.update(cx, |map, cx| {
3705            map.set_font(
3706                settings.style.text.font_id,
3707                settings.style.text.font_size,
3708                cx,
3709            )
3710        });
3711        EditorElement::new(self.handle.clone(), settings).boxed()
3712    }
3713
3714    fn ui_name() -> &'static str {
3715        "Editor"
3716    }
3717
3718    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
3719        self.focused = true;
3720        self.blink_cursors(self.blink_epoch, cx);
3721        self.buffer.update(cx, |buffer, cx| {
3722            buffer.set_active_selections(&self.selections, cx)
3723        });
3724    }
3725
3726    fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
3727        self.focused = false;
3728        self.show_local_cursors = false;
3729        self.buffer
3730            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
3731        cx.emit(Event::Blurred);
3732        cx.notify();
3733    }
3734
3735    fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
3736        let mut cx = Self::default_keymap_context();
3737        let mode = match self.mode {
3738            EditorMode::SingleLine => "single_line",
3739            EditorMode::AutoHeight { .. } => "auto_height",
3740            EditorMode::Full => "full",
3741        };
3742        cx.map.insert("mode".into(), mode.into());
3743        cx
3744    }
3745}
3746
3747impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
3748    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
3749        let start = self.start.to_point(buffer);
3750        let end = self.end.to_point(buffer);
3751        if self.reversed {
3752            end..start
3753        } else {
3754            start..end
3755        }
3756    }
3757
3758    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
3759        let start = self.start.to_offset(buffer);
3760        let end = self.end.to_offset(buffer);
3761        if self.reversed {
3762            end..start
3763        } else {
3764            start..end
3765        }
3766    }
3767
3768    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
3769        let start = self
3770            .start
3771            .to_point(&map.buffer_snapshot)
3772            .to_display_point(map);
3773        let end = self
3774            .end
3775            .to_point(&map.buffer_snapshot)
3776            .to_display_point(map);
3777        if self.reversed {
3778            end..start
3779        } else {
3780            start..end
3781        }
3782    }
3783
3784    fn spanned_rows(
3785        &self,
3786        include_end_if_at_line_start: bool,
3787        map: &DisplaySnapshot,
3788    ) -> SpannedRows {
3789        let display_start = self
3790            .start
3791            .to_point(&map.buffer_snapshot)
3792            .to_display_point(map);
3793        let mut display_end = self
3794            .end
3795            .to_point(&map.buffer_snapshot)
3796            .to_display_point(map);
3797        if !include_end_if_at_line_start
3798            && display_end.row() != map.max_point().row()
3799            && display_start.row() != display_end.row()
3800            && display_end.column() == 0
3801        {
3802            *display_end.row_mut() -= 1;
3803        }
3804
3805        let (display_start, buffer_start) = map.prev_row_boundary(display_start);
3806        let (display_end, buffer_end) = map.next_row_boundary(display_end);
3807
3808        SpannedRows {
3809            buffer_rows: buffer_start.row..buffer_end.row + 1,
3810            display_rows: display_start.row()..display_end.row() + 1,
3811        }
3812    }
3813}
3814
3815pub fn diagnostic_block_renderer(
3816    diagnostic: Diagnostic,
3817    is_valid: bool,
3818    build_settings: BuildSettings,
3819) -> RenderBlock {
3820    Arc::new(move |cx: &BlockContext| {
3821        let settings = build_settings(cx);
3822        let mut text_style = settings.style.text.clone();
3823        text_style.color = diagnostic_style(diagnostic.severity, is_valid, &settings.style).text;
3824        Text::new(diagnostic.message.clone(), text_style)
3825            .contained()
3826            .with_margin_left(cx.anchor_x)
3827            .boxed()
3828    })
3829}
3830
3831pub fn diagnostic_header_renderer(
3832    buffer: ModelHandle<Buffer>,
3833    diagnostic: Diagnostic,
3834    is_valid: bool,
3835    build_settings: BuildSettings,
3836) -> RenderBlock {
3837    Arc::new(move |cx| {
3838        let settings = build_settings(cx);
3839        let mut text_style = settings.style.text.clone();
3840        text_style.color = diagnostic_style(diagnostic.severity, is_valid, &settings.style).text;
3841        let file_path = if let Some(file) = buffer.read(&**cx).file() {
3842            file.path().to_string_lossy().to_string()
3843        } else {
3844            "untitled".to_string()
3845        };
3846
3847        Flex::column()
3848            .with_child(Label::new(diagnostic.message.clone(), text_style).boxed())
3849            .with_child(Label::new(file_path, settings.style.text.clone()).boxed())
3850            .boxed()
3851    })
3852}
3853
3854pub fn context_header_renderer(build_settings: BuildSettings) -> RenderBlock {
3855    Arc::new(move |cx| {
3856        let settings = build_settings(cx);
3857        let text_style = settings.style.text.clone();
3858        Label::new("...".to_string(), text_style).boxed()
3859    })
3860}
3861
3862pub fn diagnostic_style(
3863    severity: DiagnosticSeverity,
3864    valid: bool,
3865    style: &EditorStyle,
3866) -> DiagnosticStyle {
3867    match (severity, valid) {
3868        (DiagnosticSeverity::ERROR, true) => style.error_diagnostic,
3869        (DiagnosticSeverity::ERROR, false) => style.invalid_error_diagnostic,
3870        (DiagnosticSeverity::WARNING, true) => style.warning_diagnostic,
3871        (DiagnosticSeverity::WARNING, false) => style.invalid_warning_diagnostic,
3872        (DiagnosticSeverity::INFORMATION, true) => style.information_diagnostic,
3873        (DiagnosticSeverity::INFORMATION, false) => style.invalid_information_diagnostic,
3874        (DiagnosticSeverity::HINT, true) => style.hint_diagnostic,
3875        (DiagnosticSeverity::HINT, false) => style.invalid_hint_diagnostic,
3876        _ => Default::default(),
3877    }
3878}
3879
3880pub fn settings_builder(
3881    buffer: WeakModelHandle<MultiBuffer>,
3882    settings: watch::Receiver<workspace::Settings>,
3883) -> BuildSettings {
3884    Arc::new(move |cx| {
3885        let settings = settings.borrow();
3886        let font_cache = cx.font_cache();
3887        let font_family_id = settings.buffer_font_family;
3888        let font_family_name = cx.font_cache().family_name(font_family_id).unwrap();
3889        let font_properties = Default::default();
3890        let font_id = font_cache
3891            .select_font(font_family_id, &font_properties)
3892            .unwrap();
3893        let font_size = settings.buffer_font_size;
3894
3895        let mut theme = settings.theme.editor.clone();
3896        theme.text = TextStyle {
3897            color: theme.text.color,
3898            font_family_name,
3899            font_family_id,
3900            font_id,
3901            font_size,
3902            font_properties,
3903            underline: None,
3904        };
3905        let language = buffer.upgrade(cx).and_then(|buf| buf.read(cx).language(cx));
3906        let soft_wrap = match settings.soft_wrap(language) {
3907            workspace::settings::SoftWrap::None => SoftWrap::None,
3908            workspace::settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
3909            workspace::settings::SoftWrap::PreferredLineLength => {
3910                SoftWrap::Column(settings.preferred_line_length(language).saturating_sub(1))
3911            }
3912        };
3913
3914        EditorSettings {
3915            tab_size: settings.tab_size,
3916            soft_wrap,
3917            style: theme,
3918        }
3919    })
3920}
3921
3922#[cfg(test)]
3923mod tests {
3924    use super::*;
3925    use language::LanguageConfig;
3926    use std::time::Instant;
3927    use text::Point;
3928    use unindent::Unindent;
3929    use util::test::sample_text;
3930
3931    #[gpui::test]
3932    fn test_undo_redo_with_selection_restoration(cx: &mut MutableAppContext) {
3933        let mut now = Instant::now();
3934        let buffer = cx.add_model(|cx| language::Buffer::new(0, "123456", cx));
3935        let group_interval = buffer.read(cx).transaction_group_interval();
3936        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
3937        let settings = EditorSettings::test(cx);
3938        let (_, editor) = cx.add_window(Default::default(), |cx| {
3939            build_editor(buffer.clone(), settings, cx)
3940        });
3941
3942        editor.update(cx, |editor, cx| {
3943            editor.start_transaction_at(now, cx);
3944            editor.select_ranges([2..4], None, cx);
3945            editor.insert("cd", cx);
3946            editor.end_transaction_at(now, cx);
3947            assert_eq!(editor.text(cx), "12cd56");
3948            assert_eq!(editor.selected_ranges(cx), vec![4..4]);
3949
3950            editor.start_transaction_at(now, cx);
3951            editor.select_ranges([4..5], None, cx);
3952            editor.insert("e", cx);
3953            editor.end_transaction_at(now, cx);
3954            assert_eq!(editor.text(cx), "12cde6");
3955            assert_eq!(editor.selected_ranges(cx), vec![5..5]);
3956
3957            now += group_interval + Duration::from_millis(1);
3958            editor.select_ranges([2..2], None, cx);
3959
3960            // Simulate an edit in another editor
3961            buffer.update(cx, |buffer, cx| {
3962                buffer.start_transaction_at(now, cx);
3963                buffer.edit([0..1], "a", cx);
3964                buffer.edit([1..1], "b", cx);
3965                buffer.end_transaction_at(now, cx);
3966            });
3967
3968            assert_eq!(editor.text(cx), "ab2cde6");
3969            assert_eq!(editor.selected_ranges(cx), vec![3..3]);
3970
3971            // Last transaction happened past the group interval in a different editor.
3972            // Undo it individually and don't restore selections.
3973            editor.undo(&Undo, cx);
3974            assert_eq!(editor.text(cx), "12cde6");
3975            assert_eq!(editor.selected_ranges(cx), vec![2..2]);
3976
3977            // First two transactions happened within the group interval in this editor.
3978            // Undo them together and restore selections.
3979            editor.undo(&Undo, cx);
3980            editor.undo(&Undo, cx); // Undo stack is empty here, so this is a no-op.
3981            assert_eq!(editor.text(cx), "123456");
3982            assert_eq!(editor.selected_ranges(cx), vec![0..0]);
3983
3984            // Redo the first two transactions together.
3985            editor.redo(&Redo, cx);
3986            assert_eq!(editor.text(cx), "12cde6");
3987            assert_eq!(editor.selected_ranges(cx), vec![5..5]);
3988
3989            // Redo the last transaction on its own.
3990            editor.redo(&Redo, cx);
3991            assert_eq!(editor.text(cx), "ab2cde6");
3992            assert_eq!(editor.selected_ranges(cx), vec![6..6]);
3993
3994            // Test empty transactions.
3995            editor.start_transaction_at(now, cx);
3996            editor.end_transaction_at(now, cx);
3997            editor.undo(&Undo, cx);
3998            assert_eq!(editor.text(cx), "12cde6");
3999        });
4000    }
4001
4002    #[gpui::test]
4003    fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
4004        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
4005        let settings = EditorSettings::test(cx);
4006        let (_, editor) =
4007            cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4008
4009        editor.update(cx, |view, cx| {
4010            view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
4011        });
4012
4013        assert_eq!(
4014            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4015            [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
4016        );
4017
4018        editor.update(cx, |view, cx| {
4019            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
4020        });
4021
4022        assert_eq!(
4023            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4024            [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
4025        );
4026
4027        editor.update(cx, |view, cx| {
4028            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
4029        });
4030
4031        assert_eq!(
4032            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4033            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
4034        );
4035
4036        editor.update(cx, |view, cx| {
4037            view.end_selection(cx);
4038            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
4039        });
4040
4041        assert_eq!(
4042            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4043            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
4044        );
4045
4046        editor.update(cx, |view, cx| {
4047            view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
4048            view.update_selection(DisplayPoint::new(0, 0), 0, Vector2F::zero(), cx);
4049        });
4050
4051        assert_eq!(
4052            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4053            [
4054                DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
4055                DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
4056            ]
4057        );
4058
4059        editor.update(cx, |view, cx| {
4060            view.end_selection(cx);
4061        });
4062
4063        assert_eq!(
4064            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4065            [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
4066        );
4067    }
4068
4069    #[gpui::test]
4070    fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
4071        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
4072        let settings = EditorSettings::test(cx);
4073        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4074
4075        view.update(cx, |view, cx| {
4076            view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
4077            assert_eq!(
4078                view.selected_display_ranges(cx),
4079                [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
4080            );
4081        });
4082
4083        view.update(cx, |view, cx| {
4084            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
4085            assert_eq!(
4086                view.selected_display_ranges(cx),
4087                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
4088            );
4089        });
4090
4091        view.update(cx, |view, cx| {
4092            view.cancel(&Cancel, cx);
4093            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
4094            assert_eq!(
4095                view.selected_display_ranges(cx),
4096                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
4097            );
4098        });
4099    }
4100
4101    #[gpui::test]
4102    fn test_cancel(cx: &mut gpui::MutableAppContext) {
4103        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
4104        let settings = EditorSettings::test(cx);
4105        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4106
4107        view.update(cx, |view, cx| {
4108            view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
4109            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
4110            view.end_selection(cx);
4111
4112            view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
4113            view.update_selection(DisplayPoint::new(0, 3), 0, Vector2F::zero(), cx);
4114            view.end_selection(cx);
4115            assert_eq!(
4116                view.selected_display_ranges(cx),
4117                [
4118                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
4119                    DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
4120                ]
4121            );
4122        });
4123
4124        view.update(cx, |view, cx| {
4125            view.cancel(&Cancel, cx);
4126            assert_eq!(
4127                view.selected_display_ranges(cx),
4128                [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
4129            );
4130        });
4131
4132        view.update(cx, |view, cx| {
4133            view.cancel(&Cancel, cx);
4134            assert_eq!(
4135                view.selected_display_ranges(cx),
4136                [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
4137            );
4138        });
4139    }
4140
4141    #[gpui::test]
4142    fn test_fold(cx: &mut gpui::MutableAppContext) {
4143        let buffer = MultiBuffer::build_simple(
4144            &"
4145                impl Foo {
4146                    // Hello!
4147
4148                    fn a() {
4149                        1
4150                    }
4151
4152                    fn b() {
4153                        2
4154                    }
4155
4156                    fn c() {
4157                        3
4158                    }
4159                }
4160            "
4161            .unindent(),
4162            cx,
4163        );
4164        let settings = EditorSettings::test(&cx);
4165        let (_, view) = cx.add_window(Default::default(), |cx| {
4166            build_editor(buffer.clone(), settings, cx)
4167        });
4168
4169        view.update(cx, |view, cx| {
4170            view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx)
4171                .unwrap();
4172            view.fold(&Fold, cx);
4173            assert_eq!(
4174                view.display_text(cx),
4175                "
4176                    impl Foo {
4177                        // Hello!
4178
4179                        fn a() {
4180                            1
4181                        }
4182
4183                        fn b() {…
4184                        }
4185
4186                        fn c() {…
4187                        }
4188                    }
4189                "
4190                .unindent(),
4191            );
4192
4193            view.fold(&Fold, cx);
4194            assert_eq!(
4195                view.display_text(cx),
4196                "
4197                    impl Foo {…
4198                    }
4199                "
4200                .unindent(),
4201            );
4202
4203            view.unfold(&Unfold, cx);
4204            assert_eq!(
4205                view.display_text(cx),
4206                "
4207                    impl Foo {
4208                        // Hello!
4209
4210                        fn a() {
4211                            1
4212                        }
4213
4214                        fn b() {…
4215                        }
4216
4217                        fn c() {…
4218                        }
4219                    }
4220                "
4221                .unindent(),
4222            );
4223
4224            view.unfold(&Unfold, cx);
4225            assert_eq!(view.display_text(cx), buffer.read(cx).read(cx).text());
4226        });
4227    }
4228
4229    #[gpui::test]
4230    fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
4231        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
4232        let settings = EditorSettings::test(&cx);
4233        let (_, view) = cx.add_window(Default::default(), |cx| {
4234            build_editor(buffer.clone(), settings, cx)
4235        });
4236
4237        buffer.update(cx, |buffer, cx| {
4238            buffer.edit(
4239                vec![
4240                    Point::new(1, 0)..Point::new(1, 0),
4241                    Point::new(1, 1)..Point::new(1, 1),
4242                ],
4243                "\t",
4244                cx,
4245            );
4246        });
4247
4248        view.update(cx, |view, cx| {
4249            assert_eq!(
4250                view.selected_display_ranges(cx),
4251                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4252            );
4253
4254            view.move_down(&MoveDown, cx);
4255            assert_eq!(
4256                view.selected_display_ranges(cx),
4257                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
4258            );
4259
4260            view.move_right(&MoveRight, cx);
4261            assert_eq!(
4262                view.selected_display_ranges(cx),
4263                &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
4264            );
4265
4266            view.move_left(&MoveLeft, cx);
4267            assert_eq!(
4268                view.selected_display_ranges(cx),
4269                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
4270            );
4271
4272            view.move_up(&MoveUp, cx);
4273            assert_eq!(
4274                view.selected_display_ranges(cx),
4275                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4276            );
4277
4278            view.move_to_end(&MoveToEnd, cx);
4279            assert_eq!(
4280                view.selected_display_ranges(cx),
4281                &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
4282            );
4283
4284            view.move_to_beginning(&MoveToBeginning, cx);
4285            assert_eq!(
4286                view.selected_display_ranges(cx),
4287                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4288            );
4289
4290            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx)
4291                .unwrap();
4292            view.select_to_beginning(&SelectToBeginning, cx);
4293            assert_eq!(
4294                view.selected_display_ranges(cx),
4295                &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
4296            );
4297
4298            view.select_to_end(&SelectToEnd, cx);
4299            assert_eq!(
4300                view.selected_display_ranges(cx),
4301                &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
4302            );
4303        });
4304    }
4305
4306    #[gpui::test]
4307    fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
4308        let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx);
4309        let settings = EditorSettings::test(&cx);
4310        let (_, view) = cx.add_window(Default::default(), |cx| {
4311            build_editor(buffer.clone(), settings, cx)
4312        });
4313
4314        assert_eq!('ⓐ'.len_utf8(), 3);
4315        assert_eq!('α'.len_utf8(), 2);
4316
4317        view.update(cx, |view, cx| {
4318            view.fold_ranges(
4319                vec![
4320                    Point::new(0, 6)..Point::new(0, 12),
4321                    Point::new(1, 2)..Point::new(1, 4),
4322                    Point::new(2, 4)..Point::new(2, 8),
4323                ],
4324                cx,
4325            );
4326            assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
4327
4328            view.move_right(&MoveRight, cx);
4329            assert_eq!(
4330                view.selected_display_ranges(cx),
4331                &[empty_range(0, "".len())]
4332            );
4333            view.move_right(&MoveRight, cx);
4334            assert_eq!(
4335                view.selected_display_ranges(cx),
4336                &[empty_range(0, "ⓐⓑ".len())]
4337            );
4338            view.move_right(&MoveRight, cx);
4339            assert_eq!(
4340                view.selected_display_ranges(cx),
4341                &[empty_range(0, "ⓐⓑ…".len())]
4342            );
4343
4344            view.move_down(&MoveDown, cx);
4345            assert_eq!(
4346                view.selected_display_ranges(cx),
4347                &[empty_range(1, "ab…".len())]
4348            );
4349            view.move_left(&MoveLeft, cx);
4350            assert_eq!(
4351                view.selected_display_ranges(cx),
4352                &[empty_range(1, "ab".len())]
4353            );
4354            view.move_left(&MoveLeft, cx);
4355            assert_eq!(
4356                view.selected_display_ranges(cx),
4357                &[empty_range(1, "a".len())]
4358            );
4359
4360            view.move_down(&MoveDown, cx);
4361            assert_eq!(
4362                view.selected_display_ranges(cx),
4363                &[empty_range(2, "α".len())]
4364            );
4365            view.move_right(&MoveRight, cx);
4366            assert_eq!(
4367                view.selected_display_ranges(cx),
4368                &[empty_range(2, "αβ".len())]
4369            );
4370            view.move_right(&MoveRight, cx);
4371            assert_eq!(
4372                view.selected_display_ranges(cx),
4373                &[empty_range(2, "αβ…".len())]
4374            );
4375            view.move_right(&MoveRight, cx);
4376            assert_eq!(
4377                view.selected_display_ranges(cx),
4378                &[empty_range(2, "αβ…ε".len())]
4379            );
4380
4381            view.move_up(&MoveUp, cx);
4382            assert_eq!(
4383                view.selected_display_ranges(cx),
4384                &[empty_range(1, "ab…e".len())]
4385            );
4386            view.move_up(&MoveUp, cx);
4387            assert_eq!(
4388                view.selected_display_ranges(cx),
4389                &[empty_range(0, "ⓐⓑ…ⓔ".len())]
4390            );
4391            view.move_left(&MoveLeft, cx);
4392            assert_eq!(
4393                view.selected_display_ranges(cx),
4394                &[empty_range(0, "ⓐⓑ…".len())]
4395            );
4396            view.move_left(&MoveLeft, cx);
4397            assert_eq!(
4398                view.selected_display_ranges(cx),
4399                &[empty_range(0, "ⓐⓑ".len())]
4400            );
4401            view.move_left(&MoveLeft, cx);
4402            assert_eq!(
4403                view.selected_display_ranges(cx),
4404                &[empty_range(0, "".len())]
4405            );
4406        });
4407    }
4408
4409    #[gpui::test]
4410    fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
4411        let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
4412        let settings = EditorSettings::test(&cx);
4413        let (_, view) = cx.add_window(Default::default(), |cx| {
4414            build_editor(buffer.clone(), settings, cx)
4415        });
4416        view.update(cx, |view, cx| {
4417            view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx)
4418                .unwrap();
4419
4420            view.move_down(&MoveDown, cx);
4421            assert_eq!(
4422                view.selected_display_ranges(cx),
4423                &[empty_range(1, "abcd".len())]
4424            );
4425
4426            view.move_down(&MoveDown, cx);
4427            assert_eq!(
4428                view.selected_display_ranges(cx),
4429                &[empty_range(2, "αβγ".len())]
4430            );
4431
4432            view.move_down(&MoveDown, cx);
4433            assert_eq!(
4434                view.selected_display_ranges(cx),
4435                &[empty_range(3, "abcd".len())]
4436            );
4437
4438            view.move_down(&MoveDown, cx);
4439            assert_eq!(
4440                view.selected_display_ranges(cx),
4441                &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
4442            );
4443
4444            view.move_up(&MoveUp, cx);
4445            assert_eq!(
4446                view.selected_display_ranges(cx),
4447                &[empty_range(3, "abcd".len())]
4448            );
4449
4450            view.move_up(&MoveUp, cx);
4451            assert_eq!(
4452                view.selected_display_ranges(cx),
4453                &[empty_range(2, "αβγ".len())]
4454            );
4455        });
4456    }
4457
4458    #[gpui::test]
4459    fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
4460        let buffer = MultiBuffer::build_simple("abc\n  def", cx);
4461        let settings = EditorSettings::test(&cx);
4462        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4463        view.update(cx, |view, cx| {
4464            view.select_display_ranges(
4465                &[
4466                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4467                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
4468                ],
4469                cx,
4470            )
4471            .unwrap();
4472        });
4473
4474        view.update(cx, |view, cx| {
4475            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4476            assert_eq!(
4477                view.selected_display_ranges(cx),
4478                &[
4479                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4480                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4481                ]
4482            );
4483        });
4484
4485        view.update(cx, |view, cx| {
4486            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4487            assert_eq!(
4488                view.selected_display_ranges(cx),
4489                &[
4490                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4491                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4492                ]
4493            );
4494        });
4495
4496        view.update(cx, |view, cx| {
4497            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4498            assert_eq!(
4499                view.selected_display_ranges(cx),
4500                &[
4501                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4502                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4503                ]
4504            );
4505        });
4506
4507        view.update(cx, |view, cx| {
4508            view.move_to_end_of_line(&MoveToEndOfLine, cx);
4509            assert_eq!(
4510                view.selected_display_ranges(cx),
4511                &[
4512                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4513                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4514                ]
4515            );
4516        });
4517
4518        // Moving to the end of line again is a no-op.
4519        view.update(cx, |view, cx| {
4520            view.move_to_end_of_line(&MoveToEndOfLine, cx);
4521            assert_eq!(
4522                view.selected_display_ranges(cx),
4523                &[
4524                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4525                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4526                ]
4527            );
4528        });
4529
4530        view.update(cx, |view, cx| {
4531            view.move_left(&MoveLeft, cx);
4532            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4533            assert_eq!(
4534                view.selected_display_ranges(cx),
4535                &[
4536                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4537                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
4538                ]
4539            );
4540        });
4541
4542        view.update(cx, |view, cx| {
4543            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4544            assert_eq!(
4545                view.selected_display_ranges(cx),
4546                &[
4547                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4548                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
4549                ]
4550            );
4551        });
4552
4553        view.update(cx, |view, cx| {
4554            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4555            assert_eq!(
4556                view.selected_display_ranges(cx),
4557                &[
4558                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4559                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
4560                ]
4561            );
4562        });
4563
4564        view.update(cx, |view, cx| {
4565            view.select_to_end_of_line(&SelectToEndOfLine, cx);
4566            assert_eq!(
4567                view.selected_display_ranges(cx),
4568                &[
4569                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
4570                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
4571                ]
4572            );
4573        });
4574
4575        view.update(cx, |view, cx| {
4576            view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
4577            assert_eq!(view.display_text(cx), "ab\n  de");
4578            assert_eq!(
4579                view.selected_display_ranges(cx),
4580                &[
4581                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4582                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
4583                ]
4584            );
4585        });
4586
4587        view.update(cx, |view, cx| {
4588            view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
4589            assert_eq!(view.display_text(cx), "\n");
4590            assert_eq!(
4591                view.selected_display_ranges(cx),
4592                &[
4593                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4594                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4595                ]
4596            );
4597        });
4598    }
4599
4600    #[gpui::test]
4601    fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
4602        let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n  {baz.qux()}", cx);
4603        let settings = EditorSettings::test(&cx);
4604        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4605        view.update(cx, |view, cx| {
4606            view.select_display_ranges(
4607                &[
4608                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
4609                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
4610                ],
4611                cx,
4612            )
4613            .unwrap();
4614        });
4615
4616        view.update(cx, |view, cx| {
4617            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4618            assert_eq!(
4619                view.selected_display_ranges(cx),
4620                &[
4621                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
4622                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
4623                ]
4624            );
4625        });
4626
4627        view.update(cx, |view, cx| {
4628            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4629            assert_eq!(
4630                view.selected_display_ranges(cx),
4631                &[
4632                    DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
4633                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
4634                ]
4635            );
4636        });
4637
4638        view.update(cx, |view, cx| {
4639            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4640            assert_eq!(
4641                view.selected_display_ranges(cx),
4642                &[
4643                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
4644                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
4645                ]
4646            );
4647        });
4648
4649        view.update(cx, |view, cx| {
4650            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4651            assert_eq!(
4652                view.selected_display_ranges(cx),
4653                &[
4654                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4655                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4656                ]
4657            );
4658        });
4659
4660        view.update(cx, |view, cx| {
4661            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4662            assert_eq!(
4663                view.selected_display_ranges(cx),
4664                &[
4665                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4666                    DisplayPoint::new(0, 23)..DisplayPoint::new(0, 23),
4667                ]
4668            );
4669        });
4670
4671        view.update(cx, |view, cx| {
4672            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4673            assert_eq!(
4674                view.selected_display_ranges(cx),
4675                &[
4676                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4677                    DisplayPoint::new(0, 24)..DisplayPoint::new(0, 24),
4678                ]
4679            );
4680        });
4681
4682        view.update(cx, |view, cx| {
4683            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4684            assert_eq!(
4685                view.selected_display_ranges(cx),
4686                &[
4687                    DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
4688                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4689                ]
4690            );
4691        });
4692
4693        view.update(cx, |view, cx| {
4694            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4695            assert_eq!(
4696                view.selected_display_ranges(cx),
4697                &[
4698                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
4699                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
4700                ]
4701            );
4702        });
4703
4704        view.update(cx, |view, cx| {
4705            view.move_right(&MoveRight, cx);
4706            view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
4707            assert_eq!(
4708                view.selected_display_ranges(cx),
4709                &[
4710                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
4711                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
4712                ]
4713            );
4714        });
4715
4716        view.update(cx, |view, cx| {
4717            view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
4718            assert_eq!(
4719                view.selected_display_ranges(cx),
4720                &[
4721                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 7),
4722                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 2),
4723                ]
4724            );
4725        });
4726
4727        view.update(cx, |view, cx| {
4728            view.select_to_next_word_boundary(&SelectToNextWordBoundary, cx);
4729            assert_eq!(
4730                view.selected_display_ranges(cx),
4731                &[
4732                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
4733                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
4734                ]
4735            );
4736        });
4737    }
4738
4739    #[gpui::test]
4740    fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
4741        let buffer = MultiBuffer::build_simple("use one::{\n    two::three::four::five\n};", cx);
4742        let settings = EditorSettings::test(&cx);
4743        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4744
4745        view.update(cx, |view, cx| {
4746            view.set_wrap_width(Some(140.), cx);
4747            assert_eq!(
4748                view.display_text(cx),
4749                "use one::{\n    two::three::\n    four::five\n};"
4750            );
4751
4752            view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx)
4753                .unwrap();
4754
4755            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4756            assert_eq!(
4757                view.selected_display_ranges(cx),
4758                &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
4759            );
4760
4761            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4762            assert_eq!(
4763                view.selected_display_ranges(cx),
4764                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
4765            );
4766
4767            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4768            assert_eq!(
4769                view.selected_display_ranges(cx),
4770                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
4771            );
4772
4773            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4774            assert_eq!(
4775                view.selected_display_ranges(cx),
4776                &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
4777            );
4778
4779            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4780            assert_eq!(
4781                view.selected_display_ranges(cx),
4782                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
4783            );
4784
4785            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4786            assert_eq!(
4787                view.selected_display_ranges(cx),
4788                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
4789            );
4790        });
4791    }
4792
4793    #[gpui::test]
4794    fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
4795        let buffer = MultiBuffer::build_simple("one two three four", cx);
4796        let settings = EditorSettings::test(&cx);
4797        let (_, view) = cx.add_window(Default::default(), |cx| {
4798            build_editor(buffer.clone(), settings, cx)
4799        });
4800
4801        view.update(cx, |view, cx| {
4802            view.select_display_ranges(
4803                &[
4804                    // an empty selection - the preceding word fragment is deleted
4805                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4806                    // characters selected - they are deleted
4807                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
4808                ],
4809                cx,
4810            )
4811            .unwrap();
4812            view.delete_to_previous_word_boundary(&DeleteToPreviousWordBoundary, cx);
4813        });
4814
4815        assert_eq!(buffer.read(cx).read(cx).text(), "e two te four");
4816
4817        view.update(cx, |view, cx| {
4818            view.select_display_ranges(
4819                &[
4820                    // an empty selection - the following word fragment is deleted
4821                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4822                    // characters selected - they are deleted
4823                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
4824                ],
4825                cx,
4826            )
4827            .unwrap();
4828            view.delete_to_next_word_boundary(&DeleteToNextWordBoundary, cx);
4829        });
4830
4831        assert_eq!(buffer.read(cx).read(cx).text(), "e t te our");
4832    }
4833
4834    #[gpui::test]
4835    fn test_newline(cx: &mut gpui::MutableAppContext) {
4836        let buffer = MultiBuffer::build_simple("aaaa\n    bbbb\n", cx);
4837        let settings = EditorSettings::test(&cx);
4838        let (_, view) = cx.add_window(Default::default(), |cx| {
4839            build_editor(buffer.clone(), settings, cx)
4840        });
4841
4842        view.update(cx, |view, cx| {
4843            view.select_display_ranges(
4844                &[
4845                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4846                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4847                    DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
4848                ],
4849                cx,
4850            )
4851            .unwrap();
4852
4853            view.newline(&Newline, cx);
4854            assert_eq!(view.text(cx), "aa\naa\n  \n    bb\n    bb\n");
4855        });
4856    }
4857
4858    #[gpui::test]
4859    fn test_indent_outdent(cx: &mut gpui::MutableAppContext) {
4860        let buffer = MultiBuffer::build_simple("  one two\nthree\n four", cx);
4861        let settings = EditorSettings::test(&cx);
4862        let (_, view) = cx.add_window(Default::default(), |cx| {
4863            build_editor(buffer.clone(), settings, cx)
4864        });
4865
4866        view.update(cx, |view, cx| {
4867            // two selections on the same line
4868            view.select_display_ranges(
4869                &[
4870                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 5),
4871                    DisplayPoint::new(0, 6)..DisplayPoint::new(0, 9),
4872                ],
4873                cx,
4874            )
4875            .unwrap();
4876
4877            // indent from mid-tabstop to full tabstop
4878            view.tab(&Tab, cx);
4879            assert_eq!(view.text(cx), "    one two\nthree\n four");
4880            assert_eq!(
4881                view.selected_display_ranges(cx),
4882                &[
4883                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
4884                    DisplayPoint::new(0, 8)..DisplayPoint::new(0, 11),
4885                ]
4886            );
4887
4888            // outdent from 1 tabstop to 0 tabstops
4889            view.outdent(&Outdent, cx);
4890            assert_eq!(view.text(cx), "one two\nthree\n four");
4891            assert_eq!(
4892                view.selected_display_ranges(cx),
4893                &[
4894                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 3),
4895                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
4896                ]
4897            );
4898
4899            // select across line ending
4900            view.select_display_ranges(&[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)], cx)
4901                .unwrap();
4902
4903            // indent and outdent affect only the preceding line
4904            view.tab(&Tab, cx);
4905            assert_eq!(view.text(cx), "one two\n    three\n four");
4906            assert_eq!(
4907                view.selected_display_ranges(cx),
4908                &[DisplayPoint::new(1, 5)..DisplayPoint::new(2, 0)]
4909            );
4910            view.outdent(&Outdent, cx);
4911            assert_eq!(view.text(cx), "one two\nthree\n four");
4912            assert_eq!(
4913                view.selected_display_ranges(cx),
4914                &[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)]
4915            );
4916        });
4917    }
4918
4919    #[gpui::test]
4920    fn test_backspace(cx: &mut gpui::MutableAppContext) {
4921        let buffer =
4922            MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
4923        let settings = EditorSettings::test(&cx);
4924        let (_, view) = cx.add_window(Default::default(), |cx| {
4925            build_editor(buffer.clone(), settings, cx)
4926        });
4927
4928        view.update(cx, |view, cx| {
4929            view.select_display_ranges(
4930                &[
4931                    // an empty selection - the preceding character is deleted
4932                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4933                    // one character selected - it is deleted
4934                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4935                    // a line suffix selected - it is deleted
4936                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
4937                ],
4938                cx,
4939            )
4940            .unwrap();
4941            view.backspace(&Backspace, cx);
4942        });
4943
4944        assert_eq!(
4945            buffer.read(cx).read(cx).text(),
4946            "oe two three\nfou five six\nseven ten\n"
4947        );
4948    }
4949
4950    #[gpui::test]
4951    fn test_delete(cx: &mut gpui::MutableAppContext) {
4952        let buffer =
4953            MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
4954        let settings = EditorSettings::test(&cx);
4955        let (_, view) = cx.add_window(Default::default(), |cx| {
4956            build_editor(buffer.clone(), settings, cx)
4957        });
4958
4959        view.update(cx, |view, cx| {
4960            view.select_display_ranges(
4961                &[
4962                    // an empty selection - the following character is deleted
4963                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4964                    // one character selected - it is deleted
4965                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4966                    // a line suffix selected - it is deleted
4967                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
4968                ],
4969                cx,
4970            )
4971            .unwrap();
4972            view.delete(&Delete, cx);
4973        });
4974
4975        assert_eq!(
4976            buffer.read(cx).read(cx).text(),
4977            "on two three\nfou five six\nseven ten\n"
4978        );
4979    }
4980
4981    #[gpui::test]
4982    fn test_delete_line(cx: &mut gpui::MutableAppContext) {
4983        let settings = EditorSettings::test(&cx);
4984        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
4985        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4986        view.update(cx, |view, cx| {
4987            view.select_display_ranges(
4988                &[
4989                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4990                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
4991                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4992                ],
4993                cx,
4994            )
4995            .unwrap();
4996            view.delete_line(&DeleteLine, cx);
4997            assert_eq!(view.display_text(cx), "ghi");
4998            assert_eq!(
4999                view.selected_display_ranges(cx),
5000                vec![
5001                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
5002                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
5003                ]
5004            );
5005        });
5006
5007        let settings = EditorSettings::test(&cx);
5008        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
5009        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5010        view.update(cx, |view, cx| {
5011            view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx)
5012                .unwrap();
5013            view.delete_line(&DeleteLine, cx);
5014            assert_eq!(view.display_text(cx), "ghi\n");
5015            assert_eq!(
5016                view.selected_display_ranges(cx),
5017                vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
5018            );
5019        });
5020    }
5021
5022    #[gpui::test]
5023    fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
5024        let settings = EditorSettings::test(&cx);
5025        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
5026        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5027        view.update(cx, |view, cx| {
5028            view.select_display_ranges(
5029                &[
5030                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5031                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5032                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5033                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5034                ],
5035                cx,
5036            )
5037            .unwrap();
5038            view.duplicate_line(&DuplicateLine, cx);
5039            assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
5040            assert_eq!(
5041                view.selected_display_ranges(cx),
5042                vec![
5043                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
5044                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
5045                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5046                    DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
5047                ]
5048            );
5049        });
5050
5051        let settings = EditorSettings::test(&cx);
5052        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
5053        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5054        view.update(cx, |view, cx| {
5055            view.select_display_ranges(
5056                &[
5057                    DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
5058                    DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
5059                ],
5060                cx,
5061            )
5062            .unwrap();
5063            view.duplicate_line(&DuplicateLine, cx);
5064            assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
5065            assert_eq!(
5066                view.selected_display_ranges(cx),
5067                vec![
5068                    DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
5069                    DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
5070                ]
5071            );
5072        });
5073    }
5074
5075    #[gpui::test]
5076    fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
5077        let settings = EditorSettings::test(&cx);
5078        let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
5079        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5080        view.update(cx, |view, cx| {
5081            view.fold_ranges(
5082                vec![
5083                    Point::new(0, 2)..Point::new(1, 2),
5084                    Point::new(2, 3)..Point::new(4, 1),
5085                    Point::new(7, 0)..Point::new(8, 4),
5086                ],
5087                cx,
5088            );
5089            view.select_display_ranges(
5090                &[
5091                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5092                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
5093                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
5094                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
5095                ],
5096                cx,
5097            )
5098            .unwrap();
5099            assert_eq!(
5100                view.display_text(cx),
5101                "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
5102            );
5103
5104            view.move_line_up(&MoveLineUp, cx);
5105            assert_eq!(
5106                view.display_text(cx),
5107                "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
5108            );
5109            assert_eq!(
5110                view.selected_display_ranges(cx),
5111                vec![
5112                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5113                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5114                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
5115                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
5116                ]
5117            );
5118        });
5119
5120        view.update(cx, |view, cx| {
5121            view.move_line_down(&MoveLineDown, cx);
5122            assert_eq!(
5123                view.display_text(cx),
5124                "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
5125            );
5126            assert_eq!(
5127                view.selected_display_ranges(cx),
5128                vec![
5129                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5130                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
5131                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
5132                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
5133                ]
5134            );
5135        });
5136
5137        view.update(cx, |view, cx| {
5138            view.move_line_down(&MoveLineDown, cx);
5139            assert_eq!(
5140                view.display_text(cx),
5141                "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
5142            );
5143            assert_eq!(
5144                view.selected_display_ranges(cx),
5145                vec![
5146                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5147                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
5148                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
5149                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
5150                ]
5151            );
5152        });
5153
5154        view.update(cx, |view, cx| {
5155            view.move_line_up(&MoveLineUp, cx);
5156            assert_eq!(
5157                view.display_text(cx),
5158                "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
5159            );
5160            assert_eq!(
5161                view.selected_display_ranges(cx),
5162                vec![
5163                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5164                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5165                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
5166                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
5167                ]
5168            );
5169        });
5170    }
5171
5172    #[gpui::test]
5173    fn test_move_line_up_down_with_blocks(cx: &mut gpui::MutableAppContext) {
5174        let settings = EditorSettings::test(&cx);
5175        let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
5176        let (_, editor) =
5177            cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5178        editor.update(cx, |editor, cx| {
5179            editor.insert_blocks(
5180                [BlockProperties {
5181                    position: Point::new(2, 0),
5182                    disposition: BlockDisposition::Below,
5183                    height: 1,
5184                    render: Arc::new(|_| Empty::new().boxed()),
5185                }],
5186                cx,
5187            );
5188            editor.select_ranges([Point::new(2, 0)..Point::new(2, 0)], None, cx);
5189            editor.move_line_down(&MoveLineDown, cx);
5190        });
5191    }
5192
5193    #[gpui::test]
5194    fn test_clipboard(cx: &mut gpui::MutableAppContext) {
5195        let buffer = MultiBuffer::build_simple("one✅ two three four five six ", cx);
5196        let settings = EditorSettings::test(&cx);
5197        let view = cx
5198            .add_window(Default::default(), |cx| {
5199                build_editor(buffer.clone(), settings, cx)
5200            })
5201            .1;
5202
5203        // Cut with three selections. Clipboard text is divided into three slices.
5204        view.update(cx, |view, cx| {
5205            view.select_ranges(vec![0..7, 11..17, 22..27], None, cx);
5206            view.cut(&Cut, cx);
5207            assert_eq!(view.display_text(cx), "two four six ");
5208        });
5209
5210        // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
5211        view.update(cx, |view, cx| {
5212            view.select_ranges(vec![4..4, 9..9, 13..13], None, cx);
5213            view.paste(&Paste, cx);
5214            assert_eq!(view.display_text(cx), "two one✅ four three six five ");
5215            assert_eq!(
5216                view.selected_display_ranges(cx),
5217                &[
5218                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
5219                    DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
5220                    DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
5221                ]
5222            );
5223        });
5224
5225        // Paste again but with only two cursors. Since the number of cursors doesn't
5226        // match the number of slices in the clipboard, the entire clipboard text
5227        // is pasted at each cursor.
5228        view.update(cx, |view, cx| {
5229            view.select_ranges(vec![0..0, 31..31], None, cx);
5230            view.handle_input(&Input("( ".into()), cx);
5231            view.paste(&Paste, cx);
5232            view.handle_input(&Input(") ".into()), cx);
5233            assert_eq!(
5234                view.display_text(cx),
5235                "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
5236            );
5237        });
5238
5239        view.update(cx, |view, cx| {
5240            view.select_ranges(vec![0..0], None, cx);
5241            view.handle_input(&Input("123\n4567\n89\n".into()), cx);
5242            assert_eq!(
5243                view.display_text(cx),
5244                "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
5245            );
5246        });
5247
5248        // Cut with three selections, one of which is full-line.
5249        view.update(cx, |view, cx| {
5250            view.select_display_ranges(
5251                &[
5252                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
5253                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5254                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
5255                ],
5256                cx,
5257            )
5258            .unwrap();
5259            view.cut(&Cut, cx);
5260            assert_eq!(
5261                view.display_text(cx),
5262                "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
5263            );
5264        });
5265
5266        // Paste with three selections, noticing how the copied selection that was full-line
5267        // gets inserted before the second cursor.
5268        view.update(cx, |view, cx| {
5269            view.select_display_ranges(
5270                &[
5271                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5272                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5273                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
5274                ],
5275                cx,
5276            )
5277            .unwrap();
5278            view.paste(&Paste, cx);
5279            assert_eq!(
5280                view.display_text(cx),
5281                "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
5282            );
5283            assert_eq!(
5284                view.selected_display_ranges(cx),
5285                &[
5286                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5287                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5288                    DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
5289                ]
5290            );
5291        });
5292
5293        // Copy with a single cursor only, which writes the whole line into the clipboard.
5294        view.update(cx, |view, cx| {
5295            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx)
5296                .unwrap();
5297            view.copy(&Copy, cx);
5298        });
5299
5300        // Paste with three selections, noticing how the copied full-line selection is inserted
5301        // before the empty selections but replaces the selection that is non-empty.
5302        view.update(cx, |view, cx| {
5303            view.select_display_ranges(
5304                &[
5305                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5306                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
5307                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5308                ],
5309                cx,
5310            )
5311            .unwrap();
5312            view.paste(&Paste, cx);
5313            assert_eq!(
5314                view.display_text(cx),
5315                "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
5316            );
5317            assert_eq!(
5318                view.selected_display_ranges(cx),
5319                &[
5320                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5321                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5322                    DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
5323                ]
5324            );
5325        });
5326    }
5327
5328    #[gpui::test]
5329    fn test_select_all(cx: &mut gpui::MutableAppContext) {
5330        let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
5331        let settings = EditorSettings::test(&cx);
5332        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5333        view.update(cx, |view, cx| {
5334            view.select_all(&SelectAll, cx);
5335            assert_eq!(
5336                view.selected_display_ranges(cx),
5337                &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
5338            );
5339        });
5340    }
5341
5342    #[gpui::test]
5343    fn test_select_line(cx: &mut gpui::MutableAppContext) {
5344        let settings = EditorSettings::test(&cx);
5345        let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
5346        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5347        view.update(cx, |view, cx| {
5348            view.select_display_ranges(
5349                &[
5350                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5351                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5352                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5353                    DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
5354                ],
5355                cx,
5356            )
5357            .unwrap();
5358            view.select_line(&SelectLine, cx);
5359            assert_eq!(
5360                view.selected_display_ranges(cx),
5361                vec![
5362                    DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
5363                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
5364                ]
5365            );
5366        });
5367
5368        view.update(cx, |view, cx| {
5369            view.select_line(&SelectLine, cx);
5370            assert_eq!(
5371                view.selected_display_ranges(cx),
5372                vec![
5373                    DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
5374                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
5375                ]
5376            );
5377        });
5378
5379        view.update(cx, |view, cx| {
5380            view.select_line(&SelectLine, cx);
5381            assert_eq!(
5382                view.selected_display_ranges(cx),
5383                vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
5384            );
5385        });
5386    }
5387
5388    #[gpui::test]
5389    fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
5390        let settings = EditorSettings::test(&cx);
5391        let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
5392        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5393        view.update(cx, |view, cx| {
5394            view.fold_ranges(
5395                vec![
5396                    Point::new(0, 2)..Point::new(1, 2),
5397                    Point::new(2, 3)..Point::new(4, 1),
5398                    Point::new(7, 0)..Point::new(8, 4),
5399                ],
5400                cx,
5401            );
5402            view.select_display_ranges(
5403                &[
5404                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5405                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5406                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5407                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
5408                ],
5409                cx,
5410            )
5411            .unwrap();
5412            assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
5413        });
5414
5415        view.update(cx, |view, cx| {
5416            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
5417            assert_eq!(
5418                view.display_text(cx),
5419                "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
5420            );
5421            assert_eq!(
5422                view.selected_display_ranges(cx),
5423                [
5424                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5425                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5426                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
5427                    DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
5428                ]
5429            );
5430        });
5431
5432        view.update(cx, |view, cx| {
5433            view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx)
5434                .unwrap();
5435            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
5436            assert_eq!(
5437                view.display_text(cx),
5438                "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
5439            );
5440            assert_eq!(
5441                view.selected_display_ranges(cx),
5442                [
5443                    DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
5444                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
5445                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
5446                    DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
5447                    DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
5448                    DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
5449                    DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
5450                    DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
5451                ]
5452            );
5453        });
5454    }
5455
5456    #[gpui::test]
5457    fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
5458        let settings = EditorSettings::test(&cx);
5459        let buffer = MultiBuffer::build_simple("abc\ndefghi\n\njk\nlmno\n", cx);
5460        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5461
5462        view.update(cx, |view, cx| {
5463            view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx)
5464                .unwrap();
5465        });
5466        view.update(cx, |view, cx| {
5467            view.add_selection_above(&AddSelectionAbove, cx);
5468            assert_eq!(
5469                view.selected_display_ranges(cx),
5470                vec![
5471                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5472                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
5473                ]
5474            );
5475        });
5476
5477        view.update(cx, |view, cx| {
5478            view.add_selection_above(&AddSelectionAbove, cx);
5479            assert_eq!(
5480                view.selected_display_ranges(cx),
5481                vec![
5482                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5483                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
5484                ]
5485            );
5486        });
5487
5488        view.update(cx, |view, cx| {
5489            view.add_selection_below(&AddSelectionBelow, cx);
5490            assert_eq!(
5491                view.selected_display_ranges(cx),
5492                vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
5493            );
5494        });
5495
5496        view.update(cx, |view, cx| {
5497            view.add_selection_below(&AddSelectionBelow, cx);
5498            assert_eq!(
5499                view.selected_display_ranges(cx),
5500                vec![
5501                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
5502                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
5503                ]
5504            );
5505        });
5506
5507        view.update(cx, |view, cx| {
5508            view.add_selection_below(&AddSelectionBelow, cx);
5509            assert_eq!(
5510                view.selected_display_ranges(cx),
5511                vec![
5512                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
5513                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
5514                ]
5515            );
5516        });
5517
5518        view.update(cx, |view, cx| {
5519            view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx)
5520                .unwrap();
5521        });
5522        view.update(cx, |view, cx| {
5523            view.add_selection_below(&AddSelectionBelow, cx);
5524            assert_eq!(
5525                view.selected_display_ranges(cx),
5526                vec![
5527                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5528                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
5529                ]
5530            );
5531        });
5532
5533        view.update(cx, |view, cx| {
5534            view.add_selection_below(&AddSelectionBelow, cx);
5535            assert_eq!(
5536                view.selected_display_ranges(cx),
5537                vec![
5538                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5539                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
5540                ]
5541            );
5542        });
5543
5544        view.update(cx, |view, cx| {
5545            view.add_selection_above(&AddSelectionAbove, cx);
5546            assert_eq!(
5547                view.selected_display_ranges(cx),
5548                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
5549            );
5550        });
5551
5552        view.update(cx, |view, cx| {
5553            view.add_selection_above(&AddSelectionAbove, cx);
5554            assert_eq!(
5555                view.selected_display_ranges(cx),
5556                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
5557            );
5558        });
5559
5560        view.update(cx, |view, cx| {
5561            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx)
5562                .unwrap();
5563            view.add_selection_below(&AddSelectionBelow, cx);
5564            assert_eq!(
5565                view.selected_display_ranges(cx),
5566                vec![
5567                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5568                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5569                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5570                ]
5571            );
5572        });
5573
5574        view.update(cx, |view, cx| {
5575            view.add_selection_below(&AddSelectionBelow, cx);
5576            assert_eq!(
5577                view.selected_display_ranges(cx),
5578                vec![
5579                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5580                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5581                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5582                    DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
5583                ]
5584            );
5585        });
5586
5587        view.update(cx, |view, cx| {
5588            view.add_selection_above(&AddSelectionAbove, cx);
5589            assert_eq!(
5590                view.selected_display_ranges(cx),
5591                vec![
5592                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5593                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5594                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5595                ]
5596            );
5597        });
5598
5599        view.update(cx, |view, cx| {
5600            view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx)
5601                .unwrap();
5602        });
5603        view.update(cx, |view, cx| {
5604            view.add_selection_above(&AddSelectionAbove, cx);
5605            assert_eq!(
5606                view.selected_display_ranges(cx),
5607                vec![
5608                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
5609                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
5610                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
5611                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
5612                ]
5613            );
5614        });
5615
5616        view.update(cx, |view, cx| {
5617            view.add_selection_below(&AddSelectionBelow, cx);
5618            assert_eq!(
5619                view.selected_display_ranges(cx),
5620                vec![
5621                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
5622                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
5623                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
5624                ]
5625            );
5626        });
5627    }
5628
5629    #[gpui::test]
5630    async fn test_select_larger_smaller_syntax_node(mut cx: gpui::TestAppContext) {
5631        let settings = cx.read(EditorSettings::test);
5632        let language = Some(Arc::new(Language::new(
5633            LanguageConfig::default(),
5634            Some(tree_sitter_rust::language()),
5635        )));
5636
5637        let text = r#"
5638            use mod1::mod2::{mod3, mod4};
5639
5640            fn fn_1(param1: bool, param2: &str) {
5641                let var1 = "text";
5642            }
5643        "#
5644        .unindent();
5645
5646        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5647        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5648        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5649        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
5650            .await;
5651
5652        view.update(&mut cx, |view, cx| {
5653            view.select_display_ranges(
5654                &[
5655                    DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5656                    DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5657                    DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5658                ],
5659                cx,
5660            )
5661            .unwrap();
5662            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5663        });
5664        assert_eq!(
5665            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5666            &[
5667                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
5668                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5669                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
5670            ]
5671        );
5672
5673        view.update(&mut cx, |view, cx| {
5674            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5675        });
5676        assert_eq!(
5677            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5678            &[
5679                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5680                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
5681            ]
5682        );
5683
5684        view.update(&mut cx, |view, cx| {
5685            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5686        });
5687        assert_eq!(
5688            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5689            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
5690        );
5691
5692        // Trying to expand the selected syntax node one more time has no effect.
5693        view.update(&mut cx, |view, cx| {
5694            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5695        });
5696        assert_eq!(
5697            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5698            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
5699        );
5700
5701        view.update(&mut cx, |view, cx| {
5702            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5703        });
5704        assert_eq!(
5705            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5706            &[
5707                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5708                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
5709            ]
5710        );
5711
5712        view.update(&mut cx, |view, cx| {
5713            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5714        });
5715        assert_eq!(
5716            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5717            &[
5718                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
5719                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5720                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
5721            ]
5722        );
5723
5724        view.update(&mut cx, |view, cx| {
5725            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5726        });
5727        assert_eq!(
5728            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5729            &[
5730                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5731                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5732                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5733            ]
5734        );
5735
5736        // Trying to shrink the selected syntax node one more time has no effect.
5737        view.update(&mut cx, |view, cx| {
5738            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5739        });
5740        assert_eq!(
5741            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5742            &[
5743                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5744                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5745                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5746            ]
5747        );
5748
5749        // Ensure that we keep expanding the selection if the larger selection starts or ends within
5750        // a fold.
5751        view.update(&mut cx, |view, cx| {
5752            view.fold_ranges(
5753                vec![
5754                    Point::new(0, 21)..Point::new(0, 24),
5755                    Point::new(3, 20)..Point::new(3, 22),
5756                ],
5757                cx,
5758            );
5759            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5760        });
5761        assert_eq!(
5762            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5763            &[
5764                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5765                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5766                DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
5767            ]
5768        );
5769    }
5770
5771    #[gpui::test]
5772    async fn test_autoindent_selections(mut cx: gpui::TestAppContext) {
5773        let settings = cx.read(EditorSettings::test);
5774        let language = Some(Arc::new(
5775            Language::new(
5776                LanguageConfig {
5777                    brackets: vec![
5778                        BracketPair {
5779                            start: "{".to_string(),
5780                            end: "}".to_string(),
5781                            close: false,
5782                            newline: true,
5783                        },
5784                        BracketPair {
5785                            start: "(".to_string(),
5786                            end: ")".to_string(),
5787                            close: false,
5788                            newline: true,
5789                        },
5790                    ],
5791                    ..Default::default()
5792                },
5793                Some(tree_sitter_rust::language()),
5794            )
5795            .with_indents_query(
5796                r#"
5797                (_ "(" ")" @end) @indent
5798                (_ "{" "}" @end) @indent
5799                "#,
5800            )
5801            .unwrap(),
5802        ));
5803
5804        let text = "fn a() {}";
5805
5806        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5807        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5808        let (_, editor) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5809        editor
5810            .condition(&cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
5811            .await;
5812
5813        editor.update(&mut cx, |editor, cx| {
5814            editor.select_ranges([5..5, 8..8, 9..9], None, cx);
5815            editor.newline(&Newline, cx);
5816            assert_eq!(editor.text(cx), "fn a(\n    \n) {\n    \n}\n");
5817            assert_eq!(
5818                editor.selected_ranges(cx),
5819                &[
5820                    Point::new(1, 4)..Point::new(1, 4),
5821                    Point::new(3, 4)..Point::new(3, 4),
5822                    Point::new(5, 0)..Point::new(5, 0)
5823                ]
5824            );
5825        });
5826    }
5827
5828    #[gpui::test]
5829    async fn test_autoclose_pairs(mut cx: gpui::TestAppContext) {
5830        let settings = cx.read(EditorSettings::test);
5831        let language = Some(Arc::new(Language::new(
5832            LanguageConfig {
5833                brackets: vec![
5834                    BracketPair {
5835                        start: "{".to_string(),
5836                        end: "}".to_string(),
5837                        close: true,
5838                        newline: true,
5839                    },
5840                    BracketPair {
5841                        start: "/*".to_string(),
5842                        end: " */".to_string(),
5843                        close: true,
5844                        newline: true,
5845                    },
5846                ],
5847                ..Default::default()
5848            },
5849            Some(tree_sitter_rust::language()),
5850        )));
5851
5852        let text = r#"
5853            a
5854
5855            /
5856
5857        "#
5858        .unindent();
5859
5860        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5861        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5862        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5863        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
5864            .await;
5865
5866        view.update(&mut cx, |view, cx| {
5867            view.select_display_ranges(
5868                &[
5869                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5870                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5871                ],
5872                cx,
5873            )
5874            .unwrap();
5875            view.handle_input(&Input("{".to_string()), cx);
5876            view.handle_input(&Input("{".to_string()), cx);
5877            view.handle_input(&Input("{".to_string()), cx);
5878            assert_eq!(
5879                view.text(cx),
5880                "
5881                {{{}}}
5882                {{{}}}
5883                /
5884
5885                "
5886                .unindent()
5887            );
5888
5889            view.move_right(&MoveRight, cx);
5890            view.handle_input(&Input("}".to_string()), cx);
5891            view.handle_input(&Input("}".to_string()), cx);
5892            view.handle_input(&Input("}".to_string()), cx);
5893            assert_eq!(
5894                view.text(cx),
5895                "
5896                {{{}}}}
5897                {{{}}}}
5898                /
5899
5900                "
5901                .unindent()
5902            );
5903
5904            view.undo(&Undo, cx);
5905            view.handle_input(&Input("/".to_string()), cx);
5906            view.handle_input(&Input("*".to_string()), cx);
5907            assert_eq!(
5908                view.text(cx),
5909                "
5910                /* */
5911                /* */
5912                /
5913
5914                "
5915                .unindent()
5916            );
5917
5918            view.undo(&Undo, cx);
5919            view.select_display_ranges(
5920                &[
5921                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5922                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5923                ],
5924                cx,
5925            )
5926            .unwrap();
5927            view.handle_input(&Input("*".to_string()), cx);
5928            assert_eq!(
5929                view.text(cx),
5930                "
5931                a
5932
5933                /*
5934                *
5935                "
5936                .unindent()
5937            );
5938        });
5939    }
5940
5941    #[gpui::test]
5942    async fn test_toggle_comment(mut cx: gpui::TestAppContext) {
5943        let settings = cx.read(EditorSettings::test);
5944        let language = Some(Arc::new(Language::new(
5945            LanguageConfig {
5946                line_comment: Some("// ".to_string()),
5947                ..Default::default()
5948            },
5949            Some(tree_sitter_rust::language()),
5950        )));
5951
5952        let text = "
5953            fn a() {
5954                //b();
5955                // c();
5956                //  d();
5957            }
5958        "
5959        .unindent();
5960
5961        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5962        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5963        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5964
5965        view.update(&mut cx, |editor, cx| {
5966            // If multiple selections intersect a line, the line is only
5967            // toggled once.
5968            editor
5969                .select_display_ranges(
5970                    &[
5971                        DisplayPoint::new(1, 3)..DisplayPoint::new(2, 3),
5972                        DisplayPoint::new(3, 5)..DisplayPoint::new(3, 6),
5973                    ],
5974                    cx,
5975                )
5976                .unwrap();
5977            editor.toggle_comments(&ToggleComments, cx);
5978            assert_eq!(
5979                editor.text(cx),
5980                "
5981                    fn a() {
5982                        b();
5983                        c();
5984                         d();
5985                    }
5986                "
5987                .unindent()
5988            );
5989
5990            // The comment prefix is inserted at the same column for every line
5991            // in a selection.
5992            editor
5993                .select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(3, 6)], cx)
5994                .unwrap();
5995            editor.toggle_comments(&ToggleComments, cx);
5996            assert_eq!(
5997                editor.text(cx),
5998                "
5999                    fn a() {
6000                        // b();
6001                        // c();
6002                        //  d();
6003                    }
6004                "
6005                .unindent()
6006            );
6007
6008            // If a selection ends at the beginning of a line, that line is not toggled.
6009            editor
6010                .select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(3, 0)], cx)
6011                .unwrap();
6012            editor.toggle_comments(&ToggleComments, cx);
6013            assert_eq!(
6014                editor.text(cx),
6015                "
6016                        fn a() {
6017                            // b();
6018                            c();
6019                            //  d();
6020                        }
6021                    "
6022                .unindent()
6023            );
6024        });
6025    }
6026
6027    #[gpui::test]
6028    fn test_editing_disjoint_excerpts(cx: &mut gpui::MutableAppContext) {
6029        let settings = EditorSettings::test(cx);
6030        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
6031        let multibuffer = cx.add_model(|cx| {
6032            let mut multibuffer = MultiBuffer::new(0);
6033            multibuffer.push_excerpt(
6034                ExcerptProperties {
6035                    buffer: &buffer,
6036                    range: Point::new(0, 0)..Point::new(0, 4),
6037                },
6038                cx,
6039            );
6040            multibuffer.push_excerpt(
6041                ExcerptProperties {
6042                    buffer: &buffer,
6043                    range: Point::new(1, 0)..Point::new(1, 4),
6044                },
6045                cx,
6046            );
6047            multibuffer
6048        });
6049
6050        assert_eq!(multibuffer.read(cx).read(cx).text(), "aaaa\nbbbb");
6051
6052        let (_, view) = cx.add_window(Default::default(), |cx| {
6053            build_editor(multibuffer, settings, cx)
6054        });
6055        view.update(cx, |view, cx| {
6056            view.select_display_ranges(
6057                &[
6058                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6059                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6060                ],
6061                cx,
6062            )
6063            .unwrap();
6064
6065            view.handle_input(&Input("X".to_string()), cx);
6066            assert_eq!(view.text(cx), "Xaaaa\nXbbbb");
6067            assert_eq!(
6068                view.selected_display_ranges(cx),
6069                &[
6070                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6071                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
6072                ]
6073            )
6074        });
6075    }
6076
6077    #[gpui::test]
6078    fn test_editing_overlapping_excerpts(cx: &mut gpui::MutableAppContext) {
6079        let settings = EditorSettings::test(cx);
6080        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
6081        let multibuffer = cx.add_model(|cx| {
6082            let mut multibuffer = MultiBuffer::new(0);
6083            multibuffer.push_excerpt(
6084                ExcerptProperties {
6085                    buffer: &buffer,
6086                    range: Point::new(0, 0)..Point::new(1, 4),
6087                },
6088                cx,
6089            );
6090            multibuffer.push_excerpt(
6091                ExcerptProperties {
6092                    buffer: &buffer,
6093                    range: Point::new(1, 0)..Point::new(2, 4),
6094                },
6095                cx,
6096            );
6097            multibuffer
6098        });
6099
6100        assert_eq!(
6101            multibuffer.read(cx).read(cx).text(),
6102            "aaaa\nbbbb\nbbbb\ncccc"
6103        );
6104
6105        let (_, view) = cx.add_window(Default::default(), |cx| {
6106            build_editor(multibuffer, settings, cx)
6107        });
6108        view.update(cx, |view, cx| {
6109            view.select_display_ranges(
6110                &[
6111                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
6112                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
6113                ],
6114                cx,
6115            )
6116            .unwrap();
6117
6118            view.handle_input(&Input("X".to_string()), cx);
6119            assert_eq!(view.text(cx), "aaaa\nbXbbXb\nbXbbXb\ncccc");
6120            assert_eq!(
6121                view.selected_display_ranges(cx),
6122                &[
6123                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6124                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
6125                ]
6126            )
6127        });
6128    }
6129
6130    #[gpui::test]
6131    async fn test_extra_newline_insertion(mut cx: gpui::TestAppContext) {
6132        let settings = cx.read(EditorSettings::test);
6133        let language = Some(Arc::new(Language::new(
6134            LanguageConfig {
6135                brackets: vec![
6136                    BracketPair {
6137                        start: "{".to_string(),
6138                        end: "}".to_string(),
6139                        close: true,
6140                        newline: true,
6141                    },
6142                    BracketPair {
6143                        start: "/* ".to_string(),
6144                        end: " */".to_string(),
6145                        close: true,
6146                        newline: true,
6147                    },
6148                ],
6149                ..Default::default()
6150            },
6151            Some(tree_sitter_rust::language()),
6152        )));
6153
6154        let text = concat!(
6155            "{   }\n",     // Suppress rustfmt
6156            "  x\n",       //
6157            "  /*   */\n", //
6158            "x\n",         //
6159            "{{} }\n",     //
6160        );
6161
6162        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
6163        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
6164        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
6165        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
6166            .await;
6167
6168        view.update(&mut cx, |view, cx| {
6169            view.select_display_ranges(
6170                &[
6171                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
6172                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
6173                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
6174                ],
6175                cx,
6176            )
6177            .unwrap();
6178            view.newline(&Newline, cx);
6179
6180            assert_eq!(
6181                view.buffer().read(cx).read(cx).text(),
6182                concat!(
6183                    "{ \n",    // Suppress rustfmt
6184                    "\n",      //
6185                    "}\n",     //
6186                    "  x\n",   //
6187                    "  /* \n", //
6188                    "  \n",    //
6189                    "  */\n",  //
6190                    "x\n",     //
6191                    "{{} \n",  //
6192                    "}\n",     //
6193                )
6194            );
6195        });
6196    }
6197
6198    impl Editor {
6199        fn selected_ranges<D: TextDimension + Ord + Sub<D, Output = D>>(
6200            &self,
6201            cx: &mut MutableAppContext,
6202        ) -> Vec<Range<D>> {
6203            self.local_selections::<D>(cx)
6204                .iter()
6205                .map(|s| {
6206                    if s.reversed {
6207                        s.end.clone()..s.start.clone()
6208                    } else {
6209                        s.start.clone()..s.end.clone()
6210                    }
6211                })
6212                .collect()
6213        }
6214
6215        fn selected_display_ranges(&self, cx: &mut MutableAppContext) -> Vec<Range<DisplayPoint>> {
6216            let display_map = self
6217                .display_map
6218                .update(cx, |display_map, cx| display_map.snapshot(cx));
6219            self.selections
6220                .iter()
6221                .chain(
6222                    self.pending_selection
6223                        .as_ref()
6224                        .map(|pending| &pending.selection),
6225                )
6226                .map(|s| {
6227                    if s.reversed {
6228                        s.end.to_display_point(&display_map)..s.start.to_display_point(&display_map)
6229                    } else {
6230                        s.start.to_display_point(&display_map)..s.end.to_display_point(&display_map)
6231                    }
6232                })
6233                .collect()
6234        }
6235    }
6236
6237    fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
6238        let point = DisplayPoint::new(row as u32, column as u32);
6239        point..point
6240    }
6241
6242    fn build_editor(
6243        buffer: ModelHandle<MultiBuffer>,
6244        settings: EditorSettings,
6245        cx: &mut ViewContext<Editor>,
6246    ) -> Editor {
6247        Editor::for_buffer(buffer, Arc::new(move |_| settings.clone()), cx)
6248    }
6249}
6250
6251trait RangeExt<T> {
6252    fn sorted(&self) -> Range<T>;
6253    fn to_inclusive(&self) -> RangeInclusive<T>;
6254}
6255
6256impl<T: Ord + Clone> RangeExt<T> for Range<T> {
6257    fn sorted(&self) -> Self {
6258        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
6259    }
6260
6261    fn to_inclusive(&self) -> RangeInclusive<T> {
6262        self.start.clone()..=self.end.clone()
6263    }
6264}