editor.rs

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