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