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.range.is_empty()
4215                    && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
4216                {
4217                    Some((entry.range, entry.diagnostic.group_id))
4218                } else {
4219                    None
4220                }
4221            });
4222
4223            if let Some((primary_range, group_id)) = group {
4224                self.activate_diagnostics(group_id, cx);
4225                self.update_selections(
4226                    vec![Selection {
4227                        id: selection.id,
4228                        start: primary_range.start,
4229                        end: primary_range.start,
4230                        reversed: false,
4231                        goal: SelectionGoal::None,
4232                    }],
4233                    Some(Autoscroll::Center),
4234                    cx,
4235                );
4236                break;
4237            } else {
4238                // Cycle around to the start of the buffer, potentially moving back to the start of
4239                // the currently active diagnostic.
4240                active_primary_range.take();
4241                if direction == Direction::Prev {
4242                    if search_start == buffer.len() {
4243                        break;
4244                    } else {
4245                        search_start = buffer.len();
4246                    }
4247                } else {
4248                    if search_start == 0 {
4249                        break;
4250                    } else {
4251                        search_start = 0;
4252                    }
4253                }
4254            }
4255        }
4256    }
4257
4258    pub fn go_to_definition(
4259        workspace: &mut Workspace,
4260        _: &GoToDefinition,
4261        cx: &mut ViewContext<Workspace>,
4262    ) {
4263        let active_item = workspace.active_item(cx);
4264        let editor_handle = if let Some(editor) = active_item
4265            .as_ref()
4266            .and_then(|item| item.act_as::<Self>(cx))
4267        {
4268            editor
4269        } else {
4270            return;
4271        };
4272
4273        let editor = editor_handle.read(cx);
4274        let head = editor.newest_selection::<usize>(cx).head();
4275        let (buffer, head) =
4276            if let Some(text_anchor) = editor.buffer.read(cx).text_anchor_for_position(head, cx) {
4277                text_anchor
4278            } else {
4279                return;
4280            };
4281
4282        let definitions = workspace
4283            .project()
4284            .update(cx, |project, cx| project.definition(&buffer, head, cx));
4285        cx.spawn(|workspace, mut cx| async move {
4286            let definitions = definitions.await?;
4287            workspace.update(&mut cx, |workspace, cx| {
4288                let nav_history = workspace.active_pane().read(cx).nav_history().clone();
4289                for definition in definitions {
4290                    let range = definition.range.to_offset(definition.buffer.read(cx));
4291                    let target_editor_handle = workspace
4292                        .open_item(BufferItemHandle(definition.buffer), cx)
4293                        .downcast::<Self>()
4294                        .unwrap();
4295
4296                    target_editor_handle.update(cx, |target_editor, cx| {
4297                        // When selecting a definition in a different buffer, disable the nav history
4298                        // to avoid creating a history entry at the previous cursor location.
4299                        if editor_handle != target_editor_handle {
4300                            nav_history.borrow_mut().disable();
4301                        }
4302                        target_editor.select_ranges([range], Some(Autoscroll::Center), cx);
4303                        nav_history.borrow_mut().enable();
4304                    });
4305                }
4306            });
4307
4308            Ok::<(), anyhow::Error>(())
4309        })
4310        .detach_and_log_err(cx);
4311    }
4312
4313    pub fn find_all_references(
4314        workspace: &mut Workspace,
4315        _: &FindAllReferences,
4316        cx: &mut ViewContext<Workspace>,
4317    ) -> Option<Task<Result<()>>> {
4318        let active_item = workspace.active_item(cx)?;
4319        let editor_handle = active_item.act_as::<Self>(cx)?;
4320
4321        let editor = editor_handle.read(cx);
4322        let head = editor.newest_selection::<usize>(cx).head();
4323        let (buffer, head) = editor.buffer.read(cx).text_anchor_for_position(head, cx)?;
4324        let replica_id = editor.replica_id(cx);
4325
4326        let references = workspace
4327            .project()
4328            .update(cx, |project, cx| project.references(&buffer, head, cx));
4329        Some(cx.spawn(|workspace, mut cx| async move {
4330            let mut locations = references.await?;
4331            if locations.is_empty() {
4332                return Ok(());
4333            }
4334
4335            locations.sort_by_key(|location| location.buffer.id());
4336            let mut locations = locations.into_iter().peekable();
4337            let mut ranges_to_highlight = Vec::new();
4338
4339            let excerpt_buffer = cx.add_model(|cx| {
4340                let mut symbol_name = None;
4341                let mut multibuffer = MultiBuffer::new(replica_id);
4342                while let Some(location) = locations.next() {
4343                    let buffer = location.buffer.read(cx);
4344                    let mut ranges_for_buffer = Vec::new();
4345                    let range = location.range.to_offset(buffer);
4346                    ranges_for_buffer.push(range.clone());
4347                    if symbol_name.is_none() {
4348                        symbol_name = Some(buffer.text_for_range(range).collect::<String>());
4349                    }
4350
4351                    while let Some(next_location) = locations.peek() {
4352                        if next_location.buffer == location.buffer {
4353                            ranges_for_buffer.push(next_location.range.to_offset(buffer));
4354                            locations.next();
4355                        } else {
4356                            break;
4357                        }
4358                    }
4359
4360                    ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
4361                    ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
4362                        location.buffer.clone(),
4363                        ranges_for_buffer,
4364                        1,
4365                        cx,
4366                    ));
4367                }
4368                multibuffer.with_title(format!("References to `{}`", symbol_name.unwrap()))
4369            });
4370
4371            workspace.update(&mut cx, |workspace, cx| {
4372                let editor = workspace.open_item(MultiBufferItemHandle(excerpt_buffer), cx);
4373                if let Some(editor) = editor.act_as::<Self>(cx) {
4374                    editor.update(cx, |editor, cx| {
4375                        let color = editor.style(cx).highlighted_line_background;
4376                        editor.highlight_background::<Self>(ranges_to_highlight, color, cx);
4377                    });
4378                }
4379            });
4380
4381            Ok(())
4382        }))
4383    }
4384
4385    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
4386        use language::ToOffset as _;
4387
4388        let project = self.project.clone()?;
4389        let selection = self.newest_anchor_selection().clone();
4390        let (cursor_buffer, cursor_buffer_position) = self
4391            .buffer
4392            .read(cx)
4393            .text_anchor_for_position(selection.head(), cx)?;
4394        let (tail_buffer, _) = self
4395            .buffer
4396            .read(cx)
4397            .text_anchor_for_position(selection.tail(), cx)?;
4398        if tail_buffer != cursor_buffer {
4399            return None;
4400        }
4401
4402        let snapshot = cursor_buffer.read(cx).snapshot();
4403        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
4404        let prepare_rename = project.update(cx, |project, cx| {
4405            project.prepare_rename(cursor_buffer, cursor_buffer_offset, cx)
4406        });
4407
4408        Some(cx.spawn(|this, mut cx| async move {
4409            if let Some(rename_range) = prepare_rename.await? {
4410                let rename_buffer_range = rename_range.to_offset(&snapshot);
4411                let cursor_offset_in_rename_range =
4412                    cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
4413
4414                this.update(&mut cx, |this, cx| {
4415                    this.take_rename(false, cx);
4416                    let style = this.style(cx);
4417                    let buffer = this.buffer.read(cx).read(cx);
4418                    let cursor_offset = selection.head().to_offset(&buffer);
4419                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
4420                    let rename_end = rename_start + rename_buffer_range.len();
4421                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
4422                    let mut old_highlight_id = None;
4423                    let old_name = buffer
4424                        .chunks(rename_start..rename_end, true)
4425                        .map(|chunk| {
4426                            if old_highlight_id.is_none() {
4427                                old_highlight_id = chunk.syntax_highlight_id;
4428                            }
4429                            chunk.text
4430                        })
4431                        .collect();
4432
4433                    drop(buffer);
4434
4435                    // Position the selection in the rename editor so that it matches the current selection.
4436                    this.show_local_selections = false;
4437                    let rename_editor = cx.add_view(|cx| {
4438                        let mut editor = Editor::single_line(None, cx);
4439                        if let Some(old_highlight_id) = old_highlight_id {
4440                            editor.override_text_style =
4441                                Some(Box::new(move |style| old_highlight_id.style(&style.syntax)));
4442                        }
4443                        editor
4444                            .buffer
4445                            .update(cx, |buffer, cx| buffer.edit([0..0], &old_name, cx));
4446                        editor.select_all(&SelectAll, cx);
4447                        editor
4448                    });
4449
4450                    let ranges = this
4451                        .clear_background_highlights::<DocumentHighlightWrite>(cx)
4452                        .into_iter()
4453                        .flat_map(|(_, ranges)| ranges)
4454                        .chain(
4455                            this.clear_background_highlights::<DocumentHighlightRead>(cx)
4456                                .into_iter()
4457                                .flat_map(|(_, ranges)| ranges),
4458                        )
4459                        .collect();
4460                    this.highlight_text::<Rename>(
4461                        ranges,
4462                        HighlightStyle {
4463                            fade_out: Some(style.rename_fade),
4464                            ..Default::default()
4465                        },
4466                        cx,
4467                    );
4468                    cx.focus(&rename_editor);
4469                    let block_id = this.insert_blocks(
4470                        [BlockProperties {
4471                            position: range.start.clone(),
4472                            height: 1,
4473                            render: Arc::new({
4474                                let editor = rename_editor.clone();
4475                                move |cx: &BlockContext| {
4476                                    ChildView::new(editor.clone())
4477                                        .contained()
4478                                        .with_padding_left(cx.anchor_x)
4479                                        .boxed()
4480                                }
4481                            }),
4482                            disposition: BlockDisposition::Below,
4483                        }],
4484                        cx,
4485                    )[0];
4486                    this.pending_rename = Some(RenameState {
4487                        range,
4488                        old_name,
4489                        editor: rename_editor,
4490                        block_id,
4491                    });
4492                });
4493            }
4494
4495            Ok(())
4496        }))
4497    }
4498
4499    pub fn confirm_rename(
4500        workspace: &mut Workspace,
4501        _: &ConfirmRename,
4502        cx: &mut ViewContext<Workspace>,
4503    ) -> Option<Task<Result<()>>> {
4504        let editor = workspace.active_item(cx)?.act_as::<Editor>(cx)?;
4505
4506        let (buffer, range, old_name, new_name) = editor.update(cx, |editor, cx| {
4507            let rename = editor.take_rename(false, cx)?;
4508            let buffer = editor.buffer.read(cx);
4509            let (start_buffer, start) =
4510                buffer.text_anchor_for_position(rename.range.start.clone(), cx)?;
4511            let (end_buffer, end) =
4512                buffer.text_anchor_for_position(rename.range.end.clone(), cx)?;
4513            if start_buffer == end_buffer {
4514                let new_name = rename.editor.read(cx).text(cx);
4515                Some((start_buffer, start..end, rename.old_name, new_name))
4516            } else {
4517                None
4518            }
4519        })?;
4520
4521        let rename = workspace.project().clone().update(cx, |project, cx| {
4522            project.perform_rename(
4523                buffer.clone(),
4524                range.start.clone(),
4525                new_name.clone(),
4526                true,
4527                cx,
4528            )
4529        });
4530
4531        Some(cx.spawn(|workspace, mut cx| async move {
4532            let project_transaction = rename.await?;
4533            Self::open_project_transaction(
4534                editor.clone(),
4535                workspace,
4536                project_transaction,
4537                format!("Rename: {}{}", old_name, new_name),
4538                cx.clone(),
4539            )
4540            .await?;
4541
4542            editor.update(&mut cx, |editor, cx| {
4543                editor.refresh_document_highlights(cx);
4544            });
4545            Ok(())
4546        }))
4547    }
4548
4549    fn take_rename(
4550        &mut self,
4551        moving_cursor: bool,
4552        cx: &mut ViewContext<Self>,
4553    ) -> Option<RenameState> {
4554        let rename = self.pending_rename.take()?;
4555        self.remove_blocks([rename.block_id].into_iter().collect(), cx);
4556        self.clear_text_highlights::<Rename>(cx);
4557        self.show_local_selections = true;
4558
4559        if moving_cursor {
4560            let cursor_in_rename_editor =
4561                rename.editor.read(cx).newest_selection::<usize>(cx).head();
4562
4563            // Update the selection to match the position of the selection inside
4564            // the rename editor.
4565            let snapshot = self.buffer.read(cx).read(cx);
4566            let rename_range = rename.range.to_offset(&snapshot);
4567            let cursor_in_editor = snapshot
4568                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
4569                .min(rename_range.end);
4570            drop(snapshot);
4571
4572            self.update_selections(
4573                vec![Selection {
4574                    id: self.newest_anchor_selection().id,
4575                    start: cursor_in_editor,
4576                    end: cursor_in_editor,
4577                    reversed: false,
4578                    goal: SelectionGoal::None,
4579                }],
4580                None,
4581                cx,
4582            );
4583        }
4584
4585        Some(rename)
4586    }
4587
4588    fn invalidate_rename_range(
4589        &mut self,
4590        buffer: &MultiBufferSnapshot,
4591        cx: &mut ViewContext<Self>,
4592    ) {
4593        if let Some(rename) = self.pending_rename.as_ref() {
4594            if self.selections.len() == 1 {
4595                let head = self.selections[0].head().to_offset(buffer);
4596                let range = rename.range.to_offset(buffer).to_inclusive();
4597                if range.contains(&head) {
4598                    return;
4599                }
4600            }
4601            let rename = self.pending_rename.take().unwrap();
4602            self.remove_blocks([rename.block_id].into_iter().collect(), cx);
4603            self.clear_background_highlights::<Rename>(cx);
4604        }
4605    }
4606
4607    #[cfg(any(test, feature = "test-support"))]
4608    pub fn pending_rename(&self) -> Option<&RenameState> {
4609        self.pending_rename.as_ref()
4610    }
4611
4612    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
4613        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
4614            let buffer = self.buffer.read(cx).snapshot(cx);
4615            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
4616            let is_valid = buffer
4617                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
4618                .any(|entry| {
4619                    entry.diagnostic.is_primary
4620                        && !entry.range.is_empty()
4621                        && entry.range.start == primary_range_start
4622                        && entry.diagnostic.message == active_diagnostics.primary_message
4623                });
4624
4625            if is_valid != active_diagnostics.is_valid {
4626                active_diagnostics.is_valid = is_valid;
4627                let mut new_styles = HashMap::default();
4628                for (block_id, diagnostic) in &active_diagnostics.blocks {
4629                    new_styles.insert(
4630                        *block_id,
4631                        diagnostic_block_renderer(diagnostic.clone(), is_valid),
4632                    );
4633                }
4634                self.display_map
4635                    .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
4636            }
4637        }
4638    }
4639
4640    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
4641        self.dismiss_diagnostics(cx);
4642        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
4643            let buffer = self.buffer.read(cx).snapshot(cx);
4644
4645            let mut primary_range = None;
4646            let mut primary_message = None;
4647            let mut group_end = Point::zero();
4648            let diagnostic_group = buffer
4649                .diagnostic_group::<Point>(group_id)
4650                .map(|entry| {
4651                    if entry.range.end > group_end {
4652                        group_end = entry.range.end;
4653                    }
4654                    if entry.diagnostic.is_primary {
4655                        primary_range = Some(entry.range.clone());
4656                        primary_message = Some(entry.diagnostic.message.clone());
4657                    }
4658                    entry
4659                })
4660                .collect::<Vec<_>>();
4661            let primary_range = primary_range.unwrap();
4662            let primary_message = primary_message.unwrap();
4663            let primary_range =
4664                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
4665
4666            let blocks = display_map
4667                .insert_blocks(
4668                    diagnostic_group.iter().map(|entry| {
4669                        let diagnostic = entry.diagnostic.clone();
4670                        let message_height = diagnostic.message.lines().count() as u8;
4671                        BlockProperties {
4672                            position: buffer.anchor_after(entry.range.start),
4673                            height: message_height,
4674                            render: diagnostic_block_renderer(diagnostic, true),
4675                            disposition: BlockDisposition::Below,
4676                        }
4677                    }),
4678                    cx,
4679                )
4680                .into_iter()
4681                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
4682                .collect();
4683
4684            Some(ActiveDiagnosticGroup {
4685                primary_range,
4686                primary_message,
4687                blocks,
4688                is_valid: true,
4689            })
4690        });
4691    }
4692
4693    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
4694        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
4695            self.display_map.update(cx, |display_map, cx| {
4696                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
4697            });
4698            cx.notify();
4699        }
4700    }
4701
4702    fn build_columnar_selection(
4703        &mut self,
4704        display_map: &DisplaySnapshot,
4705        row: u32,
4706        columns: &Range<u32>,
4707        reversed: bool,
4708    ) -> Option<Selection<Point>> {
4709        let is_empty = columns.start == columns.end;
4710        let line_len = display_map.line_len(row);
4711        if columns.start < line_len || (is_empty && columns.start == line_len) {
4712            let start = DisplayPoint::new(row, columns.start);
4713            let end = DisplayPoint::new(row, cmp::min(columns.end, line_len));
4714            Some(Selection {
4715                id: post_inc(&mut self.next_selection_id),
4716                start: start.to_point(display_map),
4717                end: end.to_point(display_map),
4718                reversed,
4719                goal: SelectionGoal::ColumnRange {
4720                    start: columns.start,
4721                    end: columns.end,
4722                },
4723            })
4724        } else {
4725            None
4726        }
4727    }
4728
4729    pub fn local_selections_in_range(
4730        &self,
4731        range: Range<Anchor>,
4732        display_map: &DisplaySnapshot,
4733    ) -> Vec<Selection<Point>> {
4734        let buffer = &display_map.buffer_snapshot;
4735
4736        let start_ix = match self
4737            .selections
4738            .binary_search_by(|probe| probe.end.cmp(&range.start, &buffer).unwrap())
4739        {
4740            Ok(ix) | Err(ix) => ix,
4741        };
4742        let end_ix = match self
4743            .selections
4744            .binary_search_by(|probe| probe.start.cmp(&range.end, &buffer).unwrap())
4745        {
4746            Ok(ix) => ix + 1,
4747            Err(ix) => ix,
4748        };
4749
4750        fn point_selection(
4751            selection: &Selection<Anchor>,
4752            buffer: &MultiBufferSnapshot,
4753        ) -> Selection<Point> {
4754            let start = selection.start.to_point(&buffer);
4755            let end = selection.end.to_point(&buffer);
4756            Selection {
4757                id: selection.id,
4758                start,
4759                end,
4760                reversed: selection.reversed,
4761                goal: selection.goal,
4762            }
4763        }
4764
4765        self.selections[start_ix..end_ix]
4766            .iter()
4767            .chain(
4768                self.pending_selection
4769                    .as_ref()
4770                    .map(|pending| &pending.selection),
4771            )
4772            .map(|s| point_selection(s, &buffer))
4773            .collect()
4774    }
4775
4776    pub fn local_selections<'a, D>(&self, cx: &'a AppContext) -> Vec<Selection<D>>
4777    where
4778        D: 'a + TextDimension + Ord + Sub<D, Output = D>,
4779    {
4780        let buffer = self.buffer.read(cx).snapshot(cx);
4781        let mut selections = self
4782            .resolve_selections::<D, _>(self.selections.iter(), &buffer)
4783            .peekable();
4784
4785        let mut pending_selection = self.pending_selection::<D>(&buffer);
4786
4787        iter::from_fn(move || {
4788            if let Some(pending) = pending_selection.as_mut() {
4789                while let Some(next_selection) = selections.peek() {
4790                    if pending.start <= next_selection.end && pending.end >= next_selection.start {
4791                        let next_selection = selections.next().unwrap();
4792                        if next_selection.start < pending.start {
4793                            pending.start = next_selection.start;
4794                        }
4795                        if next_selection.end > pending.end {
4796                            pending.end = next_selection.end;
4797                        }
4798                    } else if next_selection.end < pending.start {
4799                        return selections.next();
4800                    } else {
4801                        break;
4802                    }
4803                }
4804
4805                pending_selection.take()
4806            } else {
4807                selections.next()
4808            }
4809        })
4810        .collect()
4811    }
4812
4813    fn resolve_selections<'a, D, I>(
4814        &self,
4815        selections: I,
4816        snapshot: &MultiBufferSnapshot,
4817    ) -> impl 'a + Iterator<Item = Selection<D>>
4818    where
4819        D: TextDimension + Ord + Sub<D, Output = D>,
4820        I: 'a + IntoIterator<Item = &'a Selection<Anchor>>,
4821    {
4822        let (to_summarize, selections) = selections.into_iter().tee();
4823        let mut summaries = snapshot
4824            .summaries_for_anchors::<D, _>(to_summarize.flat_map(|s| [&s.start, &s.end]))
4825            .into_iter();
4826        selections.map(move |s| Selection {
4827            id: s.id,
4828            start: summaries.next().unwrap(),
4829            end: summaries.next().unwrap(),
4830            reversed: s.reversed,
4831            goal: s.goal,
4832        })
4833    }
4834
4835    fn pending_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
4836        &self,
4837        snapshot: &MultiBufferSnapshot,
4838    ) -> Option<Selection<D>> {
4839        self.pending_selection
4840            .as_ref()
4841            .map(|pending| self.resolve_selection(&pending.selection, &snapshot))
4842    }
4843
4844    fn resolve_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
4845        &self,
4846        selection: &Selection<Anchor>,
4847        buffer: &MultiBufferSnapshot,
4848    ) -> Selection<D> {
4849        Selection {
4850            id: selection.id,
4851            start: selection.start.summary::<D>(&buffer),
4852            end: selection.end.summary::<D>(&buffer),
4853            reversed: selection.reversed,
4854            goal: selection.goal,
4855        }
4856    }
4857
4858    fn selection_count<'a>(&self) -> usize {
4859        let mut count = self.selections.len();
4860        if self.pending_selection.is_some() {
4861            count += 1;
4862        }
4863        count
4864    }
4865
4866    pub fn oldest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
4867        &self,
4868        cx: &AppContext,
4869    ) -> Selection<D> {
4870        let snapshot = self.buffer.read(cx).read(cx);
4871        self.selections
4872            .iter()
4873            .min_by_key(|s| s.id)
4874            .map(|selection| self.resolve_selection(selection, &snapshot))
4875            .or_else(|| self.pending_selection(&snapshot))
4876            .unwrap()
4877    }
4878
4879    pub fn newest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
4880        &self,
4881        cx: &AppContext,
4882    ) -> Selection<D> {
4883        self.resolve_selection(
4884            self.newest_anchor_selection(),
4885            &self.buffer.read(cx).read(cx),
4886        )
4887    }
4888
4889    pub fn newest_selection_with_snapshot<D: TextDimension + Ord + Sub<D, Output = D>>(
4890        &self,
4891        snapshot: &MultiBufferSnapshot,
4892    ) -> Selection<D> {
4893        self.resolve_selection(self.newest_anchor_selection(), snapshot)
4894    }
4895
4896    pub fn newest_anchor_selection(&self) -> &Selection<Anchor> {
4897        self.pending_selection
4898            .as_ref()
4899            .map(|s| &s.selection)
4900            .or_else(|| self.selections.iter().max_by_key(|s| s.id))
4901            .unwrap()
4902    }
4903
4904    pub fn update_selections<T>(
4905        &mut self,
4906        mut selections: Vec<Selection<T>>,
4907        autoscroll: Option<Autoscroll>,
4908        cx: &mut ViewContext<Self>,
4909    ) where
4910        T: ToOffset + ToPoint + Ord + std::marker::Copy + std::fmt::Debug,
4911    {
4912        let buffer = self.buffer.read(cx).snapshot(cx);
4913        selections.sort_unstable_by_key(|s| s.start);
4914
4915        // Merge overlapping selections.
4916        let mut i = 1;
4917        while i < selections.len() {
4918            if selections[i - 1].end >= selections[i].start {
4919                let removed = selections.remove(i);
4920                if removed.start < selections[i - 1].start {
4921                    selections[i - 1].start = removed.start;
4922                }
4923                if removed.end > selections[i - 1].end {
4924                    selections[i - 1].end = removed.end;
4925                }
4926            } else {
4927                i += 1;
4928            }
4929        }
4930
4931        if let Some(autoscroll) = autoscroll {
4932            self.request_autoscroll(autoscroll, cx);
4933        }
4934
4935        self.set_selections(
4936            Arc::from_iter(selections.into_iter().map(|selection| {
4937                let end_bias = if selection.end > selection.start {
4938                    Bias::Left
4939                } else {
4940                    Bias::Right
4941                };
4942                Selection {
4943                    id: selection.id,
4944                    start: buffer.anchor_after(selection.start),
4945                    end: buffer.anchor_at(selection.end, end_bias),
4946                    reversed: selection.reversed,
4947                    goal: selection.goal,
4948                }
4949            })),
4950            None,
4951            cx,
4952        );
4953    }
4954
4955    /// Compute new ranges for any selections that were located in excerpts that have
4956    /// since been removed.
4957    ///
4958    /// Returns a `HashMap` indicating which selections whose former head position
4959    /// was no longer present. The keys of the map are selection ids. The values are
4960    /// the id of the new excerpt where the head of the selection has been moved.
4961    pub fn refresh_selections(&mut self, cx: &mut ViewContext<Self>) -> HashMap<usize, ExcerptId> {
4962        let snapshot = self.buffer.read(cx).read(cx);
4963        let anchors_with_status = snapshot.refresh_anchors(
4964            self.selections
4965                .iter()
4966                .flat_map(|selection| [&selection.start, &selection.end]),
4967        );
4968        let offsets =
4969            snapshot.summaries_for_anchors::<usize, _>(anchors_with_status.iter().map(|a| &a.1));
4970        assert_eq!(anchors_with_status.len(), 2 * self.selections.len());
4971        assert_eq!(offsets.len(), anchors_with_status.len());
4972
4973        let offsets = offsets.chunks(2);
4974        let statuses = anchors_with_status
4975            .chunks(2)
4976            .map(|a| (a[0].0 / 2, a[0].2, a[1].2));
4977
4978        let mut selections_with_lost_position = HashMap::default();
4979        let new_selections = offsets
4980            .zip(statuses)
4981            .map(|(offsets, (selection_ix, kept_start, kept_end))| {
4982                let selection = &self.selections[selection_ix];
4983                let kept_head = if selection.reversed {
4984                    kept_start
4985                } else {
4986                    kept_end
4987                };
4988                if !kept_head {
4989                    selections_with_lost_position
4990                        .insert(selection.id, selection.head().excerpt_id.clone());
4991                }
4992
4993                Selection {
4994                    id: selection.id,
4995                    start: offsets[0],
4996                    end: offsets[1],
4997                    reversed: selection.reversed,
4998                    goal: selection.goal,
4999                }
5000            })
5001            .collect();
5002        drop(snapshot);
5003        self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
5004        selections_with_lost_position
5005    }
5006
5007    fn set_selections(
5008        &mut self,
5009        selections: Arc<[Selection<Anchor>]>,
5010        pending_selection: Option<PendingSelection>,
5011        cx: &mut ViewContext<Self>,
5012    ) {
5013        assert!(
5014            !selections.is_empty() || pending_selection.is_some(),
5015            "must have at least one selection"
5016        );
5017
5018        let old_cursor_position = self.newest_anchor_selection().head();
5019
5020        self.selections = selections;
5021        self.pending_selection = pending_selection;
5022        if self.focused {
5023            self.buffer.update(cx, |buffer, cx| {
5024                buffer.set_active_selections(&self.selections, cx)
5025            });
5026        }
5027
5028        let display_map = self
5029            .display_map
5030            .update(cx, |display_map, cx| display_map.snapshot(cx));
5031        let buffer = &display_map.buffer_snapshot;
5032        self.add_selections_state = None;
5033        self.select_next_state = None;
5034        self.select_larger_syntax_node_stack.clear();
5035        self.autoclose_stack.invalidate(&self.selections, &buffer);
5036        self.snippet_stack.invalidate(&self.selections, &buffer);
5037        self.invalidate_rename_range(&buffer, cx);
5038
5039        let new_cursor_position = self.newest_anchor_selection().head();
5040
5041        self.push_to_nav_history(
5042            old_cursor_position.clone(),
5043            Some(new_cursor_position.to_point(&buffer)),
5044            cx,
5045        );
5046
5047        let completion_menu = match self.context_menu.as_mut() {
5048            Some(ContextMenu::Completions(menu)) => Some(menu),
5049            _ => {
5050                self.context_menu.take();
5051                None
5052            }
5053        };
5054
5055        if let Some(completion_menu) = completion_menu {
5056            let cursor_position = new_cursor_position.to_offset(&buffer);
5057            let (word_range, kind) =
5058                buffer.surrounding_word(completion_menu.initial_position.clone());
5059            if kind == Some(CharKind::Word) && word_range.to_inclusive().contains(&cursor_position)
5060            {
5061                let query = Self::completion_query(&buffer, cursor_position);
5062                cx.background()
5063                    .block(completion_menu.filter(query.as_deref(), cx.background().clone()));
5064                self.show_completions(&ShowCompletions, cx);
5065            } else {
5066                self.hide_context_menu(cx);
5067            }
5068        }
5069
5070        if old_cursor_position.to_display_point(&display_map).row()
5071            != new_cursor_position.to_display_point(&display_map).row()
5072        {
5073            self.available_code_actions.take();
5074        }
5075        self.refresh_code_actions(cx);
5076        self.refresh_document_highlights(cx);
5077
5078        self.pause_cursor_blinking(cx);
5079        cx.emit(Event::SelectionsChanged);
5080    }
5081
5082    pub fn request_autoscroll(&mut self, autoscroll: Autoscroll, cx: &mut ViewContext<Self>) {
5083        self.autoscroll_request = Some(autoscroll);
5084        cx.notify();
5085    }
5086
5087    fn start_transaction(&mut self, cx: &mut ViewContext<Self>) {
5088        self.start_transaction_at(Instant::now(), cx);
5089    }
5090
5091    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
5092        self.end_selection(cx);
5093        if let Some(tx_id) = self
5094            .buffer
5095            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
5096        {
5097            self.selection_history
5098                .insert(tx_id, (self.selections.clone(), None));
5099        }
5100    }
5101
5102    fn end_transaction(&mut self, cx: &mut ViewContext<Self>) {
5103        self.end_transaction_at(Instant::now(), cx);
5104    }
5105
5106    fn end_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
5107        if let Some(tx_id) = self
5108            .buffer
5109            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
5110        {
5111            if let Some((_, end_selections)) = self.selection_history.get_mut(&tx_id) {
5112                *end_selections = Some(self.selections.clone());
5113            } else {
5114                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
5115            }
5116        }
5117    }
5118
5119    pub fn page_up(&mut self, _: &PageUp, _: &mut ViewContext<Self>) {
5120        log::info!("Editor::page_up");
5121    }
5122
5123    pub fn page_down(&mut self, _: &PageDown, _: &mut ViewContext<Self>) {
5124        log::info!("Editor::page_down");
5125    }
5126
5127    pub fn fold(&mut self, _: &Fold, cx: &mut ViewContext<Self>) {
5128        let mut fold_ranges = Vec::new();
5129
5130        let selections = self.local_selections::<Point>(cx);
5131        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5132        for selection in selections {
5133            let range = selection.display_range(&display_map).sorted();
5134            let buffer_start_row = range.start.to_point(&display_map).row;
5135
5136            for row in (0..=range.end.row()).rev() {
5137                if self.is_line_foldable(&display_map, row) && !display_map.is_line_folded(row) {
5138                    let fold_range = self.foldable_range_for_line(&display_map, row);
5139                    if fold_range.end.row >= buffer_start_row {
5140                        fold_ranges.push(fold_range);
5141                        if row <= range.start.row() {
5142                            break;
5143                        }
5144                    }
5145                }
5146            }
5147        }
5148
5149        self.fold_ranges(fold_ranges, cx);
5150    }
5151
5152    pub fn unfold(&mut self, _: &Unfold, cx: &mut ViewContext<Self>) {
5153        let selections = self.local_selections::<Point>(cx);
5154        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5155        let buffer = &display_map.buffer_snapshot;
5156        let ranges = selections
5157            .iter()
5158            .map(|s| {
5159                let range = s.display_range(&display_map).sorted();
5160                let mut start = range.start.to_point(&display_map);
5161                let mut end = range.end.to_point(&display_map);
5162                start.column = 0;
5163                end.column = buffer.line_len(end.row);
5164                start..end
5165            })
5166            .collect::<Vec<_>>();
5167        self.unfold_ranges(ranges, cx);
5168    }
5169
5170    fn is_line_foldable(&self, display_map: &DisplaySnapshot, display_row: u32) -> bool {
5171        let max_point = display_map.max_point();
5172        if display_row >= max_point.row() {
5173            false
5174        } else {
5175            let (start_indent, is_blank) = display_map.line_indent(display_row);
5176            if is_blank {
5177                false
5178            } else {
5179                for display_row in display_row + 1..=max_point.row() {
5180                    let (indent, is_blank) = display_map.line_indent(display_row);
5181                    if !is_blank {
5182                        return indent > start_indent;
5183                    }
5184                }
5185                false
5186            }
5187        }
5188    }
5189
5190    fn foldable_range_for_line(
5191        &self,
5192        display_map: &DisplaySnapshot,
5193        start_row: u32,
5194    ) -> Range<Point> {
5195        let max_point = display_map.max_point();
5196
5197        let (start_indent, _) = display_map.line_indent(start_row);
5198        let start = DisplayPoint::new(start_row, display_map.line_len(start_row));
5199        let mut end = None;
5200        for row in start_row + 1..=max_point.row() {
5201            let (indent, is_blank) = display_map.line_indent(row);
5202            if !is_blank && indent <= start_indent {
5203                end = Some(DisplayPoint::new(row - 1, display_map.line_len(row - 1)));
5204                break;
5205            }
5206        }
5207
5208        let end = end.unwrap_or(max_point);
5209        return start.to_point(display_map)..end.to_point(display_map);
5210    }
5211
5212    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
5213        let selections = self.local_selections::<Point>(cx);
5214        let ranges = selections.into_iter().map(|s| s.start..s.end);
5215        self.fold_ranges(ranges, cx);
5216    }
5217
5218    fn fold_ranges<T: ToOffset>(
5219        &mut self,
5220        ranges: impl IntoIterator<Item = Range<T>>,
5221        cx: &mut ViewContext<Self>,
5222    ) {
5223        let mut ranges = ranges.into_iter().peekable();
5224        if ranges.peek().is_some() {
5225            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
5226            self.request_autoscroll(Autoscroll::Fit, cx);
5227            cx.notify();
5228        }
5229    }
5230
5231    fn unfold_ranges<T: ToOffset>(&mut self, ranges: Vec<Range<T>>, cx: &mut ViewContext<Self>) {
5232        if !ranges.is_empty() {
5233            self.display_map
5234                .update(cx, |map, cx| map.unfold(ranges, cx));
5235            self.request_autoscroll(Autoscroll::Fit, cx);
5236            cx.notify();
5237        }
5238    }
5239
5240    pub fn insert_blocks(
5241        &mut self,
5242        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
5243        cx: &mut ViewContext<Self>,
5244    ) -> Vec<BlockId> {
5245        let blocks = self
5246            .display_map
5247            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
5248        self.request_autoscroll(Autoscroll::Fit, cx);
5249        blocks
5250    }
5251
5252    pub fn replace_blocks(
5253        &mut self,
5254        blocks: HashMap<BlockId, RenderBlock>,
5255        cx: &mut ViewContext<Self>,
5256    ) {
5257        self.display_map
5258            .update(cx, |display_map, _| display_map.replace_blocks(blocks));
5259        self.request_autoscroll(Autoscroll::Fit, cx);
5260    }
5261
5262    pub fn remove_blocks(&mut self, block_ids: HashSet<BlockId>, cx: &mut ViewContext<Self>) {
5263        self.display_map.update(cx, |display_map, cx| {
5264            display_map.remove_blocks(block_ids, cx)
5265        });
5266    }
5267
5268    pub fn longest_row(&self, cx: &mut MutableAppContext) -> u32 {
5269        self.display_map
5270            .update(cx, |map, cx| map.snapshot(cx))
5271            .longest_row()
5272    }
5273
5274    pub fn max_point(&self, cx: &mut MutableAppContext) -> DisplayPoint {
5275        self.display_map
5276            .update(cx, |map, cx| map.snapshot(cx))
5277            .max_point()
5278    }
5279
5280    pub fn text(&self, cx: &AppContext) -> String {
5281        self.buffer.read(cx).read(cx).text()
5282    }
5283
5284    pub fn set_text(&mut self, text: impl Into<String>, cx: &mut ViewContext<Self>) {
5285        self.buffer
5286            .read(cx)
5287            .as_singleton()
5288            .expect("you can only call set_text on editors for singleton buffers")
5289            .update(cx, |buffer, cx| buffer.set_text(text, cx));
5290    }
5291
5292    pub fn display_text(&self, cx: &mut MutableAppContext) -> String {
5293        self.display_map
5294            .update(cx, |map, cx| map.snapshot(cx))
5295            .text()
5296    }
5297
5298    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
5299        let language = self.language(cx);
5300        let settings = cx.app_state::<Settings>();
5301        let mode = self
5302            .soft_wrap_mode_override
5303            .unwrap_or_else(|| settings.soft_wrap(language));
5304        match mode {
5305            settings::SoftWrap::None => SoftWrap::None,
5306            settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
5307            settings::SoftWrap::PreferredLineLength => {
5308                SoftWrap::Column(settings.preferred_line_length(language))
5309            }
5310        }
5311    }
5312
5313    pub fn set_soft_wrap_mode(&mut self, mode: settings::SoftWrap, cx: &mut ViewContext<Self>) {
5314        self.soft_wrap_mode_override = Some(mode);
5315        cx.notify();
5316    }
5317
5318    pub fn set_wrap_width(&self, width: Option<f32>, cx: &mut MutableAppContext) -> bool {
5319        self.display_map
5320            .update(cx, |map, cx| map.set_wrap_width(width, cx))
5321    }
5322
5323    pub fn highlight_rows(&mut self, rows: Option<Range<u32>>) {
5324        self.highlighted_rows = rows;
5325    }
5326
5327    pub fn highlighted_rows(&self) -> Option<Range<u32>> {
5328        self.highlighted_rows.clone()
5329    }
5330
5331    pub fn highlight_background<T: 'static>(
5332        &mut self,
5333        ranges: Vec<Range<Anchor>>,
5334        color: Color,
5335        cx: &mut ViewContext<Self>,
5336    ) {
5337        self.background_highlights
5338            .insert(TypeId::of::<T>(), (color, ranges));
5339        cx.notify();
5340    }
5341
5342    pub fn clear_background_highlights<T: 'static>(
5343        &mut self,
5344        cx: &mut ViewContext<Self>,
5345    ) -> Option<(Color, Vec<Range<Anchor>>)> {
5346        cx.notify();
5347        self.background_highlights.remove(&TypeId::of::<T>())
5348    }
5349
5350    #[cfg(feature = "test-support")]
5351    pub fn all_background_highlights(
5352        &mut self,
5353        cx: &mut ViewContext<Self>,
5354    ) -> Vec<(Range<DisplayPoint>, Color)> {
5355        let snapshot = self.snapshot(cx);
5356        let buffer = &snapshot.buffer_snapshot;
5357        let start = buffer.anchor_before(0);
5358        let end = buffer.anchor_after(buffer.len());
5359        self.background_highlights_in_range(start..end, &snapshot)
5360    }
5361
5362    pub fn background_highlights_for_type<T: 'static>(&self) -> Option<(Color, &[Range<Anchor>])> {
5363        self.background_highlights
5364            .get(&TypeId::of::<T>())
5365            .map(|(color, ranges)| (*color, ranges.as_slice()))
5366    }
5367
5368    pub fn background_highlights_in_range(
5369        &self,
5370        search_range: Range<Anchor>,
5371        display_snapshot: &DisplaySnapshot,
5372    ) -> Vec<(Range<DisplayPoint>, Color)> {
5373        let mut results = Vec::new();
5374        let buffer = &display_snapshot.buffer_snapshot;
5375        for (color, ranges) in self.background_highlights.values() {
5376            let start_ix = match ranges.binary_search_by(|probe| {
5377                let cmp = probe.end.cmp(&search_range.start, &buffer).unwrap();
5378                if cmp.is_gt() {
5379                    Ordering::Greater
5380                } else {
5381                    Ordering::Less
5382                }
5383            }) {
5384                Ok(i) | Err(i) => i,
5385            };
5386            for range in &ranges[start_ix..] {
5387                if range.start.cmp(&search_range.end, &buffer).unwrap().is_ge() {
5388                    break;
5389                }
5390                let start = range
5391                    .start
5392                    .to_point(buffer)
5393                    .to_display_point(display_snapshot);
5394                let end = range
5395                    .end
5396                    .to_point(buffer)
5397                    .to_display_point(display_snapshot);
5398                results.push((start..end, *color))
5399            }
5400        }
5401        results
5402    }
5403
5404    pub fn highlight_text<T: 'static>(
5405        &mut self,
5406        ranges: Vec<Range<Anchor>>,
5407        style: HighlightStyle,
5408        cx: &mut ViewContext<Self>,
5409    ) {
5410        self.display_map.update(cx, |map, _| {
5411            map.highlight_text(TypeId::of::<T>(), ranges, style)
5412        });
5413        cx.notify();
5414    }
5415
5416    pub fn clear_text_highlights<T: 'static>(
5417        &mut self,
5418        cx: &mut ViewContext<Self>,
5419    ) -> Option<Arc<(HighlightStyle, Vec<Range<Anchor>>)>> {
5420        cx.notify();
5421        self.display_map
5422            .update(cx, |map, _| map.clear_text_highlights(TypeId::of::<T>()))
5423    }
5424
5425    fn next_blink_epoch(&mut self) -> usize {
5426        self.blink_epoch += 1;
5427        self.blink_epoch
5428    }
5429
5430    fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
5431        if !self.focused {
5432            return;
5433        }
5434
5435        self.show_local_cursors = true;
5436        cx.notify();
5437
5438        let epoch = self.next_blink_epoch();
5439        cx.spawn(|this, mut cx| {
5440            let this = this.downgrade();
5441            async move {
5442                Timer::after(CURSOR_BLINK_INTERVAL).await;
5443                if let Some(this) = this.upgrade(&cx) {
5444                    this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
5445                }
5446            }
5447        })
5448        .detach();
5449    }
5450
5451    fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
5452        if epoch == self.blink_epoch {
5453            self.blinking_paused = false;
5454            self.blink_cursors(epoch, cx);
5455        }
5456    }
5457
5458    fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
5459        if epoch == self.blink_epoch && self.focused && !self.blinking_paused {
5460            self.show_local_cursors = !self.show_local_cursors;
5461            cx.notify();
5462
5463            let epoch = self.next_blink_epoch();
5464            cx.spawn(|this, mut cx| {
5465                let this = this.downgrade();
5466                async move {
5467                    Timer::after(CURSOR_BLINK_INTERVAL).await;
5468                    if let Some(this) = this.upgrade(&cx) {
5469                        this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx));
5470                    }
5471                }
5472            })
5473            .detach();
5474        }
5475    }
5476
5477    pub fn show_local_cursors(&self) -> bool {
5478        self.show_local_cursors
5479    }
5480
5481    fn on_buffer_changed(&mut self, _: ModelHandle<MultiBuffer>, cx: &mut ViewContext<Self>) {
5482        cx.notify();
5483    }
5484
5485    fn on_buffer_event(
5486        &mut self,
5487        _: ModelHandle<MultiBuffer>,
5488        event: &language::Event,
5489        cx: &mut ViewContext<Self>,
5490    ) {
5491        match event {
5492            language::Event::Edited => {
5493                self.refresh_active_diagnostics(cx);
5494                self.refresh_code_actions(cx);
5495                cx.emit(Event::Edited);
5496            }
5497            language::Event::Dirtied => cx.emit(Event::Dirtied),
5498            language::Event::Saved => cx.emit(Event::Saved),
5499            language::Event::FileHandleChanged => cx.emit(Event::TitleChanged),
5500            language::Event::Reloaded => cx.emit(Event::TitleChanged),
5501            language::Event::Closed => cx.emit(Event::Closed),
5502            language::Event::DiagnosticsUpdated => {
5503                self.refresh_active_diagnostics(cx);
5504            }
5505            _ => {}
5506        }
5507    }
5508
5509    fn on_display_map_changed(&mut self, _: ModelHandle<DisplayMap>, cx: &mut ViewContext<Self>) {
5510        cx.notify();
5511    }
5512
5513    pub fn set_searchable(&mut self, searchable: bool) {
5514        self.searchable = searchable;
5515    }
5516
5517    pub fn searchable(&self) -> bool {
5518        self.searchable
5519    }
5520
5521    fn open_excerpts(workspace: &mut Workspace, _: &OpenExcerpts, cx: &mut ViewContext<Workspace>) {
5522        let active_item = workspace.active_item(cx);
5523        let editor_handle = if let Some(editor) = active_item
5524            .as_ref()
5525            .and_then(|item| item.act_as::<Self>(cx))
5526        {
5527            editor
5528        } else {
5529            cx.propagate_action();
5530            return;
5531        };
5532
5533        let editor = editor_handle.read(cx);
5534        let buffer = editor.buffer.read(cx);
5535        if buffer.is_singleton() {
5536            cx.propagate_action();
5537            return;
5538        }
5539
5540        let mut new_selections_by_buffer = HashMap::default();
5541        for selection in editor.local_selections::<usize>(cx) {
5542            for (buffer, mut range) in
5543                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
5544            {
5545                if selection.reversed {
5546                    mem::swap(&mut range.start, &mut range.end);
5547                }
5548                new_selections_by_buffer
5549                    .entry(buffer)
5550                    .or_insert(Vec::new())
5551                    .push(range)
5552            }
5553        }
5554
5555        editor_handle.update(cx, |editor, cx| {
5556            editor.push_to_nav_history(editor.newest_anchor_selection().head(), None, cx);
5557        });
5558        let nav_history = workspace.active_pane().read(cx).nav_history().clone();
5559        nav_history.borrow_mut().disable();
5560
5561        // We defer the pane interaction because we ourselves are a workspace item
5562        // and activating a new item causes the pane to call a method on us reentrantly,
5563        // which panics if we're on the stack.
5564        cx.defer(move |workspace, cx| {
5565            for (ix, (buffer, ranges)) in new_selections_by_buffer.into_iter().enumerate() {
5566                let buffer = BufferItemHandle(buffer);
5567                if ix == 0 && !workspace.activate_pane_for_item(&buffer, cx) {
5568                    workspace.activate_next_pane(cx);
5569                }
5570
5571                let editor = workspace
5572                    .open_item(buffer, cx)
5573                    .downcast::<Editor>()
5574                    .unwrap();
5575
5576                editor.update(cx, |editor, cx| {
5577                    editor.select_ranges(ranges, Some(Autoscroll::Newest), cx);
5578                });
5579            }
5580
5581            nav_history.borrow_mut().enable();
5582        });
5583    }
5584}
5585
5586impl EditorSnapshot {
5587    pub fn is_focused(&self) -> bool {
5588        self.is_focused
5589    }
5590
5591    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
5592        self.placeholder_text.as_ref()
5593    }
5594
5595    pub fn scroll_position(&self) -> Vector2F {
5596        compute_scroll_position(
5597            &self.display_snapshot,
5598            self.scroll_position,
5599            &self.scroll_top_anchor,
5600        )
5601    }
5602}
5603
5604impl Deref for EditorSnapshot {
5605    type Target = DisplaySnapshot;
5606
5607    fn deref(&self) -> &Self::Target {
5608        &self.display_snapshot
5609    }
5610}
5611
5612fn compute_scroll_position(
5613    snapshot: &DisplaySnapshot,
5614    mut scroll_position: Vector2F,
5615    scroll_top_anchor: &Option<Anchor>,
5616) -> Vector2F {
5617    if let Some(anchor) = scroll_top_anchor {
5618        let scroll_top = anchor.to_display_point(snapshot).row() as f32;
5619        scroll_position.set_y(scroll_top + scroll_position.y());
5620    } else {
5621        scroll_position.set_y(0.);
5622    }
5623    scroll_position
5624}
5625
5626#[derive(Copy, Clone)]
5627pub enum Event {
5628    Activate,
5629    Edited,
5630    Blurred,
5631    Dirtied,
5632    Saved,
5633    TitleChanged,
5634    SelectionsChanged,
5635    Closed,
5636}
5637
5638impl Entity for Editor {
5639    type Event = Event;
5640}
5641
5642impl View for Editor {
5643    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
5644        let style = self.style(cx);
5645        self.display_map.update(cx, |map, cx| {
5646            map.set_font(style.text.font_id, style.text.font_size, cx)
5647        });
5648        EditorElement::new(self.handle.clone(), style.clone(), self.cursor_shape).boxed()
5649    }
5650
5651    fn ui_name() -> &'static str {
5652        "Editor"
5653    }
5654
5655    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
5656        if let Some(rename) = self.pending_rename.as_ref() {
5657            cx.focus(&rename.editor);
5658        } else {
5659            self.focused = true;
5660            self.blink_cursors(self.blink_epoch, cx);
5661            self.buffer.update(cx, |buffer, cx| {
5662                buffer.finalize_last_transaction(cx);
5663                buffer.set_active_selections(&self.selections, cx)
5664            });
5665        }
5666    }
5667
5668    fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
5669        self.focused = false;
5670        self.buffer
5671            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
5672        self.hide_context_menu(cx);
5673        cx.emit(Event::Blurred);
5674        cx.notify();
5675    }
5676
5677    fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
5678        let mut cx = Self::default_keymap_context();
5679        let mode = match self.mode {
5680            EditorMode::SingleLine => "single_line",
5681            EditorMode::AutoHeight { .. } => "auto_height",
5682            EditorMode::Full => "full",
5683        };
5684        cx.map.insert("mode".into(), mode.into());
5685        if self.pending_rename.is_some() {
5686            cx.set.insert("renaming".into());
5687        }
5688        match self.context_menu.as_ref() {
5689            Some(ContextMenu::Completions(_)) => {
5690                cx.set.insert("showing_completions".into());
5691            }
5692            Some(ContextMenu::CodeActions(_)) => {
5693                cx.set.insert("showing_code_actions".into());
5694            }
5695            None => {}
5696        }
5697        cx
5698    }
5699}
5700
5701fn build_style(
5702    settings: &Settings,
5703    get_field_editor_theme: Option<GetFieldEditorTheme>,
5704    override_text_style: Option<&OverrideTextStyle>,
5705    cx: &AppContext,
5706) -> EditorStyle {
5707    let font_cache = cx.font_cache();
5708
5709    let mut theme = settings.theme.editor.clone();
5710    let mut style = if let Some(get_field_editor_theme) = get_field_editor_theme {
5711        let field_editor_theme = get_field_editor_theme(&settings.theme);
5712        theme.text_color = field_editor_theme.text.color;
5713        theme.selection = field_editor_theme.selection;
5714        theme.background = field_editor_theme
5715            .container
5716            .background_color
5717            .unwrap_or_default();
5718        EditorStyle {
5719            text: field_editor_theme.text,
5720            placeholder_text: field_editor_theme.placeholder_text,
5721            theme,
5722        }
5723    } else {
5724        let font_family_id = settings.buffer_font_family;
5725        let font_family_name = cx.font_cache().family_name(font_family_id).unwrap();
5726        let font_properties = Default::default();
5727        let font_id = font_cache
5728            .select_font(font_family_id, &font_properties)
5729            .unwrap();
5730        let font_size = settings.buffer_font_size;
5731        EditorStyle {
5732            text: TextStyle {
5733                color: settings.theme.editor.text_color,
5734                font_family_name,
5735                font_family_id,
5736                font_id,
5737                font_size,
5738                font_properties,
5739                underline: Default::default(),
5740            },
5741            placeholder_text: None,
5742            theme,
5743        }
5744    };
5745
5746    if let Some(highlight_style) = override_text_style.and_then(|build_style| build_style(&style)) {
5747        if let Some(highlighted) = style
5748            .text
5749            .clone()
5750            .highlight(highlight_style, font_cache)
5751            .log_err()
5752        {
5753            style.text = highlighted;
5754        }
5755    }
5756
5757    style
5758}
5759
5760impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
5761    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
5762        let start = self.start.to_point(buffer);
5763        let end = self.end.to_point(buffer);
5764        if self.reversed {
5765            end..start
5766        } else {
5767            start..end
5768        }
5769    }
5770
5771    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
5772        let start = self.start.to_offset(buffer);
5773        let end = self.end.to_offset(buffer);
5774        if self.reversed {
5775            end..start
5776        } else {
5777            start..end
5778        }
5779    }
5780
5781    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
5782        let start = self
5783            .start
5784            .to_point(&map.buffer_snapshot)
5785            .to_display_point(map);
5786        let end = self
5787            .end
5788            .to_point(&map.buffer_snapshot)
5789            .to_display_point(map);
5790        if self.reversed {
5791            end..start
5792        } else {
5793            start..end
5794        }
5795    }
5796
5797    fn spanned_rows(
5798        &self,
5799        include_end_if_at_line_start: bool,
5800        map: &DisplaySnapshot,
5801    ) -> Range<u32> {
5802        let start = self.start.to_point(&map.buffer_snapshot);
5803        let mut end = self.end.to_point(&map.buffer_snapshot);
5804        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
5805            end.row -= 1;
5806        }
5807
5808        let buffer_start = map.prev_line_boundary(start).0;
5809        let buffer_end = map.next_line_boundary(end).0;
5810        buffer_start.row..buffer_end.row + 1
5811    }
5812}
5813
5814impl<T: InvalidationRegion> InvalidationStack<T> {
5815    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
5816    where
5817        S: Clone + ToOffset,
5818    {
5819        while let Some(region) = self.last() {
5820            let all_selections_inside_invalidation_ranges =
5821                if selections.len() == region.ranges().len() {
5822                    selections
5823                        .iter()
5824                        .zip(region.ranges().iter().map(|r| r.to_offset(&buffer)))
5825                        .all(|(selection, invalidation_range)| {
5826                            let head = selection.head().to_offset(&buffer);
5827                            invalidation_range.start <= head && invalidation_range.end >= head
5828                        })
5829                } else {
5830                    false
5831                };
5832
5833            if all_selections_inside_invalidation_ranges {
5834                break;
5835            } else {
5836                self.pop();
5837            }
5838        }
5839    }
5840}
5841
5842impl<T> Default for InvalidationStack<T> {
5843    fn default() -> Self {
5844        Self(Default::default())
5845    }
5846}
5847
5848impl<T> Deref for InvalidationStack<T> {
5849    type Target = Vec<T>;
5850
5851    fn deref(&self) -> &Self::Target {
5852        &self.0
5853    }
5854}
5855
5856impl<T> DerefMut for InvalidationStack<T> {
5857    fn deref_mut(&mut self) -> &mut Self::Target {
5858        &mut self.0
5859    }
5860}
5861
5862impl InvalidationRegion for BracketPairState {
5863    fn ranges(&self) -> &[Range<Anchor>] {
5864        &self.ranges
5865    }
5866}
5867
5868impl InvalidationRegion for SnippetState {
5869    fn ranges(&self) -> &[Range<Anchor>] {
5870        &self.ranges[self.active_index]
5871    }
5872}
5873
5874impl Deref for EditorStyle {
5875    type Target = theme::Editor;
5876
5877    fn deref(&self) -> &Self::Target {
5878        &self.theme
5879    }
5880}
5881
5882pub fn diagnostic_block_renderer(diagnostic: Diagnostic, is_valid: bool) -> RenderBlock {
5883    let mut highlighted_lines = Vec::new();
5884    for line in diagnostic.message.lines() {
5885        highlighted_lines.push(highlight_diagnostic_message(line));
5886    }
5887
5888    Arc::new(move |cx: &BlockContext| {
5889        let settings = cx.app_state::<Settings>();
5890        let theme = &settings.theme.editor;
5891        let style = diagnostic_style(diagnostic.severity, is_valid, theme);
5892        let font_size = (style.text_scale_factor * settings.buffer_font_size).round();
5893        Flex::column()
5894            .with_children(highlighted_lines.iter().map(|(line, highlights)| {
5895                Label::new(
5896                    line.clone(),
5897                    style.message.clone().with_font_size(font_size),
5898                )
5899                .with_highlights(highlights.clone())
5900                .contained()
5901                .with_margin_left(cx.anchor_x)
5902                .boxed()
5903            }))
5904            .aligned()
5905            .left()
5906            .boxed()
5907    })
5908}
5909
5910pub fn highlight_diagnostic_message(message: &str) -> (String, Vec<usize>) {
5911    let mut message_without_backticks = String::new();
5912    let mut prev_offset = 0;
5913    let mut inside_block = false;
5914    let mut highlights = Vec::new();
5915    for (match_ix, (offset, _)) in message
5916        .match_indices('`')
5917        .chain([(message.len(), "")])
5918        .enumerate()
5919    {
5920        message_without_backticks.push_str(&message[prev_offset..offset]);
5921        if inside_block {
5922            highlights.extend(prev_offset - match_ix..offset - match_ix);
5923        }
5924
5925        inside_block = !inside_block;
5926        prev_offset = offset + 1;
5927    }
5928
5929    (message_without_backticks, highlights)
5930}
5931
5932pub fn diagnostic_style(
5933    severity: DiagnosticSeverity,
5934    valid: bool,
5935    theme: &theme::Editor,
5936) -> DiagnosticStyle {
5937    match (severity, valid) {
5938        (DiagnosticSeverity::ERROR, true) => theme.error_diagnostic.clone(),
5939        (DiagnosticSeverity::ERROR, false) => theme.invalid_error_diagnostic.clone(),
5940        (DiagnosticSeverity::WARNING, true) => theme.warning_diagnostic.clone(),
5941        (DiagnosticSeverity::WARNING, false) => theme.invalid_warning_diagnostic.clone(),
5942        (DiagnosticSeverity::INFORMATION, true) => theme.information_diagnostic.clone(),
5943        (DiagnosticSeverity::INFORMATION, false) => theme.invalid_information_diagnostic.clone(),
5944        (DiagnosticSeverity::HINT, true) => theme.hint_diagnostic.clone(),
5945        (DiagnosticSeverity::HINT, false) => theme.invalid_hint_diagnostic.clone(),
5946        _ => theme.invalid_hint_diagnostic.clone(),
5947    }
5948}
5949
5950pub fn combine_syntax_and_fuzzy_match_highlights(
5951    text: &str,
5952    default_style: HighlightStyle,
5953    syntax_ranges: impl Iterator<Item = (Range<usize>, HighlightStyle)>,
5954    match_indices: &[usize],
5955) -> Vec<(Range<usize>, HighlightStyle)> {
5956    let mut result = Vec::new();
5957    let mut match_indices = match_indices.iter().copied().peekable();
5958
5959    for (range, mut syntax_highlight) in syntax_ranges.chain([(usize::MAX..0, Default::default())])
5960    {
5961        syntax_highlight.weight = None;
5962
5963        // Add highlights for any fuzzy match characters before the next
5964        // syntax highlight range.
5965        while let Some(&match_index) = match_indices.peek() {
5966            if match_index >= range.start {
5967                break;
5968            }
5969            match_indices.next();
5970            let end_index = char_ix_after(match_index, text);
5971            let mut match_style = default_style;
5972            match_style.weight = Some(fonts::Weight::BOLD);
5973            result.push((match_index..end_index, match_style));
5974        }
5975
5976        if range.start == usize::MAX {
5977            break;
5978        }
5979
5980        // Add highlights for any fuzzy match characters within the
5981        // syntax highlight range.
5982        let mut offset = range.start;
5983        while let Some(&match_index) = match_indices.peek() {
5984            if match_index >= range.end {
5985                break;
5986            }
5987
5988            match_indices.next();
5989            if match_index > offset {
5990                result.push((offset..match_index, syntax_highlight));
5991            }
5992
5993            let mut end_index = char_ix_after(match_index, text);
5994            while let Some(&next_match_index) = match_indices.peek() {
5995                if next_match_index == end_index && next_match_index < range.end {
5996                    end_index = char_ix_after(next_match_index, text);
5997                    match_indices.next();
5998                } else {
5999                    break;
6000                }
6001            }
6002
6003            let mut match_style = syntax_highlight;
6004            match_style.weight = Some(fonts::Weight::BOLD);
6005            result.push((match_index..end_index, match_style));
6006            offset = end_index;
6007        }
6008
6009        if offset < range.end {
6010            result.push((offset..range.end, syntax_highlight));
6011        }
6012    }
6013
6014    fn char_ix_after(ix: usize, text: &str) -> usize {
6015        ix + text[ix..].chars().next().unwrap().len_utf8()
6016    }
6017
6018    result
6019}
6020
6021pub fn styled_runs_for_code_label<'a>(
6022    label: &'a CodeLabel,
6023    syntax_theme: &'a theme::SyntaxTheme,
6024) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
6025    let fade_out = HighlightStyle {
6026        fade_out: Some(0.35),
6027        ..Default::default()
6028    };
6029
6030    let mut prev_end = label.filter_range.end;
6031    label
6032        .runs
6033        .iter()
6034        .enumerate()
6035        .flat_map(move |(ix, (range, highlight_id))| {
6036            let style = if let Some(style) = highlight_id.style(syntax_theme) {
6037                style
6038            } else {
6039                return Default::default();
6040            };
6041            let mut muted_style = style.clone();
6042            muted_style.highlight(fade_out);
6043
6044            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
6045            if range.start >= label.filter_range.end {
6046                if range.start > prev_end {
6047                    runs.push((prev_end..range.start, fade_out));
6048                }
6049                runs.push((range.clone(), muted_style));
6050            } else if range.end <= label.filter_range.end {
6051                runs.push((range.clone(), style));
6052            } else {
6053                runs.push((range.start..label.filter_range.end, style));
6054                runs.push((label.filter_range.end..range.end, muted_style));
6055            }
6056            prev_end = cmp::max(prev_end, range.end);
6057
6058            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
6059                runs.push((prev_end..label.text.len(), fade_out));
6060            }
6061
6062            runs
6063        })
6064}
6065
6066#[cfg(test)]
6067mod tests {
6068    use super::*;
6069    use language::{LanguageConfig, LanguageServerConfig};
6070    use lsp::FakeLanguageServer;
6071    use project::FakeFs;
6072    use smol::stream::StreamExt;
6073    use std::{cell::RefCell, rc::Rc, time::Instant};
6074    use text::Point;
6075    use unindent::Unindent;
6076    use util::test::sample_text;
6077
6078    #[gpui::test]
6079    fn test_undo_redo_with_selection_restoration(cx: &mut MutableAppContext) {
6080        populate_settings(cx);
6081        let mut now = Instant::now();
6082        let buffer = cx.add_model(|cx| language::Buffer::new(0, "123456", cx));
6083        let group_interval = buffer.read(cx).transaction_group_interval();
6084        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
6085        let (_, editor) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6086
6087        editor.update(cx, |editor, cx| {
6088            editor.start_transaction_at(now, cx);
6089            editor.select_ranges([2..4], None, cx);
6090            editor.insert("cd", cx);
6091            editor.end_transaction_at(now, cx);
6092            assert_eq!(editor.text(cx), "12cd56");
6093            assert_eq!(editor.selected_ranges(cx), vec![4..4]);
6094
6095            editor.start_transaction_at(now, cx);
6096            editor.select_ranges([4..5], None, cx);
6097            editor.insert("e", cx);
6098            editor.end_transaction_at(now, cx);
6099            assert_eq!(editor.text(cx), "12cde6");
6100            assert_eq!(editor.selected_ranges(cx), vec![5..5]);
6101
6102            now += group_interval + Duration::from_millis(1);
6103            editor.select_ranges([2..2], None, cx);
6104
6105            // Simulate an edit in another editor
6106            buffer.update(cx, |buffer, cx| {
6107                buffer.start_transaction_at(now, cx);
6108                buffer.edit([0..1], "a", cx);
6109                buffer.edit([1..1], "b", cx);
6110                buffer.end_transaction_at(now, cx);
6111            });
6112
6113            assert_eq!(editor.text(cx), "ab2cde6");
6114            assert_eq!(editor.selected_ranges(cx), vec![3..3]);
6115
6116            // Last transaction happened past the group interval in a different editor.
6117            // Undo it individually and don't restore selections.
6118            editor.undo(&Undo, cx);
6119            assert_eq!(editor.text(cx), "12cde6");
6120            assert_eq!(editor.selected_ranges(cx), vec![2..2]);
6121
6122            // First two transactions happened within the group interval in this editor.
6123            // Undo them together and restore selections.
6124            editor.undo(&Undo, cx);
6125            editor.undo(&Undo, cx); // Undo stack is empty here, so this is a no-op.
6126            assert_eq!(editor.text(cx), "123456");
6127            assert_eq!(editor.selected_ranges(cx), vec![0..0]);
6128
6129            // Redo the first two transactions together.
6130            editor.redo(&Redo, cx);
6131            assert_eq!(editor.text(cx), "12cde6");
6132            assert_eq!(editor.selected_ranges(cx), vec![5..5]);
6133
6134            // Redo the last transaction on its own.
6135            editor.redo(&Redo, cx);
6136            assert_eq!(editor.text(cx), "ab2cde6");
6137            assert_eq!(editor.selected_ranges(cx), vec![6..6]);
6138
6139            // Test empty transactions.
6140            editor.start_transaction_at(now, cx);
6141            editor.end_transaction_at(now, cx);
6142            editor.undo(&Undo, cx);
6143            assert_eq!(editor.text(cx), "12cde6");
6144        });
6145    }
6146
6147    #[gpui::test]
6148    fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
6149        populate_settings(cx);
6150        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
6151        let (_, editor) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6152
6153        editor.update(cx, |view, cx| {
6154            view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
6155        });
6156
6157        assert_eq!(
6158            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6159            [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
6160        );
6161
6162        editor.update(cx, |view, cx| {
6163            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
6164        });
6165
6166        assert_eq!(
6167            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6168            [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
6169        );
6170
6171        editor.update(cx, |view, cx| {
6172            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
6173        });
6174
6175        assert_eq!(
6176            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6177            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
6178        );
6179
6180        editor.update(cx, |view, cx| {
6181            view.end_selection(cx);
6182            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
6183        });
6184
6185        assert_eq!(
6186            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6187            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
6188        );
6189
6190        editor.update(cx, |view, cx| {
6191            view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
6192            view.update_selection(DisplayPoint::new(0, 0), 0, Vector2F::zero(), cx);
6193        });
6194
6195        assert_eq!(
6196            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6197            [
6198                DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
6199                DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
6200            ]
6201        );
6202
6203        editor.update(cx, |view, cx| {
6204            view.end_selection(cx);
6205        });
6206
6207        assert_eq!(
6208            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6209            [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
6210        );
6211    }
6212
6213    #[gpui::test]
6214    fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
6215        populate_settings(cx);
6216        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
6217        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6218
6219        view.update(cx, |view, cx| {
6220            view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
6221            assert_eq!(
6222                view.selected_display_ranges(cx),
6223                [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
6224            );
6225        });
6226
6227        view.update(cx, |view, cx| {
6228            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
6229            assert_eq!(
6230                view.selected_display_ranges(cx),
6231                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
6232            );
6233        });
6234
6235        view.update(cx, |view, cx| {
6236            view.cancel(&Cancel, cx);
6237            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
6238            assert_eq!(
6239                view.selected_display_ranges(cx),
6240                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
6241            );
6242        });
6243    }
6244
6245    #[gpui::test]
6246    fn test_navigation_history(cx: &mut gpui::MutableAppContext) {
6247        populate_settings(cx);
6248        use workspace::ItemView;
6249        let nav_history = Rc::new(RefCell::new(workspace::NavHistory::default()));
6250        let buffer = MultiBuffer::build_simple(&sample_text(30, 5, 'a'), cx);
6251
6252        cx.add_window(Default::default(), |cx| {
6253            let mut editor = build_editor(buffer.clone(), cx);
6254            editor.nav_history = Some(ItemNavHistory::new(nav_history.clone(), &cx.handle()));
6255
6256            // Move the cursor a small distance.
6257            // Nothing is added to the navigation history.
6258            editor.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
6259            editor.select_display_ranges(&[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)], cx);
6260            assert!(nav_history.borrow_mut().pop_backward().is_none());
6261
6262            // Move the cursor a large distance.
6263            // The history can jump back to the previous position.
6264            editor.select_display_ranges(&[DisplayPoint::new(13, 0)..DisplayPoint::new(13, 3)], cx);
6265            let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
6266            editor.navigate(nav_entry.data.unwrap(), cx);
6267            assert_eq!(nav_entry.item_view.id(), cx.view_id());
6268            assert_eq!(
6269                editor.selected_display_ranges(cx),
6270                &[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)]
6271            );
6272
6273            // Move the cursor a small distance via the mouse.
6274            // Nothing is added to the navigation history.
6275            editor.begin_selection(DisplayPoint::new(5, 0), false, 1, cx);
6276            editor.end_selection(cx);
6277            assert_eq!(
6278                editor.selected_display_ranges(cx),
6279                &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
6280            );
6281            assert!(nav_history.borrow_mut().pop_backward().is_none());
6282
6283            // Move the cursor a large distance via the mouse.
6284            // The history can jump back to the previous position.
6285            editor.begin_selection(DisplayPoint::new(15, 0), false, 1, cx);
6286            editor.end_selection(cx);
6287            assert_eq!(
6288                editor.selected_display_ranges(cx),
6289                &[DisplayPoint::new(15, 0)..DisplayPoint::new(15, 0)]
6290            );
6291            let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
6292            editor.navigate(nav_entry.data.unwrap(), cx);
6293            assert_eq!(nav_entry.item_view.id(), cx.view_id());
6294            assert_eq!(
6295                editor.selected_display_ranges(cx),
6296                &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
6297            );
6298
6299            editor
6300        });
6301    }
6302
6303    #[gpui::test]
6304    fn test_cancel(cx: &mut gpui::MutableAppContext) {
6305        populate_settings(cx);
6306        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
6307        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6308
6309        view.update(cx, |view, cx| {
6310            view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
6311            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
6312            view.end_selection(cx);
6313
6314            view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
6315            view.update_selection(DisplayPoint::new(0, 3), 0, Vector2F::zero(), cx);
6316            view.end_selection(cx);
6317            assert_eq!(
6318                view.selected_display_ranges(cx),
6319                [
6320                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
6321                    DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
6322                ]
6323            );
6324        });
6325
6326        view.update(cx, |view, cx| {
6327            view.cancel(&Cancel, cx);
6328            assert_eq!(
6329                view.selected_display_ranges(cx),
6330                [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
6331            );
6332        });
6333
6334        view.update(cx, |view, cx| {
6335            view.cancel(&Cancel, cx);
6336            assert_eq!(
6337                view.selected_display_ranges(cx),
6338                [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
6339            );
6340        });
6341    }
6342
6343    #[gpui::test]
6344    fn test_fold(cx: &mut gpui::MutableAppContext) {
6345        populate_settings(cx);
6346        let buffer = MultiBuffer::build_simple(
6347            &"
6348                impl Foo {
6349                    // Hello!
6350
6351                    fn a() {
6352                        1
6353                    }
6354
6355                    fn b() {
6356                        2
6357                    }
6358
6359                    fn c() {
6360                        3
6361                    }
6362                }
6363            "
6364            .unindent(),
6365            cx,
6366        );
6367        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6368
6369        view.update(cx, |view, cx| {
6370            view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx);
6371            view.fold(&Fold, cx);
6372            assert_eq!(
6373                view.display_text(cx),
6374                "
6375                    impl Foo {
6376                        // Hello!
6377
6378                        fn a() {
6379                            1
6380                        }
6381
6382                        fn b() {…
6383                        }
6384
6385                        fn c() {…
6386                        }
6387                    }
6388                "
6389                .unindent(),
6390            );
6391
6392            view.fold(&Fold, cx);
6393            assert_eq!(
6394                view.display_text(cx),
6395                "
6396                    impl Foo {…
6397                    }
6398                "
6399                .unindent(),
6400            );
6401
6402            view.unfold(&Unfold, cx);
6403            assert_eq!(
6404                view.display_text(cx),
6405                "
6406                    impl Foo {
6407                        // Hello!
6408
6409                        fn a() {
6410                            1
6411                        }
6412
6413                        fn b() {…
6414                        }
6415
6416                        fn c() {…
6417                        }
6418                    }
6419                "
6420                .unindent(),
6421            );
6422
6423            view.unfold(&Unfold, cx);
6424            assert_eq!(view.display_text(cx), buffer.read(cx).read(cx).text());
6425        });
6426    }
6427
6428    #[gpui::test]
6429    fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
6430        populate_settings(cx);
6431        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
6432        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6433
6434        buffer.update(cx, |buffer, cx| {
6435            buffer.edit(
6436                vec![
6437                    Point::new(1, 0)..Point::new(1, 0),
6438                    Point::new(1, 1)..Point::new(1, 1),
6439                ],
6440                "\t",
6441                cx,
6442            );
6443        });
6444
6445        view.update(cx, |view, cx| {
6446            assert_eq!(
6447                view.selected_display_ranges(cx),
6448                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6449            );
6450
6451            view.move_down(&MoveDown, cx);
6452            assert_eq!(
6453                view.selected_display_ranges(cx),
6454                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
6455            );
6456
6457            view.move_right(&MoveRight, cx);
6458            assert_eq!(
6459                view.selected_display_ranges(cx),
6460                &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
6461            );
6462
6463            view.move_left(&MoveLeft, cx);
6464            assert_eq!(
6465                view.selected_display_ranges(cx),
6466                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
6467            );
6468
6469            view.move_up(&MoveUp, cx);
6470            assert_eq!(
6471                view.selected_display_ranges(cx),
6472                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6473            );
6474
6475            view.move_to_end(&MoveToEnd, cx);
6476            assert_eq!(
6477                view.selected_display_ranges(cx),
6478                &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
6479            );
6480
6481            view.move_to_beginning(&MoveToBeginning, cx);
6482            assert_eq!(
6483                view.selected_display_ranges(cx),
6484                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6485            );
6486
6487            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx);
6488            view.select_to_beginning(&SelectToBeginning, cx);
6489            assert_eq!(
6490                view.selected_display_ranges(cx),
6491                &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
6492            );
6493
6494            view.select_to_end(&SelectToEnd, cx);
6495            assert_eq!(
6496                view.selected_display_ranges(cx),
6497                &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
6498            );
6499        });
6500    }
6501
6502    #[gpui::test]
6503    fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
6504        populate_settings(cx);
6505        let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx);
6506        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6507
6508        assert_eq!('ⓐ'.len_utf8(), 3);
6509        assert_eq!('α'.len_utf8(), 2);
6510
6511        view.update(cx, |view, cx| {
6512            view.fold_ranges(
6513                vec![
6514                    Point::new(0, 6)..Point::new(0, 12),
6515                    Point::new(1, 2)..Point::new(1, 4),
6516                    Point::new(2, 4)..Point::new(2, 8),
6517                ],
6518                cx,
6519            );
6520            assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
6521
6522            view.move_right(&MoveRight, cx);
6523            assert_eq!(
6524                view.selected_display_ranges(cx),
6525                &[empty_range(0, "".len())]
6526            );
6527            view.move_right(&MoveRight, cx);
6528            assert_eq!(
6529                view.selected_display_ranges(cx),
6530                &[empty_range(0, "ⓐⓑ".len())]
6531            );
6532            view.move_right(&MoveRight, cx);
6533            assert_eq!(
6534                view.selected_display_ranges(cx),
6535                &[empty_range(0, "ⓐⓑ…".len())]
6536            );
6537
6538            view.move_down(&MoveDown, cx);
6539            assert_eq!(
6540                view.selected_display_ranges(cx),
6541                &[empty_range(1, "ab…".len())]
6542            );
6543            view.move_left(&MoveLeft, cx);
6544            assert_eq!(
6545                view.selected_display_ranges(cx),
6546                &[empty_range(1, "ab".len())]
6547            );
6548            view.move_left(&MoveLeft, cx);
6549            assert_eq!(
6550                view.selected_display_ranges(cx),
6551                &[empty_range(1, "a".len())]
6552            );
6553
6554            view.move_down(&MoveDown, cx);
6555            assert_eq!(
6556                view.selected_display_ranges(cx),
6557                &[empty_range(2, "α".len())]
6558            );
6559            view.move_right(&MoveRight, cx);
6560            assert_eq!(
6561                view.selected_display_ranges(cx),
6562                &[empty_range(2, "αβ".len())]
6563            );
6564            view.move_right(&MoveRight, cx);
6565            assert_eq!(
6566                view.selected_display_ranges(cx),
6567                &[empty_range(2, "αβ…".len())]
6568            );
6569            view.move_right(&MoveRight, cx);
6570            assert_eq!(
6571                view.selected_display_ranges(cx),
6572                &[empty_range(2, "αβ…ε".len())]
6573            );
6574
6575            view.move_up(&MoveUp, cx);
6576            assert_eq!(
6577                view.selected_display_ranges(cx),
6578                &[empty_range(1, "ab…e".len())]
6579            );
6580            view.move_up(&MoveUp, cx);
6581            assert_eq!(
6582                view.selected_display_ranges(cx),
6583                &[empty_range(0, "ⓐⓑ…ⓔ".len())]
6584            );
6585            view.move_left(&MoveLeft, cx);
6586            assert_eq!(
6587                view.selected_display_ranges(cx),
6588                &[empty_range(0, "ⓐⓑ…".len())]
6589            );
6590            view.move_left(&MoveLeft, cx);
6591            assert_eq!(
6592                view.selected_display_ranges(cx),
6593                &[empty_range(0, "ⓐⓑ".len())]
6594            );
6595            view.move_left(&MoveLeft, cx);
6596            assert_eq!(
6597                view.selected_display_ranges(cx),
6598                &[empty_range(0, "".len())]
6599            );
6600        });
6601    }
6602
6603    #[gpui::test]
6604    fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
6605        populate_settings(cx);
6606        let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
6607        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6608        view.update(cx, |view, cx| {
6609            view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx);
6610            view.move_down(&MoveDown, cx);
6611            assert_eq!(
6612                view.selected_display_ranges(cx),
6613                &[empty_range(1, "abcd".len())]
6614            );
6615
6616            view.move_down(&MoveDown, cx);
6617            assert_eq!(
6618                view.selected_display_ranges(cx),
6619                &[empty_range(2, "αβγ".len())]
6620            );
6621
6622            view.move_down(&MoveDown, cx);
6623            assert_eq!(
6624                view.selected_display_ranges(cx),
6625                &[empty_range(3, "abcd".len())]
6626            );
6627
6628            view.move_down(&MoveDown, cx);
6629            assert_eq!(
6630                view.selected_display_ranges(cx),
6631                &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
6632            );
6633
6634            view.move_up(&MoveUp, cx);
6635            assert_eq!(
6636                view.selected_display_ranges(cx),
6637                &[empty_range(3, "abcd".len())]
6638            );
6639
6640            view.move_up(&MoveUp, cx);
6641            assert_eq!(
6642                view.selected_display_ranges(cx),
6643                &[empty_range(2, "αβγ".len())]
6644            );
6645        });
6646    }
6647
6648    #[gpui::test]
6649    fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
6650        populate_settings(cx);
6651        let buffer = MultiBuffer::build_simple("abc\n  def", cx);
6652        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6653        view.update(cx, |view, cx| {
6654            view.select_display_ranges(
6655                &[
6656                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6657                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
6658                ],
6659                cx,
6660            );
6661        });
6662
6663        view.update(cx, |view, cx| {
6664            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
6665            assert_eq!(
6666                view.selected_display_ranges(cx),
6667                &[
6668                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6669                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6670                ]
6671            );
6672        });
6673
6674        view.update(cx, |view, cx| {
6675            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
6676            assert_eq!(
6677                view.selected_display_ranges(cx),
6678                &[
6679                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6680                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6681                ]
6682            );
6683        });
6684
6685        view.update(cx, |view, cx| {
6686            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
6687            assert_eq!(
6688                view.selected_display_ranges(cx),
6689                &[
6690                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6691                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6692                ]
6693            );
6694        });
6695
6696        view.update(cx, |view, cx| {
6697            view.move_to_end_of_line(&MoveToEndOfLine, cx);
6698            assert_eq!(
6699                view.selected_display_ranges(cx),
6700                &[
6701                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6702                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
6703                ]
6704            );
6705        });
6706
6707        // Moving to the end of line again is a no-op.
6708        view.update(cx, |view, cx| {
6709            view.move_to_end_of_line(&MoveToEndOfLine, cx);
6710            assert_eq!(
6711                view.selected_display_ranges(cx),
6712                &[
6713                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6714                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
6715                ]
6716            );
6717        });
6718
6719        view.update(cx, |view, cx| {
6720            view.move_left(&MoveLeft, cx);
6721            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
6722            assert_eq!(
6723                view.selected_display_ranges(cx),
6724                &[
6725                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
6726                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
6727                ]
6728            );
6729        });
6730
6731        view.update(cx, |view, cx| {
6732            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
6733            assert_eq!(
6734                view.selected_display_ranges(cx),
6735                &[
6736                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
6737                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
6738                ]
6739            );
6740        });
6741
6742        view.update(cx, |view, cx| {
6743            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
6744            assert_eq!(
6745                view.selected_display_ranges(cx),
6746                &[
6747                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
6748                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
6749                ]
6750            );
6751        });
6752
6753        view.update(cx, |view, cx| {
6754            view.select_to_end_of_line(&SelectToEndOfLine(true), cx);
6755            assert_eq!(
6756                view.selected_display_ranges(cx),
6757                &[
6758                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
6759                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
6760                ]
6761            );
6762        });
6763
6764        view.update(cx, |view, cx| {
6765            view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
6766            assert_eq!(view.display_text(cx), "ab\n  de");
6767            assert_eq!(
6768                view.selected_display_ranges(cx),
6769                &[
6770                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6771                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
6772                ]
6773            );
6774        });
6775
6776        view.update(cx, |view, cx| {
6777            view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
6778            assert_eq!(view.display_text(cx), "\n");
6779            assert_eq!(
6780                view.selected_display_ranges(cx),
6781                &[
6782                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6783                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6784                ]
6785            );
6786        });
6787    }
6788
6789    #[gpui::test]
6790    fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
6791        populate_settings(cx);
6792        let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n  {baz.qux()}", cx);
6793        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6794        view.update(cx, |view, cx| {
6795            view.select_display_ranges(
6796                &[
6797                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
6798                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
6799                ],
6800                cx,
6801            );
6802        });
6803
6804        view.update(cx, |view, cx| {
6805            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6806            assert_eq!(
6807                view.selected_display_ranges(cx),
6808                &[
6809                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
6810                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
6811                ]
6812            );
6813        });
6814
6815        view.update(cx, |view, cx| {
6816            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6817            assert_eq!(
6818                view.selected_display_ranges(cx),
6819                &[
6820                    DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
6821                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
6822                ]
6823            );
6824        });
6825
6826        view.update(cx, |view, cx| {
6827            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6828            assert_eq!(
6829                view.selected_display_ranges(cx),
6830                &[
6831                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
6832                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
6833                ]
6834            );
6835        });
6836
6837        view.update(cx, |view, cx| {
6838            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6839            assert_eq!(
6840                view.selected_display_ranges(cx),
6841                &[
6842                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6843                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6844                ]
6845            );
6846        });
6847
6848        view.update(cx, |view, cx| {
6849            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6850            assert_eq!(
6851                view.selected_display_ranges(cx),
6852                &[
6853                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6854                    DisplayPoint::new(0, 23)..DisplayPoint::new(0, 23),
6855                ]
6856            );
6857        });
6858
6859        view.update(cx, |view, cx| {
6860            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6861            assert_eq!(
6862                view.selected_display_ranges(cx),
6863                &[
6864                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6865                    DisplayPoint::new(0, 24)..DisplayPoint::new(0, 24),
6866                ]
6867            );
6868        });
6869
6870        view.update(cx, |view, cx| {
6871            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6872            assert_eq!(
6873                view.selected_display_ranges(cx),
6874                &[
6875                    DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
6876                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6877                ]
6878            );
6879        });
6880
6881        view.update(cx, |view, cx| {
6882            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6883            assert_eq!(
6884                view.selected_display_ranges(cx),
6885                &[
6886                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
6887                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
6888                ]
6889            );
6890        });
6891
6892        view.update(cx, |view, cx| {
6893            view.move_right(&MoveRight, cx);
6894            view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
6895            assert_eq!(
6896                view.selected_display_ranges(cx),
6897                &[
6898                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
6899                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
6900                ]
6901            );
6902        });
6903
6904        view.update(cx, |view, cx| {
6905            view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
6906            assert_eq!(
6907                view.selected_display_ranges(cx),
6908                &[
6909                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 7),
6910                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 2),
6911                ]
6912            );
6913        });
6914
6915        view.update(cx, |view, cx| {
6916            view.select_to_next_word_boundary(&SelectToNextWordBoundary, cx);
6917            assert_eq!(
6918                view.selected_display_ranges(cx),
6919                &[
6920                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
6921                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
6922                ]
6923            );
6924        });
6925    }
6926
6927    #[gpui::test]
6928    fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
6929        populate_settings(cx);
6930        let buffer = MultiBuffer::build_simple("use one::{\n    two::three::four::five\n};", cx);
6931        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6932
6933        view.update(cx, |view, cx| {
6934            view.set_wrap_width(Some(140.), cx);
6935            assert_eq!(
6936                view.display_text(cx),
6937                "use one::{\n    two::three::\n    four::five\n};"
6938            );
6939
6940            view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx);
6941
6942            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6943            assert_eq!(
6944                view.selected_display_ranges(cx),
6945                &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
6946            );
6947
6948            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6949            assert_eq!(
6950                view.selected_display_ranges(cx),
6951                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
6952            );
6953
6954            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6955            assert_eq!(
6956                view.selected_display_ranges(cx),
6957                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
6958            );
6959
6960            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6961            assert_eq!(
6962                view.selected_display_ranges(cx),
6963                &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
6964            );
6965
6966            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6967            assert_eq!(
6968                view.selected_display_ranges(cx),
6969                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
6970            );
6971
6972            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6973            assert_eq!(
6974                view.selected_display_ranges(cx),
6975                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
6976            );
6977        });
6978    }
6979
6980    #[gpui::test]
6981    fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
6982        populate_settings(cx);
6983        let buffer = MultiBuffer::build_simple("one two three four", cx);
6984        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6985
6986        view.update(cx, |view, cx| {
6987            view.select_display_ranges(
6988                &[
6989                    // an empty selection - the preceding word fragment is deleted
6990                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6991                    // characters selected - they are deleted
6992                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
6993                ],
6994                cx,
6995            );
6996            view.delete_to_previous_word_boundary(&DeleteToPreviousWordBoundary, cx);
6997        });
6998
6999        assert_eq!(buffer.read(cx).read(cx).text(), "e two te four");
7000
7001        view.update(cx, |view, cx| {
7002            view.select_display_ranges(
7003                &[
7004                    // an empty selection - the following word fragment is deleted
7005                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
7006                    // characters selected - they are deleted
7007                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
7008                ],
7009                cx,
7010            );
7011            view.delete_to_next_word_boundary(&DeleteToNextWordBoundary, cx);
7012        });
7013
7014        assert_eq!(buffer.read(cx).read(cx).text(), "e t te our");
7015    }
7016
7017    #[gpui::test]
7018    fn test_newline(cx: &mut gpui::MutableAppContext) {
7019        populate_settings(cx);
7020        let buffer = MultiBuffer::build_simple("aaaa\n    bbbb\n", cx);
7021        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7022
7023        view.update(cx, |view, cx| {
7024            view.select_display_ranges(
7025                &[
7026                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7027                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
7028                    DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
7029                ],
7030                cx,
7031            );
7032
7033            view.newline(&Newline, cx);
7034            assert_eq!(view.text(cx), "aa\naa\n  \n    bb\n    bb\n");
7035        });
7036    }
7037
7038    #[gpui::test]
7039    fn test_newline_with_old_selections(cx: &mut gpui::MutableAppContext) {
7040        populate_settings(cx);
7041        let buffer = MultiBuffer::build_simple(
7042            "
7043                a
7044                b(
7045                    X
7046                )
7047                c(
7048                    X
7049                )
7050            "
7051            .unindent()
7052            .as_str(),
7053            cx,
7054        );
7055
7056        let (_, editor) = cx.add_window(Default::default(), |cx| {
7057            let mut editor = build_editor(buffer.clone(), cx);
7058            editor.select_ranges(
7059                [
7060                    Point::new(2, 4)..Point::new(2, 5),
7061                    Point::new(5, 4)..Point::new(5, 5),
7062                ],
7063                None,
7064                cx,
7065            );
7066            editor
7067        });
7068
7069        // Edit the buffer directly, deleting ranges surrounding the editor's selections
7070        buffer.update(cx, |buffer, cx| {
7071            buffer.edit(
7072                [
7073                    Point::new(1, 2)..Point::new(3, 0),
7074                    Point::new(4, 2)..Point::new(6, 0),
7075                ],
7076                "",
7077                cx,
7078            );
7079            assert_eq!(
7080                buffer.read(cx).text(),
7081                "
7082                    a
7083                    b()
7084                    c()
7085                "
7086                .unindent()
7087            );
7088        });
7089
7090        editor.update(cx, |editor, cx| {
7091            assert_eq!(
7092                editor.selected_ranges(cx),
7093                &[
7094                    Point::new(1, 2)..Point::new(1, 2),
7095                    Point::new(2, 2)..Point::new(2, 2),
7096                ],
7097            );
7098
7099            editor.newline(&Newline, cx);
7100            assert_eq!(
7101                editor.text(cx),
7102                "
7103                    a
7104                    b(
7105                    )
7106                    c(
7107                    )
7108                "
7109                .unindent()
7110            );
7111
7112            // The selections are moved after the inserted newlines
7113            assert_eq!(
7114                editor.selected_ranges(cx),
7115                &[
7116                    Point::new(2, 0)..Point::new(2, 0),
7117                    Point::new(4, 0)..Point::new(4, 0),
7118                ],
7119            );
7120        });
7121    }
7122
7123    #[gpui::test]
7124    fn test_insert_with_old_selections(cx: &mut gpui::MutableAppContext) {
7125        populate_settings(cx);
7126        let buffer = MultiBuffer::build_simple("a( X ), b( Y ), c( Z )", cx);
7127        let (_, editor) = cx.add_window(Default::default(), |cx| {
7128            let mut editor = build_editor(buffer.clone(), cx);
7129            editor.select_ranges([3..4, 11..12, 19..20], None, cx);
7130            editor
7131        });
7132
7133        // Edit the buffer directly, deleting ranges surrounding the editor's selections
7134        buffer.update(cx, |buffer, cx| {
7135            buffer.edit([2..5, 10..13, 18..21], "", cx);
7136            assert_eq!(buffer.read(cx).text(), "a(), b(), c()".unindent());
7137        });
7138
7139        editor.update(cx, |editor, cx| {
7140            assert_eq!(editor.selected_ranges(cx), &[2..2, 7..7, 12..12],);
7141
7142            editor.insert("Z", cx);
7143            assert_eq!(editor.text(cx), "a(Z), b(Z), c(Z)");
7144
7145            // The selections are moved after the inserted characters
7146            assert_eq!(editor.selected_ranges(cx), &[3..3, 9..9, 15..15],);
7147        });
7148    }
7149
7150    #[gpui::test]
7151    fn test_indent_outdent(cx: &mut gpui::MutableAppContext) {
7152        populate_settings(cx);
7153        let buffer = MultiBuffer::build_simple("  one two\nthree\n four", cx);
7154        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7155
7156        view.update(cx, |view, cx| {
7157            // two selections on the same line
7158            view.select_display_ranges(
7159                &[
7160                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 5),
7161                    DisplayPoint::new(0, 6)..DisplayPoint::new(0, 9),
7162                ],
7163                cx,
7164            );
7165
7166            // indent from mid-tabstop to full tabstop
7167            view.tab(&Tab, cx);
7168            assert_eq!(view.text(cx), "    one two\nthree\n four");
7169            assert_eq!(
7170                view.selected_display_ranges(cx),
7171                &[
7172                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
7173                    DisplayPoint::new(0, 8)..DisplayPoint::new(0, 11),
7174                ]
7175            );
7176
7177            // outdent from 1 tabstop to 0 tabstops
7178            view.outdent(&Outdent, cx);
7179            assert_eq!(view.text(cx), "one two\nthree\n four");
7180            assert_eq!(
7181                view.selected_display_ranges(cx),
7182                &[
7183                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 3),
7184                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
7185                ]
7186            );
7187
7188            // select across line ending
7189            view.select_display_ranges(&[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)], cx);
7190
7191            // indent and outdent affect only the preceding line
7192            view.tab(&Tab, cx);
7193            assert_eq!(view.text(cx), "one two\n    three\n four");
7194            assert_eq!(
7195                view.selected_display_ranges(cx),
7196                &[DisplayPoint::new(1, 5)..DisplayPoint::new(2, 0)]
7197            );
7198            view.outdent(&Outdent, cx);
7199            assert_eq!(view.text(cx), "one two\nthree\n four");
7200            assert_eq!(
7201                view.selected_display_ranges(cx),
7202                &[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)]
7203            );
7204
7205            // Ensure that indenting/outdenting works when the cursor is at column 0.
7206            view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
7207            view.tab(&Tab, cx);
7208            assert_eq!(view.text(cx), "one two\n    three\n four");
7209            assert_eq!(
7210                view.selected_display_ranges(cx),
7211                &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
7212            );
7213
7214            view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
7215            view.outdent(&Outdent, cx);
7216            assert_eq!(view.text(cx), "one two\nthree\n four");
7217            assert_eq!(
7218                view.selected_display_ranges(cx),
7219                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
7220            );
7221        });
7222    }
7223
7224    #[gpui::test]
7225    fn test_backspace(cx: &mut gpui::MutableAppContext) {
7226        populate_settings(cx);
7227        let (_, view) = cx.add_window(Default::default(), |cx| {
7228            build_editor(MultiBuffer::build_simple("", cx), cx)
7229        });
7230
7231        view.update(cx, |view, cx| {
7232            view.set_text("one two three\nfour five six\nseven eight nine\nten\n", cx);
7233            view.select_display_ranges(
7234                &[
7235                    // an empty selection - the preceding character is deleted
7236                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7237                    // one character selected - it is deleted
7238                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7239                    // a line suffix selected - it is deleted
7240                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
7241                ],
7242                cx,
7243            );
7244            view.backspace(&Backspace, cx);
7245            assert_eq!(view.text(cx), "oe two three\nfou five six\nseven ten\n");
7246
7247            view.set_text("    one\n        two\n        three\n   four", cx);
7248            view.select_display_ranges(
7249                &[
7250                    // cursors at the the end of leading indent - last indent is deleted
7251                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
7252                    DisplayPoint::new(1, 8)..DisplayPoint::new(1, 8),
7253                    // cursors inside leading indent - overlapping indent deletions are coalesced
7254                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
7255                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
7256                    DisplayPoint::new(2, 6)..DisplayPoint::new(2, 6),
7257                    // cursor at the beginning of a line - preceding newline is deleted
7258                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7259                    // selection inside leading indent - only the selected character is deleted
7260                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3),
7261                ],
7262                cx,
7263            );
7264            view.backspace(&Backspace, cx);
7265            assert_eq!(view.text(cx), "one\n    two\n  three  four");
7266        });
7267    }
7268
7269    #[gpui::test]
7270    fn test_delete(cx: &mut gpui::MutableAppContext) {
7271        populate_settings(cx);
7272        let buffer =
7273            MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
7274        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7275
7276        view.update(cx, |view, cx| {
7277            view.select_display_ranges(
7278                &[
7279                    // an empty selection - the following character is deleted
7280                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7281                    // one character selected - it is deleted
7282                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7283                    // a line suffix selected - it is deleted
7284                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
7285                ],
7286                cx,
7287            );
7288            view.delete(&Delete, cx);
7289        });
7290
7291        assert_eq!(
7292            buffer.read(cx).read(cx).text(),
7293            "on two three\nfou five six\nseven ten\n"
7294        );
7295    }
7296
7297    #[gpui::test]
7298    fn test_delete_line(cx: &mut gpui::MutableAppContext) {
7299        populate_settings(cx);
7300        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7301        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7302        view.update(cx, |view, cx| {
7303            view.select_display_ranges(
7304                &[
7305                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7306                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
7307                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7308                ],
7309                cx,
7310            );
7311            view.delete_line(&DeleteLine, cx);
7312            assert_eq!(view.display_text(cx), "ghi");
7313            assert_eq!(
7314                view.selected_display_ranges(cx),
7315                vec![
7316                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
7317                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
7318                ]
7319            );
7320        });
7321
7322        populate_settings(cx);
7323        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7324        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7325        view.update(cx, |view, cx| {
7326            view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx);
7327            view.delete_line(&DeleteLine, cx);
7328            assert_eq!(view.display_text(cx), "ghi\n");
7329            assert_eq!(
7330                view.selected_display_ranges(cx),
7331                vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
7332            );
7333        });
7334    }
7335
7336    #[gpui::test]
7337    fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
7338        populate_settings(cx);
7339        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7340        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7341        view.update(cx, |view, cx| {
7342            view.select_display_ranges(
7343                &[
7344                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7345                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7346                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7347                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7348                ],
7349                cx,
7350            );
7351            view.duplicate_line(&DuplicateLine, cx);
7352            assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
7353            assert_eq!(
7354                view.selected_display_ranges(cx),
7355                vec![
7356                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
7357                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
7358                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7359                    DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
7360                ]
7361            );
7362        });
7363
7364        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7365        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7366        view.update(cx, |view, cx| {
7367            view.select_display_ranges(
7368                &[
7369                    DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
7370                    DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
7371                ],
7372                cx,
7373            );
7374            view.duplicate_line(&DuplicateLine, cx);
7375            assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
7376            assert_eq!(
7377                view.selected_display_ranges(cx),
7378                vec![
7379                    DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
7380                    DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
7381                ]
7382            );
7383        });
7384    }
7385
7386    #[gpui::test]
7387    fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
7388        populate_settings(cx);
7389        let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
7390        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7391        view.update(cx, |view, cx| {
7392            view.fold_ranges(
7393                vec![
7394                    Point::new(0, 2)..Point::new(1, 2),
7395                    Point::new(2, 3)..Point::new(4, 1),
7396                    Point::new(7, 0)..Point::new(8, 4),
7397                ],
7398                cx,
7399            );
7400            view.select_display_ranges(
7401                &[
7402                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7403                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7404                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7405                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
7406                ],
7407                cx,
7408            );
7409            assert_eq!(
7410                view.display_text(cx),
7411                "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
7412            );
7413
7414            view.move_line_up(&MoveLineUp, cx);
7415            assert_eq!(
7416                view.display_text(cx),
7417                "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
7418            );
7419            assert_eq!(
7420                view.selected_display_ranges(cx),
7421                vec![
7422                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7423                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7424                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
7425                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
7426                ]
7427            );
7428        });
7429
7430        view.update(cx, |view, cx| {
7431            view.move_line_down(&MoveLineDown, cx);
7432            assert_eq!(
7433                view.display_text(cx),
7434                "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
7435            );
7436            assert_eq!(
7437                view.selected_display_ranges(cx),
7438                vec![
7439                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7440                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7441                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7442                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
7443                ]
7444            );
7445        });
7446
7447        view.update(cx, |view, cx| {
7448            view.move_line_down(&MoveLineDown, cx);
7449            assert_eq!(
7450                view.display_text(cx),
7451                "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
7452            );
7453            assert_eq!(
7454                view.selected_display_ranges(cx),
7455                vec![
7456                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7457                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7458                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7459                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
7460                ]
7461            );
7462        });
7463
7464        view.update(cx, |view, cx| {
7465            view.move_line_up(&MoveLineUp, cx);
7466            assert_eq!(
7467                view.display_text(cx),
7468                "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
7469            );
7470            assert_eq!(
7471                view.selected_display_ranges(cx),
7472                vec![
7473                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7474                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7475                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
7476                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
7477                ]
7478            );
7479        });
7480    }
7481
7482    #[gpui::test]
7483    fn test_move_line_up_down_with_blocks(cx: &mut gpui::MutableAppContext) {
7484        populate_settings(cx);
7485        let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
7486        let snapshot = buffer.read(cx).snapshot(cx);
7487        let (_, editor) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7488        editor.update(cx, |editor, cx| {
7489            editor.insert_blocks(
7490                [BlockProperties {
7491                    position: snapshot.anchor_after(Point::new(2, 0)),
7492                    disposition: BlockDisposition::Below,
7493                    height: 1,
7494                    render: Arc::new(|_| Empty::new().boxed()),
7495                }],
7496                cx,
7497            );
7498            editor.select_ranges([Point::new(2, 0)..Point::new(2, 0)], None, cx);
7499            editor.move_line_down(&MoveLineDown, cx);
7500        });
7501    }
7502
7503    #[gpui::test]
7504    fn test_clipboard(cx: &mut gpui::MutableAppContext) {
7505        populate_settings(cx);
7506        let buffer = MultiBuffer::build_simple("one✅ two three four five six ", cx);
7507        let view = cx
7508            .add_window(Default::default(), |cx| build_editor(buffer.clone(), cx))
7509            .1;
7510
7511        // Cut with three selections. Clipboard text is divided into three slices.
7512        view.update(cx, |view, cx| {
7513            view.select_ranges(vec![0..7, 11..17, 22..27], None, cx);
7514            view.cut(&Cut, cx);
7515            assert_eq!(view.display_text(cx), "two four six ");
7516        });
7517
7518        // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
7519        view.update(cx, |view, cx| {
7520            view.select_ranges(vec![4..4, 9..9, 13..13], None, cx);
7521            view.paste(&Paste, cx);
7522            assert_eq!(view.display_text(cx), "two one✅ four three six five ");
7523            assert_eq!(
7524                view.selected_display_ranges(cx),
7525                &[
7526                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
7527                    DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
7528                    DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
7529                ]
7530            );
7531        });
7532
7533        // Paste again but with only two cursors. Since the number of cursors doesn't
7534        // match the number of slices in the clipboard, the entire clipboard text
7535        // is pasted at each cursor.
7536        view.update(cx, |view, cx| {
7537            view.select_ranges(vec![0..0, 31..31], None, cx);
7538            view.handle_input(&Input("( ".into()), cx);
7539            view.paste(&Paste, cx);
7540            view.handle_input(&Input(") ".into()), cx);
7541            assert_eq!(
7542                view.display_text(cx),
7543                "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
7544            );
7545        });
7546
7547        view.update(cx, |view, cx| {
7548            view.select_ranges(vec![0..0], None, cx);
7549            view.handle_input(&Input("123\n4567\n89\n".into()), cx);
7550            assert_eq!(
7551                view.display_text(cx),
7552                "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
7553            );
7554        });
7555
7556        // Cut with three selections, one of which is full-line.
7557        view.update(cx, |view, cx| {
7558            view.select_display_ranges(
7559                &[
7560                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
7561                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7562                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
7563                ],
7564                cx,
7565            );
7566            view.cut(&Cut, cx);
7567            assert_eq!(
7568                view.display_text(cx),
7569                "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
7570            );
7571        });
7572
7573        // Paste with three selections, noticing how the copied selection that was full-line
7574        // gets inserted before the second cursor.
7575        view.update(cx, |view, cx| {
7576            view.select_display_ranges(
7577                &[
7578                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7579                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7580                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
7581                ],
7582                cx,
7583            );
7584            view.paste(&Paste, cx);
7585            assert_eq!(
7586                view.display_text(cx),
7587                "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
7588            );
7589            assert_eq!(
7590                view.selected_display_ranges(cx),
7591                &[
7592                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7593                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7594                    DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
7595                ]
7596            );
7597        });
7598
7599        // Copy with a single cursor only, which writes the whole line into the clipboard.
7600        view.update(cx, |view, cx| {
7601            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx);
7602            view.copy(&Copy, cx);
7603        });
7604
7605        // Paste with three selections, noticing how the copied full-line selection is inserted
7606        // before the empty selections but replaces the selection that is non-empty.
7607        view.update(cx, |view, cx| {
7608            view.select_display_ranges(
7609                &[
7610                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7611                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
7612                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7613                ],
7614                cx,
7615            );
7616            view.paste(&Paste, cx);
7617            assert_eq!(
7618                view.display_text(cx),
7619                "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
7620            );
7621            assert_eq!(
7622                view.selected_display_ranges(cx),
7623                &[
7624                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7625                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7626                    DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
7627                ]
7628            );
7629        });
7630    }
7631
7632    #[gpui::test]
7633    fn test_select_all(cx: &mut gpui::MutableAppContext) {
7634        populate_settings(cx);
7635        let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
7636        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7637        view.update(cx, |view, cx| {
7638            view.select_all(&SelectAll, cx);
7639            assert_eq!(
7640                view.selected_display_ranges(cx),
7641                &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
7642            );
7643        });
7644    }
7645
7646    #[gpui::test]
7647    fn test_select_line(cx: &mut gpui::MutableAppContext) {
7648        populate_settings(cx);
7649        let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
7650        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7651        view.update(cx, |view, cx| {
7652            view.select_display_ranges(
7653                &[
7654                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7655                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7656                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7657                    DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
7658                ],
7659                cx,
7660            );
7661            view.select_line(&SelectLine, cx);
7662            assert_eq!(
7663                view.selected_display_ranges(cx),
7664                vec![
7665                    DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
7666                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
7667                ]
7668            );
7669        });
7670
7671        view.update(cx, |view, cx| {
7672            view.select_line(&SelectLine, cx);
7673            assert_eq!(
7674                view.selected_display_ranges(cx),
7675                vec![
7676                    DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
7677                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
7678                ]
7679            );
7680        });
7681
7682        view.update(cx, |view, cx| {
7683            view.select_line(&SelectLine, cx);
7684            assert_eq!(
7685                view.selected_display_ranges(cx),
7686                vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
7687            );
7688        });
7689    }
7690
7691    #[gpui::test]
7692    fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
7693        populate_settings(cx);
7694        let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
7695        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7696        view.update(cx, |view, cx| {
7697            view.fold_ranges(
7698                vec![
7699                    Point::new(0, 2)..Point::new(1, 2),
7700                    Point::new(2, 3)..Point::new(4, 1),
7701                    Point::new(7, 0)..Point::new(8, 4),
7702                ],
7703                cx,
7704            );
7705            view.select_display_ranges(
7706                &[
7707                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7708                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7709                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7710                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
7711                ],
7712                cx,
7713            );
7714            assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
7715        });
7716
7717        view.update(cx, |view, cx| {
7718            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
7719            assert_eq!(
7720                view.display_text(cx),
7721                "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
7722            );
7723            assert_eq!(
7724                view.selected_display_ranges(cx),
7725                [
7726                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7727                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7728                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
7729                    DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
7730                ]
7731            );
7732        });
7733
7734        view.update(cx, |view, cx| {
7735            view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx);
7736            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
7737            assert_eq!(
7738                view.display_text(cx),
7739                "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
7740            );
7741            assert_eq!(
7742                view.selected_display_ranges(cx),
7743                [
7744                    DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
7745                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
7746                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
7747                    DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
7748                    DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
7749                    DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
7750                    DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
7751                    DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
7752                ]
7753            );
7754        });
7755    }
7756
7757    #[gpui::test]
7758    fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
7759        populate_settings(cx);
7760        let buffer = MultiBuffer::build_simple("abc\ndefghi\n\njk\nlmno\n", cx);
7761        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7762
7763        view.update(cx, |view, cx| {
7764            view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx);
7765        });
7766        view.update(cx, |view, cx| {
7767            view.add_selection_above(&AddSelectionAbove, cx);
7768            assert_eq!(
7769                view.selected_display_ranges(cx),
7770                vec![
7771                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
7772                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
7773                ]
7774            );
7775        });
7776
7777        view.update(cx, |view, cx| {
7778            view.add_selection_above(&AddSelectionAbove, cx);
7779            assert_eq!(
7780                view.selected_display_ranges(cx),
7781                vec![
7782                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
7783                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
7784                ]
7785            );
7786        });
7787
7788        view.update(cx, |view, cx| {
7789            view.add_selection_below(&AddSelectionBelow, cx);
7790            assert_eq!(
7791                view.selected_display_ranges(cx),
7792                vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
7793            );
7794        });
7795
7796        view.update(cx, |view, cx| {
7797            view.add_selection_below(&AddSelectionBelow, cx);
7798            assert_eq!(
7799                view.selected_display_ranges(cx),
7800                vec![
7801                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
7802                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
7803                ]
7804            );
7805        });
7806
7807        view.update(cx, |view, cx| {
7808            view.add_selection_below(&AddSelectionBelow, cx);
7809            assert_eq!(
7810                view.selected_display_ranges(cx),
7811                vec![
7812                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
7813                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
7814                ]
7815            );
7816        });
7817
7818        view.update(cx, |view, cx| {
7819            view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx);
7820        });
7821        view.update(cx, |view, cx| {
7822            view.add_selection_below(&AddSelectionBelow, cx);
7823            assert_eq!(
7824                view.selected_display_ranges(cx),
7825                vec![
7826                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7827                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
7828                ]
7829            );
7830        });
7831
7832        view.update(cx, |view, cx| {
7833            view.add_selection_below(&AddSelectionBelow, cx);
7834            assert_eq!(
7835                view.selected_display_ranges(cx),
7836                vec![
7837                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7838                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
7839                ]
7840            );
7841        });
7842
7843        view.update(cx, |view, cx| {
7844            view.add_selection_above(&AddSelectionAbove, cx);
7845            assert_eq!(
7846                view.selected_display_ranges(cx),
7847                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
7848            );
7849        });
7850
7851        view.update(cx, |view, cx| {
7852            view.add_selection_above(&AddSelectionAbove, cx);
7853            assert_eq!(
7854                view.selected_display_ranges(cx),
7855                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
7856            );
7857        });
7858
7859        view.update(cx, |view, cx| {
7860            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx);
7861            view.add_selection_below(&AddSelectionBelow, cx);
7862            assert_eq!(
7863                view.selected_display_ranges(cx),
7864                vec![
7865                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
7866                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
7867                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
7868                ]
7869            );
7870        });
7871
7872        view.update(cx, |view, cx| {
7873            view.add_selection_below(&AddSelectionBelow, cx);
7874            assert_eq!(
7875                view.selected_display_ranges(cx),
7876                vec![
7877                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
7878                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
7879                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
7880                    DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
7881                ]
7882            );
7883        });
7884
7885        view.update(cx, |view, cx| {
7886            view.add_selection_above(&AddSelectionAbove, cx);
7887            assert_eq!(
7888                view.selected_display_ranges(cx),
7889                vec![
7890                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
7891                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
7892                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
7893                ]
7894            );
7895        });
7896
7897        view.update(cx, |view, cx| {
7898            view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx);
7899        });
7900        view.update(cx, |view, cx| {
7901            view.add_selection_above(&AddSelectionAbove, cx);
7902            assert_eq!(
7903                view.selected_display_ranges(cx),
7904                vec![
7905                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
7906                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
7907                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
7908                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
7909                ]
7910            );
7911        });
7912
7913        view.update(cx, |view, cx| {
7914            view.add_selection_below(&AddSelectionBelow, cx);
7915            assert_eq!(
7916                view.selected_display_ranges(cx),
7917                vec![
7918                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
7919                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
7920                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
7921                ]
7922            );
7923        });
7924    }
7925
7926    #[gpui::test]
7927    async fn test_select_larger_smaller_syntax_node(cx: &mut gpui::TestAppContext) {
7928        cx.update(populate_settings);
7929        let language = Arc::new(Language::new(
7930            LanguageConfig::default(),
7931            Some(tree_sitter_rust::language()),
7932        ));
7933
7934        let text = r#"
7935            use mod1::mod2::{mod3, mod4};
7936
7937            fn fn_1(param1: bool, param2: &str) {
7938                let var1 = "text";
7939            }
7940        "#
7941        .unindent();
7942
7943        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
7944        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
7945        let (_, view) = cx.add_window(|cx| build_editor(buffer, cx));
7946        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
7947            .await;
7948
7949        view.update(cx, |view, cx| {
7950            view.select_display_ranges(
7951                &[
7952                    DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
7953                    DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
7954                    DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
7955                ],
7956                cx,
7957            );
7958            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
7959        });
7960        assert_eq!(
7961            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
7962            &[
7963                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
7964                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
7965                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
7966            ]
7967        );
7968
7969        view.update(cx, |view, cx| {
7970            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
7971        });
7972        assert_eq!(
7973            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
7974            &[
7975                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
7976                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
7977            ]
7978        );
7979
7980        view.update(cx, |view, cx| {
7981            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
7982        });
7983        assert_eq!(
7984            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
7985            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
7986        );
7987
7988        // Trying to expand the selected syntax node one more time has no effect.
7989        view.update(cx, |view, cx| {
7990            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
7991        });
7992        assert_eq!(
7993            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
7994            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
7995        );
7996
7997        view.update(cx, |view, cx| {
7998            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
7999        });
8000        assert_eq!(
8001            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8002            &[
8003                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
8004                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
8005            ]
8006        );
8007
8008        view.update(cx, |view, cx| {
8009            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
8010        });
8011        assert_eq!(
8012            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8013            &[
8014                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
8015                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
8016                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
8017            ]
8018        );
8019
8020        view.update(cx, |view, cx| {
8021            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
8022        });
8023        assert_eq!(
8024            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8025            &[
8026                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
8027                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
8028                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
8029            ]
8030        );
8031
8032        // Trying to shrink the selected syntax node one more time has no effect.
8033        view.update(cx, |view, cx| {
8034            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
8035        });
8036        assert_eq!(
8037            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8038            &[
8039                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
8040                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
8041                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
8042            ]
8043        );
8044
8045        // Ensure that we keep expanding the selection if the larger selection starts or ends within
8046        // a fold.
8047        view.update(cx, |view, cx| {
8048            view.fold_ranges(
8049                vec![
8050                    Point::new(0, 21)..Point::new(0, 24),
8051                    Point::new(3, 20)..Point::new(3, 22),
8052                ],
8053                cx,
8054            );
8055            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8056        });
8057        assert_eq!(
8058            view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8059            &[
8060                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
8061                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
8062                DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
8063            ]
8064        );
8065    }
8066
8067    #[gpui::test]
8068    async fn test_autoindent_selections(cx: &mut gpui::TestAppContext) {
8069        cx.update(populate_settings);
8070        let language = Arc::new(
8071            Language::new(
8072                LanguageConfig {
8073                    brackets: vec![
8074                        BracketPair {
8075                            start: "{".to_string(),
8076                            end: "}".to_string(),
8077                            close: false,
8078                            newline: true,
8079                        },
8080                        BracketPair {
8081                            start: "(".to_string(),
8082                            end: ")".to_string(),
8083                            close: false,
8084                            newline: true,
8085                        },
8086                    ],
8087                    ..Default::default()
8088                },
8089                Some(tree_sitter_rust::language()),
8090            )
8091            .with_indents_query(
8092                r#"
8093                (_ "(" ")" @end) @indent
8094                (_ "{" "}" @end) @indent
8095                "#,
8096            )
8097            .unwrap(),
8098        );
8099
8100        let text = "fn a() {}";
8101
8102        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8103        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8104        let (_, editor) = cx.add_window(|cx| build_editor(buffer, cx));
8105        editor
8106            .condition(&cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
8107            .await;
8108
8109        editor.update(cx, |editor, cx| {
8110            editor.select_ranges([5..5, 8..8, 9..9], None, cx);
8111            editor.newline(&Newline, cx);
8112            assert_eq!(editor.text(cx), "fn a(\n    \n) {\n    \n}\n");
8113            assert_eq!(
8114                editor.selected_ranges(cx),
8115                &[
8116                    Point::new(1, 4)..Point::new(1, 4),
8117                    Point::new(3, 4)..Point::new(3, 4),
8118                    Point::new(5, 0)..Point::new(5, 0)
8119                ]
8120            );
8121        });
8122    }
8123
8124    #[gpui::test]
8125    async fn test_autoclose_pairs(cx: &mut gpui::TestAppContext) {
8126        cx.update(populate_settings);
8127        let language = Arc::new(Language::new(
8128            LanguageConfig {
8129                brackets: vec![
8130                    BracketPair {
8131                        start: "{".to_string(),
8132                        end: "}".to_string(),
8133                        close: true,
8134                        newline: true,
8135                    },
8136                    BracketPair {
8137                        start: "/*".to_string(),
8138                        end: " */".to_string(),
8139                        close: true,
8140                        newline: true,
8141                    },
8142                ],
8143                autoclose_before: "})]".to_string(),
8144                ..Default::default()
8145            },
8146            Some(tree_sitter_rust::language()),
8147        ));
8148
8149        let text = r#"
8150            a
8151
8152            /
8153
8154        "#
8155        .unindent();
8156
8157        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8158        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8159        let (_, view) = cx.add_window(|cx| build_editor(buffer, cx));
8160        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
8161            .await;
8162
8163        view.update(cx, |view, cx| {
8164            view.select_display_ranges(
8165                &[
8166                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
8167                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
8168                ],
8169                cx,
8170            );
8171
8172            view.handle_input(&Input("{".to_string()), cx);
8173            view.handle_input(&Input("{".to_string()), cx);
8174            view.handle_input(&Input("{".to_string()), cx);
8175            assert_eq!(
8176                view.text(cx),
8177                "
8178                {{{}}}
8179                {{{}}}
8180                /
8181
8182                "
8183                .unindent()
8184            );
8185
8186            view.move_right(&MoveRight, cx);
8187            view.handle_input(&Input("}".to_string()), cx);
8188            view.handle_input(&Input("}".to_string()), cx);
8189            view.handle_input(&Input("}".to_string()), cx);
8190            assert_eq!(
8191                view.text(cx),
8192                "
8193                {{{}}}}
8194                {{{}}}}
8195                /
8196
8197                "
8198                .unindent()
8199            );
8200
8201            view.undo(&Undo, cx);
8202            view.handle_input(&Input("/".to_string()), cx);
8203            view.handle_input(&Input("*".to_string()), cx);
8204            assert_eq!(
8205                view.text(cx),
8206                "
8207                /* */
8208                /* */
8209                /
8210
8211                "
8212                .unindent()
8213            );
8214
8215            view.undo(&Undo, cx);
8216            view.select_display_ranges(
8217                &[
8218                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
8219                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
8220                ],
8221                cx,
8222            );
8223            view.handle_input(&Input("*".to_string()), cx);
8224            assert_eq!(
8225                view.text(cx),
8226                "
8227                a
8228
8229                /*
8230                *
8231                "
8232                .unindent()
8233            );
8234
8235            // Don't autoclose if the next character isn't whitespace and isn't
8236            // listed in the language's "autoclose_before" section.
8237            view.finalize_last_transaction(cx);
8238            view.select_display_ranges(&[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)], cx);
8239            view.handle_input(&Input("{".to_string()), cx);
8240            assert_eq!(
8241                view.text(cx),
8242                "
8243                {a
8244
8245                /*
8246                *
8247                "
8248                .unindent()
8249            );
8250
8251            view.undo(&Undo, cx);
8252            view.select_display_ranges(&[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1)], cx);
8253            view.handle_input(&Input("{".to_string()), cx);
8254            assert_eq!(
8255                view.text(cx),
8256                "
8257                {a}
8258
8259                /*
8260                *
8261                "
8262                .unindent()
8263            );
8264            assert_eq!(
8265                view.selected_display_ranges(cx),
8266                [DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)]
8267            );
8268        });
8269    }
8270
8271    #[gpui::test]
8272    async fn test_snippets(cx: &mut gpui::TestAppContext) {
8273        cx.update(populate_settings);
8274
8275        let text = "
8276            a. b
8277            a. b
8278            a. b
8279        "
8280        .unindent();
8281        let buffer = cx.update(|cx| MultiBuffer::build_simple(&text, cx));
8282        let (_, editor) = cx.add_window(|cx| build_editor(buffer, cx));
8283
8284        editor.update(cx, |editor, cx| {
8285            let buffer = &editor.snapshot(cx).buffer_snapshot;
8286            let snippet = Snippet::parse("f(${1:one}, ${2:two}, ${1:three})$0").unwrap();
8287            let insertion_ranges = [
8288                Point::new(0, 2).to_offset(buffer)..Point::new(0, 2).to_offset(buffer),
8289                Point::new(1, 2).to_offset(buffer)..Point::new(1, 2).to_offset(buffer),
8290                Point::new(2, 2).to_offset(buffer)..Point::new(2, 2).to_offset(buffer),
8291            ];
8292
8293            editor
8294                .insert_snippet(&insertion_ranges, snippet, cx)
8295                .unwrap();
8296            assert_eq!(
8297                editor.text(cx),
8298                "
8299                    a.f(one, two, three) b
8300                    a.f(one, two, three) b
8301                    a.f(one, two, three) b
8302                "
8303                .unindent()
8304            );
8305            assert_eq!(
8306                editor.selected_ranges::<Point>(cx),
8307                &[
8308                    Point::new(0, 4)..Point::new(0, 7),
8309                    Point::new(0, 14)..Point::new(0, 19),
8310                    Point::new(1, 4)..Point::new(1, 7),
8311                    Point::new(1, 14)..Point::new(1, 19),
8312                    Point::new(2, 4)..Point::new(2, 7),
8313                    Point::new(2, 14)..Point::new(2, 19),
8314                ]
8315            );
8316
8317            // Can't move earlier than the first tab stop
8318            editor.move_to_prev_snippet_tabstop(cx);
8319            assert_eq!(
8320                editor.selected_ranges::<Point>(cx),
8321                &[
8322                    Point::new(0, 4)..Point::new(0, 7),
8323                    Point::new(0, 14)..Point::new(0, 19),
8324                    Point::new(1, 4)..Point::new(1, 7),
8325                    Point::new(1, 14)..Point::new(1, 19),
8326                    Point::new(2, 4)..Point::new(2, 7),
8327                    Point::new(2, 14)..Point::new(2, 19),
8328                ]
8329            );
8330
8331            assert!(editor.move_to_next_snippet_tabstop(cx));
8332            assert_eq!(
8333                editor.selected_ranges::<Point>(cx),
8334                &[
8335                    Point::new(0, 9)..Point::new(0, 12),
8336                    Point::new(1, 9)..Point::new(1, 12),
8337                    Point::new(2, 9)..Point::new(2, 12)
8338                ]
8339            );
8340
8341            editor.move_to_prev_snippet_tabstop(cx);
8342            assert_eq!(
8343                editor.selected_ranges::<Point>(cx),
8344                &[
8345                    Point::new(0, 4)..Point::new(0, 7),
8346                    Point::new(0, 14)..Point::new(0, 19),
8347                    Point::new(1, 4)..Point::new(1, 7),
8348                    Point::new(1, 14)..Point::new(1, 19),
8349                    Point::new(2, 4)..Point::new(2, 7),
8350                    Point::new(2, 14)..Point::new(2, 19),
8351                ]
8352            );
8353
8354            assert!(editor.move_to_next_snippet_tabstop(cx));
8355            assert!(editor.move_to_next_snippet_tabstop(cx));
8356            assert_eq!(
8357                editor.selected_ranges::<Point>(cx),
8358                &[
8359                    Point::new(0, 20)..Point::new(0, 20),
8360                    Point::new(1, 20)..Point::new(1, 20),
8361                    Point::new(2, 20)..Point::new(2, 20)
8362                ]
8363            );
8364
8365            // As soon as the last tab stop is reached, snippet state is gone
8366            editor.move_to_prev_snippet_tabstop(cx);
8367            assert_eq!(
8368                editor.selected_ranges::<Point>(cx),
8369                &[
8370                    Point::new(0, 20)..Point::new(0, 20),
8371                    Point::new(1, 20)..Point::new(1, 20),
8372                    Point::new(2, 20)..Point::new(2, 20)
8373                ]
8374            );
8375        });
8376    }
8377
8378    #[gpui::test]
8379    async fn test_completion(cx: &mut gpui::TestAppContext) {
8380        cx.update(populate_settings);
8381
8382        let (mut language_server_config, mut fake_servers) = LanguageServerConfig::fake();
8383        language_server_config.set_fake_capabilities(lsp::ServerCapabilities {
8384            completion_provider: Some(lsp::CompletionOptions {
8385                trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
8386                ..Default::default()
8387            }),
8388            ..Default::default()
8389        });
8390        let language = Arc::new(Language::new(
8391            LanguageConfig {
8392                name: "Rust".into(),
8393                path_suffixes: vec!["rs".to_string()],
8394                language_server: Some(language_server_config),
8395                ..Default::default()
8396            },
8397            Some(tree_sitter_rust::language()),
8398        ));
8399
8400        let text = "
8401            one
8402            two
8403            three
8404        "
8405        .unindent();
8406
8407        let fs = FakeFs::new(cx.background().clone());
8408        fs.insert_file("/file.rs", text).await;
8409
8410        let project = Project::test(fs, cx);
8411        project.update(cx, |project, _| project.languages().add(language));
8412
8413        let worktree_id = project
8414            .update(cx, |project, cx| {
8415                project.find_or_create_local_worktree("/file.rs", true, cx)
8416            })
8417            .await
8418            .unwrap()
8419            .0
8420            .read_with(cx, |tree, _| tree.id());
8421        let buffer = project
8422            .update(cx, |project, cx| project.open_buffer((worktree_id, ""), cx))
8423            .await
8424            .unwrap();
8425        let mut fake_server = fake_servers.next().await.unwrap();
8426
8427        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8428        let (_, editor) = cx.add_window(|cx| build_editor(buffer, cx));
8429
8430        editor.update(cx, |editor, cx| {
8431            editor.project = Some(project);
8432            editor.select_ranges([Point::new(0, 3)..Point::new(0, 3)], None, cx);
8433            editor.handle_input(&Input(".".to_string()), cx);
8434        });
8435
8436        handle_completion_request(
8437            &mut fake_server,
8438            "/file.rs",
8439            Point::new(0, 4),
8440            vec![
8441                (Point::new(0, 4)..Point::new(0, 4), "first_completion"),
8442                (Point::new(0, 4)..Point::new(0, 4), "second_completion"),
8443            ],
8444        )
8445        .await;
8446        editor
8447            .condition(&cx, |editor, _| editor.context_menu_visible())
8448            .await;
8449
8450        let apply_additional_edits = editor.update(cx, |editor, cx| {
8451            editor.move_down(&MoveDown, cx);
8452            let apply_additional_edits = editor
8453                .confirm_completion(&ConfirmCompletion(None), cx)
8454                .unwrap();
8455            assert_eq!(
8456                editor.text(cx),
8457                "
8458                    one.second_completion
8459                    two
8460                    three
8461                "
8462                .unindent()
8463            );
8464            apply_additional_edits
8465        });
8466
8467        handle_resolve_completion_request(
8468            &mut fake_server,
8469            Some((Point::new(2, 5)..Point::new(2, 5), "\nadditional edit")),
8470        )
8471        .await;
8472        apply_additional_edits.await.unwrap();
8473        assert_eq!(
8474            editor.read_with(cx, |editor, cx| editor.text(cx)),
8475            "
8476                one.second_completion
8477                two
8478                three
8479                additional edit
8480            "
8481            .unindent()
8482        );
8483
8484        editor.update(cx, |editor, cx| {
8485            editor.select_ranges(
8486                [
8487                    Point::new(1, 3)..Point::new(1, 3),
8488                    Point::new(2, 5)..Point::new(2, 5),
8489                ],
8490                None,
8491                cx,
8492            );
8493
8494            editor.handle_input(&Input(" ".to_string()), cx);
8495            assert!(editor.context_menu.is_none());
8496            editor.handle_input(&Input("s".to_string()), cx);
8497            assert!(editor.context_menu.is_none());
8498        });
8499
8500        handle_completion_request(
8501            &mut fake_server,
8502            "/file.rs",
8503            Point::new(2, 7),
8504            vec![
8505                (Point::new(2, 6)..Point::new(2, 7), "fourth_completion"),
8506                (Point::new(2, 6)..Point::new(2, 7), "fifth_completion"),
8507                (Point::new(2, 6)..Point::new(2, 7), "sixth_completion"),
8508            ],
8509        )
8510        .await;
8511        editor
8512            .condition(&cx, |editor, _| editor.context_menu_visible())
8513            .await;
8514
8515        editor.update(cx, |editor, cx| {
8516            editor.handle_input(&Input("i".to_string()), cx);
8517        });
8518
8519        handle_completion_request(
8520            &mut fake_server,
8521            "/file.rs",
8522            Point::new(2, 8),
8523            vec![
8524                (Point::new(2, 6)..Point::new(2, 8), "fourth_completion"),
8525                (Point::new(2, 6)..Point::new(2, 8), "fifth_completion"),
8526                (Point::new(2, 6)..Point::new(2, 8), "sixth_completion"),
8527            ],
8528        )
8529        .await;
8530        editor
8531            .condition(&cx, |editor, _| editor.context_menu_visible())
8532            .await;
8533
8534        let apply_additional_edits = editor.update(cx, |editor, cx| {
8535            let apply_additional_edits = editor
8536                .confirm_completion(&ConfirmCompletion(None), cx)
8537                .unwrap();
8538            assert_eq!(
8539                editor.text(cx),
8540                "
8541                    one.second_completion
8542                    two sixth_completion
8543                    three sixth_completion
8544                    additional edit
8545                "
8546                .unindent()
8547            );
8548            apply_additional_edits
8549        });
8550        handle_resolve_completion_request(&mut fake_server, None).await;
8551        apply_additional_edits.await.unwrap();
8552
8553        async fn handle_completion_request(
8554            fake: &mut FakeLanguageServer,
8555            path: &'static str,
8556            position: Point,
8557            completions: Vec<(Range<Point>, &'static str)>,
8558        ) {
8559            fake.handle_request::<lsp::request::Completion, _>(move |params, _| {
8560                assert_eq!(
8561                    params.text_document_position.text_document.uri,
8562                    lsp::Url::from_file_path(path).unwrap()
8563                );
8564                assert_eq!(
8565                    params.text_document_position.position,
8566                    lsp::Position::new(position.row, position.column)
8567                );
8568                Some(lsp::CompletionResponse::Array(
8569                    completions
8570                        .iter()
8571                        .map(|(range, new_text)| lsp::CompletionItem {
8572                            label: new_text.to_string(),
8573                            text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
8574                                range: lsp::Range::new(
8575                                    lsp::Position::new(range.start.row, range.start.column),
8576                                    lsp::Position::new(range.start.row, range.start.column),
8577                                ),
8578                                new_text: new_text.to_string(),
8579                            })),
8580                            ..Default::default()
8581                        })
8582                        .collect(),
8583                ))
8584            })
8585            .next()
8586            .await;
8587        }
8588
8589        async fn handle_resolve_completion_request(
8590            fake: &mut FakeLanguageServer,
8591            edit: Option<(Range<Point>, &'static str)>,
8592        ) {
8593            fake.handle_request::<lsp::request::ResolveCompletionItem, _>(move |_, _| {
8594                lsp::CompletionItem {
8595                    additional_text_edits: edit.clone().map(|(range, new_text)| {
8596                        vec![lsp::TextEdit::new(
8597                            lsp::Range::new(
8598                                lsp::Position::new(range.start.row, range.start.column),
8599                                lsp::Position::new(range.end.row, range.end.column),
8600                            ),
8601                            new_text.to_string(),
8602                        )]
8603                    }),
8604                    ..Default::default()
8605                }
8606            })
8607            .next()
8608            .await;
8609        }
8610    }
8611
8612    #[gpui::test]
8613    async fn test_toggle_comment(cx: &mut gpui::TestAppContext) {
8614        cx.update(populate_settings);
8615        let language = Arc::new(Language::new(
8616            LanguageConfig {
8617                line_comment: Some("// ".to_string()),
8618                ..Default::default()
8619            },
8620            Some(tree_sitter_rust::language()),
8621        ));
8622
8623        let text = "
8624            fn a() {
8625                //b();
8626                // c();
8627                //  d();
8628            }
8629        "
8630        .unindent();
8631
8632        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8633        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8634        let (_, view) = cx.add_window(|cx| build_editor(buffer, cx));
8635
8636        view.update(cx, |editor, cx| {
8637            // If multiple selections intersect a line, the line is only
8638            // toggled once.
8639            editor.select_display_ranges(
8640                &[
8641                    DisplayPoint::new(1, 3)..DisplayPoint::new(2, 3),
8642                    DisplayPoint::new(3, 5)..DisplayPoint::new(3, 6),
8643                ],
8644                cx,
8645            );
8646            editor.toggle_comments(&ToggleComments, cx);
8647            assert_eq!(
8648                editor.text(cx),
8649                "
8650                    fn a() {
8651                        b();
8652                        c();
8653                         d();
8654                    }
8655                "
8656                .unindent()
8657            );
8658
8659            // The comment prefix is inserted at the same column for every line
8660            // in a selection.
8661            editor.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(3, 6)], cx);
8662            editor.toggle_comments(&ToggleComments, cx);
8663            assert_eq!(
8664                editor.text(cx),
8665                "
8666                    fn a() {
8667                        // b();
8668                        // c();
8669                        //  d();
8670                    }
8671                "
8672                .unindent()
8673            );
8674
8675            // If a selection ends at the beginning of a line, that line is not toggled.
8676            editor.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(3, 0)], cx);
8677            editor.toggle_comments(&ToggleComments, cx);
8678            assert_eq!(
8679                editor.text(cx),
8680                "
8681                        fn a() {
8682                            // b();
8683                            c();
8684                            //  d();
8685                        }
8686                    "
8687                .unindent()
8688            );
8689        });
8690    }
8691
8692    #[gpui::test]
8693    fn test_editing_disjoint_excerpts(cx: &mut gpui::MutableAppContext) {
8694        populate_settings(cx);
8695        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
8696        let multibuffer = cx.add_model(|cx| {
8697            let mut multibuffer = MultiBuffer::new(0);
8698            multibuffer.push_excerpts(
8699                buffer.clone(),
8700                [
8701                    Point::new(0, 0)..Point::new(0, 4),
8702                    Point::new(1, 0)..Point::new(1, 4),
8703                ],
8704                cx,
8705            );
8706            multibuffer
8707        });
8708
8709        assert_eq!(multibuffer.read(cx).read(cx).text(), "aaaa\nbbbb");
8710
8711        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(multibuffer, cx));
8712        view.update(cx, |view, cx| {
8713            assert_eq!(view.text(cx), "aaaa\nbbbb");
8714            view.select_ranges(
8715                [
8716                    Point::new(0, 0)..Point::new(0, 0),
8717                    Point::new(1, 0)..Point::new(1, 0),
8718                ],
8719                None,
8720                cx,
8721            );
8722
8723            view.handle_input(&Input("X".to_string()), cx);
8724            assert_eq!(view.text(cx), "Xaaaa\nXbbbb");
8725            assert_eq!(
8726                view.selected_ranges(cx),
8727                [
8728                    Point::new(0, 1)..Point::new(0, 1),
8729                    Point::new(1, 1)..Point::new(1, 1),
8730                ]
8731            )
8732        });
8733    }
8734
8735    #[gpui::test]
8736    fn test_editing_overlapping_excerpts(cx: &mut gpui::MutableAppContext) {
8737        populate_settings(cx);
8738        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
8739        let multibuffer = cx.add_model(|cx| {
8740            let mut multibuffer = MultiBuffer::new(0);
8741            multibuffer.push_excerpts(
8742                buffer,
8743                [
8744                    Point::new(0, 0)..Point::new(1, 4),
8745                    Point::new(1, 0)..Point::new(2, 4),
8746                ],
8747                cx,
8748            );
8749            multibuffer
8750        });
8751
8752        assert_eq!(
8753            multibuffer.read(cx).read(cx).text(),
8754            "aaaa\nbbbb\nbbbb\ncccc"
8755        );
8756
8757        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(multibuffer, cx));
8758        view.update(cx, |view, cx| {
8759            view.select_ranges(
8760                [
8761                    Point::new(1, 1)..Point::new(1, 1),
8762                    Point::new(2, 3)..Point::new(2, 3),
8763                ],
8764                None,
8765                cx,
8766            );
8767
8768            view.handle_input(&Input("X".to_string()), cx);
8769            assert_eq!(view.text(cx), "aaaa\nbXbbXb\nbXbbXb\ncccc");
8770            assert_eq!(
8771                view.selected_ranges(cx),
8772                [
8773                    Point::new(1, 2)..Point::new(1, 2),
8774                    Point::new(2, 5)..Point::new(2, 5),
8775                ]
8776            );
8777
8778            view.newline(&Newline, cx);
8779            assert_eq!(view.text(cx), "aaaa\nbX\nbbX\nb\nbX\nbbX\nb\ncccc");
8780            assert_eq!(
8781                view.selected_ranges(cx),
8782                [
8783                    Point::new(2, 0)..Point::new(2, 0),
8784                    Point::new(6, 0)..Point::new(6, 0),
8785                ]
8786            );
8787        });
8788    }
8789
8790    #[gpui::test]
8791    fn test_refresh_selections(cx: &mut gpui::MutableAppContext) {
8792        populate_settings(cx);
8793        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
8794        let mut excerpt1_id = None;
8795        let multibuffer = cx.add_model(|cx| {
8796            let mut multibuffer = MultiBuffer::new(0);
8797            excerpt1_id = multibuffer
8798                .push_excerpts(
8799                    buffer.clone(),
8800                    [
8801                        Point::new(0, 0)..Point::new(1, 4),
8802                        Point::new(1, 0)..Point::new(2, 4),
8803                    ],
8804                    cx,
8805                )
8806                .into_iter()
8807                .next();
8808            multibuffer
8809        });
8810        assert_eq!(
8811            multibuffer.read(cx).read(cx).text(),
8812            "aaaa\nbbbb\nbbbb\ncccc"
8813        );
8814        let (_, editor) = cx.add_window(Default::default(), |cx| {
8815            let mut editor = build_editor(multibuffer.clone(), cx);
8816            editor.select_ranges(
8817                [
8818                    Point::new(1, 3)..Point::new(1, 3),
8819                    Point::new(2, 1)..Point::new(2, 1),
8820                ],
8821                None,
8822                cx,
8823            );
8824            editor
8825        });
8826
8827        // Refreshing selections is a no-op when excerpts haven't changed.
8828        editor.update(cx, |editor, cx| {
8829            editor.refresh_selections(cx);
8830            assert_eq!(
8831                editor.selected_ranges(cx),
8832                [
8833                    Point::new(1, 3)..Point::new(1, 3),
8834                    Point::new(2, 1)..Point::new(2, 1),
8835                ]
8836            );
8837        });
8838
8839        multibuffer.update(cx, |multibuffer, cx| {
8840            multibuffer.remove_excerpts([&excerpt1_id.unwrap()], cx);
8841        });
8842        editor.update(cx, |editor, cx| {
8843            // Removing an excerpt causes the first selection to become degenerate.
8844            assert_eq!(
8845                editor.selected_ranges(cx),
8846                [
8847                    Point::new(0, 0)..Point::new(0, 0),
8848                    Point::new(0, 1)..Point::new(0, 1)
8849                ]
8850            );
8851
8852            // Refreshing selections will relocate the first selection to the original buffer
8853            // location.
8854            editor.refresh_selections(cx);
8855            assert_eq!(
8856                editor.selected_ranges(cx),
8857                [
8858                    Point::new(0, 1)..Point::new(0, 1),
8859                    Point::new(0, 3)..Point::new(0, 3)
8860                ]
8861            );
8862        });
8863    }
8864
8865    #[gpui::test]
8866    async fn test_extra_newline_insertion(cx: &mut gpui::TestAppContext) {
8867        cx.update(populate_settings);
8868        let language = Arc::new(Language::new(
8869            LanguageConfig {
8870                brackets: vec![
8871                    BracketPair {
8872                        start: "{".to_string(),
8873                        end: "}".to_string(),
8874                        close: true,
8875                        newline: true,
8876                    },
8877                    BracketPair {
8878                        start: "/* ".to_string(),
8879                        end: " */".to_string(),
8880                        close: true,
8881                        newline: true,
8882                    },
8883                ],
8884                ..Default::default()
8885            },
8886            Some(tree_sitter_rust::language()),
8887        ));
8888
8889        let text = concat!(
8890            "{   }\n",     // Suppress rustfmt
8891            "  x\n",       //
8892            "  /*   */\n", //
8893            "x\n",         //
8894            "{{} }\n",     //
8895        );
8896
8897        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8898        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8899        let (_, view) = cx.add_window(|cx| build_editor(buffer, cx));
8900        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
8901            .await;
8902
8903        view.update(cx, |view, cx| {
8904            view.select_display_ranges(
8905                &[
8906                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
8907                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
8908                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
8909                ],
8910                cx,
8911            );
8912            view.newline(&Newline, cx);
8913
8914            assert_eq!(
8915                view.buffer().read(cx).read(cx).text(),
8916                concat!(
8917                    "{ \n",    // Suppress rustfmt
8918                    "\n",      //
8919                    "}\n",     //
8920                    "  x\n",   //
8921                    "  /* \n", //
8922                    "  \n",    //
8923                    "  */\n",  //
8924                    "x\n",     //
8925                    "{{} \n",  //
8926                    "}\n",     //
8927                )
8928            );
8929        });
8930    }
8931
8932    #[gpui::test]
8933    fn test_highlighted_ranges(cx: &mut gpui::MutableAppContext) {
8934        let buffer = MultiBuffer::build_simple(&sample_text(16, 8, 'a'), cx);
8935        populate_settings(cx);
8936        let (_, editor) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
8937
8938        editor.update(cx, |editor, cx| {
8939            struct Type1;
8940            struct Type2;
8941
8942            let buffer = buffer.read(cx).snapshot(cx);
8943
8944            let anchor_range = |range: Range<Point>| {
8945                buffer.anchor_after(range.start)..buffer.anchor_after(range.end)
8946            };
8947
8948            editor.highlight_background::<Type1>(
8949                vec![
8950                    anchor_range(Point::new(2, 1)..Point::new(2, 3)),
8951                    anchor_range(Point::new(4, 2)..Point::new(4, 4)),
8952                    anchor_range(Point::new(6, 3)..Point::new(6, 5)),
8953                    anchor_range(Point::new(8, 4)..Point::new(8, 6)),
8954                ],
8955                Color::red(),
8956                cx,
8957            );
8958            editor.highlight_background::<Type2>(
8959                vec![
8960                    anchor_range(Point::new(3, 2)..Point::new(3, 5)),
8961                    anchor_range(Point::new(5, 3)..Point::new(5, 6)),
8962                    anchor_range(Point::new(7, 4)..Point::new(7, 7)),
8963                    anchor_range(Point::new(9, 5)..Point::new(9, 8)),
8964                ],
8965                Color::green(),
8966                cx,
8967            );
8968
8969            let snapshot = editor.snapshot(cx);
8970            let mut highlighted_ranges = editor.background_highlights_in_range(
8971                anchor_range(Point::new(3, 4)..Point::new(7, 4)),
8972                &snapshot,
8973            );
8974            // Enforce a consistent ordering based on color without relying on the ordering of the
8975            // highlight's `TypeId` which is non-deterministic.
8976            highlighted_ranges.sort_unstable_by_key(|(_, color)| *color);
8977            assert_eq!(
8978                highlighted_ranges,
8979                &[
8980                    (
8981                        DisplayPoint::new(3, 2)..DisplayPoint::new(3, 5),
8982                        Color::green(),
8983                    ),
8984                    (
8985                        DisplayPoint::new(5, 3)..DisplayPoint::new(5, 6),
8986                        Color::green(),
8987                    ),
8988                    (
8989                        DisplayPoint::new(4, 2)..DisplayPoint::new(4, 4),
8990                        Color::red(),
8991                    ),
8992                    (
8993                        DisplayPoint::new(6, 3)..DisplayPoint::new(6, 5),
8994                        Color::red(),
8995                    ),
8996                ]
8997            );
8998            assert_eq!(
8999                editor.background_highlights_in_range(
9000                    anchor_range(Point::new(5, 6)..Point::new(6, 4)),
9001                    &snapshot,
9002                ),
9003                &[(
9004                    DisplayPoint::new(6, 3)..DisplayPoint::new(6, 5),
9005                    Color::red(),
9006                )]
9007            );
9008        });
9009    }
9010
9011    #[test]
9012    fn test_combine_syntax_and_fuzzy_match_highlights() {
9013        let string = "abcdefghijklmnop";
9014        let syntax_ranges = [
9015            (
9016                0..3,
9017                HighlightStyle {
9018                    color: Some(Color::red()),
9019                    ..Default::default()
9020                },
9021            ),
9022            (
9023                4..8,
9024                HighlightStyle {
9025                    color: Some(Color::green()),
9026                    ..Default::default()
9027                },
9028            ),
9029        ];
9030        let match_indices = [4, 6, 7, 8];
9031        assert_eq!(
9032            combine_syntax_and_fuzzy_match_highlights(
9033                &string,
9034                Default::default(),
9035                syntax_ranges.into_iter(),
9036                &match_indices,
9037            ),
9038            &[
9039                (
9040                    0..3,
9041                    HighlightStyle {
9042                        color: Some(Color::red()),
9043                        ..Default::default()
9044                    },
9045                ),
9046                (
9047                    4..5,
9048                    HighlightStyle {
9049                        color: Some(Color::green()),
9050                        weight: Some(fonts::Weight::BOLD),
9051                        ..Default::default()
9052                    },
9053                ),
9054                (
9055                    5..6,
9056                    HighlightStyle {
9057                        color: Some(Color::green()),
9058                        ..Default::default()
9059                    },
9060                ),
9061                (
9062                    6..8,
9063                    HighlightStyle {
9064                        color: Some(Color::green()),
9065                        weight: Some(fonts::Weight::BOLD),
9066                        ..Default::default()
9067                    },
9068                ),
9069                (
9070                    8..9,
9071                    HighlightStyle {
9072                        weight: Some(fonts::Weight::BOLD),
9073                        ..Default::default()
9074                    },
9075                ),
9076            ]
9077        );
9078    }
9079
9080    fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
9081        let point = DisplayPoint::new(row as u32, column as u32);
9082        point..point
9083    }
9084
9085    fn build_editor(buffer: ModelHandle<MultiBuffer>, cx: &mut ViewContext<Editor>) -> Editor {
9086        Editor::new(EditorMode::Full, buffer, None, None, cx)
9087    }
9088
9089    fn populate_settings(cx: &mut gpui::MutableAppContext) {
9090        let settings = Settings::test(cx);
9091        cx.add_app_state(settings);
9092    }
9093}
9094
9095trait RangeExt<T> {
9096    fn sorted(&self) -> Range<T>;
9097    fn to_inclusive(&self) -> RangeInclusive<T>;
9098}
9099
9100impl<T: Ord + Clone> RangeExt<T> for Range<T> {
9101    fn sorted(&self) -> Self {
9102        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
9103    }
9104
9105    fn to_inclusive(&self) -> RangeInclusive<T> {
9106        self.start.clone()..=self.end.clone()
9107    }
9108}