editor.rs

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