editor.rs

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