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