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