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 _;
  33use language::{
  34    AnchorRangeExt as _, BracketPair, Buffer, CodeAction, CodeLabel, Completion, Diagnostic,
  35    DiagnosticSeverity, Language, Point, Selection, SelectionGoal, TransactionId,
  36};
  37use multi_buffer::MultiBufferChunks;
  38pub use multi_buffer::{
  39    char_kind, Anchor, AnchorRangeExt, CharKind, ExcerptId, MultiBuffer, MultiBufferSnapshot,
  40    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 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        EditorStyle {
5470            text: field_editor_theme.text,
5471            placeholder_text: field_editor_theme.placeholder_text,
5472            theme,
5473        }
5474    } else {
5475        let font_cache = cx.font_cache();
5476        let font_family_id = settings.buffer_font_family;
5477        let font_family_name = cx.font_cache().family_name(font_family_id).unwrap();
5478        let font_properties = Default::default();
5479        let font_id = font_cache
5480            .select_font(font_family_id, &font_properties)
5481            .unwrap();
5482        let font_size = settings.buffer_font_size;
5483        EditorStyle {
5484            text: TextStyle {
5485                color: settings.theme.editor.text_color,
5486                font_family_name,
5487                font_family_id,
5488                font_id,
5489                font_size,
5490                font_properties,
5491                underline: None,
5492            },
5493            placeholder_text: None,
5494            theme,
5495        }
5496    }
5497}
5498
5499impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
5500    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
5501        let start = self.start.to_point(buffer);
5502        let end = self.end.to_point(buffer);
5503        if self.reversed {
5504            end..start
5505        } else {
5506            start..end
5507        }
5508    }
5509
5510    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
5511        let start = self.start.to_offset(buffer);
5512        let end = self.end.to_offset(buffer);
5513        if self.reversed {
5514            end..start
5515        } else {
5516            start..end
5517        }
5518    }
5519
5520    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
5521        let start = self
5522            .start
5523            .to_point(&map.buffer_snapshot)
5524            .to_display_point(map);
5525        let end = self
5526            .end
5527            .to_point(&map.buffer_snapshot)
5528            .to_display_point(map);
5529        if self.reversed {
5530            end..start
5531        } else {
5532            start..end
5533        }
5534    }
5535
5536    fn spanned_rows(
5537        &self,
5538        include_end_if_at_line_start: bool,
5539        map: &DisplaySnapshot,
5540    ) -> Range<u32> {
5541        let start = self.start.to_point(&map.buffer_snapshot);
5542        let mut end = self.end.to_point(&map.buffer_snapshot);
5543        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
5544            end.row -= 1;
5545        }
5546
5547        let buffer_start = map.prev_line_boundary(start).0;
5548        let buffer_end = map.next_line_boundary(end).0;
5549        buffer_start.row..buffer_end.row + 1
5550    }
5551}
5552
5553impl<T: InvalidationRegion> InvalidationStack<T> {
5554    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
5555    where
5556        S: Clone + ToOffset,
5557    {
5558        while let Some(region) = self.last() {
5559            let all_selections_inside_invalidation_ranges =
5560                if selections.len() == region.ranges().len() {
5561                    selections
5562                        .iter()
5563                        .zip(region.ranges().iter().map(|r| r.to_offset(&buffer)))
5564                        .all(|(selection, invalidation_range)| {
5565                            let head = selection.head().to_offset(&buffer);
5566                            invalidation_range.start <= head && invalidation_range.end >= head
5567                        })
5568                } else {
5569                    false
5570                };
5571
5572            if all_selections_inside_invalidation_ranges {
5573                break;
5574            } else {
5575                self.pop();
5576            }
5577        }
5578    }
5579}
5580
5581impl<T> Default for InvalidationStack<T> {
5582    fn default() -> Self {
5583        Self(Default::default())
5584    }
5585}
5586
5587impl<T> Deref for InvalidationStack<T> {
5588    type Target = Vec<T>;
5589
5590    fn deref(&self) -> &Self::Target {
5591        &self.0
5592    }
5593}
5594
5595impl<T> DerefMut for InvalidationStack<T> {
5596    fn deref_mut(&mut self) -> &mut Self::Target {
5597        &mut self.0
5598    }
5599}
5600
5601impl InvalidationRegion for BracketPairState {
5602    fn ranges(&self) -> &[Range<Anchor>] {
5603        &self.ranges
5604    }
5605}
5606
5607impl InvalidationRegion for SnippetState {
5608    fn ranges(&self) -> &[Range<Anchor>] {
5609        &self.ranges[self.active_index]
5610    }
5611}
5612
5613impl Deref for EditorStyle {
5614    type Target = theme::Editor;
5615
5616    fn deref(&self) -> &Self::Target {
5617        &self.theme
5618    }
5619}
5620
5621pub fn diagnostic_block_renderer(
5622    diagnostic: Diagnostic,
5623    is_valid: bool,
5624    settings: watch::Receiver<Settings>,
5625) -> RenderBlock {
5626    let mut highlighted_lines = Vec::new();
5627    for line in diagnostic.message.lines() {
5628        highlighted_lines.push(highlight_diagnostic_message(line));
5629    }
5630
5631    Arc::new(move |cx: &BlockContext| {
5632        let settings = settings.borrow();
5633        let theme = &settings.theme.editor;
5634        let style = diagnostic_style(diagnostic.severity, is_valid, theme);
5635        let font_size = (style.text_scale_factor * settings.buffer_font_size).round();
5636        Flex::column()
5637            .with_children(highlighted_lines.iter().map(|(line, highlights)| {
5638                Label::new(
5639                    line.clone(),
5640                    style.message.clone().with_font_size(font_size),
5641                )
5642                .with_highlights(highlights.clone())
5643                .contained()
5644                .with_margin_left(cx.anchor_x)
5645                .boxed()
5646            }))
5647            .aligned()
5648            .left()
5649            .boxed()
5650    })
5651}
5652
5653pub fn highlight_diagnostic_message(message: &str) -> (String, Vec<usize>) {
5654    let mut message_without_backticks = String::new();
5655    let mut prev_offset = 0;
5656    let mut inside_block = false;
5657    let mut highlights = Vec::new();
5658    for (match_ix, (offset, _)) in message
5659        .match_indices('`')
5660        .chain([(message.len(), "")])
5661        .enumerate()
5662    {
5663        message_without_backticks.push_str(&message[prev_offset..offset]);
5664        if inside_block {
5665            highlights.extend(prev_offset - match_ix..offset - match_ix);
5666        }
5667
5668        inside_block = !inside_block;
5669        prev_offset = offset + 1;
5670    }
5671
5672    (message_without_backticks, highlights)
5673}
5674
5675pub fn diagnostic_style(
5676    severity: DiagnosticSeverity,
5677    valid: bool,
5678    theme: &theme::Editor,
5679) -> DiagnosticStyle {
5680    match (severity, valid) {
5681        (DiagnosticSeverity::ERROR, true) => theme.error_diagnostic.clone(),
5682        (DiagnosticSeverity::ERROR, false) => theme.invalid_error_diagnostic.clone(),
5683        (DiagnosticSeverity::WARNING, true) => theme.warning_diagnostic.clone(),
5684        (DiagnosticSeverity::WARNING, false) => theme.invalid_warning_diagnostic.clone(),
5685        (DiagnosticSeverity::INFORMATION, true) => theme.information_diagnostic.clone(),
5686        (DiagnosticSeverity::INFORMATION, false) => theme.invalid_information_diagnostic.clone(),
5687        (DiagnosticSeverity::HINT, true) => theme.hint_diagnostic.clone(),
5688        (DiagnosticSeverity::HINT, false) => theme.invalid_hint_diagnostic.clone(),
5689        _ => theme.invalid_hint_diagnostic.clone(),
5690    }
5691}
5692
5693pub fn combine_syntax_and_fuzzy_match_highlights(
5694    text: &str,
5695    default_style: HighlightStyle,
5696    syntax_ranges: impl Iterator<Item = (Range<usize>, HighlightStyle)>,
5697    match_indices: &[usize],
5698) -> Vec<(Range<usize>, HighlightStyle)> {
5699    let mut result = Vec::new();
5700    let mut match_indices = match_indices.iter().copied().peekable();
5701
5702    for (range, mut syntax_highlight) in syntax_ranges.chain([(usize::MAX..0, Default::default())])
5703    {
5704        syntax_highlight.font_properties.weight(Default::default());
5705
5706        // Add highlights for any fuzzy match characters before the next
5707        // syntax highlight range.
5708        while let Some(&match_index) = match_indices.peek() {
5709            if match_index >= range.start {
5710                break;
5711            }
5712            match_indices.next();
5713            let end_index = char_ix_after(match_index, text);
5714            let mut match_style = default_style;
5715            match_style.font_properties.weight(fonts::Weight::BOLD);
5716            result.push((match_index..end_index, match_style));
5717        }
5718
5719        if range.start == usize::MAX {
5720            break;
5721        }
5722
5723        // Add highlights for any fuzzy match characters within the
5724        // syntax highlight range.
5725        let mut offset = range.start;
5726        while let Some(&match_index) = match_indices.peek() {
5727            if match_index >= range.end {
5728                break;
5729            }
5730
5731            match_indices.next();
5732            if match_index > offset {
5733                result.push((offset..match_index, syntax_highlight));
5734            }
5735
5736            let mut end_index = char_ix_after(match_index, text);
5737            while let Some(&next_match_index) = match_indices.peek() {
5738                if next_match_index == end_index && next_match_index < range.end {
5739                    end_index = char_ix_after(next_match_index, text);
5740                    match_indices.next();
5741                } else {
5742                    break;
5743                }
5744            }
5745
5746            let mut match_style = syntax_highlight;
5747            match_style.font_properties.weight(fonts::Weight::BOLD);
5748            result.push((match_index..end_index, match_style));
5749            offset = end_index;
5750        }
5751
5752        if offset < range.end {
5753            result.push((offset..range.end, syntax_highlight));
5754        }
5755    }
5756
5757    fn char_ix_after(ix: usize, text: &str) -> usize {
5758        ix + text[ix..].chars().next().unwrap().len_utf8()
5759    }
5760
5761    result
5762}
5763
5764pub fn styled_runs_for_code_label<'a>(
5765    label: &'a CodeLabel,
5766    default_color: Color,
5767    syntax_theme: &'a theme::SyntaxTheme,
5768) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
5769    const MUTED_OPACITY: usize = 165;
5770
5771    let mut muted_default_style = HighlightStyle {
5772        color: default_color,
5773        ..Default::default()
5774    };
5775    muted_default_style.color.a = ((default_color.a as usize * MUTED_OPACITY) / 255) as u8;
5776
5777    let mut prev_end = label.filter_range.end;
5778    label
5779        .runs
5780        .iter()
5781        .enumerate()
5782        .flat_map(move |(ix, (range, highlight_id))| {
5783            let style = if let Some(style) = highlight_id.style(syntax_theme) {
5784                style
5785            } else {
5786                return Default::default();
5787            };
5788            let mut muted_style = style.clone();
5789            muted_style.color.a = ((style.color.a as usize * MUTED_OPACITY) / 255) as u8;
5790
5791            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
5792            if range.start >= label.filter_range.end {
5793                if range.start > prev_end {
5794                    runs.push((prev_end..range.start, muted_default_style));
5795                }
5796                runs.push((range.clone(), muted_style));
5797            } else if range.end <= label.filter_range.end {
5798                runs.push((range.clone(), style));
5799            } else {
5800                runs.push((range.start..label.filter_range.end, style));
5801                runs.push((label.filter_range.end..range.end, muted_style));
5802            }
5803            prev_end = cmp::max(prev_end, range.end);
5804
5805            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
5806                runs.push((prev_end..label.text.len(), muted_default_style));
5807            }
5808
5809            runs
5810        })
5811}
5812
5813#[cfg(test)]
5814mod tests {
5815    use super::*;
5816    use language::LanguageConfig;
5817    use lsp::FakeLanguageServer;
5818    use project::{FakeFs, ProjectPath};
5819    use smol::stream::StreamExt;
5820    use std::{cell::RefCell, rc::Rc, time::Instant};
5821    use text::Point;
5822    use unindent::Unindent;
5823    use util::test::sample_text;
5824
5825    #[gpui::test]
5826    fn test_undo_redo_with_selection_restoration(cx: &mut MutableAppContext) {
5827        let mut now = Instant::now();
5828        let buffer = cx.add_model(|cx| language::Buffer::new(0, "123456", cx));
5829        let group_interval = buffer.read(cx).transaction_group_interval();
5830        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5831        let settings = Settings::test(cx);
5832        let (_, editor) = cx.add_window(Default::default(), |cx| {
5833            build_editor(buffer.clone(), settings, cx)
5834        });
5835
5836        editor.update(cx, |editor, cx| {
5837            editor.start_transaction_at(now, cx);
5838            editor.select_ranges([2..4], None, cx);
5839            editor.insert("cd", cx);
5840            editor.end_transaction_at(now, cx);
5841            assert_eq!(editor.text(cx), "12cd56");
5842            assert_eq!(editor.selected_ranges(cx), vec![4..4]);
5843
5844            editor.start_transaction_at(now, cx);
5845            editor.select_ranges([4..5], None, cx);
5846            editor.insert("e", cx);
5847            editor.end_transaction_at(now, cx);
5848            assert_eq!(editor.text(cx), "12cde6");
5849            assert_eq!(editor.selected_ranges(cx), vec![5..5]);
5850
5851            now += group_interval + Duration::from_millis(1);
5852            editor.select_ranges([2..2], None, cx);
5853
5854            // Simulate an edit in another editor
5855            buffer.update(cx, |buffer, cx| {
5856                buffer.start_transaction_at(now, cx);
5857                buffer.edit([0..1], "a", cx);
5858                buffer.edit([1..1], "b", cx);
5859                buffer.end_transaction_at(now, cx);
5860            });
5861
5862            assert_eq!(editor.text(cx), "ab2cde6");
5863            assert_eq!(editor.selected_ranges(cx), vec![3..3]);
5864
5865            // Last transaction happened past the group interval in a different editor.
5866            // Undo it individually and don't restore selections.
5867            editor.undo(&Undo, cx);
5868            assert_eq!(editor.text(cx), "12cde6");
5869            assert_eq!(editor.selected_ranges(cx), vec![2..2]);
5870
5871            // First two transactions happened within the group interval in this editor.
5872            // Undo them together and restore selections.
5873            editor.undo(&Undo, cx);
5874            editor.undo(&Undo, cx); // Undo stack is empty here, so this is a no-op.
5875            assert_eq!(editor.text(cx), "123456");
5876            assert_eq!(editor.selected_ranges(cx), vec![0..0]);
5877
5878            // Redo the first two transactions together.
5879            editor.redo(&Redo, cx);
5880            assert_eq!(editor.text(cx), "12cde6");
5881            assert_eq!(editor.selected_ranges(cx), vec![5..5]);
5882
5883            // Redo the last transaction on its own.
5884            editor.redo(&Redo, cx);
5885            assert_eq!(editor.text(cx), "ab2cde6");
5886            assert_eq!(editor.selected_ranges(cx), vec![6..6]);
5887
5888            // Test empty transactions.
5889            editor.start_transaction_at(now, cx);
5890            editor.end_transaction_at(now, cx);
5891            editor.undo(&Undo, cx);
5892            assert_eq!(editor.text(cx), "12cde6");
5893        });
5894    }
5895
5896    #[gpui::test]
5897    fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
5898        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
5899        let settings = Settings::test(cx);
5900        let (_, editor) =
5901            cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5902
5903        editor.update(cx, |view, cx| {
5904            view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
5905        });
5906
5907        assert_eq!(
5908            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5909            [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
5910        );
5911
5912        editor.update(cx, |view, cx| {
5913            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
5914        });
5915
5916        assert_eq!(
5917            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5918            [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
5919        );
5920
5921        editor.update(cx, |view, cx| {
5922            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
5923        });
5924
5925        assert_eq!(
5926            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5927            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
5928        );
5929
5930        editor.update(cx, |view, cx| {
5931            view.end_selection(cx);
5932            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
5933        });
5934
5935        assert_eq!(
5936            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5937            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
5938        );
5939
5940        editor.update(cx, |view, cx| {
5941            view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
5942            view.update_selection(DisplayPoint::new(0, 0), 0, Vector2F::zero(), cx);
5943        });
5944
5945        assert_eq!(
5946            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5947            [
5948                DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
5949                DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
5950            ]
5951        );
5952
5953        editor.update(cx, |view, cx| {
5954            view.end_selection(cx);
5955        });
5956
5957        assert_eq!(
5958            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5959            [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
5960        );
5961    }
5962
5963    #[gpui::test]
5964    fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
5965        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
5966        let settings = Settings::test(cx);
5967        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5968
5969        view.update(cx, |view, cx| {
5970            view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
5971            assert_eq!(
5972                view.selected_display_ranges(cx),
5973                [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
5974            );
5975        });
5976
5977        view.update(cx, |view, cx| {
5978            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
5979            assert_eq!(
5980                view.selected_display_ranges(cx),
5981                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
5982            );
5983        });
5984
5985        view.update(cx, |view, cx| {
5986            view.cancel(&Cancel, cx);
5987            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
5988            assert_eq!(
5989                view.selected_display_ranges(cx),
5990                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
5991            );
5992        });
5993    }
5994
5995    #[gpui::test]
5996    fn test_navigation_history(cx: &mut gpui::MutableAppContext) {
5997        cx.add_window(Default::default(), |cx| {
5998            use workspace::ItemView;
5999            let nav_history = Rc::new(RefCell::new(workspace::NavHistory::default()));
6000            let settings = Settings::test(&cx);
6001            let buffer = MultiBuffer::build_simple(&sample_text(30, 5, 'a'), cx);
6002            let mut editor = build_editor(buffer.clone(), settings, cx);
6003            editor.nav_history = Some(ItemNavHistory::new(nav_history.clone(), &cx.handle()));
6004
6005            // Move the cursor a small distance.
6006            // Nothing is added to the navigation history.
6007            editor.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
6008            editor.select_display_ranges(&[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)], cx);
6009            assert!(nav_history.borrow_mut().pop_backward().is_none());
6010
6011            // Move the cursor a large distance.
6012            // The history can jump back to the previous position.
6013            editor.select_display_ranges(&[DisplayPoint::new(13, 0)..DisplayPoint::new(13, 3)], cx);
6014            let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
6015            editor.navigate(nav_entry.data.unwrap(), cx);
6016            assert_eq!(nav_entry.item_view.id(), cx.view_id());
6017            assert_eq!(
6018                editor.selected_display_ranges(cx),
6019                &[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)]
6020            );
6021
6022            // Move the cursor a small distance via the mouse.
6023            // Nothing is added to the navigation history.
6024            editor.begin_selection(DisplayPoint::new(5, 0), false, 1, cx);
6025            editor.end_selection(cx);
6026            assert_eq!(
6027                editor.selected_display_ranges(cx),
6028                &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
6029            );
6030            assert!(nav_history.borrow_mut().pop_backward().is_none());
6031
6032            // Move the cursor a large distance via the mouse.
6033            // The history can jump back to the previous position.
6034            editor.begin_selection(DisplayPoint::new(15, 0), false, 1, cx);
6035            editor.end_selection(cx);
6036            assert_eq!(
6037                editor.selected_display_ranges(cx),
6038                &[DisplayPoint::new(15, 0)..DisplayPoint::new(15, 0)]
6039            );
6040            let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
6041            editor.navigate(nav_entry.data.unwrap(), cx);
6042            assert_eq!(nav_entry.item_view.id(), cx.view_id());
6043            assert_eq!(
6044                editor.selected_display_ranges(cx),
6045                &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
6046            );
6047
6048            editor
6049        });
6050    }
6051
6052    #[gpui::test]
6053    fn test_cancel(cx: &mut gpui::MutableAppContext) {
6054        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
6055        let settings = Settings::test(cx);
6056        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6057
6058        view.update(cx, |view, cx| {
6059            view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
6060            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
6061            view.end_selection(cx);
6062
6063            view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
6064            view.update_selection(DisplayPoint::new(0, 3), 0, Vector2F::zero(), cx);
6065            view.end_selection(cx);
6066            assert_eq!(
6067                view.selected_display_ranges(cx),
6068                [
6069                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
6070                    DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
6071                ]
6072            );
6073        });
6074
6075        view.update(cx, |view, cx| {
6076            view.cancel(&Cancel, cx);
6077            assert_eq!(
6078                view.selected_display_ranges(cx),
6079                [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
6080            );
6081        });
6082
6083        view.update(cx, |view, cx| {
6084            view.cancel(&Cancel, cx);
6085            assert_eq!(
6086                view.selected_display_ranges(cx),
6087                [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
6088            );
6089        });
6090    }
6091
6092    #[gpui::test]
6093    fn test_fold(cx: &mut gpui::MutableAppContext) {
6094        let buffer = MultiBuffer::build_simple(
6095            &"
6096                impl Foo {
6097                    // Hello!
6098
6099                    fn a() {
6100                        1
6101                    }
6102
6103                    fn b() {
6104                        2
6105                    }
6106
6107                    fn c() {
6108                        3
6109                    }
6110                }
6111            "
6112            .unindent(),
6113            cx,
6114        );
6115        let settings = Settings::test(&cx);
6116        let (_, view) = cx.add_window(Default::default(), |cx| {
6117            build_editor(buffer.clone(), settings, cx)
6118        });
6119
6120        view.update(cx, |view, cx| {
6121            view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx);
6122            view.fold(&Fold, cx);
6123            assert_eq!(
6124                view.display_text(cx),
6125                "
6126                    impl Foo {
6127                        // Hello!
6128
6129                        fn a() {
6130                            1
6131                        }
6132
6133                        fn b() {…
6134                        }
6135
6136                        fn c() {…
6137                        }
6138                    }
6139                "
6140                .unindent(),
6141            );
6142
6143            view.fold(&Fold, cx);
6144            assert_eq!(
6145                view.display_text(cx),
6146                "
6147                    impl Foo {…
6148                    }
6149                "
6150                .unindent(),
6151            );
6152
6153            view.unfold(&Unfold, cx);
6154            assert_eq!(
6155                view.display_text(cx),
6156                "
6157                    impl Foo {
6158                        // Hello!
6159
6160                        fn a() {
6161                            1
6162                        }
6163
6164                        fn b() {…
6165                        }
6166
6167                        fn c() {…
6168                        }
6169                    }
6170                "
6171                .unindent(),
6172            );
6173
6174            view.unfold(&Unfold, cx);
6175            assert_eq!(view.display_text(cx), buffer.read(cx).read(cx).text());
6176        });
6177    }
6178
6179    #[gpui::test]
6180    fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
6181        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
6182        let settings = Settings::test(&cx);
6183        let (_, view) = cx.add_window(Default::default(), |cx| {
6184            build_editor(buffer.clone(), settings, cx)
6185        });
6186
6187        buffer.update(cx, |buffer, cx| {
6188            buffer.edit(
6189                vec![
6190                    Point::new(1, 0)..Point::new(1, 0),
6191                    Point::new(1, 1)..Point::new(1, 1),
6192                ],
6193                "\t",
6194                cx,
6195            );
6196        });
6197
6198        view.update(cx, |view, cx| {
6199            assert_eq!(
6200                view.selected_display_ranges(cx),
6201                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6202            );
6203
6204            view.move_down(&MoveDown, cx);
6205            assert_eq!(
6206                view.selected_display_ranges(cx),
6207                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
6208            );
6209
6210            view.move_right(&MoveRight, cx);
6211            assert_eq!(
6212                view.selected_display_ranges(cx),
6213                &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
6214            );
6215
6216            view.move_left(&MoveLeft, cx);
6217            assert_eq!(
6218                view.selected_display_ranges(cx),
6219                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
6220            );
6221
6222            view.move_up(&MoveUp, cx);
6223            assert_eq!(
6224                view.selected_display_ranges(cx),
6225                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6226            );
6227
6228            view.move_to_end(&MoveToEnd, cx);
6229            assert_eq!(
6230                view.selected_display_ranges(cx),
6231                &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
6232            );
6233
6234            view.move_to_beginning(&MoveToBeginning, cx);
6235            assert_eq!(
6236                view.selected_display_ranges(cx),
6237                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6238            );
6239
6240            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx);
6241            view.select_to_beginning(&SelectToBeginning, cx);
6242            assert_eq!(
6243                view.selected_display_ranges(cx),
6244                &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
6245            );
6246
6247            view.select_to_end(&SelectToEnd, cx);
6248            assert_eq!(
6249                view.selected_display_ranges(cx),
6250                &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
6251            );
6252        });
6253    }
6254
6255    #[gpui::test]
6256    fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
6257        let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx);
6258        let settings = Settings::test(&cx);
6259        let (_, view) = cx.add_window(Default::default(), |cx| {
6260            build_editor(buffer.clone(), settings, cx)
6261        });
6262
6263        assert_eq!('ⓐ'.len_utf8(), 3);
6264        assert_eq!('α'.len_utf8(), 2);
6265
6266        view.update(cx, |view, cx| {
6267            view.fold_ranges(
6268                vec![
6269                    Point::new(0, 6)..Point::new(0, 12),
6270                    Point::new(1, 2)..Point::new(1, 4),
6271                    Point::new(2, 4)..Point::new(2, 8),
6272                ],
6273                cx,
6274            );
6275            assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
6276
6277            view.move_right(&MoveRight, cx);
6278            assert_eq!(
6279                view.selected_display_ranges(cx),
6280                &[empty_range(0, "".len())]
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
6293            view.move_down(&MoveDown, cx);
6294            assert_eq!(
6295                view.selected_display_ranges(cx),
6296                &[empty_range(1, "ab…".len())]
6297            );
6298            view.move_left(&MoveLeft, 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, "a".len())]
6307            );
6308
6309            view.move_down(&MoveDown, cx);
6310            assert_eq!(
6311                view.selected_display_ranges(cx),
6312                &[empty_range(2, "α".len())]
6313            );
6314            view.move_right(&MoveRight, 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
6330            view.move_up(&MoveUp, cx);
6331            assert_eq!(
6332                view.selected_display_ranges(cx),
6333                &[empty_range(1, "ab…e".len())]
6334            );
6335            view.move_up(&MoveUp, cx);
6336            assert_eq!(
6337                view.selected_display_ranges(cx),
6338                &[empty_range(0, "ⓐⓑ…ⓔ".len())]
6339            );
6340            view.move_left(&MoveLeft, 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        });
6356    }
6357
6358    #[gpui::test]
6359    fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
6360        let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
6361        let settings = Settings::test(&cx);
6362        let (_, view) = cx.add_window(Default::default(), |cx| {
6363            build_editor(buffer.clone(), settings, cx)
6364        });
6365        view.update(cx, |view, cx| {
6366            view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx);
6367            view.move_down(&MoveDown, cx);
6368            assert_eq!(
6369                view.selected_display_ranges(cx),
6370                &[empty_range(1, "abcd".len())]
6371            );
6372
6373            view.move_down(&MoveDown, cx);
6374            assert_eq!(
6375                view.selected_display_ranges(cx),
6376                &[empty_range(2, "αβγ".len())]
6377            );
6378
6379            view.move_down(&MoveDown, cx);
6380            assert_eq!(
6381                view.selected_display_ranges(cx),
6382                &[empty_range(3, "abcd".len())]
6383            );
6384
6385            view.move_down(&MoveDown, cx);
6386            assert_eq!(
6387                view.selected_display_ranges(cx),
6388                &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
6389            );
6390
6391            view.move_up(&MoveUp, cx);
6392            assert_eq!(
6393                view.selected_display_ranges(cx),
6394                &[empty_range(3, "abcd".len())]
6395            );
6396
6397            view.move_up(&MoveUp, cx);
6398            assert_eq!(
6399                view.selected_display_ranges(cx),
6400                &[empty_range(2, "αβγ".len())]
6401            );
6402        });
6403    }
6404
6405    #[gpui::test]
6406    fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
6407        let buffer = MultiBuffer::build_simple("abc\n  def", cx);
6408        let settings = Settings::test(&cx);
6409        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6410        view.update(cx, |view, cx| {
6411            view.select_display_ranges(
6412                &[
6413                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6414                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
6415                ],
6416                cx,
6417            );
6418        });
6419
6420        view.update(cx, |view, cx| {
6421            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
6422            assert_eq!(
6423                view.selected_display_ranges(cx),
6424                &[
6425                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6426                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6427                ]
6428            );
6429        });
6430
6431        view.update(cx, |view, cx| {
6432            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
6433            assert_eq!(
6434                view.selected_display_ranges(cx),
6435                &[
6436                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6437                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6438                ]
6439            );
6440        });
6441
6442        view.update(cx, |view, cx| {
6443            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
6444            assert_eq!(
6445                view.selected_display_ranges(cx),
6446                &[
6447                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6448                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6449                ]
6450            );
6451        });
6452
6453        view.update(cx, |view, cx| {
6454            view.move_to_end_of_line(&MoveToEndOfLine, cx);
6455            assert_eq!(
6456                view.selected_display_ranges(cx),
6457                &[
6458                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6459                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
6460                ]
6461            );
6462        });
6463
6464        // Moving to the end of line again is a no-op.
6465        view.update(cx, |view, cx| {
6466            view.move_to_end_of_line(&MoveToEndOfLine, cx);
6467            assert_eq!(
6468                view.selected_display_ranges(cx),
6469                &[
6470                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6471                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
6472                ]
6473            );
6474        });
6475
6476        view.update(cx, |view, cx| {
6477            view.move_left(&MoveLeft, cx);
6478            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
6479            assert_eq!(
6480                view.selected_display_ranges(cx),
6481                &[
6482                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
6483                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
6484                ]
6485            );
6486        });
6487
6488        view.update(cx, |view, cx| {
6489            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
6490            assert_eq!(
6491                view.selected_display_ranges(cx),
6492                &[
6493                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
6494                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
6495                ]
6496            );
6497        });
6498
6499        view.update(cx, |view, cx| {
6500            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
6501            assert_eq!(
6502                view.selected_display_ranges(cx),
6503                &[
6504                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
6505                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
6506                ]
6507            );
6508        });
6509
6510        view.update(cx, |view, cx| {
6511            view.select_to_end_of_line(&SelectToEndOfLine(true), cx);
6512            assert_eq!(
6513                view.selected_display_ranges(cx),
6514                &[
6515                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
6516                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
6517                ]
6518            );
6519        });
6520
6521        view.update(cx, |view, cx| {
6522            view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
6523            assert_eq!(view.display_text(cx), "ab\n  de");
6524            assert_eq!(
6525                view.selected_display_ranges(cx),
6526                &[
6527                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6528                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
6529                ]
6530            );
6531        });
6532
6533        view.update(cx, |view, cx| {
6534            view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
6535            assert_eq!(view.display_text(cx), "\n");
6536            assert_eq!(
6537                view.selected_display_ranges(cx),
6538                &[
6539                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6540                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6541                ]
6542            );
6543        });
6544    }
6545
6546    #[gpui::test]
6547    fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
6548        let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n  {baz.qux()}", cx);
6549        let settings = Settings::test(&cx);
6550        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6551        view.update(cx, |view, cx| {
6552            view.select_display_ranges(
6553                &[
6554                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
6555                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
6556                ],
6557                cx,
6558            );
6559        });
6560
6561        view.update(cx, |view, cx| {
6562            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6563            assert_eq!(
6564                view.selected_display_ranges(cx),
6565                &[
6566                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
6567                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
6568                ]
6569            );
6570        });
6571
6572        view.update(cx, |view, cx| {
6573            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6574            assert_eq!(
6575                view.selected_display_ranges(cx),
6576                &[
6577                    DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
6578                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
6579                ]
6580            );
6581        });
6582
6583        view.update(cx, |view, cx| {
6584            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6585            assert_eq!(
6586                view.selected_display_ranges(cx),
6587                &[
6588                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
6589                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
6590                ]
6591            );
6592        });
6593
6594        view.update(cx, |view, cx| {
6595            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6596            assert_eq!(
6597                view.selected_display_ranges(cx),
6598                &[
6599                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6600                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6601                ]
6602            );
6603        });
6604
6605        view.update(cx, |view, cx| {
6606            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6607            assert_eq!(
6608                view.selected_display_ranges(cx),
6609                &[
6610                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6611                    DisplayPoint::new(0, 23)..DisplayPoint::new(0, 23),
6612                ]
6613            );
6614        });
6615
6616        view.update(cx, |view, cx| {
6617            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6618            assert_eq!(
6619                view.selected_display_ranges(cx),
6620                &[
6621                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6622                    DisplayPoint::new(0, 24)..DisplayPoint::new(0, 24),
6623                ]
6624            );
6625        });
6626
6627        view.update(cx, |view, cx| {
6628            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6629            assert_eq!(
6630                view.selected_display_ranges(cx),
6631                &[
6632                    DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
6633                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6634                ]
6635            );
6636        });
6637
6638        view.update(cx, |view, cx| {
6639            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6640            assert_eq!(
6641                view.selected_display_ranges(cx),
6642                &[
6643                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
6644                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
6645                ]
6646            );
6647        });
6648
6649        view.update(cx, |view, cx| {
6650            view.move_right(&MoveRight, cx);
6651            view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
6652            assert_eq!(
6653                view.selected_display_ranges(cx),
6654                &[
6655                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
6656                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
6657                ]
6658            );
6659        });
6660
6661        view.update(cx, |view, cx| {
6662            view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
6663            assert_eq!(
6664                view.selected_display_ranges(cx),
6665                &[
6666                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 7),
6667                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 2),
6668                ]
6669            );
6670        });
6671
6672        view.update(cx, |view, cx| {
6673            view.select_to_next_word_boundary(&SelectToNextWordBoundary, cx);
6674            assert_eq!(
6675                view.selected_display_ranges(cx),
6676                &[
6677                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
6678                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
6679                ]
6680            );
6681        });
6682    }
6683
6684    #[gpui::test]
6685    fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
6686        let buffer = MultiBuffer::build_simple("use one::{\n    two::three::four::five\n};", cx);
6687        let settings = Settings::test(&cx);
6688        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6689
6690        view.update(cx, |view, cx| {
6691            view.set_wrap_width(Some(140.), cx);
6692            assert_eq!(
6693                view.display_text(cx),
6694                "use one::{\n    two::three::\n    four::five\n};"
6695            );
6696
6697            view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx);
6698
6699            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6700            assert_eq!(
6701                view.selected_display_ranges(cx),
6702                &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
6703            );
6704
6705            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6706            assert_eq!(
6707                view.selected_display_ranges(cx),
6708                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
6709            );
6710
6711            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6712            assert_eq!(
6713                view.selected_display_ranges(cx),
6714                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
6715            );
6716
6717            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6718            assert_eq!(
6719                view.selected_display_ranges(cx),
6720                &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
6721            );
6722
6723            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6724            assert_eq!(
6725                view.selected_display_ranges(cx),
6726                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
6727            );
6728
6729            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6730            assert_eq!(
6731                view.selected_display_ranges(cx),
6732                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
6733            );
6734        });
6735    }
6736
6737    #[gpui::test]
6738    fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
6739        let buffer = MultiBuffer::build_simple("one two three four", cx);
6740        let settings = Settings::test(&cx);
6741        let (_, view) = cx.add_window(Default::default(), |cx| {
6742            build_editor(buffer.clone(), settings, cx)
6743        });
6744
6745        view.update(cx, |view, cx| {
6746            view.select_display_ranges(
6747                &[
6748                    // an empty selection - the preceding word fragment is deleted
6749                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6750                    // characters selected - they are deleted
6751                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
6752                ],
6753                cx,
6754            );
6755            view.delete_to_previous_word_boundary(&DeleteToPreviousWordBoundary, cx);
6756        });
6757
6758        assert_eq!(buffer.read(cx).read(cx).text(), "e two te four");
6759
6760        view.update(cx, |view, cx| {
6761            view.select_display_ranges(
6762                &[
6763                    // an empty selection - the following word fragment is deleted
6764                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6765                    // characters selected - they are deleted
6766                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
6767                ],
6768                cx,
6769            );
6770            view.delete_to_next_word_boundary(&DeleteToNextWordBoundary, cx);
6771        });
6772
6773        assert_eq!(buffer.read(cx).read(cx).text(), "e t te our");
6774    }
6775
6776    #[gpui::test]
6777    fn test_newline(cx: &mut gpui::MutableAppContext) {
6778        let buffer = MultiBuffer::build_simple("aaaa\n    bbbb\n", cx);
6779        let settings = Settings::test(&cx);
6780        let (_, view) = cx.add_window(Default::default(), |cx| {
6781            build_editor(buffer.clone(), settings, cx)
6782        });
6783
6784        view.update(cx, |view, cx| {
6785            view.select_display_ranges(
6786                &[
6787                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6788                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6789                    DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
6790                ],
6791                cx,
6792            );
6793
6794            view.newline(&Newline, cx);
6795            assert_eq!(view.text(cx), "aa\naa\n  \n    bb\n    bb\n");
6796        });
6797    }
6798
6799    #[gpui::test]
6800    fn test_newline_with_old_selections(cx: &mut gpui::MutableAppContext) {
6801        let buffer = MultiBuffer::build_simple(
6802            "
6803                a
6804                b(
6805                    X
6806                )
6807                c(
6808                    X
6809                )
6810            "
6811            .unindent()
6812            .as_str(),
6813            cx,
6814        );
6815
6816        let settings = Settings::test(&cx);
6817        let (_, editor) = cx.add_window(Default::default(), |cx| {
6818            let mut editor = build_editor(buffer.clone(), settings, cx);
6819            editor.select_ranges(
6820                [
6821                    Point::new(2, 4)..Point::new(2, 5),
6822                    Point::new(5, 4)..Point::new(5, 5),
6823                ],
6824                None,
6825                cx,
6826            );
6827            editor
6828        });
6829
6830        // Edit the buffer directly, deleting ranges surrounding the editor's selections
6831        buffer.update(cx, |buffer, cx| {
6832            buffer.edit(
6833                [
6834                    Point::new(1, 2)..Point::new(3, 0),
6835                    Point::new(4, 2)..Point::new(6, 0),
6836                ],
6837                "",
6838                cx,
6839            );
6840            assert_eq!(
6841                buffer.read(cx).text(),
6842                "
6843                    a
6844                    b()
6845                    c()
6846                "
6847                .unindent()
6848            );
6849        });
6850
6851        editor.update(cx, |editor, cx| {
6852            assert_eq!(
6853                editor.selected_ranges(cx),
6854                &[
6855                    Point::new(1, 2)..Point::new(1, 2),
6856                    Point::new(2, 2)..Point::new(2, 2),
6857                ],
6858            );
6859
6860            editor.newline(&Newline, cx);
6861            assert_eq!(
6862                editor.text(cx),
6863                "
6864                    a
6865                    b(
6866                    )
6867                    c(
6868                    )
6869                "
6870                .unindent()
6871            );
6872
6873            // The selections are moved after the inserted newlines
6874            assert_eq!(
6875                editor.selected_ranges(cx),
6876                &[
6877                    Point::new(2, 0)..Point::new(2, 0),
6878                    Point::new(4, 0)..Point::new(4, 0),
6879                ],
6880            );
6881        });
6882    }
6883
6884    #[gpui::test]
6885    fn test_insert_with_old_selections(cx: &mut gpui::MutableAppContext) {
6886        let buffer = MultiBuffer::build_simple("a( X ), b( Y ), c( Z )", cx);
6887
6888        let settings = Settings::test(&cx);
6889        let (_, editor) = cx.add_window(Default::default(), |cx| {
6890            let mut editor = build_editor(buffer.clone(), settings, cx);
6891            editor.select_ranges([3..4, 11..12, 19..20], None, cx);
6892            editor
6893        });
6894
6895        // Edit the buffer directly, deleting ranges surrounding the editor's selections
6896        buffer.update(cx, |buffer, cx| {
6897            buffer.edit([2..5, 10..13, 18..21], "", cx);
6898            assert_eq!(buffer.read(cx).text(), "a(), b(), c()".unindent());
6899        });
6900
6901        editor.update(cx, |editor, cx| {
6902            assert_eq!(editor.selected_ranges(cx), &[2..2, 7..7, 12..12],);
6903
6904            editor.insert("Z", cx);
6905            assert_eq!(editor.text(cx), "a(Z), b(Z), c(Z)");
6906
6907            // The selections are moved after the inserted characters
6908            assert_eq!(editor.selected_ranges(cx), &[3..3, 9..9, 15..15],);
6909        });
6910    }
6911
6912    #[gpui::test]
6913    fn test_indent_outdent(cx: &mut gpui::MutableAppContext) {
6914        let buffer = MultiBuffer::build_simple("  one two\nthree\n four", cx);
6915        let settings = Settings::test(&cx);
6916        let (_, view) = cx.add_window(Default::default(), |cx| {
6917            build_editor(buffer.clone(), settings, cx)
6918        });
6919
6920        view.update(cx, |view, cx| {
6921            // two selections on the same line
6922            view.select_display_ranges(
6923                &[
6924                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 5),
6925                    DisplayPoint::new(0, 6)..DisplayPoint::new(0, 9),
6926                ],
6927                cx,
6928            );
6929
6930            // indent from mid-tabstop to full tabstop
6931            view.tab(&Tab, cx);
6932            assert_eq!(view.text(cx), "    one two\nthree\n four");
6933            assert_eq!(
6934                view.selected_display_ranges(cx),
6935                &[
6936                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
6937                    DisplayPoint::new(0, 8)..DisplayPoint::new(0, 11),
6938                ]
6939            );
6940
6941            // outdent from 1 tabstop to 0 tabstops
6942            view.outdent(&Outdent, cx);
6943            assert_eq!(view.text(cx), "one two\nthree\n four");
6944            assert_eq!(
6945                view.selected_display_ranges(cx),
6946                &[
6947                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 3),
6948                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
6949                ]
6950            );
6951
6952            // select across line ending
6953            view.select_display_ranges(&[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)], cx);
6954
6955            // indent and outdent affect only the preceding line
6956            view.tab(&Tab, cx);
6957            assert_eq!(view.text(cx), "one two\n    three\n four");
6958            assert_eq!(
6959                view.selected_display_ranges(cx),
6960                &[DisplayPoint::new(1, 5)..DisplayPoint::new(2, 0)]
6961            );
6962            view.outdent(&Outdent, cx);
6963            assert_eq!(view.text(cx), "one two\nthree\n four");
6964            assert_eq!(
6965                view.selected_display_ranges(cx),
6966                &[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)]
6967            );
6968
6969            // Ensure that indenting/outdenting works when the cursor is at column 0.
6970            view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
6971            view.tab(&Tab, cx);
6972            assert_eq!(view.text(cx), "one two\n    three\n four");
6973            assert_eq!(
6974                view.selected_display_ranges(cx),
6975                &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
6976            );
6977
6978            view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
6979            view.outdent(&Outdent, cx);
6980            assert_eq!(view.text(cx), "one two\nthree\n four");
6981            assert_eq!(
6982                view.selected_display_ranges(cx),
6983                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
6984            );
6985        });
6986    }
6987
6988    #[gpui::test]
6989    fn test_backspace(cx: &mut gpui::MutableAppContext) {
6990        let buffer =
6991            MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
6992        let settings = Settings::test(&cx);
6993        let (_, view) = cx.add_window(Default::default(), |cx| {
6994            build_editor(buffer.clone(), settings, cx)
6995        });
6996
6997        view.update(cx, |view, cx| {
6998            view.select_display_ranges(
6999                &[
7000                    // an empty selection - the preceding character is deleted
7001                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7002                    // one character selected - it is deleted
7003                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7004                    // a line suffix selected - it is deleted
7005                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
7006                ],
7007                cx,
7008            );
7009            view.backspace(&Backspace, cx);
7010        });
7011
7012        assert_eq!(
7013            buffer.read(cx).read(cx).text(),
7014            "oe two three\nfou five six\nseven ten\n"
7015        );
7016    }
7017
7018    #[gpui::test]
7019    fn test_delete(cx: &mut gpui::MutableAppContext) {
7020        let buffer =
7021            MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
7022        let settings = Settings::test(&cx);
7023        let (_, view) = cx.add_window(Default::default(), |cx| {
7024            build_editor(buffer.clone(), settings, cx)
7025        });
7026
7027        view.update(cx, |view, cx| {
7028            view.select_display_ranges(
7029                &[
7030                    // an empty selection - the following character is deleted
7031                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7032                    // one character selected - it is deleted
7033                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7034                    // a line suffix selected - it is deleted
7035                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
7036                ],
7037                cx,
7038            );
7039            view.delete(&Delete, cx);
7040        });
7041
7042        assert_eq!(
7043            buffer.read(cx).read(cx).text(),
7044            "on two three\nfou five six\nseven ten\n"
7045        );
7046    }
7047
7048    #[gpui::test]
7049    fn test_delete_line(cx: &mut gpui::MutableAppContext) {
7050        let settings = Settings::test(&cx);
7051        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7052        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7053        view.update(cx, |view, cx| {
7054            view.select_display_ranges(
7055                &[
7056                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7057                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
7058                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7059                ],
7060                cx,
7061            );
7062            view.delete_line(&DeleteLine, cx);
7063            assert_eq!(view.display_text(cx), "ghi");
7064            assert_eq!(
7065                view.selected_display_ranges(cx),
7066                vec![
7067                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
7068                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
7069                ]
7070            );
7071        });
7072
7073        let settings = Settings::test(&cx);
7074        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7075        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7076        view.update(cx, |view, cx| {
7077            view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx);
7078            view.delete_line(&DeleteLine, cx);
7079            assert_eq!(view.display_text(cx), "ghi\n");
7080            assert_eq!(
7081                view.selected_display_ranges(cx),
7082                vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
7083            );
7084        });
7085    }
7086
7087    #[gpui::test]
7088    fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
7089        let settings = Settings::test(&cx);
7090        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7091        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7092        view.update(cx, |view, cx| {
7093            view.select_display_ranges(
7094                &[
7095                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7096                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7097                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7098                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7099                ],
7100                cx,
7101            );
7102            view.duplicate_line(&DuplicateLine, cx);
7103            assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
7104            assert_eq!(
7105                view.selected_display_ranges(cx),
7106                vec![
7107                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
7108                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
7109                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7110                    DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
7111                ]
7112            );
7113        });
7114
7115        let settings = Settings::test(&cx);
7116        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7117        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7118        view.update(cx, |view, cx| {
7119            view.select_display_ranges(
7120                &[
7121                    DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
7122                    DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
7123                ],
7124                cx,
7125            );
7126            view.duplicate_line(&DuplicateLine, cx);
7127            assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
7128            assert_eq!(
7129                view.selected_display_ranges(cx),
7130                vec![
7131                    DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
7132                    DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
7133                ]
7134            );
7135        });
7136    }
7137
7138    #[gpui::test]
7139    fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
7140        let settings = Settings::test(&cx);
7141        let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
7142        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7143        view.update(cx, |view, cx| {
7144            view.fold_ranges(
7145                vec![
7146                    Point::new(0, 2)..Point::new(1, 2),
7147                    Point::new(2, 3)..Point::new(4, 1),
7148                    Point::new(7, 0)..Point::new(8, 4),
7149                ],
7150                cx,
7151            );
7152            view.select_display_ranges(
7153                &[
7154                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7155                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7156                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7157                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
7158                ],
7159                cx,
7160            );
7161            assert_eq!(
7162                view.display_text(cx),
7163                "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
7164            );
7165
7166            view.move_line_up(&MoveLineUp, cx);
7167            assert_eq!(
7168                view.display_text(cx),
7169                "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
7170            );
7171            assert_eq!(
7172                view.selected_display_ranges(cx),
7173                vec![
7174                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7175                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7176                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
7177                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
7178                ]
7179            );
7180        });
7181
7182        view.update(cx, |view, cx| {
7183            view.move_line_down(&MoveLineDown, cx);
7184            assert_eq!(
7185                view.display_text(cx),
7186                "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
7187            );
7188            assert_eq!(
7189                view.selected_display_ranges(cx),
7190                vec![
7191                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7192                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7193                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7194                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
7195                ]
7196            );
7197        });
7198
7199        view.update(cx, |view, cx| {
7200            view.move_line_down(&MoveLineDown, cx);
7201            assert_eq!(
7202                view.display_text(cx),
7203                "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
7204            );
7205            assert_eq!(
7206                view.selected_display_ranges(cx),
7207                vec![
7208                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7209                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7210                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7211                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
7212                ]
7213            );
7214        });
7215
7216        view.update(cx, |view, cx| {
7217            view.move_line_up(&MoveLineUp, cx);
7218            assert_eq!(
7219                view.display_text(cx),
7220                "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
7221            );
7222            assert_eq!(
7223                view.selected_display_ranges(cx),
7224                vec![
7225                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7226                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7227                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
7228                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
7229                ]
7230            );
7231        });
7232    }
7233
7234    #[gpui::test]
7235    fn test_move_line_up_down_with_blocks(cx: &mut gpui::MutableAppContext) {
7236        let settings = Settings::test(&cx);
7237        let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
7238        let snapshot = buffer.read(cx).snapshot(cx);
7239        let (_, editor) =
7240            cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7241        editor.update(cx, |editor, cx| {
7242            editor.insert_blocks(
7243                [BlockProperties {
7244                    position: snapshot.anchor_after(Point::new(2, 0)),
7245                    disposition: BlockDisposition::Below,
7246                    height: 1,
7247                    render: Arc::new(|_| Empty::new().boxed()),
7248                }],
7249                cx,
7250            );
7251            editor.select_ranges([Point::new(2, 0)..Point::new(2, 0)], None, cx);
7252            editor.move_line_down(&MoveLineDown, cx);
7253        });
7254    }
7255
7256    #[gpui::test]
7257    fn test_clipboard(cx: &mut gpui::MutableAppContext) {
7258        let buffer = MultiBuffer::build_simple("one✅ two three four five six ", cx);
7259        let settings = Settings::test(&cx);
7260        let view = cx
7261            .add_window(Default::default(), |cx| {
7262                build_editor(buffer.clone(), settings, cx)
7263            })
7264            .1;
7265
7266        // Cut with three selections. Clipboard text is divided into three slices.
7267        view.update(cx, |view, cx| {
7268            view.select_ranges(vec![0..7, 11..17, 22..27], None, cx);
7269            view.cut(&Cut, cx);
7270            assert_eq!(view.display_text(cx), "two four six ");
7271        });
7272
7273        // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
7274        view.update(cx, |view, cx| {
7275            view.select_ranges(vec![4..4, 9..9, 13..13], None, cx);
7276            view.paste(&Paste, cx);
7277            assert_eq!(view.display_text(cx), "two one✅ four three six five ");
7278            assert_eq!(
7279                view.selected_display_ranges(cx),
7280                &[
7281                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
7282                    DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
7283                    DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
7284                ]
7285            );
7286        });
7287
7288        // Paste again but with only two cursors. Since the number of cursors doesn't
7289        // match the number of slices in the clipboard, the entire clipboard text
7290        // is pasted at each cursor.
7291        view.update(cx, |view, cx| {
7292            view.select_ranges(vec![0..0, 31..31], None, cx);
7293            view.handle_input(&Input("( ".into()), cx);
7294            view.paste(&Paste, cx);
7295            view.handle_input(&Input(") ".into()), cx);
7296            assert_eq!(
7297                view.display_text(cx),
7298                "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
7299            );
7300        });
7301
7302        view.update(cx, |view, cx| {
7303            view.select_ranges(vec![0..0], None, cx);
7304            view.handle_input(&Input("123\n4567\n89\n".into()), cx);
7305            assert_eq!(
7306                view.display_text(cx),
7307                "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
7308            );
7309        });
7310
7311        // Cut with three selections, one of which is full-line.
7312        view.update(cx, |view, cx| {
7313            view.select_display_ranges(
7314                &[
7315                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
7316                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7317                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
7318                ],
7319                cx,
7320            );
7321            view.cut(&Cut, cx);
7322            assert_eq!(
7323                view.display_text(cx),
7324                "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
7325            );
7326        });
7327
7328        // Paste with three selections, noticing how the copied selection that was full-line
7329        // gets inserted before the second cursor.
7330        view.update(cx, |view, cx| {
7331            view.select_display_ranges(
7332                &[
7333                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7334                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7335                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
7336                ],
7337                cx,
7338            );
7339            view.paste(&Paste, cx);
7340            assert_eq!(
7341                view.display_text(cx),
7342                "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
7343            );
7344            assert_eq!(
7345                view.selected_display_ranges(cx),
7346                &[
7347                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7348                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7349                    DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
7350                ]
7351            );
7352        });
7353
7354        // Copy with a single cursor only, which writes the whole line into the clipboard.
7355        view.update(cx, |view, cx| {
7356            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx);
7357            view.copy(&Copy, cx);
7358        });
7359
7360        // Paste with three selections, noticing how the copied full-line selection is inserted
7361        // before the empty selections but replaces the selection that is non-empty.
7362        view.update(cx, |view, cx| {
7363            view.select_display_ranges(
7364                &[
7365                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7366                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
7367                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7368                ],
7369                cx,
7370            );
7371            view.paste(&Paste, cx);
7372            assert_eq!(
7373                view.display_text(cx),
7374                "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
7375            );
7376            assert_eq!(
7377                view.selected_display_ranges(cx),
7378                &[
7379                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7380                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7381                    DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
7382                ]
7383            );
7384        });
7385    }
7386
7387    #[gpui::test]
7388    fn test_select_all(cx: &mut gpui::MutableAppContext) {
7389        let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
7390        let settings = Settings::test(&cx);
7391        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7392        view.update(cx, |view, cx| {
7393            view.select_all(&SelectAll, cx);
7394            assert_eq!(
7395                view.selected_display_ranges(cx),
7396                &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
7397            );
7398        });
7399    }
7400
7401    #[gpui::test]
7402    fn test_select_line(cx: &mut gpui::MutableAppContext) {
7403        let settings = Settings::test(&cx);
7404        let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
7405        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7406        view.update(cx, |view, cx| {
7407            view.select_display_ranges(
7408                &[
7409                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7410                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7411                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7412                    DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
7413                ],
7414                cx,
7415            );
7416            view.select_line(&SelectLine, cx);
7417            assert_eq!(
7418                view.selected_display_ranges(cx),
7419                vec![
7420                    DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
7421                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
7422                ]
7423            );
7424        });
7425
7426        view.update(cx, |view, cx| {
7427            view.select_line(&SelectLine, cx);
7428            assert_eq!(
7429                view.selected_display_ranges(cx),
7430                vec![
7431                    DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
7432                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
7433                ]
7434            );
7435        });
7436
7437        view.update(cx, |view, cx| {
7438            view.select_line(&SelectLine, cx);
7439            assert_eq!(
7440                view.selected_display_ranges(cx),
7441                vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
7442            );
7443        });
7444    }
7445
7446    #[gpui::test]
7447    fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
7448        let settings = Settings::test(&cx);
7449        let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
7450        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7451        view.update(cx, |view, cx| {
7452            view.fold_ranges(
7453                vec![
7454                    Point::new(0, 2)..Point::new(1, 2),
7455                    Point::new(2, 3)..Point::new(4, 1),
7456                    Point::new(7, 0)..Point::new(8, 4),
7457                ],
7458                cx,
7459            );
7460            view.select_display_ranges(
7461                &[
7462                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7463                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7464                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7465                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
7466                ],
7467                cx,
7468            );
7469            assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
7470        });
7471
7472        view.update(cx, |view, cx| {
7473            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
7474            assert_eq!(
7475                view.display_text(cx),
7476                "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
7477            );
7478            assert_eq!(
7479                view.selected_display_ranges(cx),
7480                [
7481                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7482                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7483                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
7484                    DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
7485                ]
7486            );
7487        });
7488
7489        view.update(cx, |view, cx| {
7490            view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx);
7491            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
7492            assert_eq!(
7493                view.display_text(cx),
7494                "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
7495            );
7496            assert_eq!(
7497                view.selected_display_ranges(cx),
7498                [
7499                    DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
7500                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
7501                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
7502                    DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
7503                    DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
7504                    DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
7505                    DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
7506                    DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
7507                ]
7508            );
7509        });
7510    }
7511
7512    #[gpui::test]
7513    fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
7514        let settings = Settings::test(&cx);
7515        let buffer = MultiBuffer::build_simple("abc\ndefghi\n\njk\nlmno\n", cx);
7516        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7517
7518        view.update(cx, |view, cx| {
7519            view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx);
7520        });
7521        view.update(cx, |view, cx| {
7522            view.add_selection_above(&AddSelectionAbove, cx);
7523            assert_eq!(
7524                view.selected_display_ranges(cx),
7525                vec![
7526                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
7527                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
7528                ]
7529            );
7530        });
7531
7532        view.update(cx, |view, cx| {
7533            view.add_selection_above(&AddSelectionAbove, cx);
7534            assert_eq!(
7535                view.selected_display_ranges(cx),
7536                vec![
7537                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
7538                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
7539                ]
7540            );
7541        });
7542
7543        view.update(cx, |view, cx| {
7544            view.add_selection_below(&AddSelectionBelow, cx);
7545            assert_eq!(
7546                view.selected_display_ranges(cx),
7547                vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
7548            );
7549        });
7550
7551        view.update(cx, |view, cx| {
7552            view.add_selection_below(&AddSelectionBelow, cx);
7553            assert_eq!(
7554                view.selected_display_ranges(cx),
7555                vec![
7556                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
7557                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
7558                ]
7559            );
7560        });
7561
7562        view.update(cx, |view, cx| {
7563            view.add_selection_below(&AddSelectionBelow, cx);
7564            assert_eq!(
7565                view.selected_display_ranges(cx),
7566                vec![
7567                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
7568                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
7569                ]
7570            );
7571        });
7572
7573        view.update(cx, |view, cx| {
7574            view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx);
7575        });
7576        view.update(cx, |view, cx| {
7577            view.add_selection_below(&AddSelectionBelow, cx);
7578            assert_eq!(
7579                view.selected_display_ranges(cx),
7580                vec![
7581                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7582                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
7583                ]
7584            );
7585        });
7586
7587        view.update(cx, |view, cx| {
7588            view.add_selection_below(&AddSelectionBelow, cx);
7589            assert_eq!(
7590                view.selected_display_ranges(cx),
7591                vec![
7592                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7593                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
7594                ]
7595            );
7596        });
7597
7598        view.update(cx, |view, cx| {
7599            view.add_selection_above(&AddSelectionAbove, cx);
7600            assert_eq!(
7601                view.selected_display_ranges(cx),
7602                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
7603            );
7604        });
7605
7606        view.update(cx, |view, cx| {
7607            view.add_selection_above(&AddSelectionAbove, cx);
7608            assert_eq!(
7609                view.selected_display_ranges(cx),
7610                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
7611            );
7612        });
7613
7614        view.update(cx, |view, cx| {
7615            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx);
7616            view.add_selection_below(&AddSelectionBelow, cx);
7617            assert_eq!(
7618                view.selected_display_ranges(cx),
7619                vec![
7620                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
7621                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
7622                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
7623                ]
7624            );
7625        });
7626
7627        view.update(cx, |view, cx| {
7628            view.add_selection_below(&AddSelectionBelow, cx);
7629            assert_eq!(
7630                view.selected_display_ranges(cx),
7631                vec![
7632                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
7633                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
7634                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
7635                    DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
7636                ]
7637            );
7638        });
7639
7640        view.update(cx, |view, cx| {
7641            view.add_selection_above(&AddSelectionAbove, cx);
7642            assert_eq!(
7643                view.selected_display_ranges(cx),
7644                vec![
7645                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
7646                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
7647                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
7648                ]
7649            );
7650        });
7651
7652        view.update(cx, |view, cx| {
7653            view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx);
7654        });
7655        view.update(cx, |view, cx| {
7656            view.add_selection_above(&AddSelectionAbove, cx);
7657            assert_eq!(
7658                view.selected_display_ranges(cx),
7659                vec![
7660                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
7661                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
7662                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
7663                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
7664                ]
7665            );
7666        });
7667
7668        view.update(cx, |view, cx| {
7669            view.add_selection_below(&AddSelectionBelow, cx);
7670            assert_eq!(
7671                view.selected_display_ranges(cx),
7672                vec![
7673                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
7674                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
7675                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
7676                ]
7677            );
7678        });
7679    }
7680
7681    #[gpui::test]
7682    async fn test_select_larger_smaller_syntax_node(mut cx: gpui::TestAppContext) {
7683        let settings = cx.read(Settings::test);
7684        let language = Arc::new(Language::new(
7685            LanguageConfig::default(),
7686            Some(tree_sitter_rust::language()),
7687        ));
7688
7689        let text = r#"
7690            use mod1::mod2::{mod3, mod4};
7691
7692            fn fn_1(param1: bool, param2: &str) {
7693                let var1 = "text";
7694            }
7695        "#
7696        .unindent();
7697
7698        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
7699        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
7700        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
7701        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
7702            .await;
7703
7704        view.update(&mut cx, |view, cx| {
7705            view.select_display_ranges(
7706                &[
7707                    DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
7708                    DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
7709                    DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
7710                ],
7711                cx,
7712            );
7713            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
7714        });
7715        assert_eq!(
7716            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7717            &[
7718                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
7719                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
7720                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
7721            ]
7722        );
7723
7724        view.update(&mut cx, |view, cx| {
7725            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
7726        });
7727        assert_eq!(
7728            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7729            &[
7730                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
7731                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
7732            ]
7733        );
7734
7735        view.update(&mut cx, |view, cx| {
7736            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
7737        });
7738        assert_eq!(
7739            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7740            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
7741        );
7742
7743        // Trying to expand the selected syntax node one more time has no effect.
7744        view.update(&mut cx, |view, cx| {
7745            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
7746        });
7747        assert_eq!(
7748            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7749            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
7750        );
7751
7752        view.update(&mut cx, |view, cx| {
7753            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
7754        });
7755        assert_eq!(
7756            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7757            &[
7758                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
7759                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
7760            ]
7761        );
7762
7763        view.update(&mut cx, |view, cx| {
7764            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
7765        });
7766        assert_eq!(
7767            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7768            &[
7769                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
7770                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
7771                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
7772            ]
7773        );
7774
7775        view.update(&mut cx, |view, cx| {
7776            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
7777        });
7778        assert_eq!(
7779            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7780            &[
7781                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
7782                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
7783                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
7784            ]
7785        );
7786
7787        // Trying to shrink the selected syntax node one more time has no effect.
7788        view.update(&mut cx, |view, cx| {
7789            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
7790        });
7791        assert_eq!(
7792            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7793            &[
7794                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
7795                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
7796                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
7797            ]
7798        );
7799
7800        // Ensure that we keep expanding the selection if the larger selection starts or ends within
7801        // a fold.
7802        view.update(&mut cx, |view, cx| {
7803            view.fold_ranges(
7804                vec![
7805                    Point::new(0, 21)..Point::new(0, 24),
7806                    Point::new(3, 20)..Point::new(3, 22),
7807                ],
7808                cx,
7809            );
7810            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
7811        });
7812        assert_eq!(
7813            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7814            &[
7815                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
7816                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
7817                DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
7818            ]
7819        );
7820    }
7821
7822    #[gpui::test]
7823    async fn test_autoindent_selections(mut cx: gpui::TestAppContext) {
7824        let settings = cx.read(Settings::test);
7825        let language = Arc::new(
7826            Language::new(
7827                LanguageConfig {
7828                    brackets: vec![
7829                        BracketPair {
7830                            start: "{".to_string(),
7831                            end: "}".to_string(),
7832                            close: false,
7833                            newline: true,
7834                        },
7835                        BracketPair {
7836                            start: "(".to_string(),
7837                            end: ")".to_string(),
7838                            close: false,
7839                            newline: true,
7840                        },
7841                    ],
7842                    ..Default::default()
7843                },
7844                Some(tree_sitter_rust::language()),
7845            )
7846            .with_indents_query(
7847                r#"
7848                (_ "(" ")" @end) @indent
7849                (_ "{" "}" @end) @indent
7850                "#,
7851            )
7852            .unwrap(),
7853        );
7854
7855        let text = "fn a() {}";
7856
7857        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
7858        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
7859        let (_, editor) = cx.add_window(|cx| build_editor(buffer, settings, cx));
7860        editor
7861            .condition(&cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
7862            .await;
7863
7864        editor.update(&mut cx, |editor, cx| {
7865            editor.select_ranges([5..5, 8..8, 9..9], None, cx);
7866            editor.newline(&Newline, cx);
7867            assert_eq!(editor.text(cx), "fn a(\n    \n) {\n    \n}\n");
7868            assert_eq!(
7869                editor.selected_ranges(cx),
7870                &[
7871                    Point::new(1, 4)..Point::new(1, 4),
7872                    Point::new(3, 4)..Point::new(3, 4),
7873                    Point::new(5, 0)..Point::new(5, 0)
7874                ]
7875            );
7876        });
7877    }
7878
7879    #[gpui::test]
7880    async fn test_autoclose_pairs(mut cx: gpui::TestAppContext) {
7881        let settings = cx.read(Settings::test);
7882        let language = Arc::new(Language::new(
7883            LanguageConfig {
7884                brackets: vec![
7885                    BracketPair {
7886                        start: "{".to_string(),
7887                        end: "}".to_string(),
7888                        close: true,
7889                        newline: true,
7890                    },
7891                    BracketPair {
7892                        start: "/*".to_string(),
7893                        end: " */".to_string(),
7894                        close: true,
7895                        newline: true,
7896                    },
7897                ],
7898                ..Default::default()
7899            },
7900            Some(tree_sitter_rust::language()),
7901        ));
7902
7903        let text = r#"
7904            a
7905
7906            /
7907
7908        "#
7909        .unindent();
7910
7911        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
7912        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
7913        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
7914        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
7915            .await;
7916
7917        view.update(&mut cx, |view, cx| {
7918            view.select_display_ranges(
7919                &[
7920                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7921                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7922                ],
7923                cx,
7924            );
7925            view.handle_input(&Input("{".to_string()), cx);
7926            view.handle_input(&Input("{".to_string()), cx);
7927            view.handle_input(&Input("{".to_string()), cx);
7928            assert_eq!(
7929                view.text(cx),
7930                "
7931                {{{}}}
7932                {{{}}}
7933                /
7934
7935                "
7936                .unindent()
7937            );
7938
7939            view.move_right(&MoveRight, cx);
7940            view.handle_input(&Input("}".to_string()), cx);
7941            view.handle_input(&Input("}".to_string()), cx);
7942            view.handle_input(&Input("}".to_string()), cx);
7943            assert_eq!(
7944                view.text(cx),
7945                "
7946                {{{}}}}
7947                {{{}}}}
7948                /
7949
7950                "
7951                .unindent()
7952            );
7953
7954            view.undo(&Undo, cx);
7955            view.handle_input(&Input("/".to_string()), cx);
7956            view.handle_input(&Input("*".to_string()), cx);
7957            assert_eq!(
7958                view.text(cx),
7959                "
7960                /* */
7961                /* */
7962                /
7963
7964                "
7965                .unindent()
7966            );
7967
7968            view.undo(&Undo, cx);
7969            view.select_display_ranges(
7970                &[
7971                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7972                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7973                ],
7974                cx,
7975            );
7976            view.handle_input(&Input("*".to_string()), cx);
7977            assert_eq!(
7978                view.text(cx),
7979                "
7980                a
7981
7982                /*
7983                *
7984                "
7985                .unindent()
7986            );
7987        });
7988    }
7989
7990    #[gpui::test]
7991    async fn test_snippets(mut cx: gpui::TestAppContext) {
7992        let settings = cx.read(Settings::test);
7993
7994        let text = "
7995            a. b
7996            a. b
7997            a. b
7998        "
7999        .unindent();
8000        let buffer = cx.update(|cx| MultiBuffer::build_simple(&text, cx));
8001        let (_, editor) = cx.add_window(|cx| build_editor(buffer, settings, cx));
8002
8003        editor.update(&mut cx, |editor, cx| {
8004            let buffer = &editor.snapshot(cx).buffer_snapshot;
8005            let snippet = Snippet::parse("f(${1:one}, ${2:two}, ${1:three})$0").unwrap();
8006            let insertion_ranges = [
8007                Point::new(0, 2).to_offset(buffer)..Point::new(0, 2).to_offset(buffer),
8008                Point::new(1, 2).to_offset(buffer)..Point::new(1, 2).to_offset(buffer),
8009                Point::new(2, 2).to_offset(buffer)..Point::new(2, 2).to_offset(buffer),
8010            ];
8011
8012            editor
8013                .insert_snippet(&insertion_ranges, snippet, cx)
8014                .unwrap();
8015            assert_eq!(
8016                editor.text(cx),
8017                "
8018                    a.f(one, two, three) b
8019                    a.f(one, two, three) b
8020                    a.f(one, two, three) b
8021                "
8022                .unindent()
8023            );
8024            assert_eq!(
8025                editor.selected_ranges::<Point>(cx),
8026                &[
8027                    Point::new(0, 4)..Point::new(0, 7),
8028                    Point::new(0, 14)..Point::new(0, 19),
8029                    Point::new(1, 4)..Point::new(1, 7),
8030                    Point::new(1, 14)..Point::new(1, 19),
8031                    Point::new(2, 4)..Point::new(2, 7),
8032                    Point::new(2, 14)..Point::new(2, 19),
8033                ]
8034            );
8035
8036            // Can't move earlier than the first tab stop
8037            editor.move_to_prev_snippet_tabstop(cx);
8038            assert_eq!(
8039                editor.selected_ranges::<Point>(cx),
8040                &[
8041                    Point::new(0, 4)..Point::new(0, 7),
8042                    Point::new(0, 14)..Point::new(0, 19),
8043                    Point::new(1, 4)..Point::new(1, 7),
8044                    Point::new(1, 14)..Point::new(1, 19),
8045                    Point::new(2, 4)..Point::new(2, 7),
8046                    Point::new(2, 14)..Point::new(2, 19),
8047                ]
8048            );
8049
8050            assert!(editor.move_to_next_snippet_tabstop(cx));
8051            assert_eq!(
8052                editor.selected_ranges::<Point>(cx),
8053                &[
8054                    Point::new(0, 9)..Point::new(0, 12),
8055                    Point::new(1, 9)..Point::new(1, 12),
8056                    Point::new(2, 9)..Point::new(2, 12)
8057                ]
8058            );
8059
8060            editor.move_to_prev_snippet_tabstop(cx);
8061            assert_eq!(
8062                editor.selected_ranges::<Point>(cx),
8063                &[
8064                    Point::new(0, 4)..Point::new(0, 7),
8065                    Point::new(0, 14)..Point::new(0, 19),
8066                    Point::new(1, 4)..Point::new(1, 7),
8067                    Point::new(1, 14)..Point::new(1, 19),
8068                    Point::new(2, 4)..Point::new(2, 7),
8069                    Point::new(2, 14)..Point::new(2, 19),
8070                ]
8071            );
8072
8073            assert!(editor.move_to_next_snippet_tabstop(cx));
8074            assert!(editor.move_to_next_snippet_tabstop(cx));
8075            assert_eq!(
8076                editor.selected_ranges::<Point>(cx),
8077                &[
8078                    Point::new(0, 20)..Point::new(0, 20),
8079                    Point::new(1, 20)..Point::new(1, 20),
8080                    Point::new(2, 20)..Point::new(2, 20)
8081                ]
8082            );
8083
8084            // As soon as the last tab stop is reached, snippet state is gone
8085            editor.move_to_prev_snippet_tabstop(cx);
8086            assert_eq!(
8087                editor.selected_ranges::<Point>(cx),
8088                &[
8089                    Point::new(0, 20)..Point::new(0, 20),
8090                    Point::new(1, 20)..Point::new(1, 20),
8091                    Point::new(2, 20)..Point::new(2, 20)
8092                ]
8093            );
8094        });
8095    }
8096
8097    #[gpui::test]
8098    async fn test_completion(mut cx: gpui::TestAppContext) {
8099        let settings = cx.read(Settings::test);
8100        let (language_server, mut fake) = cx.update(|cx| {
8101            lsp::LanguageServer::fake_with_capabilities(
8102                lsp::ServerCapabilities {
8103                    completion_provider: Some(lsp::CompletionOptions {
8104                        trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
8105                        ..Default::default()
8106                    }),
8107                    ..Default::default()
8108                },
8109                cx,
8110            )
8111        });
8112
8113        let text = "
8114            one
8115            two
8116            three
8117        "
8118        .unindent();
8119
8120        let fs = FakeFs::new(cx.background().clone());
8121        fs.insert_file("/file", text).await;
8122
8123        let project = Project::test(fs, &mut cx);
8124
8125        let (worktree, relative_path) = project
8126            .update(&mut cx, |project, cx| {
8127                project.find_or_create_local_worktree("/file", false, cx)
8128            })
8129            .await
8130            .unwrap();
8131        let project_path = ProjectPath {
8132            worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
8133            path: relative_path.into(),
8134        };
8135        let buffer = project
8136            .update(&mut cx, |project, cx| project.open_buffer(project_path, cx))
8137            .await
8138            .unwrap();
8139        buffer.update(&mut cx, |buffer, cx| {
8140            buffer.set_language_server(Some(language_server), cx);
8141        });
8142
8143        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8144        buffer.next_notification(&cx).await;
8145
8146        let (_, editor) = cx.add_window(|cx| build_editor(buffer, settings, cx));
8147
8148        editor.update(&mut cx, |editor, cx| {
8149            editor.project = Some(project);
8150            editor.select_ranges([Point::new(0, 3)..Point::new(0, 3)], None, cx);
8151            editor.handle_input(&Input(".".to_string()), cx);
8152        });
8153
8154        handle_completion_request(
8155            &mut fake,
8156            "/file",
8157            Point::new(0, 4),
8158            vec![
8159                (Point::new(0, 4)..Point::new(0, 4), "first_completion"),
8160                (Point::new(0, 4)..Point::new(0, 4), "second_completion"),
8161            ],
8162        )
8163        .await;
8164        editor
8165            .condition(&cx, |editor, _| editor.context_menu_visible())
8166            .await;
8167
8168        let apply_additional_edits = editor.update(&mut cx, |editor, cx| {
8169            editor.move_down(&MoveDown, cx);
8170            let apply_additional_edits = editor
8171                .confirm_completion(&ConfirmCompletion(None), cx)
8172                .unwrap();
8173            assert_eq!(
8174                editor.text(cx),
8175                "
8176                    one.second_completion
8177                    two
8178                    three
8179                "
8180                .unindent()
8181            );
8182            apply_additional_edits
8183        });
8184
8185        handle_resolve_completion_request(
8186            &mut fake,
8187            Some((Point::new(2, 5)..Point::new(2, 5), "\nadditional edit")),
8188        )
8189        .await;
8190        apply_additional_edits.await.unwrap();
8191        assert_eq!(
8192            editor.read_with(&cx, |editor, cx| editor.text(cx)),
8193            "
8194                one.second_completion
8195                two
8196                three
8197                additional edit
8198            "
8199            .unindent()
8200        );
8201
8202        editor.update(&mut cx, |editor, cx| {
8203            editor.select_ranges(
8204                [
8205                    Point::new(1, 3)..Point::new(1, 3),
8206                    Point::new(2, 5)..Point::new(2, 5),
8207                ],
8208                None,
8209                cx,
8210            );
8211
8212            editor.handle_input(&Input(" ".to_string()), cx);
8213            assert!(editor.context_menu.is_none());
8214            editor.handle_input(&Input("s".to_string()), cx);
8215            assert!(editor.context_menu.is_none());
8216        });
8217
8218        handle_completion_request(
8219            &mut fake,
8220            "/file",
8221            Point::new(2, 7),
8222            vec![
8223                (Point::new(2, 6)..Point::new(2, 7), "fourth_completion"),
8224                (Point::new(2, 6)..Point::new(2, 7), "fifth_completion"),
8225                (Point::new(2, 6)..Point::new(2, 7), "sixth_completion"),
8226            ],
8227        )
8228        .await;
8229        editor
8230            .condition(&cx, |editor, _| editor.context_menu_visible())
8231            .await;
8232
8233        editor.update(&mut cx, |editor, cx| {
8234            editor.handle_input(&Input("i".to_string()), cx);
8235        });
8236
8237        handle_completion_request(
8238            &mut fake,
8239            "/file",
8240            Point::new(2, 8),
8241            vec![
8242                (Point::new(2, 6)..Point::new(2, 8), "fourth_completion"),
8243                (Point::new(2, 6)..Point::new(2, 8), "fifth_completion"),
8244                (Point::new(2, 6)..Point::new(2, 8), "sixth_completion"),
8245            ],
8246        )
8247        .await;
8248        editor
8249            .condition(&cx, |editor, _| editor.context_menu_visible())
8250            .await;
8251
8252        let apply_additional_edits = editor.update(&mut cx, |editor, cx| {
8253            let apply_additional_edits = editor
8254                .confirm_completion(&ConfirmCompletion(None), cx)
8255                .unwrap();
8256            assert_eq!(
8257                editor.text(cx),
8258                "
8259                    one.second_completion
8260                    two sixth_completion
8261                    three sixth_completion
8262                    additional edit
8263                "
8264                .unindent()
8265            );
8266            apply_additional_edits
8267        });
8268        handle_resolve_completion_request(&mut fake, None).await;
8269        apply_additional_edits.await.unwrap();
8270
8271        async fn handle_completion_request(
8272            fake: &mut FakeLanguageServer,
8273            path: &'static str,
8274            position: Point,
8275            completions: Vec<(Range<Point>, &'static str)>,
8276        ) {
8277            fake.handle_request::<lsp::request::Completion, _>(move |params, _| {
8278                assert_eq!(
8279                    params.text_document_position.text_document.uri,
8280                    lsp::Url::from_file_path(path).unwrap()
8281                );
8282                assert_eq!(
8283                    params.text_document_position.position,
8284                    lsp::Position::new(position.row, position.column)
8285                );
8286                Some(lsp::CompletionResponse::Array(
8287                    completions
8288                        .iter()
8289                        .map(|(range, new_text)| lsp::CompletionItem {
8290                            label: new_text.to_string(),
8291                            text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
8292                                range: lsp::Range::new(
8293                                    lsp::Position::new(range.start.row, range.start.column),
8294                                    lsp::Position::new(range.start.row, range.start.column),
8295                                ),
8296                                new_text: new_text.to_string(),
8297                            })),
8298                            ..Default::default()
8299                        })
8300                        .collect(),
8301                ))
8302            })
8303            .next()
8304            .await;
8305        }
8306
8307        async fn handle_resolve_completion_request(
8308            fake: &mut FakeLanguageServer,
8309            edit: Option<(Range<Point>, &'static str)>,
8310        ) {
8311            fake.handle_request::<lsp::request::ResolveCompletionItem, _>(move |_, _| {
8312                lsp::CompletionItem {
8313                    additional_text_edits: edit.clone().map(|(range, new_text)| {
8314                        vec![lsp::TextEdit::new(
8315                            lsp::Range::new(
8316                                lsp::Position::new(range.start.row, range.start.column),
8317                                lsp::Position::new(range.end.row, range.end.column),
8318                            ),
8319                            new_text.to_string(),
8320                        )]
8321                    }),
8322                    ..Default::default()
8323                }
8324            })
8325            .next()
8326            .await;
8327        }
8328    }
8329
8330    #[gpui::test]
8331    async fn test_toggle_comment(mut cx: gpui::TestAppContext) {
8332        let settings = cx.read(Settings::test);
8333        let language = Arc::new(Language::new(
8334            LanguageConfig {
8335                line_comment: Some("// ".to_string()),
8336                ..Default::default()
8337            },
8338            Some(tree_sitter_rust::language()),
8339        ));
8340
8341        let text = "
8342            fn a() {
8343                //b();
8344                // c();
8345                //  d();
8346            }
8347        "
8348        .unindent();
8349
8350        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8351        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8352        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
8353
8354        view.update(&mut cx, |editor, cx| {
8355            // If multiple selections intersect a line, the line is only
8356            // toggled once.
8357            editor.select_display_ranges(
8358                &[
8359                    DisplayPoint::new(1, 3)..DisplayPoint::new(2, 3),
8360                    DisplayPoint::new(3, 5)..DisplayPoint::new(3, 6),
8361                ],
8362                cx,
8363            );
8364            editor.toggle_comments(&ToggleComments, cx);
8365            assert_eq!(
8366                editor.text(cx),
8367                "
8368                    fn a() {
8369                        b();
8370                        c();
8371                         d();
8372                    }
8373                "
8374                .unindent()
8375            );
8376
8377            // The comment prefix is inserted at the same column for every line
8378            // in a selection.
8379            editor.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(3, 6)], cx);
8380            editor.toggle_comments(&ToggleComments, cx);
8381            assert_eq!(
8382                editor.text(cx),
8383                "
8384                    fn a() {
8385                        // b();
8386                        // c();
8387                        //  d();
8388                    }
8389                "
8390                .unindent()
8391            );
8392
8393            // If a selection ends at the beginning of a line, that line is not toggled.
8394            editor.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(3, 0)], cx);
8395            editor.toggle_comments(&ToggleComments, cx);
8396            assert_eq!(
8397                editor.text(cx),
8398                "
8399                        fn a() {
8400                            // b();
8401                            c();
8402                            //  d();
8403                        }
8404                    "
8405                .unindent()
8406            );
8407        });
8408    }
8409
8410    #[gpui::test]
8411    fn test_editing_disjoint_excerpts(cx: &mut gpui::MutableAppContext) {
8412        let settings = Settings::test(cx);
8413        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
8414        let multibuffer = cx.add_model(|cx| {
8415            let mut multibuffer = MultiBuffer::new(0);
8416            multibuffer.push_excerpts(
8417                buffer.clone(),
8418                [
8419                    Point::new(0, 0)..Point::new(0, 4),
8420                    Point::new(1, 0)..Point::new(1, 4),
8421                ],
8422                cx,
8423            );
8424            multibuffer
8425        });
8426
8427        assert_eq!(multibuffer.read(cx).read(cx).text(), "aaaa\nbbbb");
8428
8429        let (_, view) = cx.add_window(Default::default(), |cx| {
8430            build_editor(multibuffer, settings, cx)
8431        });
8432        view.update(cx, |view, cx| {
8433            assert_eq!(view.text(cx), "aaaa\nbbbb");
8434            view.select_ranges(
8435                [
8436                    Point::new(0, 0)..Point::new(0, 0),
8437                    Point::new(1, 0)..Point::new(1, 0),
8438                ],
8439                None,
8440                cx,
8441            );
8442
8443            view.handle_input(&Input("X".to_string()), cx);
8444            assert_eq!(view.text(cx), "Xaaaa\nXbbbb");
8445            assert_eq!(
8446                view.selected_ranges(cx),
8447                [
8448                    Point::new(0, 1)..Point::new(0, 1),
8449                    Point::new(1, 1)..Point::new(1, 1),
8450                ]
8451            )
8452        });
8453    }
8454
8455    #[gpui::test]
8456    fn test_editing_overlapping_excerpts(cx: &mut gpui::MutableAppContext) {
8457        let settings = Settings::test(cx);
8458        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
8459        let multibuffer = cx.add_model(|cx| {
8460            let mut multibuffer = MultiBuffer::new(0);
8461            multibuffer.push_excerpts(
8462                buffer,
8463                [
8464                    Point::new(0, 0)..Point::new(1, 4),
8465                    Point::new(1, 0)..Point::new(2, 4),
8466                ],
8467                cx,
8468            );
8469            multibuffer
8470        });
8471
8472        assert_eq!(
8473            multibuffer.read(cx).read(cx).text(),
8474            "aaaa\nbbbb\nbbbb\ncccc"
8475        );
8476
8477        let (_, view) = cx.add_window(Default::default(), |cx| {
8478            build_editor(multibuffer, settings, cx)
8479        });
8480        view.update(cx, |view, cx| {
8481            view.select_ranges(
8482                [
8483                    Point::new(1, 1)..Point::new(1, 1),
8484                    Point::new(2, 3)..Point::new(2, 3),
8485                ],
8486                None,
8487                cx,
8488            );
8489
8490            view.handle_input(&Input("X".to_string()), cx);
8491            assert_eq!(view.text(cx), "aaaa\nbXbbXb\nbXbbXb\ncccc");
8492            assert_eq!(
8493                view.selected_ranges(cx),
8494                [
8495                    Point::new(1, 2)..Point::new(1, 2),
8496                    Point::new(2, 5)..Point::new(2, 5),
8497                ]
8498            );
8499
8500            view.newline(&Newline, cx);
8501            assert_eq!(view.text(cx), "aaaa\nbX\nbbX\nb\nbX\nbbX\nb\ncccc");
8502            assert_eq!(
8503                view.selected_ranges(cx),
8504                [
8505                    Point::new(2, 0)..Point::new(2, 0),
8506                    Point::new(6, 0)..Point::new(6, 0),
8507                ]
8508            );
8509        });
8510    }
8511
8512    #[gpui::test]
8513    fn test_refresh_selections(cx: &mut gpui::MutableAppContext) {
8514        let settings = Settings::test(cx);
8515        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
8516        let mut excerpt1_id = None;
8517        let multibuffer = cx.add_model(|cx| {
8518            let mut multibuffer = MultiBuffer::new(0);
8519            excerpt1_id = multibuffer
8520                .push_excerpts(
8521                    buffer.clone(),
8522                    [
8523                        Point::new(0, 0)..Point::new(1, 4),
8524                        Point::new(1, 0)..Point::new(2, 4),
8525                    ],
8526                    cx,
8527                )
8528                .into_iter()
8529                .next();
8530            multibuffer
8531        });
8532        assert_eq!(
8533            multibuffer.read(cx).read(cx).text(),
8534            "aaaa\nbbbb\nbbbb\ncccc"
8535        );
8536        let (_, editor) = cx.add_window(Default::default(), |cx| {
8537            let mut editor = build_editor(multibuffer.clone(), settings, cx);
8538            editor.select_ranges(
8539                [
8540                    Point::new(1, 3)..Point::new(1, 3),
8541                    Point::new(2, 1)..Point::new(2, 1),
8542                ],
8543                None,
8544                cx,
8545            );
8546            editor
8547        });
8548
8549        // Refreshing selections is a no-op when excerpts haven't changed.
8550        editor.update(cx, |editor, cx| {
8551            editor.refresh_selections(cx);
8552            assert_eq!(
8553                editor.selected_ranges(cx),
8554                [
8555                    Point::new(1, 3)..Point::new(1, 3),
8556                    Point::new(2, 1)..Point::new(2, 1),
8557                ]
8558            );
8559        });
8560
8561        multibuffer.update(cx, |multibuffer, cx| {
8562            multibuffer.remove_excerpts([&excerpt1_id.unwrap()], cx);
8563        });
8564        editor.update(cx, |editor, cx| {
8565            // Removing an excerpt causes the first selection to become degenerate.
8566            assert_eq!(
8567                editor.selected_ranges(cx),
8568                [
8569                    Point::new(0, 0)..Point::new(0, 0),
8570                    Point::new(0, 1)..Point::new(0, 1)
8571                ]
8572            );
8573
8574            // Refreshing selections will relocate the first selection to the original buffer
8575            // location.
8576            editor.refresh_selections(cx);
8577            assert_eq!(
8578                editor.selected_ranges(cx),
8579                [
8580                    Point::new(0, 1)..Point::new(0, 1),
8581                    Point::new(0, 3)..Point::new(0, 3)
8582                ]
8583            );
8584        });
8585    }
8586
8587    #[gpui::test]
8588    async fn test_extra_newline_insertion(mut cx: gpui::TestAppContext) {
8589        let settings = cx.read(Settings::test);
8590        let language = Arc::new(Language::new(
8591            LanguageConfig {
8592                brackets: vec![
8593                    BracketPair {
8594                        start: "{".to_string(),
8595                        end: "}".to_string(),
8596                        close: true,
8597                        newline: true,
8598                    },
8599                    BracketPair {
8600                        start: "/* ".to_string(),
8601                        end: " */".to_string(),
8602                        close: true,
8603                        newline: true,
8604                    },
8605                ],
8606                ..Default::default()
8607            },
8608            Some(tree_sitter_rust::language()),
8609        ));
8610
8611        let text = concat!(
8612            "{   }\n",     // Suppress rustfmt
8613            "  x\n",       //
8614            "  /*   */\n", //
8615            "x\n",         //
8616            "{{} }\n",     //
8617        );
8618
8619        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8620        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8621        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
8622        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
8623            .await;
8624
8625        view.update(&mut cx, |view, cx| {
8626            view.select_display_ranges(
8627                &[
8628                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
8629                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
8630                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
8631                ],
8632                cx,
8633            );
8634            view.newline(&Newline, cx);
8635
8636            assert_eq!(
8637                view.buffer().read(cx).read(cx).text(),
8638                concat!(
8639                    "{ \n",    // Suppress rustfmt
8640                    "\n",      //
8641                    "}\n",     //
8642                    "  x\n",   //
8643                    "  /* \n", //
8644                    "  \n",    //
8645                    "  */\n",  //
8646                    "x\n",     //
8647                    "{{} \n",  //
8648                    "}\n",     //
8649                )
8650            );
8651        });
8652    }
8653
8654    #[gpui::test]
8655    fn test_highlighted_ranges(cx: &mut gpui::MutableAppContext) {
8656        let buffer = MultiBuffer::build_simple(&sample_text(16, 8, 'a'), cx);
8657        let settings = Settings::test(&cx);
8658        let (_, editor) = cx.add_window(Default::default(), |cx| {
8659            build_editor(buffer.clone(), settings, cx)
8660        });
8661
8662        editor.update(cx, |editor, cx| {
8663            struct Type1;
8664            struct Type2;
8665
8666            let buffer = buffer.read(cx).snapshot(cx);
8667
8668            let anchor_range = |range: Range<Point>| {
8669                buffer.anchor_after(range.start)..buffer.anchor_after(range.end)
8670            };
8671
8672            editor.highlight_ranges::<Type1>(
8673                vec![
8674                    anchor_range(Point::new(2, 1)..Point::new(2, 3)),
8675                    anchor_range(Point::new(4, 2)..Point::new(4, 4)),
8676                    anchor_range(Point::new(6, 3)..Point::new(6, 5)),
8677                    anchor_range(Point::new(8, 4)..Point::new(8, 6)),
8678                ],
8679                Color::red(),
8680                cx,
8681            );
8682            editor.highlight_ranges::<Type2>(
8683                vec![
8684                    anchor_range(Point::new(3, 2)..Point::new(3, 5)),
8685                    anchor_range(Point::new(5, 3)..Point::new(5, 6)),
8686                    anchor_range(Point::new(7, 4)..Point::new(7, 7)),
8687                    anchor_range(Point::new(9, 5)..Point::new(9, 8)),
8688                ],
8689                Color::green(),
8690                cx,
8691            );
8692
8693            let snapshot = editor.snapshot(cx);
8694            let mut highlighted_ranges = editor.highlighted_ranges_in_range(
8695                anchor_range(Point::new(3, 4)..Point::new(7, 4)),
8696                &snapshot,
8697            );
8698            // Enforce a consistent ordering based on color without relying on the ordering of the
8699            // highlight's `TypeId` which is non-deterministic.
8700            highlighted_ranges.sort_unstable_by_key(|(_, color)| *color);
8701            assert_eq!(
8702                highlighted_ranges,
8703                &[
8704                    (
8705                        DisplayPoint::new(3, 2)..DisplayPoint::new(3, 5),
8706                        Color::green(),
8707                    ),
8708                    (
8709                        DisplayPoint::new(5, 3)..DisplayPoint::new(5, 6),
8710                        Color::green(),
8711                    ),
8712                    (
8713                        DisplayPoint::new(4, 2)..DisplayPoint::new(4, 4),
8714                        Color::red(),
8715                    ),
8716                    (
8717                        DisplayPoint::new(6, 3)..DisplayPoint::new(6, 5),
8718                        Color::red(),
8719                    ),
8720                ]
8721            );
8722            assert_eq!(
8723                editor.highlighted_ranges_in_range(
8724                    anchor_range(Point::new(5, 6)..Point::new(6, 4)),
8725                    &snapshot,
8726                ),
8727                &[(
8728                    DisplayPoint::new(6, 3)..DisplayPoint::new(6, 5),
8729                    Color::red(),
8730                )]
8731            );
8732        });
8733    }
8734
8735    #[test]
8736    fn test_combine_syntax_and_fuzzy_match_highlights() {
8737        let string = "abcdefghijklmnop";
8738        let default = HighlightStyle::default();
8739        let syntax_ranges = [
8740            (
8741                0..3,
8742                HighlightStyle {
8743                    color: Color::red(),
8744                    ..default
8745                },
8746            ),
8747            (
8748                4..8,
8749                HighlightStyle {
8750                    color: Color::green(),
8751                    ..default
8752                },
8753            ),
8754        ];
8755        let match_indices = [4, 6, 7, 8];
8756        assert_eq!(
8757            combine_syntax_and_fuzzy_match_highlights(
8758                &string,
8759                default,
8760                syntax_ranges.into_iter(),
8761                &match_indices,
8762            ),
8763            &[
8764                (
8765                    0..3,
8766                    HighlightStyle {
8767                        color: Color::red(),
8768                        ..default
8769                    },
8770                ),
8771                (
8772                    4..5,
8773                    HighlightStyle {
8774                        color: Color::green(),
8775                        font_properties: *fonts::Properties::default().weight(fonts::Weight::BOLD),
8776                        ..default
8777                    },
8778                ),
8779                (
8780                    5..6,
8781                    HighlightStyle {
8782                        color: Color::green(),
8783                        ..default
8784                    },
8785                ),
8786                (
8787                    6..8,
8788                    HighlightStyle {
8789                        color: Color::green(),
8790                        font_properties: *fonts::Properties::default().weight(fonts::Weight::BOLD),
8791                        ..default
8792                    },
8793                ),
8794                (
8795                    8..9,
8796                    HighlightStyle {
8797                        font_properties: *fonts::Properties::default().weight(fonts::Weight::BOLD),
8798                        ..default
8799                    },
8800                ),
8801            ]
8802        );
8803    }
8804
8805    fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
8806        let point = DisplayPoint::new(row as u32, column as u32);
8807        point..point
8808    }
8809
8810    fn build_editor(
8811        buffer: ModelHandle<MultiBuffer>,
8812        settings: Settings,
8813        cx: &mut ViewContext<Editor>,
8814    ) -> Editor {
8815        let settings = watch::channel_with(settings);
8816        Editor::new(EditorMode::Full, buffer, None, settings.1, None, cx)
8817    }
8818}
8819
8820trait RangeExt<T> {
8821    fn sorted(&self) -> Range<T>;
8822    fn to_inclusive(&self) -> RangeInclusive<T>;
8823}
8824
8825impl<T: Ord + Clone> RangeExt<T> for Range<T> {
8826    fn sorted(&self) -> Self {
8827        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
8828    }
8829
8830    fn to_inclusive(&self) -> RangeInclusive<T> {
8831        self.start.clone()..=self.end.clone()
8832    }
8833}