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