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