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