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