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