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