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