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