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