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