editor.rs

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