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