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