editor_tests.rs

    1use super::*;
    2use crate::{
    3    JoinLines,
    4    scroll::scroll_amount::ScrollAmount,
    5    test::{
    6        assert_text_with_selections, build_editor,
    7        editor_lsp_test_context::{EditorLspTestContext, git_commit_lang},
    8        editor_test_context::EditorTestContext,
    9        select_ranges,
   10    },
   11};
   12use buffer_diff::{BufferDiff, DiffHunkSecondaryStatus, DiffHunkStatus, DiffHunkStatusKind};
   13use futures::StreamExt;
   14use gpui::{
   15    BackgroundExecutor, DismissEvent, SemanticVersion, TestAppContext, UpdateGlobal,
   16    VisualTestContext, WindowBounds, WindowOptions, div,
   17};
   18use indoc::indoc;
   19use language::{
   20    BracketPairConfig,
   21    Capability::ReadWrite,
   22    FakeLspAdapter, LanguageConfig, LanguageConfigOverride, LanguageMatcher, LanguageName,
   23    Override, Point,
   24    language_settings::{
   25        AllLanguageSettings, AllLanguageSettingsContent, CompletionSettings,
   26        LanguageSettingsContent, LspInsertMode, PrettierSettings,
   27    },
   28};
   29use language_settings::{Formatter, FormatterList, IndentGuideSettings};
   30use lsp::CompletionParams;
   31use multi_buffer::{IndentGuide, PathKey};
   32use parking_lot::Mutex;
   33use pretty_assertions::{assert_eq, assert_ne};
   34use project::{
   35    FakeFs,
   36    debugger::breakpoint_store::{BreakpointState, SourceBreakpoint},
   37    project_settings::{LspSettings, ProjectSettings},
   38};
   39use serde_json::{self, json};
   40use std::{cell::RefCell, future::Future, rc::Rc, sync::atomic::AtomicBool, time::Instant};
   41use std::{
   42    iter,
   43    sync::atomic::{self, AtomicUsize},
   44};
   45use test::{build_editor_with_project, editor_lsp_test_context::rust_lang};
   46use text::ToPoint as _;
   47use unindent::Unindent;
   48use util::{
   49    assert_set_eq, path,
   50    test::{TextRangeMarker, marked_text_ranges, marked_text_ranges_by, sample_text},
   51    uri,
   52};
   53use workspace::{
   54    CloseAllItems, CloseInactiveItems, NavigationEntry, ViewId,
   55    item::{FollowEvent, FollowableItem, Item, ItemHandle},
   56};
   57
   58#[gpui::test]
   59fn test_edit_events(cx: &mut TestAppContext) {
   60    init_test(cx, |_| {});
   61
   62    let buffer = cx.new(|cx| {
   63        let mut buffer = language::Buffer::local("123456", cx);
   64        buffer.set_group_interval(Duration::from_secs(1));
   65        buffer
   66    });
   67
   68    let events = Rc::new(RefCell::new(Vec::new()));
   69    let editor1 = cx.add_window({
   70        let events = events.clone();
   71        |window, cx| {
   72            let entity = cx.entity().clone();
   73            cx.subscribe_in(
   74                &entity,
   75                window,
   76                move |_, _, event: &EditorEvent, _, _| match event {
   77                    EditorEvent::Edited { .. } => events.borrow_mut().push(("editor1", "edited")),
   78                    EditorEvent::BufferEdited => {
   79                        events.borrow_mut().push(("editor1", "buffer edited"))
   80                    }
   81                    _ => {}
   82                },
   83            )
   84            .detach();
   85            Editor::for_buffer(buffer.clone(), None, window, cx)
   86        }
   87    });
   88
   89    let editor2 = cx.add_window({
   90        let events = events.clone();
   91        |window, cx| {
   92            cx.subscribe_in(
   93                &cx.entity().clone(),
   94                window,
   95                move |_, _, event: &EditorEvent, _, _| match event {
   96                    EditorEvent::Edited { .. } => events.borrow_mut().push(("editor2", "edited")),
   97                    EditorEvent::BufferEdited => {
   98                        events.borrow_mut().push(("editor2", "buffer edited"))
   99                    }
  100                    _ => {}
  101                },
  102            )
  103            .detach();
  104            Editor::for_buffer(buffer.clone(), None, window, cx)
  105        }
  106    });
  107
  108    assert_eq!(mem::take(&mut *events.borrow_mut()), []);
  109
  110    // Mutating editor 1 will emit an `Edited` event only for that editor.
  111    _ = editor1.update(cx, |editor, window, cx| editor.insert("X", window, cx));
  112    assert_eq!(
  113        mem::take(&mut *events.borrow_mut()),
  114        [
  115            ("editor1", "edited"),
  116            ("editor1", "buffer edited"),
  117            ("editor2", "buffer edited"),
  118        ]
  119    );
  120
  121    // Mutating editor 2 will emit an `Edited` event only for that editor.
  122    _ = editor2.update(cx, |editor, window, cx| editor.delete(&Delete, window, cx));
  123    assert_eq!(
  124        mem::take(&mut *events.borrow_mut()),
  125        [
  126            ("editor2", "edited"),
  127            ("editor1", "buffer edited"),
  128            ("editor2", "buffer edited"),
  129        ]
  130    );
  131
  132    // Undoing on editor 1 will emit an `Edited` event only for that editor.
  133    _ = editor1.update(cx, |editor, window, cx| editor.undo(&Undo, window, cx));
  134    assert_eq!(
  135        mem::take(&mut *events.borrow_mut()),
  136        [
  137            ("editor1", "edited"),
  138            ("editor1", "buffer edited"),
  139            ("editor2", "buffer edited"),
  140        ]
  141    );
  142
  143    // Redoing on editor 1 will emit an `Edited` event only for that editor.
  144    _ = editor1.update(cx, |editor, window, cx| editor.redo(&Redo, window, cx));
  145    assert_eq!(
  146        mem::take(&mut *events.borrow_mut()),
  147        [
  148            ("editor1", "edited"),
  149            ("editor1", "buffer edited"),
  150            ("editor2", "buffer edited"),
  151        ]
  152    );
  153
  154    // Undoing on editor 2 will emit an `Edited` event only for that editor.
  155    _ = editor2.update(cx, |editor, window, cx| editor.undo(&Undo, window, cx));
  156    assert_eq!(
  157        mem::take(&mut *events.borrow_mut()),
  158        [
  159            ("editor2", "edited"),
  160            ("editor1", "buffer edited"),
  161            ("editor2", "buffer edited"),
  162        ]
  163    );
  164
  165    // Redoing on editor 2 will emit an `Edited` event only for that editor.
  166    _ = editor2.update(cx, |editor, window, cx| editor.redo(&Redo, window, cx));
  167    assert_eq!(
  168        mem::take(&mut *events.borrow_mut()),
  169        [
  170            ("editor2", "edited"),
  171            ("editor1", "buffer edited"),
  172            ("editor2", "buffer edited"),
  173        ]
  174    );
  175
  176    // No event is emitted when the mutation is a no-op.
  177    _ = editor2.update(cx, |editor, window, cx| {
  178        editor.change_selections(None, window, cx, |s| s.select_ranges([0..0]));
  179
  180        editor.backspace(&Backspace, window, cx);
  181    });
  182    assert_eq!(mem::take(&mut *events.borrow_mut()), []);
  183}
  184
  185#[gpui::test]
  186fn test_undo_redo_with_selection_restoration(cx: &mut TestAppContext) {
  187    init_test(cx, |_| {});
  188
  189    let mut now = Instant::now();
  190    let group_interval = Duration::from_millis(1);
  191    let buffer = cx.new(|cx| {
  192        let mut buf = language::Buffer::local("123456", cx);
  193        buf.set_group_interval(group_interval);
  194        buf
  195    });
  196    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
  197    let editor = cx.add_window(|window, cx| build_editor(buffer.clone(), window, cx));
  198
  199    _ = editor.update(cx, |editor, window, cx| {
  200        editor.start_transaction_at(now, window, cx);
  201        editor.change_selections(None, window, cx, |s| s.select_ranges([2..4]));
  202
  203        editor.insert("cd", window, cx);
  204        editor.end_transaction_at(now, cx);
  205        assert_eq!(editor.text(cx), "12cd56");
  206        assert_eq!(editor.selections.ranges(cx), vec![4..4]);
  207
  208        editor.start_transaction_at(now, window, cx);
  209        editor.change_selections(None, window, cx, |s| s.select_ranges([4..5]));
  210        editor.insert("e", window, cx);
  211        editor.end_transaction_at(now, cx);
  212        assert_eq!(editor.text(cx), "12cde6");
  213        assert_eq!(editor.selections.ranges(cx), vec![5..5]);
  214
  215        now += group_interval + Duration::from_millis(1);
  216        editor.change_selections(None, window, cx, |s| s.select_ranges([2..2]));
  217
  218        // Simulate an edit in another editor
  219        buffer.update(cx, |buffer, cx| {
  220            buffer.start_transaction_at(now, cx);
  221            buffer.edit([(0..1, "a")], None, cx);
  222            buffer.edit([(1..1, "b")], None, cx);
  223            buffer.end_transaction_at(now, cx);
  224        });
  225
  226        assert_eq!(editor.text(cx), "ab2cde6");
  227        assert_eq!(editor.selections.ranges(cx), vec![3..3]);
  228
  229        // Last transaction happened past the group interval in a different editor.
  230        // Undo it individually and don't restore selections.
  231        editor.undo(&Undo, window, cx);
  232        assert_eq!(editor.text(cx), "12cde6");
  233        assert_eq!(editor.selections.ranges(cx), vec![2..2]);
  234
  235        // First two transactions happened within the group interval in this editor.
  236        // Undo them together and restore selections.
  237        editor.undo(&Undo, window, cx);
  238        editor.undo(&Undo, window, cx); // Undo stack is empty here, so this is a no-op.
  239        assert_eq!(editor.text(cx), "123456");
  240        assert_eq!(editor.selections.ranges(cx), vec![0..0]);
  241
  242        // Redo the first two transactions together.
  243        editor.redo(&Redo, window, cx);
  244        assert_eq!(editor.text(cx), "12cde6");
  245        assert_eq!(editor.selections.ranges(cx), vec![5..5]);
  246
  247        // Redo the last transaction on its own.
  248        editor.redo(&Redo, window, cx);
  249        assert_eq!(editor.text(cx), "ab2cde6");
  250        assert_eq!(editor.selections.ranges(cx), vec![6..6]);
  251
  252        // Test empty transactions.
  253        editor.start_transaction_at(now, window, cx);
  254        editor.end_transaction_at(now, cx);
  255        editor.undo(&Undo, window, cx);
  256        assert_eq!(editor.text(cx), "12cde6");
  257    });
  258}
  259
  260#[gpui::test]
  261fn test_ime_composition(cx: &mut TestAppContext) {
  262    init_test(cx, |_| {});
  263
  264    let buffer = cx.new(|cx| {
  265        let mut buffer = language::Buffer::local("abcde", cx);
  266        // Ensure automatic grouping doesn't occur.
  267        buffer.set_group_interval(Duration::ZERO);
  268        buffer
  269    });
  270
  271    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
  272    cx.add_window(|window, cx| {
  273        let mut editor = build_editor(buffer.clone(), window, cx);
  274
  275        // Start a new IME composition.
  276        editor.replace_and_mark_text_in_range(Some(0..1), "à", None, window, cx);
  277        editor.replace_and_mark_text_in_range(Some(0..1), "á", None, window, cx);
  278        editor.replace_and_mark_text_in_range(Some(0..1), "ä", None, window, cx);
  279        assert_eq!(editor.text(cx), "äbcde");
  280        assert_eq!(
  281            editor.marked_text_ranges(cx),
  282            Some(vec![OffsetUtf16(0)..OffsetUtf16(1)])
  283        );
  284
  285        // Finalize IME composition.
  286        editor.replace_text_in_range(None, "ā", window, cx);
  287        assert_eq!(editor.text(cx), "ābcde");
  288        assert_eq!(editor.marked_text_ranges(cx), None);
  289
  290        // IME composition edits are grouped and are undone/redone at once.
  291        editor.undo(&Default::default(), window, cx);
  292        assert_eq!(editor.text(cx), "abcde");
  293        assert_eq!(editor.marked_text_ranges(cx), None);
  294        editor.redo(&Default::default(), window, cx);
  295        assert_eq!(editor.text(cx), "ābcde");
  296        assert_eq!(editor.marked_text_ranges(cx), None);
  297
  298        // Start a new IME composition.
  299        editor.replace_and_mark_text_in_range(Some(0..1), "à", None, window, cx);
  300        assert_eq!(
  301            editor.marked_text_ranges(cx),
  302            Some(vec![OffsetUtf16(0)..OffsetUtf16(1)])
  303        );
  304
  305        // Undoing during an IME composition cancels it.
  306        editor.undo(&Default::default(), window, cx);
  307        assert_eq!(editor.text(cx), "ābcde");
  308        assert_eq!(editor.marked_text_ranges(cx), None);
  309
  310        // Start a new IME composition with an invalid marked range, ensuring it gets clipped.
  311        editor.replace_and_mark_text_in_range(Some(4..999), "è", None, window, cx);
  312        assert_eq!(editor.text(cx), "ābcdè");
  313        assert_eq!(
  314            editor.marked_text_ranges(cx),
  315            Some(vec![OffsetUtf16(4)..OffsetUtf16(5)])
  316        );
  317
  318        // Finalize IME composition with an invalid replacement range, ensuring it gets clipped.
  319        editor.replace_text_in_range(Some(4..999), "ę", window, cx);
  320        assert_eq!(editor.text(cx), "ābcdę");
  321        assert_eq!(editor.marked_text_ranges(cx), None);
  322
  323        // Start a new IME composition with multiple cursors.
  324        editor.change_selections(None, window, cx, |s| {
  325            s.select_ranges([
  326                OffsetUtf16(1)..OffsetUtf16(1),
  327                OffsetUtf16(3)..OffsetUtf16(3),
  328                OffsetUtf16(5)..OffsetUtf16(5),
  329            ])
  330        });
  331        editor.replace_and_mark_text_in_range(Some(4..5), "XYZ", None, window, cx);
  332        assert_eq!(editor.text(cx), "XYZbXYZdXYZ");
  333        assert_eq!(
  334            editor.marked_text_ranges(cx),
  335            Some(vec![
  336                OffsetUtf16(0)..OffsetUtf16(3),
  337                OffsetUtf16(4)..OffsetUtf16(7),
  338                OffsetUtf16(8)..OffsetUtf16(11)
  339            ])
  340        );
  341
  342        // Ensure the newly-marked range gets treated as relative to the previously-marked ranges.
  343        editor.replace_and_mark_text_in_range(Some(1..2), "1", None, window, cx);
  344        assert_eq!(editor.text(cx), "X1ZbX1ZdX1Z");
  345        assert_eq!(
  346            editor.marked_text_ranges(cx),
  347            Some(vec![
  348                OffsetUtf16(1)..OffsetUtf16(2),
  349                OffsetUtf16(5)..OffsetUtf16(6),
  350                OffsetUtf16(9)..OffsetUtf16(10)
  351            ])
  352        );
  353
  354        // Finalize IME composition with multiple cursors.
  355        editor.replace_text_in_range(Some(9..10), "2", window, cx);
  356        assert_eq!(editor.text(cx), "X2ZbX2ZdX2Z");
  357        assert_eq!(editor.marked_text_ranges(cx), None);
  358
  359        editor
  360    });
  361}
  362
  363#[gpui::test]
  364fn test_selection_with_mouse(cx: &mut TestAppContext) {
  365    init_test(cx, |_| {});
  366
  367    let editor = cx.add_window(|window, cx| {
  368        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\nddddddd\n", cx);
  369        build_editor(buffer, window, cx)
  370    });
  371
  372    _ = editor.update(cx, |editor, window, cx| {
  373        editor.begin_selection(DisplayPoint::new(DisplayRow(2), 2), false, 1, window, cx);
  374    });
  375    assert_eq!(
  376        editor
  377            .update(cx, |editor, _, cx| editor.selections.display_ranges(cx))
  378            .unwrap(),
  379        [DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(2), 2)]
  380    );
  381
  382    _ = editor.update(cx, |editor, window, cx| {
  383        editor.update_selection(
  384            DisplayPoint::new(DisplayRow(3), 3),
  385            0,
  386            gpui::Point::<f32>::default(),
  387            window,
  388            cx,
  389        );
  390    });
  391
  392    assert_eq!(
  393        editor
  394            .update(cx, |editor, _, cx| editor.selections.display_ranges(cx))
  395            .unwrap(),
  396        [DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(3), 3)]
  397    );
  398
  399    _ = editor.update(cx, |editor, window, cx| {
  400        editor.update_selection(
  401            DisplayPoint::new(DisplayRow(1), 1),
  402            0,
  403            gpui::Point::<f32>::default(),
  404            window,
  405            cx,
  406        );
  407    });
  408
  409    assert_eq!(
  410        editor
  411            .update(cx, |editor, _, cx| editor.selections.display_ranges(cx))
  412            .unwrap(),
  413        [DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(1), 1)]
  414    );
  415
  416    _ = editor.update(cx, |editor, window, cx| {
  417        editor.end_selection(window, cx);
  418        editor.update_selection(
  419            DisplayPoint::new(DisplayRow(3), 3),
  420            0,
  421            gpui::Point::<f32>::default(),
  422            window,
  423            cx,
  424        );
  425    });
  426
  427    assert_eq!(
  428        editor
  429            .update(cx, |editor, _, cx| editor.selections.display_ranges(cx))
  430            .unwrap(),
  431        [DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(1), 1)]
  432    );
  433
  434    _ = editor.update(cx, |editor, window, cx| {
  435        editor.begin_selection(DisplayPoint::new(DisplayRow(3), 3), true, 1, window, cx);
  436        editor.update_selection(
  437            DisplayPoint::new(DisplayRow(0), 0),
  438            0,
  439            gpui::Point::<f32>::default(),
  440            window,
  441            cx,
  442        );
  443    });
  444
  445    assert_eq!(
  446        editor
  447            .update(cx, |editor, _, cx| editor.selections.display_ranges(cx))
  448            .unwrap(),
  449        [
  450            DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(1), 1),
  451            DisplayPoint::new(DisplayRow(3), 3)..DisplayPoint::new(DisplayRow(0), 0)
  452        ]
  453    );
  454
  455    _ = editor.update(cx, |editor, window, cx| {
  456        editor.end_selection(window, cx);
  457    });
  458
  459    assert_eq!(
  460        editor
  461            .update(cx, |editor, _, cx| editor.selections.display_ranges(cx))
  462            .unwrap(),
  463        [DisplayPoint::new(DisplayRow(3), 3)..DisplayPoint::new(DisplayRow(0), 0)]
  464    );
  465}
  466
  467#[gpui::test]
  468fn test_multiple_cursor_removal(cx: &mut TestAppContext) {
  469    init_test(cx, |_| {});
  470
  471    let editor = cx.add_window(|window, cx| {
  472        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\nddddddd\n", cx);
  473        build_editor(buffer, window, cx)
  474    });
  475
  476    _ = editor.update(cx, |editor, window, cx| {
  477        editor.begin_selection(DisplayPoint::new(DisplayRow(2), 1), false, 1, window, cx);
  478    });
  479
  480    _ = editor.update(cx, |editor, window, cx| {
  481        editor.end_selection(window, cx);
  482    });
  483
  484    _ = editor.update(cx, |editor, window, cx| {
  485        editor.begin_selection(DisplayPoint::new(DisplayRow(3), 2), true, 1, window, cx);
  486    });
  487
  488    _ = editor.update(cx, |editor, window, cx| {
  489        editor.end_selection(window, cx);
  490    });
  491
  492    assert_eq!(
  493        editor
  494            .update(cx, |editor, _, cx| editor.selections.display_ranges(cx))
  495            .unwrap(),
  496        [
  497            DisplayPoint::new(DisplayRow(2), 1)..DisplayPoint::new(DisplayRow(2), 1),
  498            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 2)
  499        ]
  500    );
  501
  502    _ = editor.update(cx, |editor, window, cx| {
  503        editor.begin_selection(DisplayPoint::new(DisplayRow(2), 1), true, 1, window, cx);
  504    });
  505
  506    _ = editor.update(cx, |editor, window, cx| {
  507        editor.end_selection(window, cx);
  508    });
  509
  510    assert_eq!(
  511        editor
  512            .update(cx, |editor, _, cx| editor.selections.display_ranges(cx))
  513            .unwrap(),
  514        [DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 2)]
  515    );
  516}
  517
  518#[gpui::test]
  519fn test_canceling_pending_selection(cx: &mut TestAppContext) {
  520    init_test(cx, |_| {});
  521
  522    let editor = cx.add_window(|window, cx| {
  523        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
  524        build_editor(buffer, window, cx)
  525    });
  526
  527    _ = editor.update(cx, |editor, window, cx| {
  528        editor.begin_selection(DisplayPoint::new(DisplayRow(2), 2), false, 1, window, cx);
  529        assert_eq!(
  530            editor.selections.display_ranges(cx),
  531            [DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(2), 2)]
  532        );
  533    });
  534
  535    _ = editor.update(cx, |editor, window, cx| {
  536        editor.update_selection(
  537            DisplayPoint::new(DisplayRow(3), 3),
  538            0,
  539            gpui::Point::<f32>::default(),
  540            window,
  541            cx,
  542        );
  543        assert_eq!(
  544            editor.selections.display_ranges(cx),
  545            [DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(3), 3)]
  546        );
  547    });
  548
  549    _ = editor.update(cx, |editor, window, cx| {
  550        editor.cancel(&Cancel, window, cx);
  551        editor.update_selection(
  552            DisplayPoint::new(DisplayRow(1), 1),
  553            0,
  554            gpui::Point::<f32>::default(),
  555            window,
  556            cx,
  557        );
  558        assert_eq!(
  559            editor.selections.display_ranges(cx),
  560            [DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(3), 3)]
  561        );
  562    });
  563}
  564
  565#[gpui::test]
  566fn test_movement_actions_with_pending_selection(cx: &mut TestAppContext) {
  567    init_test(cx, |_| {});
  568
  569    let editor = cx.add_window(|window, cx| {
  570        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
  571        build_editor(buffer, window, cx)
  572    });
  573
  574    _ = editor.update(cx, |editor, window, cx| {
  575        editor.begin_selection(DisplayPoint::new(DisplayRow(2), 2), false, 1, window, cx);
  576        assert_eq!(
  577            editor.selections.display_ranges(cx),
  578            [DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(2), 2)]
  579        );
  580
  581        editor.move_down(&Default::default(), window, cx);
  582        assert_eq!(
  583            editor.selections.display_ranges(cx),
  584            [DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 2)]
  585        );
  586
  587        editor.begin_selection(DisplayPoint::new(DisplayRow(2), 2), false, 1, window, cx);
  588        assert_eq!(
  589            editor.selections.display_ranges(cx),
  590            [DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(2), 2)]
  591        );
  592
  593        editor.move_up(&Default::default(), window, cx);
  594        assert_eq!(
  595            editor.selections.display_ranges(cx),
  596            [DisplayPoint::new(DisplayRow(1), 2)..DisplayPoint::new(DisplayRow(1), 2)]
  597        );
  598    });
  599}
  600
  601#[gpui::test]
  602fn test_clone(cx: &mut TestAppContext) {
  603    init_test(cx, |_| {});
  604
  605    let (text, selection_ranges) = marked_text_ranges(
  606        indoc! {"
  607            one
  608            two
  609            threeˇ
  610            four
  611            fiveˇ
  612        "},
  613        true,
  614    );
  615
  616    let editor = cx.add_window(|window, cx| {
  617        let buffer = MultiBuffer::build_simple(&text, cx);
  618        build_editor(buffer, window, cx)
  619    });
  620
  621    _ = editor.update(cx, |editor, window, cx| {
  622        editor.change_selections(None, window, cx, |s| {
  623            s.select_ranges(selection_ranges.clone())
  624        });
  625        editor.fold_creases(
  626            vec![
  627                Crease::simple(Point::new(1, 0)..Point::new(2, 0), FoldPlaceholder::test()),
  628                Crease::simple(Point::new(3, 0)..Point::new(4, 0), FoldPlaceholder::test()),
  629            ],
  630            true,
  631            window,
  632            cx,
  633        );
  634    });
  635
  636    let cloned_editor = editor
  637        .update(cx, |editor, _, cx| {
  638            cx.open_window(Default::default(), |window, cx| {
  639                cx.new(|cx| editor.clone(window, cx))
  640            })
  641        })
  642        .unwrap()
  643        .unwrap();
  644
  645    let snapshot = editor
  646        .update(cx, |e, window, cx| e.snapshot(window, cx))
  647        .unwrap();
  648    let cloned_snapshot = cloned_editor
  649        .update(cx, |e, window, cx| e.snapshot(window, cx))
  650        .unwrap();
  651
  652    assert_eq!(
  653        cloned_editor
  654            .update(cx, |e, _, cx| e.display_text(cx))
  655            .unwrap(),
  656        editor.update(cx, |e, _, cx| e.display_text(cx)).unwrap()
  657    );
  658    assert_eq!(
  659        cloned_snapshot
  660            .folds_in_range(0..text.len())
  661            .collect::<Vec<_>>(),
  662        snapshot.folds_in_range(0..text.len()).collect::<Vec<_>>(),
  663    );
  664    assert_set_eq!(
  665        cloned_editor
  666            .update(cx, |editor, _, cx| editor.selections.ranges::<Point>(cx))
  667            .unwrap(),
  668        editor
  669            .update(cx, |editor, _, cx| editor.selections.ranges(cx))
  670            .unwrap()
  671    );
  672    assert_set_eq!(
  673        cloned_editor
  674            .update(cx, |e, _window, cx| e.selections.display_ranges(cx))
  675            .unwrap(),
  676        editor
  677            .update(cx, |e, _, cx| e.selections.display_ranges(cx))
  678            .unwrap()
  679    );
  680}
  681
  682#[gpui::test]
  683async fn test_navigation_history(cx: &mut TestAppContext) {
  684    init_test(cx, |_| {});
  685
  686    use workspace::item::Item;
  687
  688    let fs = FakeFs::new(cx.executor());
  689    let project = Project::test(fs, [], cx).await;
  690    let workspace = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
  691    let pane = workspace
  692        .update(cx, |workspace, _, _| workspace.active_pane().clone())
  693        .unwrap();
  694
  695    _ = workspace.update(cx, |_v, window, cx| {
  696        cx.new(|cx| {
  697            let buffer = MultiBuffer::build_simple(&sample_text(300, 5, 'a'), cx);
  698            let mut editor = build_editor(buffer.clone(), window, cx);
  699            let handle = cx.entity();
  700            editor.set_nav_history(Some(pane.read(cx).nav_history_for_item(&handle)));
  701
  702            fn pop_history(editor: &mut Editor, cx: &mut App) -> Option<NavigationEntry> {
  703                editor.nav_history.as_mut().unwrap().pop_backward(cx)
  704            }
  705
  706            // Move the cursor a small distance.
  707            // Nothing is added to the navigation history.
  708            editor.change_selections(None, window, cx, |s| {
  709                s.select_display_ranges([
  710                    DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0)
  711                ])
  712            });
  713            editor.change_selections(None, window, cx, |s| {
  714                s.select_display_ranges([
  715                    DisplayPoint::new(DisplayRow(3), 0)..DisplayPoint::new(DisplayRow(3), 0)
  716                ])
  717            });
  718            assert!(pop_history(&mut editor, cx).is_none());
  719
  720            // Move the cursor a large distance.
  721            // The history can jump back to the previous position.
  722            editor.change_selections(None, window, cx, |s| {
  723                s.select_display_ranges([
  724                    DisplayPoint::new(DisplayRow(13), 0)..DisplayPoint::new(DisplayRow(13), 3)
  725                ])
  726            });
  727            let nav_entry = pop_history(&mut editor, cx).unwrap();
  728            editor.navigate(nav_entry.data.unwrap(), window, cx);
  729            assert_eq!(nav_entry.item.id(), cx.entity_id());
  730            assert_eq!(
  731                editor.selections.display_ranges(cx),
  732                &[DisplayPoint::new(DisplayRow(3), 0)..DisplayPoint::new(DisplayRow(3), 0)]
  733            );
  734            assert!(pop_history(&mut editor, cx).is_none());
  735
  736            // Move the cursor a small distance via the mouse.
  737            // Nothing is added to the navigation history.
  738            editor.begin_selection(DisplayPoint::new(DisplayRow(5), 0), false, 1, window, cx);
  739            editor.end_selection(window, cx);
  740            assert_eq!(
  741                editor.selections.display_ranges(cx),
  742                &[DisplayPoint::new(DisplayRow(5), 0)..DisplayPoint::new(DisplayRow(5), 0)]
  743            );
  744            assert!(pop_history(&mut editor, cx).is_none());
  745
  746            // Move the cursor a large distance via the mouse.
  747            // The history can jump back to the previous position.
  748            editor.begin_selection(DisplayPoint::new(DisplayRow(15), 0), false, 1, window, cx);
  749            editor.end_selection(window, cx);
  750            assert_eq!(
  751                editor.selections.display_ranges(cx),
  752                &[DisplayPoint::new(DisplayRow(15), 0)..DisplayPoint::new(DisplayRow(15), 0)]
  753            );
  754            let nav_entry = pop_history(&mut editor, cx).unwrap();
  755            editor.navigate(nav_entry.data.unwrap(), window, cx);
  756            assert_eq!(nav_entry.item.id(), cx.entity_id());
  757            assert_eq!(
  758                editor.selections.display_ranges(cx),
  759                &[DisplayPoint::new(DisplayRow(5), 0)..DisplayPoint::new(DisplayRow(5), 0)]
  760            );
  761            assert!(pop_history(&mut editor, cx).is_none());
  762
  763            // Set scroll position to check later
  764            editor.set_scroll_position(gpui::Point::<f32>::new(5.5, 5.5), window, cx);
  765            let original_scroll_position = editor.scroll_manager.anchor();
  766
  767            // Jump to the end of the document and adjust scroll
  768            editor.move_to_end(&MoveToEnd, window, cx);
  769            editor.set_scroll_position(gpui::Point::<f32>::new(-2.5, -0.5), window, cx);
  770            assert_ne!(editor.scroll_manager.anchor(), original_scroll_position);
  771
  772            let nav_entry = pop_history(&mut editor, cx).unwrap();
  773            editor.navigate(nav_entry.data.unwrap(), window, cx);
  774            assert_eq!(editor.scroll_manager.anchor(), original_scroll_position);
  775
  776            // Ensure we don't panic when navigation data contains invalid anchors *and* points.
  777            let mut invalid_anchor = editor.scroll_manager.anchor().anchor;
  778            invalid_anchor.text_anchor.buffer_id = BufferId::new(999).ok();
  779            let invalid_point = Point::new(9999, 0);
  780            editor.navigate(
  781                Box::new(NavigationData {
  782                    cursor_anchor: invalid_anchor,
  783                    cursor_position: invalid_point,
  784                    scroll_anchor: ScrollAnchor {
  785                        anchor: invalid_anchor,
  786                        offset: Default::default(),
  787                    },
  788                    scroll_top_row: invalid_point.row,
  789                }),
  790                window,
  791                cx,
  792            );
  793            assert_eq!(
  794                editor.selections.display_ranges(cx),
  795                &[editor.max_point(cx)..editor.max_point(cx)]
  796            );
  797            assert_eq!(
  798                editor.scroll_position(cx),
  799                gpui::Point::new(0., editor.max_point(cx).row().as_f32())
  800            );
  801
  802            editor
  803        })
  804    });
  805}
  806
  807#[gpui::test]
  808fn test_cancel(cx: &mut TestAppContext) {
  809    init_test(cx, |_| {});
  810
  811    let editor = cx.add_window(|window, cx| {
  812        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
  813        build_editor(buffer, window, cx)
  814    });
  815
  816    _ = editor.update(cx, |editor, window, cx| {
  817        editor.begin_selection(DisplayPoint::new(DisplayRow(3), 4), false, 1, window, cx);
  818        editor.update_selection(
  819            DisplayPoint::new(DisplayRow(1), 1),
  820            0,
  821            gpui::Point::<f32>::default(),
  822            window,
  823            cx,
  824        );
  825        editor.end_selection(window, cx);
  826
  827        editor.begin_selection(DisplayPoint::new(DisplayRow(0), 1), true, 1, window, cx);
  828        editor.update_selection(
  829            DisplayPoint::new(DisplayRow(0), 3),
  830            0,
  831            gpui::Point::<f32>::default(),
  832            window,
  833            cx,
  834        );
  835        editor.end_selection(window, cx);
  836        assert_eq!(
  837            editor.selections.display_ranges(cx),
  838            [
  839                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 3),
  840                DisplayPoint::new(DisplayRow(3), 4)..DisplayPoint::new(DisplayRow(1), 1),
  841            ]
  842        );
  843    });
  844
  845    _ = editor.update(cx, |editor, window, cx| {
  846        editor.cancel(&Cancel, window, cx);
  847        assert_eq!(
  848            editor.selections.display_ranges(cx),
  849            [DisplayPoint::new(DisplayRow(3), 4)..DisplayPoint::new(DisplayRow(1), 1)]
  850        );
  851    });
  852
  853    _ = editor.update(cx, |editor, window, cx| {
  854        editor.cancel(&Cancel, window, cx);
  855        assert_eq!(
  856            editor.selections.display_ranges(cx),
  857            [DisplayPoint::new(DisplayRow(1), 1)..DisplayPoint::new(DisplayRow(1), 1)]
  858        );
  859    });
  860}
  861
  862#[gpui::test]
  863fn test_fold_action(cx: &mut TestAppContext) {
  864    init_test(cx, |_| {});
  865
  866    let editor = cx.add_window(|window, cx| {
  867        let buffer = MultiBuffer::build_simple(
  868            &"
  869                impl Foo {
  870                    // Hello!
  871
  872                    fn a() {
  873                        1
  874                    }
  875
  876                    fn b() {
  877                        2
  878                    }
  879
  880                    fn c() {
  881                        3
  882                    }
  883                }
  884            "
  885            .unindent(),
  886            cx,
  887        );
  888        build_editor(buffer.clone(), window, cx)
  889    });
  890
  891    _ = editor.update(cx, |editor, window, cx| {
  892        editor.change_selections(None, window, cx, |s| {
  893            s.select_display_ranges([
  894                DisplayPoint::new(DisplayRow(7), 0)..DisplayPoint::new(DisplayRow(12), 0)
  895            ]);
  896        });
  897        editor.fold(&Fold, window, cx);
  898        assert_eq!(
  899            editor.display_text(cx),
  900            "
  901                impl Foo {
  902                    // Hello!
  903
  904                    fn a() {
  905                        1
  906                    }
  907
  908                    fn b() {⋯
  909                    }
  910
  911                    fn c() {⋯
  912                    }
  913                }
  914            "
  915            .unindent(),
  916        );
  917
  918        editor.fold(&Fold, window, cx);
  919        assert_eq!(
  920            editor.display_text(cx),
  921            "
  922                impl Foo {⋯
  923                }
  924            "
  925            .unindent(),
  926        );
  927
  928        editor.unfold_lines(&UnfoldLines, window, cx);
  929        assert_eq!(
  930            editor.display_text(cx),
  931            "
  932                impl Foo {
  933                    // Hello!
  934
  935                    fn a() {
  936                        1
  937                    }
  938
  939                    fn b() {⋯
  940                    }
  941
  942                    fn c() {⋯
  943                    }
  944                }
  945            "
  946            .unindent(),
  947        );
  948
  949        editor.unfold_lines(&UnfoldLines, window, cx);
  950        assert_eq!(
  951            editor.display_text(cx),
  952            editor.buffer.read(cx).read(cx).text()
  953        );
  954    });
  955}
  956
  957#[gpui::test]
  958fn test_fold_action_whitespace_sensitive_language(cx: &mut TestAppContext) {
  959    init_test(cx, |_| {});
  960
  961    let editor = cx.add_window(|window, cx| {
  962        let buffer = MultiBuffer::build_simple(
  963            &"
  964                class Foo:
  965                    # Hello!
  966
  967                    def a():
  968                        print(1)
  969
  970                    def b():
  971                        print(2)
  972
  973                    def c():
  974                        print(3)
  975            "
  976            .unindent(),
  977            cx,
  978        );
  979        build_editor(buffer.clone(), window, cx)
  980    });
  981
  982    _ = editor.update(cx, |editor, window, cx| {
  983        editor.change_selections(None, window, cx, |s| {
  984            s.select_display_ranges([
  985                DisplayPoint::new(DisplayRow(6), 0)..DisplayPoint::new(DisplayRow(10), 0)
  986            ]);
  987        });
  988        editor.fold(&Fold, window, cx);
  989        assert_eq!(
  990            editor.display_text(cx),
  991            "
  992                class Foo:
  993                    # Hello!
  994
  995                    def a():
  996                        print(1)
  997
  998                    def b():⋯
  999
 1000                    def c():⋯
 1001            "
 1002            .unindent(),
 1003        );
 1004
 1005        editor.fold(&Fold, window, cx);
 1006        assert_eq!(
 1007            editor.display_text(cx),
 1008            "
 1009                class Foo:⋯
 1010            "
 1011            .unindent(),
 1012        );
 1013
 1014        editor.unfold_lines(&UnfoldLines, window, cx);
 1015        assert_eq!(
 1016            editor.display_text(cx),
 1017            "
 1018                class Foo:
 1019                    # Hello!
 1020
 1021                    def a():
 1022                        print(1)
 1023
 1024                    def b():⋯
 1025
 1026                    def c():⋯
 1027            "
 1028            .unindent(),
 1029        );
 1030
 1031        editor.unfold_lines(&UnfoldLines, window, cx);
 1032        assert_eq!(
 1033            editor.display_text(cx),
 1034            editor.buffer.read(cx).read(cx).text()
 1035        );
 1036    });
 1037}
 1038
 1039#[gpui::test]
 1040fn test_fold_action_multiple_line_breaks(cx: &mut TestAppContext) {
 1041    init_test(cx, |_| {});
 1042
 1043    let editor = cx.add_window(|window, cx| {
 1044        let buffer = MultiBuffer::build_simple(
 1045            &"
 1046                class Foo:
 1047                    # Hello!
 1048
 1049                    def a():
 1050                        print(1)
 1051
 1052                    def b():
 1053                        print(2)
 1054
 1055
 1056                    def c():
 1057                        print(3)
 1058
 1059
 1060            "
 1061            .unindent(),
 1062            cx,
 1063        );
 1064        build_editor(buffer.clone(), window, cx)
 1065    });
 1066
 1067    _ = editor.update(cx, |editor, window, cx| {
 1068        editor.change_selections(None, window, cx, |s| {
 1069            s.select_display_ranges([
 1070                DisplayPoint::new(DisplayRow(6), 0)..DisplayPoint::new(DisplayRow(11), 0)
 1071            ]);
 1072        });
 1073        editor.fold(&Fold, window, cx);
 1074        assert_eq!(
 1075            editor.display_text(cx),
 1076            "
 1077                class Foo:
 1078                    # Hello!
 1079
 1080                    def a():
 1081                        print(1)
 1082
 1083                    def b():⋯
 1084
 1085
 1086                    def c():⋯
 1087
 1088
 1089            "
 1090            .unindent(),
 1091        );
 1092
 1093        editor.fold(&Fold, window, cx);
 1094        assert_eq!(
 1095            editor.display_text(cx),
 1096            "
 1097                class Foo:⋯
 1098
 1099
 1100            "
 1101            .unindent(),
 1102        );
 1103
 1104        editor.unfold_lines(&UnfoldLines, window, cx);
 1105        assert_eq!(
 1106            editor.display_text(cx),
 1107            "
 1108                class Foo:
 1109                    # Hello!
 1110
 1111                    def a():
 1112                        print(1)
 1113
 1114                    def b():⋯
 1115
 1116
 1117                    def c():⋯
 1118
 1119
 1120            "
 1121            .unindent(),
 1122        );
 1123
 1124        editor.unfold_lines(&UnfoldLines, window, cx);
 1125        assert_eq!(
 1126            editor.display_text(cx),
 1127            editor.buffer.read(cx).read(cx).text()
 1128        );
 1129    });
 1130}
 1131
 1132#[gpui::test]
 1133fn test_fold_at_level(cx: &mut TestAppContext) {
 1134    init_test(cx, |_| {});
 1135
 1136    let editor = cx.add_window(|window, cx| {
 1137        let buffer = MultiBuffer::build_simple(
 1138            &"
 1139                class Foo:
 1140                    # Hello!
 1141
 1142                    def a():
 1143                        print(1)
 1144
 1145                    def b():
 1146                        print(2)
 1147
 1148
 1149                class Bar:
 1150                    # World!
 1151
 1152                    def a():
 1153                        print(1)
 1154
 1155                    def b():
 1156                        print(2)
 1157
 1158
 1159            "
 1160            .unindent(),
 1161            cx,
 1162        );
 1163        build_editor(buffer.clone(), window, cx)
 1164    });
 1165
 1166    _ = editor.update(cx, |editor, window, cx| {
 1167        editor.fold_at_level(&FoldAtLevel(2), window, cx);
 1168        assert_eq!(
 1169            editor.display_text(cx),
 1170            "
 1171                class Foo:
 1172                    # Hello!
 1173
 1174                    def a():⋯
 1175
 1176                    def b():⋯
 1177
 1178
 1179                class Bar:
 1180                    # World!
 1181
 1182                    def a():⋯
 1183
 1184                    def b():⋯
 1185
 1186
 1187            "
 1188            .unindent(),
 1189        );
 1190
 1191        editor.fold_at_level(&FoldAtLevel(1), window, cx);
 1192        assert_eq!(
 1193            editor.display_text(cx),
 1194            "
 1195                class Foo:⋯
 1196
 1197
 1198                class Bar:⋯
 1199
 1200
 1201            "
 1202            .unindent(),
 1203        );
 1204
 1205        editor.unfold_all(&UnfoldAll, window, cx);
 1206        editor.fold_at_level(&FoldAtLevel(0), window, cx);
 1207        assert_eq!(
 1208            editor.display_text(cx),
 1209            "
 1210                class Foo:
 1211                    # Hello!
 1212
 1213                    def a():
 1214                        print(1)
 1215
 1216                    def b():
 1217                        print(2)
 1218
 1219
 1220                class Bar:
 1221                    # World!
 1222
 1223                    def a():
 1224                        print(1)
 1225
 1226                    def b():
 1227                        print(2)
 1228
 1229
 1230            "
 1231            .unindent(),
 1232        );
 1233
 1234        assert_eq!(
 1235            editor.display_text(cx),
 1236            editor.buffer.read(cx).read(cx).text()
 1237        );
 1238    });
 1239}
 1240
 1241#[gpui::test]
 1242fn test_move_cursor(cx: &mut TestAppContext) {
 1243    init_test(cx, |_| {});
 1244
 1245    let buffer = cx.update(|cx| MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx));
 1246    let editor = cx.add_window(|window, cx| build_editor(buffer.clone(), window, cx));
 1247
 1248    buffer.update(cx, |buffer, cx| {
 1249        buffer.edit(
 1250            vec![
 1251                (Point::new(1, 0)..Point::new(1, 0), "\t"),
 1252                (Point::new(1, 1)..Point::new(1, 1), "\t"),
 1253            ],
 1254            None,
 1255            cx,
 1256        );
 1257    });
 1258    _ = editor.update(cx, |editor, window, cx| {
 1259        assert_eq!(
 1260            editor.selections.display_ranges(cx),
 1261            &[DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0)]
 1262        );
 1263
 1264        editor.move_down(&MoveDown, window, cx);
 1265        assert_eq!(
 1266            editor.selections.display_ranges(cx),
 1267            &[DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0)]
 1268        );
 1269
 1270        editor.move_right(&MoveRight, window, cx);
 1271        assert_eq!(
 1272            editor.selections.display_ranges(cx),
 1273            &[DisplayPoint::new(DisplayRow(1), 4)..DisplayPoint::new(DisplayRow(1), 4)]
 1274        );
 1275
 1276        editor.move_left(&MoveLeft, window, cx);
 1277        assert_eq!(
 1278            editor.selections.display_ranges(cx),
 1279            &[DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0)]
 1280        );
 1281
 1282        editor.move_up(&MoveUp, window, cx);
 1283        assert_eq!(
 1284            editor.selections.display_ranges(cx),
 1285            &[DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0)]
 1286        );
 1287
 1288        editor.move_to_end(&MoveToEnd, window, cx);
 1289        assert_eq!(
 1290            editor.selections.display_ranges(cx),
 1291            &[DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 6)]
 1292        );
 1293
 1294        editor.move_to_beginning(&MoveToBeginning, window, cx);
 1295        assert_eq!(
 1296            editor.selections.display_ranges(cx),
 1297            &[DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0)]
 1298        );
 1299
 1300        editor.change_selections(None, window, cx, |s| {
 1301            s.select_display_ranges([
 1302                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 2)
 1303            ]);
 1304        });
 1305        editor.select_to_beginning(&SelectToBeginning, window, cx);
 1306        assert_eq!(
 1307            editor.selections.display_ranges(cx),
 1308            &[DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 0)]
 1309        );
 1310
 1311        editor.select_to_end(&SelectToEnd, window, cx);
 1312        assert_eq!(
 1313            editor.selections.display_ranges(cx),
 1314            &[DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(5), 6)]
 1315        );
 1316    });
 1317}
 1318
 1319#[gpui::test]
 1320fn test_move_cursor_multibyte(cx: &mut TestAppContext) {
 1321    init_test(cx, |_| {});
 1322
 1323    let editor = cx.add_window(|window, cx| {
 1324        let buffer = MultiBuffer::build_simple("🟥🟧🟨🟩🟦🟪\nabcde\nαβγδε", cx);
 1325        build_editor(buffer.clone(), window, cx)
 1326    });
 1327
 1328    assert_eq!('🟥'.len_utf8(), 4);
 1329    assert_eq!('α'.len_utf8(), 2);
 1330
 1331    _ = editor.update(cx, |editor, window, cx| {
 1332        editor.fold_creases(
 1333            vec![
 1334                Crease::simple(Point::new(0, 8)..Point::new(0, 16), FoldPlaceholder::test()),
 1335                Crease::simple(Point::new(1, 2)..Point::new(1, 4), FoldPlaceholder::test()),
 1336                Crease::simple(Point::new(2, 4)..Point::new(2, 8), FoldPlaceholder::test()),
 1337            ],
 1338            true,
 1339            window,
 1340            cx,
 1341        );
 1342        assert_eq!(editor.display_text(cx), "🟥🟧⋯🟦🟪\nab⋯e\nαβ⋯ε");
 1343
 1344        editor.move_right(&MoveRight, window, cx);
 1345        assert_eq!(
 1346            editor.selections.display_ranges(cx),
 1347            &[empty_range(0, "🟥".len())]
 1348        );
 1349        editor.move_right(&MoveRight, window, cx);
 1350        assert_eq!(
 1351            editor.selections.display_ranges(cx),
 1352            &[empty_range(0, "🟥🟧".len())]
 1353        );
 1354        editor.move_right(&MoveRight, window, cx);
 1355        assert_eq!(
 1356            editor.selections.display_ranges(cx),
 1357            &[empty_range(0, "🟥🟧⋯".len())]
 1358        );
 1359
 1360        editor.move_down(&MoveDown, window, cx);
 1361        assert_eq!(
 1362            editor.selections.display_ranges(cx),
 1363            &[empty_range(1, "ab⋯e".len())]
 1364        );
 1365        editor.move_left(&MoveLeft, window, cx);
 1366        assert_eq!(
 1367            editor.selections.display_ranges(cx),
 1368            &[empty_range(1, "ab⋯".len())]
 1369        );
 1370        editor.move_left(&MoveLeft, window, cx);
 1371        assert_eq!(
 1372            editor.selections.display_ranges(cx),
 1373            &[empty_range(1, "ab".len())]
 1374        );
 1375        editor.move_left(&MoveLeft, window, cx);
 1376        assert_eq!(
 1377            editor.selections.display_ranges(cx),
 1378            &[empty_range(1, "a".len())]
 1379        );
 1380
 1381        editor.move_down(&MoveDown, window, cx);
 1382        assert_eq!(
 1383            editor.selections.display_ranges(cx),
 1384            &[empty_range(2, "α".len())]
 1385        );
 1386        editor.move_right(&MoveRight, window, cx);
 1387        assert_eq!(
 1388            editor.selections.display_ranges(cx),
 1389            &[empty_range(2, "αβ".len())]
 1390        );
 1391        editor.move_right(&MoveRight, window, cx);
 1392        assert_eq!(
 1393            editor.selections.display_ranges(cx),
 1394            &[empty_range(2, "αβ⋯".len())]
 1395        );
 1396        editor.move_right(&MoveRight, window, cx);
 1397        assert_eq!(
 1398            editor.selections.display_ranges(cx),
 1399            &[empty_range(2, "αβ⋯ε".len())]
 1400        );
 1401
 1402        editor.move_up(&MoveUp, window, cx);
 1403        assert_eq!(
 1404            editor.selections.display_ranges(cx),
 1405            &[empty_range(1, "ab⋯e".len())]
 1406        );
 1407        editor.move_down(&MoveDown, window, cx);
 1408        assert_eq!(
 1409            editor.selections.display_ranges(cx),
 1410            &[empty_range(2, "αβ⋯ε".len())]
 1411        );
 1412        editor.move_up(&MoveUp, window, cx);
 1413        assert_eq!(
 1414            editor.selections.display_ranges(cx),
 1415            &[empty_range(1, "ab⋯e".len())]
 1416        );
 1417
 1418        editor.move_up(&MoveUp, window, cx);
 1419        assert_eq!(
 1420            editor.selections.display_ranges(cx),
 1421            &[empty_range(0, "🟥🟧".len())]
 1422        );
 1423        editor.move_left(&MoveLeft, window, cx);
 1424        assert_eq!(
 1425            editor.selections.display_ranges(cx),
 1426            &[empty_range(0, "🟥".len())]
 1427        );
 1428        editor.move_left(&MoveLeft, window, cx);
 1429        assert_eq!(
 1430            editor.selections.display_ranges(cx),
 1431            &[empty_range(0, "".len())]
 1432        );
 1433    });
 1434}
 1435
 1436#[gpui::test]
 1437fn test_move_cursor_different_line_lengths(cx: &mut TestAppContext) {
 1438    init_test(cx, |_| {});
 1439
 1440    let editor = cx.add_window(|window, cx| {
 1441        let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
 1442        build_editor(buffer.clone(), window, cx)
 1443    });
 1444    _ = editor.update(cx, |editor, window, cx| {
 1445        editor.change_selections(None, window, cx, |s| {
 1446            s.select_display_ranges([empty_range(0, "ⓐⓑⓒⓓⓔ".len())]);
 1447        });
 1448
 1449        // moving above start of document should move selection to start of document,
 1450        // but the next move down should still be at the original goal_x
 1451        editor.move_up(&MoveUp, window, cx);
 1452        assert_eq!(
 1453            editor.selections.display_ranges(cx),
 1454            &[empty_range(0, "".len())]
 1455        );
 1456
 1457        editor.move_down(&MoveDown, window, cx);
 1458        assert_eq!(
 1459            editor.selections.display_ranges(cx),
 1460            &[empty_range(1, "abcd".len())]
 1461        );
 1462
 1463        editor.move_down(&MoveDown, window, cx);
 1464        assert_eq!(
 1465            editor.selections.display_ranges(cx),
 1466            &[empty_range(2, "αβγ".len())]
 1467        );
 1468
 1469        editor.move_down(&MoveDown, window, cx);
 1470        assert_eq!(
 1471            editor.selections.display_ranges(cx),
 1472            &[empty_range(3, "abcd".len())]
 1473        );
 1474
 1475        editor.move_down(&MoveDown, window, cx);
 1476        assert_eq!(
 1477            editor.selections.display_ranges(cx),
 1478            &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
 1479        );
 1480
 1481        // moving past end of document should not change goal_x
 1482        editor.move_down(&MoveDown, window, cx);
 1483        assert_eq!(
 1484            editor.selections.display_ranges(cx),
 1485            &[empty_range(5, "".len())]
 1486        );
 1487
 1488        editor.move_down(&MoveDown, window, cx);
 1489        assert_eq!(
 1490            editor.selections.display_ranges(cx),
 1491            &[empty_range(5, "".len())]
 1492        );
 1493
 1494        editor.move_up(&MoveUp, window, cx);
 1495        assert_eq!(
 1496            editor.selections.display_ranges(cx),
 1497            &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
 1498        );
 1499
 1500        editor.move_up(&MoveUp, window, cx);
 1501        assert_eq!(
 1502            editor.selections.display_ranges(cx),
 1503            &[empty_range(3, "abcd".len())]
 1504        );
 1505
 1506        editor.move_up(&MoveUp, window, cx);
 1507        assert_eq!(
 1508            editor.selections.display_ranges(cx),
 1509            &[empty_range(2, "αβγ".len())]
 1510        );
 1511    });
 1512}
 1513
 1514#[gpui::test]
 1515fn test_beginning_end_of_line(cx: &mut TestAppContext) {
 1516    init_test(cx, |_| {});
 1517    let move_to_beg = MoveToBeginningOfLine {
 1518        stop_at_soft_wraps: true,
 1519        stop_at_indent: true,
 1520    };
 1521
 1522    let delete_to_beg = DeleteToBeginningOfLine {
 1523        stop_at_indent: false,
 1524    };
 1525
 1526    let move_to_end = MoveToEndOfLine {
 1527        stop_at_soft_wraps: true,
 1528    };
 1529
 1530    let editor = cx.add_window(|window, cx| {
 1531        let buffer = MultiBuffer::build_simple("abc\n  def", cx);
 1532        build_editor(buffer, window, cx)
 1533    });
 1534    _ = editor.update(cx, |editor, window, cx| {
 1535        editor.change_selections(None, window, cx, |s| {
 1536            s.select_display_ranges([
 1537                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 1),
 1538                DisplayPoint::new(DisplayRow(1), 4)..DisplayPoint::new(DisplayRow(1), 4),
 1539            ]);
 1540        });
 1541    });
 1542
 1543    _ = editor.update(cx, |editor, window, cx| {
 1544        editor.move_to_beginning_of_line(&move_to_beg, window, cx);
 1545        assert_eq!(
 1546            editor.selections.display_ranges(cx),
 1547            &[
 1548                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0),
 1549                DisplayPoint::new(DisplayRow(1), 2)..DisplayPoint::new(DisplayRow(1), 2),
 1550            ]
 1551        );
 1552    });
 1553
 1554    _ = editor.update(cx, |editor, window, cx| {
 1555        editor.move_to_beginning_of_line(&move_to_beg, window, cx);
 1556        assert_eq!(
 1557            editor.selections.display_ranges(cx),
 1558            &[
 1559                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0),
 1560                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0),
 1561            ]
 1562        );
 1563    });
 1564
 1565    _ = editor.update(cx, |editor, window, cx| {
 1566        editor.move_to_beginning_of_line(&move_to_beg, window, cx);
 1567        assert_eq!(
 1568            editor.selections.display_ranges(cx),
 1569            &[
 1570                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0),
 1571                DisplayPoint::new(DisplayRow(1), 2)..DisplayPoint::new(DisplayRow(1), 2),
 1572            ]
 1573        );
 1574    });
 1575
 1576    _ = editor.update(cx, |editor, window, cx| {
 1577        editor.move_to_end_of_line(&move_to_end, window, cx);
 1578        assert_eq!(
 1579            editor.selections.display_ranges(cx),
 1580            &[
 1581                DisplayPoint::new(DisplayRow(0), 3)..DisplayPoint::new(DisplayRow(0), 3),
 1582                DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(1), 5),
 1583            ]
 1584        );
 1585    });
 1586
 1587    // Moving to the end of line again is a no-op.
 1588    _ = editor.update(cx, |editor, window, cx| {
 1589        editor.move_to_end_of_line(&move_to_end, window, cx);
 1590        assert_eq!(
 1591            editor.selections.display_ranges(cx),
 1592            &[
 1593                DisplayPoint::new(DisplayRow(0), 3)..DisplayPoint::new(DisplayRow(0), 3),
 1594                DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(1), 5),
 1595            ]
 1596        );
 1597    });
 1598
 1599    _ = editor.update(cx, |editor, window, cx| {
 1600        editor.move_left(&MoveLeft, window, cx);
 1601        editor.select_to_beginning_of_line(
 1602            &SelectToBeginningOfLine {
 1603                stop_at_soft_wraps: true,
 1604                stop_at_indent: true,
 1605            },
 1606            window,
 1607            cx,
 1608        );
 1609        assert_eq!(
 1610            editor.selections.display_ranges(cx),
 1611            &[
 1612                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 0),
 1613                DisplayPoint::new(DisplayRow(1), 4)..DisplayPoint::new(DisplayRow(1), 2),
 1614            ]
 1615        );
 1616    });
 1617
 1618    _ = editor.update(cx, |editor, window, cx| {
 1619        editor.select_to_beginning_of_line(
 1620            &SelectToBeginningOfLine {
 1621                stop_at_soft_wraps: true,
 1622                stop_at_indent: true,
 1623            },
 1624            window,
 1625            cx,
 1626        );
 1627        assert_eq!(
 1628            editor.selections.display_ranges(cx),
 1629            &[
 1630                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 0),
 1631                DisplayPoint::new(DisplayRow(1), 4)..DisplayPoint::new(DisplayRow(1), 0),
 1632            ]
 1633        );
 1634    });
 1635
 1636    _ = editor.update(cx, |editor, window, cx| {
 1637        editor.select_to_beginning_of_line(
 1638            &SelectToBeginningOfLine {
 1639                stop_at_soft_wraps: true,
 1640                stop_at_indent: true,
 1641            },
 1642            window,
 1643            cx,
 1644        );
 1645        assert_eq!(
 1646            editor.selections.display_ranges(cx),
 1647            &[
 1648                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 0),
 1649                DisplayPoint::new(DisplayRow(1), 4)..DisplayPoint::new(DisplayRow(1), 2),
 1650            ]
 1651        );
 1652    });
 1653
 1654    _ = editor.update(cx, |editor, window, cx| {
 1655        editor.select_to_end_of_line(
 1656            &SelectToEndOfLine {
 1657                stop_at_soft_wraps: true,
 1658            },
 1659            window,
 1660            cx,
 1661        );
 1662        assert_eq!(
 1663            editor.selections.display_ranges(cx),
 1664            &[
 1665                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 3),
 1666                DisplayPoint::new(DisplayRow(1), 4)..DisplayPoint::new(DisplayRow(1), 5),
 1667            ]
 1668        );
 1669    });
 1670
 1671    _ = editor.update(cx, |editor, window, cx| {
 1672        editor.delete_to_end_of_line(&DeleteToEndOfLine, window, cx);
 1673        assert_eq!(editor.display_text(cx), "ab\n  de");
 1674        assert_eq!(
 1675            editor.selections.display_ranges(cx),
 1676            &[
 1677                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 2),
 1678                DisplayPoint::new(DisplayRow(1), 4)..DisplayPoint::new(DisplayRow(1), 4),
 1679            ]
 1680        );
 1681    });
 1682
 1683    _ = editor.update(cx, |editor, window, cx| {
 1684        editor.delete_to_beginning_of_line(&delete_to_beg, window, cx);
 1685        assert_eq!(editor.display_text(cx), "\n");
 1686        assert_eq!(
 1687            editor.selections.display_ranges(cx),
 1688            &[
 1689                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0),
 1690                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0),
 1691            ]
 1692        );
 1693    });
 1694}
 1695
 1696#[gpui::test]
 1697fn test_beginning_end_of_line_ignore_soft_wrap(cx: &mut TestAppContext) {
 1698    init_test(cx, |_| {});
 1699    let move_to_beg = MoveToBeginningOfLine {
 1700        stop_at_soft_wraps: false,
 1701        stop_at_indent: false,
 1702    };
 1703
 1704    let move_to_end = MoveToEndOfLine {
 1705        stop_at_soft_wraps: false,
 1706    };
 1707
 1708    let editor = cx.add_window(|window, cx| {
 1709        let buffer = MultiBuffer::build_simple("thequickbrownfox\njumpedoverthelazydogs", cx);
 1710        build_editor(buffer, window, cx)
 1711    });
 1712
 1713    _ = editor.update(cx, |editor, window, cx| {
 1714        editor.set_wrap_width(Some(140.0.into()), cx);
 1715
 1716        // We expect the following lines after wrapping
 1717        // ```
 1718        // thequickbrownfox
 1719        // jumpedoverthelazydo
 1720        // gs
 1721        // ```
 1722        // The final `gs` was soft-wrapped onto a new line.
 1723        assert_eq!(
 1724            "thequickbrownfox\njumpedoverthelaz\nydogs",
 1725            editor.display_text(cx),
 1726        );
 1727
 1728        // First, let's assert behavior on the first line, that was not soft-wrapped.
 1729        // Start the cursor at the `k` on the first line
 1730        editor.change_selections(None, window, cx, |s| {
 1731            s.select_display_ranges([
 1732                DisplayPoint::new(DisplayRow(0), 7)..DisplayPoint::new(DisplayRow(0), 7)
 1733            ]);
 1734        });
 1735
 1736        // Moving to the beginning of the line should put us at the beginning of the line.
 1737        editor.move_to_beginning_of_line(&move_to_beg, window, cx);
 1738        assert_eq!(
 1739            vec![DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0),],
 1740            editor.selections.display_ranges(cx)
 1741        );
 1742
 1743        // Moving to the end of the line should put us at the end of the line.
 1744        editor.move_to_end_of_line(&move_to_end, window, cx);
 1745        assert_eq!(
 1746            vec![DisplayPoint::new(DisplayRow(0), 16)..DisplayPoint::new(DisplayRow(0), 16),],
 1747            editor.selections.display_ranges(cx)
 1748        );
 1749
 1750        // Now, let's assert behavior on the second line, that ended up being soft-wrapped.
 1751        // Start the cursor at the last line (`y` that was wrapped to a new line)
 1752        editor.change_selections(None, window, cx, |s| {
 1753            s.select_display_ranges([
 1754                DisplayPoint::new(DisplayRow(2), 0)..DisplayPoint::new(DisplayRow(2), 0)
 1755            ]);
 1756        });
 1757
 1758        // Moving to the beginning of the line should put us at the start of the second line of
 1759        // display text, i.e., the `j`.
 1760        editor.move_to_beginning_of_line(&move_to_beg, window, cx);
 1761        assert_eq!(
 1762            vec![DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0),],
 1763            editor.selections.display_ranges(cx)
 1764        );
 1765
 1766        // Moving to the beginning of the line again should be a no-op.
 1767        editor.move_to_beginning_of_line(&move_to_beg, window, cx);
 1768        assert_eq!(
 1769            vec![DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0),],
 1770            editor.selections.display_ranges(cx)
 1771        );
 1772
 1773        // Moving to the end of the line should put us right after the `s` that was soft-wrapped to the
 1774        // next display line.
 1775        editor.move_to_end_of_line(&move_to_end, window, cx);
 1776        assert_eq!(
 1777            vec![DisplayPoint::new(DisplayRow(2), 5)..DisplayPoint::new(DisplayRow(2), 5),],
 1778            editor.selections.display_ranges(cx)
 1779        );
 1780
 1781        // Moving to the end of the line again should be a no-op.
 1782        editor.move_to_end_of_line(&move_to_end, window, cx);
 1783        assert_eq!(
 1784            vec![DisplayPoint::new(DisplayRow(2), 5)..DisplayPoint::new(DisplayRow(2), 5),],
 1785            editor.selections.display_ranges(cx)
 1786        );
 1787    });
 1788}
 1789
 1790#[gpui::test]
 1791fn test_beginning_of_line_stop_at_indent(cx: &mut TestAppContext) {
 1792    init_test(cx, |_| {});
 1793
 1794    let move_to_beg = MoveToBeginningOfLine {
 1795        stop_at_soft_wraps: true,
 1796        stop_at_indent: true,
 1797    };
 1798
 1799    let select_to_beg = SelectToBeginningOfLine {
 1800        stop_at_soft_wraps: true,
 1801        stop_at_indent: true,
 1802    };
 1803
 1804    let delete_to_beg = DeleteToBeginningOfLine {
 1805        stop_at_indent: true,
 1806    };
 1807
 1808    let move_to_end = MoveToEndOfLine {
 1809        stop_at_soft_wraps: false,
 1810    };
 1811
 1812    let editor = cx.add_window(|window, cx| {
 1813        let buffer = MultiBuffer::build_simple("abc\n  def", cx);
 1814        build_editor(buffer, window, cx)
 1815    });
 1816
 1817    _ = editor.update(cx, |editor, window, cx| {
 1818        editor.change_selections(None, window, cx, |s| {
 1819            s.select_display_ranges([
 1820                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 1),
 1821                DisplayPoint::new(DisplayRow(1), 4)..DisplayPoint::new(DisplayRow(1), 4),
 1822            ]);
 1823        });
 1824
 1825        // Moving to the beginning of the line should put the first cursor at the beginning of the line,
 1826        // and the second cursor at the first non-whitespace character in the line.
 1827        editor.move_to_beginning_of_line(&move_to_beg, window, cx);
 1828        assert_eq!(
 1829            editor.selections.display_ranges(cx),
 1830            &[
 1831                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0),
 1832                DisplayPoint::new(DisplayRow(1), 2)..DisplayPoint::new(DisplayRow(1), 2),
 1833            ]
 1834        );
 1835
 1836        // Moving to the beginning of the line again should be a no-op for the first cursor,
 1837        // and should move the second cursor to the beginning of the line.
 1838        editor.move_to_beginning_of_line(&move_to_beg, window, cx);
 1839        assert_eq!(
 1840            editor.selections.display_ranges(cx),
 1841            &[
 1842                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0),
 1843                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0),
 1844            ]
 1845        );
 1846
 1847        // Moving to the beginning of the line again should still be a no-op for the first cursor,
 1848        // and should move the second cursor back to the first non-whitespace character in the line.
 1849        editor.move_to_beginning_of_line(&move_to_beg, window, cx);
 1850        assert_eq!(
 1851            editor.selections.display_ranges(cx),
 1852            &[
 1853                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0),
 1854                DisplayPoint::new(DisplayRow(1), 2)..DisplayPoint::new(DisplayRow(1), 2),
 1855            ]
 1856        );
 1857
 1858        // Selecting to the beginning of the line should select to the beginning of the line for the first cursor,
 1859        // and to the first non-whitespace character in the line for the second cursor.
 1860        editor.move_to_end_of_line(&move_to_end, window, cx);
 1861        editor.move_left(&MoveLeft, window, cx);
 1862        editor.select_to_beginning_of_line(&select_to_beg, window, cx);
 1863        assert_eq!(
 1864            editor.selections.display_ranges(cx),
 1865            &[
 1866                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 0),
 1867                DisplayPoint::new(DisplayRow(1), 4)..DisplayPoint::new(DisplayRow(1), 2),
 1868            ]
 1869        );
 1870
 1871        // Selecting to the beginning of the line again should be a no-op for the first cursor,
 1872        // and should select to the beginning of the line for the second cursor.
 1873        editor.select_to_beginning_of_line(&select_to_beg, window, cx);
 1874        assert_eq!(
 1875            editor.selections.display_ranges(cx),
 1876            &[
 1877                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 0),
 1878                DisplayPoint::new(DisplayRow(1), 4)..DisplayPoint::new(DisplayRow(1), 0),
 1879            ]
 1880        );
 1881
 1882        // Deleting to the beginning of the line should delete to the beginning of the line for the first cursor,
 1883        // and should delete to the first non-whitespace character in the line for the second cursor.
 1884        editor.move_to_end_of_line(&move_to_end, window, cx);
 1885        editor.move_left(&MoveLeft, window, cx);
 1886        editor.delete_to_beginning_of_line(&delete_to_beg, window, cx);
 1887        assert_eq!(editor.text(cx), "c\n  f");
 1888    });
 1889}
 1890
 1891#[gpui::test]
 1892fn test_prev_next_word_boundary(cx: &mut TestAppContext) {
 1893    init_test(cx, |_| {});
 1894
 1895    let editor = cx.add_window(|window, cx| {
 1896        let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n  {baz.qux()}", cx);
 1897        build_editor(buffer, window, cx)
 1898    });
 1899    _ = editor.update(cx, |editor, window, cx| {
 1900        editor.change_selections(None, window, cx, |s| {
 1901            s.select_display_ranges([
 1902                DisplayPoint::new(DisplayRow(0), 11)..DisplayPoint::new(DisplayRow(0), 11),
 1903                DisplayPoint::new(DisplayRow(2), 4)..DisplayPoint::new(DisplayRow(2), 4),
 1904            ])
 1905        });
 1906
 1907        editor.move_to_previous_word_start(&MoveToPreviousWordStart, window, cx);
 1908        assert_selection_ranges("use std::ˇstr::{foo, bar}\n\n  {ˇbaz.qux()}", editor, cx);
 1909
 1910        editor.move_to_previous_word_start(&MoveToPreviousWordStart, window, cx);
 1911        assert_selection_ranges("use stdˇ::str::{foo, bar}\n\n  ˇ{baz.qux()}", editor, cx);
 1912
 1913        editor.move_to_previous_word_start(&MoveToPreviousWordStart, window, cx);
 1914        assert_selection_ranges("use ˇstd::str::{foo, bar}\n\nˇ  {baz.qux()}", editor, cx);
 1915
 1916        editor.move_to_previous_word_start(&MoveToPreviousWordStart, window, cx);
 1917        assert_selection_ranges("ˇuse std::str::{foo, bar}\nˇ\n  {baz.qux()}", editor, cx);
 1918
 1919        editor.move_to_previous_word_start(&MoveToPreviousWordStart, window, cx);
 1920        assert_selection_ranges("ˇuse std::str::{foo, barˇ}\n\n  {baz.qux()}", editor, cx);
 1921
 1922        editor.move_to_next_word_end(&MoveToNextWordEnd, window, cx);
 1923        assert_selection_ranges("useˇ std::str::{foo, bar}ˇ\n\n  {baz.qux()}", editor, cx);
 1924
 1925        editor.move_to_next_word_end(&MoveToNextWordEnd, window, cx);
 1926        assert_selection_ranges("use stdˇ::str::{foo, bar}\nˇ\n  {baz.qux()}", editor, cx);
 1927
 1928        editor.move_to_next_word_end(&MoveToNextWordEnd, window, cx);
 1929        assert_selection_ranges("use std::ˇstr::{foo, bar}\n\n  {ˇbaz.qux()}", editor, cx);
 1930
 1931        editor.move_right(&MoveRight, window, cx);
 1932        editor.select_to_previous_word_start(&SelectToPreviousWordStart, window, cx);
 1933        assert_selection_ranges(
 1934            "use std::«ˇs»tr::{foo, bar}\n\n  {«ˇb»az.qux()}",
 1935            editor,
 1936            cx,
 1937        );
 1938
 1939        editor.select_to_previous_word_start(&SelectToPreviousWordStart, window, cx);
 1940        assert_selection_ranges(
 1941            "use std«ˇ::s»tr::{foo, bar}\n\n  «ˇ{b»az.qux()}",
 1942            editor,
 1943            cx,
 1944        );
 1945
 1946        editor.select_to_next_word_end(&SelectToNextWordEnd, window, cx);
 1947        assert_selection_ranges(
 1948            "use std::«ˇs»tr::{foo, bar}\n\n  {«ˇb»az.qux()}",
 1949            editor,
 1950            cx,
 1951        );
 1952    });
 1953}
 1954
 1955#[gpui::test]
 1956fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut TestAppContext) {
 1957    init_test(cx, |_| {});
 1958
 1959    let editor = cx.add_window(|window, cx| {
 1960        let buffer = MultiBuffer::build_simple("use one::{\n    two::three::four::five\n};", cx);
 1961        build_editor(buffer, window, cx)
 1962    });
 1963
 1964    _ = editor.update(cx, |editor, window, cx| {
 1965        editor.set_wrap_width(Some(140.0.into()), cx);
 1966        assert_eq!(
 1967            editor.display_text(cx),
 1968            "use one::{\n    two::three::\n    four::five\n};"
 1969        );
 1970
 1971        editor.change_selections(None, window, cx, |s| {
 1972            s.select_display_ranges([
 1973                DisplayPoint::new(DisplayRow(1), 7)..DisplayPoint::new(DisplayRow(1), 7)
 1974            ]);
 1975        });
 1976
 1977        editor.move_to_next_word_end(&MoveToNextWordEnd, window, cx);
 1978        assert_eq!(
 1979            editor.selections.display_ranges(cx),
 1980            &[DisplayPoint::new(DisplayRow(1), 9)..DisplayPoint::new(DisplayRow(1), 9)]
 1981        );
 1982
 1983        editor.move_to_next_word_end(&MoveToNextWordEnd, window, cx);
 1984        assert_eq!(
 1985            editor.selections.display_ranges(cx),
 1986            &[DisplayPoint::new(DisplayRow(1), 14)..DisplayPoint::new(DisplayRow(1), 14)]
 1987        );
 1988
 1989        editor.move_to_next_word_end(&MoveToNextWordEnd, window, cx);
 1990        assert_eq!(
 1991            editor.selections.display_ranges(cx),
 1992            &[DisplayPoint::new(DisplayRow(2), 4)..DisplayPoint::new(DisplayRow(2), 4)]
 1993        );
 1994
 1995        editor.move_to_next_word_end(&MoveToNextWordEnd, window, cx);
 1996        assert_eq!(
 1997            editor.selections.display_ranges(cx),
 1998            &[DisplayPoint::new(DisplayRow(2), 8)..DisplayPoint::new(DisplayRow(2), 8)]
 1999        );
 2000
 2001        editor.move_to_previous_word_start(&MoveToPreviousWordStart, window, cx);
 2002        assert_eq!(
 2003            editor.selections.display_ranges(cx),
 2004            &[DisplayPoint::new(DisplayRow(2), 4)..DisplayPoint::new(DisplayRow(2), 4)]
 2005        );
 2006
 2007        editor.move_to_previous_word_start(&MoveToPreviousWordStart, window, cx);
 2008        assert_eq!(
 2009            editor.selections.display_ranges(cx),
 2010            &[DisplayPoint::new(DisplayRow(1), 14)..DisplayPoint::new(DisplayRow(1), 14)]
 2011        );
 2012    });
 2013}
 2014
 2015#[gpui::test]
 2016async fn test_move_start_of_paragraph_end_of_paragraph(cx: &mut TestAppContext) {
 2017    init_test(cx, |_| {});
 2018    let mut cx = EditorTestContext::new(cx).await;
 2019
 2020    let line_height = cx.editor(|editor, window, _| {
 2021        editor
 2022            .style()
 2023            .unwrap()
 2024            .text
 2025            .line_height_in_pixels(window.rem_size())
 2026    });
 2027    cx.simulate_window_resize(cx.window, size(px(100.), 4. * line_height));
 2028
 2029    cx.set_state(
 2030        &r#"ˇone
 2031        two
 2032
 2033        three
 2034        fourˇ
 2035        five
 2036
 2037        six"#
 2038            .unindent(),
 2039    );
 2040
 2041    cx.update_editor(|editor, window, cx| {
 2042        editor.move_to_end_of_paragraph(&MoveToEndOfParagraph, window, cx)
 2043    });
 2044    cx.assert_editor_state(
 2045        &r#"one
 2046        two
 2047        ˇ
 2048        three
 2049        four
 2050        five
 2051        ˇ
 2052        six"#
 2053            .unindent(),
 2054    );
 2055
 2056    cx.update_editor(|editor, window, cx| {
 2057        editor.move_to_end_of_paragraph(&MoveToEndOfParagraph, window, cx)
 2058    });
 2059    cx.assert_editor_state(
 2060        &r#"one
 2061        two
 2062
 2063        three
 2064        four
 2065        five
 2066        ˇ
 2067        sixˇ"#
 2068            .unindent(),
 2069    );
 2070
 2071    cx.update_editor(|editor, window, cx| {
 2072        editor.move_to_end_of_paragraph(&MoveToEndOfParagraph, window, cx)
 2073    });
 2074    cx.assert_editor_state(
 2075        &r#"one
 2076        two
 2077
 2078        three
 2079        four
 2080        five
 2081
 2082        sixˇ"#
 2083            .unindent(),
 2084    );
 2085
 2086    cx.update_editor(|editor, window, cx| {
 2087        editor.move_to_start_of_paragraph(&MoveToStartOfParagraph, window, cx)
 2088    });
 2089    cx.assert_editor_state(
 2090        &r#"one
 2091        two
 2092
 2093        three
 2094        four
 2095        five
 2096        ˇ
 2097        six"#
 2098            .unindent(),
 2099    );
 2100
 2101    cx.update_editor(|editor, window, cx| {
 2102        editor.move_to_start_of_paragraph(&MoveToStartOfParagraph, window, cx)
 2103    });
 2104    cx.assert_editor_state(
 2105        &r#"one
 2106        two
 2107        ˇ
 2108        three
 2109        four
 2110        five
 2111
 2112        six"#
 2113            .unindent(),
 2114    );
 2115
 2116    cx.update_editor(|editor, window, cx| {
 2117        editor.move_to_start_of_paragraph(&MoveToStartOfParagraph, window, cx)
 2118    });
 2119    cx.assert_editor_state(
 2120        &r#"ˇone
 2121        two
 2122
 2123        three
 2124        four
 2125        five
 2126
 2127        six"#
 2128            .unindent(),
 2129    );
 2130}
 2131
 2132#[gpui::test]
 2133async fn test_scroll_page_up_page_down(cx: &mut TestAppContext) {
 2134    init_test(cx, |_| {});
 2135    let mut cx = EditorTestContext::new(cx).await;
 2136    let line_height = cx.editor(|editor, window, _| {
 2137        editor
 2138            .style()
 2139            .unwrap()
 2140            .text
 2141            .line_height_in_pixels(window.rem_size())
 2142    });
 2143    let window = cx.window;
 2144    cx.simulate_window_resize(window, size(px(1000.), 4. * line_height + px(0.5)));
 2145
 2146    cx.set_state(
 2147        r#"ˇone
 2148        two
 2149        three
 2150        four
 2151        five
 2152        six
 2153        seven
 2154        eight
 2155        nine
 2156        ten
 2157        "#,
 2158    );
 2159
 2160    cx.update_editor(|editor, window, cx| {
 2161        assert_eq!(
 2162            editor.snapshot(window, cx).scroll_position(),
 2163            gpui::Point::new(0., 0.)
 2164        );
 2165        editor.scroll_screen(&ScrollAmount::Page(1.), window, cx);
 2166        assert_eq!(
 2167            editor.snapshot(window, cx).scroll_position(),
 2168            gpui::Point::new(0., 3.)
 2169        );
 2170        editor.scroll_screen(&ScrollAmount::Page(1.), window, cx);
 2171        assert_eq!(
 2172            editor.snapshot(window, cx).scroll_position(),
 2173            gpui::Point::new(0., 6.)
 2174        );
 2175        editor.scroll_screen(&ScrollAmount::Page(-1.), window, cx);
 2176        assert_eq!(
 2177            editor.snapshot(window, cx).scroll_position(),
 2178            gpui::Point::new(0., 3.)
 2179        );
 2180
 2181        editor.scroll_screen(&ScrollAmount::Page(-0.5), window, cx);
 2182        assert_eq!(
 2183            editor.snapshot(window, cx).scroll_position(),
 2184            gpui::Point::new(0., 1.)
 2185        );
 2186        editor.scroll_screen(&ScrollAmount::Page(0.5), window, cx);
 2187        assert_eq!(
 2188            editor.snapshot(window, cx).scroll_position(),
 2189            gpui::Point::new(0., 3.)
 2190        );
 2191    });
 2192}
 2193
 2194#[gpui::test]
 2195async fn test_autoscroll(cx: &mut TestAppContext) {
 2196    init_test(cx, |_| {});
 2197    let mut cx = EditorTestContext::new(cx).await;
 2198
 2199    let line_height = cx.update_editor(|editor, window, cx| {
 2200        editor.set_vertical_scroll_margin(2, cx);
 2201        editor
 2202            .style()
 2203            .unwrap()
 2204            .text
 2205            .line_height_in_pixels(window.rem_size())
 2206    });
 2207    let window = cx.window;
 2208    cx.simulate_window_resize(window, size(px(1000.), 6. * line_height));
 2209
 2210    cx.set_state(
 2211        r#"ˇone
 2212            two
 2213            three
 2214            four
 2215            five
 2216            six
 2217            seven
 2218            eight
 2219            nine
 2220            ten
 2221        "#,
 2222    );
 2223    cx.update_editor(|editor, window, cx| {
 2224        assert_eq!(
 2225            editor.snapshot(window, cx).scroll_position(),
 2226            gpui::Point::new(0., 0.0)
 2227        );
 2228    });
 2229
 2230    // Add a cursor below the visible area. Since both cursors cannot fit
 2231    // on screen, the editor autoscrolls to reveal the newest cursor, and
 2232    // allows the vertical scroll margin below that cursor.
 2233    cx.update_editor(|editor, window, cx| {
 2234        editor.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 2235            selections.select_ranges([
 2236                Point::new(0, 0)..Point::new(0, 0),
 2237                Point::new(6, 0)..Point::new(6, 0),
 2238            ]);
 2239        })
 2240    });
 2241    cx.update_editor(|editor, window, cx| {
 2242        assert_eq!(
 2243            editor.snapshot(window, cx).scroll_position(),
 2244            gpui::Point::new(0., 3.0)
 2245        );
 2246    });
 2247
 2248    // Move down. The editor cursor scrolls down to track the newest cursor.
 2249    cx.update_editor(|editor, window, cx| {
 2250        editor.move_down(&Default::default(), window, cx);
 2251    });
 2252    cx.update_editor(|editor, window, cx| {
 2253        assert_eq!(
 2254            editor.snapshot(window, cx).scroll_position(),
 2255            gpui::Point::new(0., 4.0)
 2256        );
 2257    });
 2258
 2259    // Add a cursor above the visible area. Since both cursors fit on screen,
 2260    // the editor scrolls to show both.
 2261    cx.update_editor(|editor, window, cx| {
 2262        editor.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 2263            selections.select_ranges([
 2264                Point::new(1, 0)..Point::new(1, 0),
 2265                Point::new(6, 0)..Point::new(6, 0),
 2266            ]);
 2267        })
 2268    });
 2269    cx.update_editor(|editor, window, cx| {
 2270        assert_eq!(
 2271            editor.snapshot(window, cx).scroll_position(),
 2272            gpui::Point::new(0., 1.0)
 2273        );
 2274    });
 2275}
 2276
 2277#[gpui::test]
 2278async fn test_move_page_up_page_down(cx: &mut TestAppContext) {
 2279    init_test(cx, |_| {});
 2280    let mut cx = EditorTestContext::new(cx).await;
 2281
 2282    let line_height = cx.editor(|editor, window, _cx| {
 2283        editor
 2284            .style()
 2285            .unwrap()
 2286            .text
 2287            .line_height_in_pixels(window.rem_size())
 2288    });
 2289    let window = cx.window;
 2290    cx.simulate_window_resize(window, size(px(100.), 4. * line_height));
 2291    cx.set_state(
 2292        &r#"
 2293        ˇone
 2294        two
 2295        threeˇ
 2296        four
 2297        five
 2298        six
 2299        seven
 2300        eight
 2301        nine
 2302        ten
 2303        "#
 2304        .unindent(),
 2305    );
 2306
 2307    cx.update_editor(|editor, window, cx| {
 2308        editor.move_page_down(&MovePageDown::default(), window, cx)
 2309    });
 2310    cx.assert_editor_state(
 2311        &r#"
 2312        one
 2313        two
 2314        three
 2315        ˇfour
 2316        five
 2317        sixˇ
 2318        seven
 2319        eight
 2320        nine
 2321        ten
 2322        "#
 2323        .unindent(),
 2324    );
 2325
 2326    cx.update_editor(|editor, window, cx| {
 2327        editor.move_page_down(&MovePageDown::default(), window, cx)
 2328    });
 2329    cx.assert_editor_state(
 2330        &r#"
 2331        one
 2332        two
 2333        three
 2334        four
 2335        five
 2336        six
 2337        ˇseven
 2338        eight
 2339        nineˇ
 2340        ten
 2341        "#
 2342        .unindent(),
 2343    );
 2344
 2345    cx.update_editor(|editor, window, cx| editor.move_page_up(&MovePageUp::default(), window, cx));
 2346    cx.assert_editor_state(
 2347        &r#"
 2348        one
 2349        two
 2350        three
 2351        ˇfour
 2352        five
 2353        sixˇ
 2354        seven
 2355        eight
 2356        nine
 2357        ten
 2358        "#
 2359        .unindent(),
 2360    );
 2361
 2362    cx.update_editor(|editor, window, cx| editor.move_page_up(&MovePageUp::default(), window, cx));
 2363    cx.assert_editor_state(
 2364        &r#"
 2365        ˇone
 2366        two
 2367        threeˇ
 2368        four
 2369        five
 2370        six
 2371        seven
 2372        eight
 2373        nine
 2374        ten
 2375        "#
 2376        .unindent(),
 2377    );
 2378
 2379    // Test select collapsing
 2380    cx.update_editor(|editor, window, cx| {
 2381        editor.move_page_down(&MovePageDown::default(), window, cx);
 2382        editor.move_page_down(&MovePageDown::default(), window, cx);
 2383        editor.move_page_down(&MovePageDown::default(), window, cx);
 2384    });
 2385    cx.assert_editor_state(
 2386        &r#"
 2387        one
 2388        two
 2389        three
 2390        four
 2391        five
 2392        six
 2393        seven
 2394        eight
 2395        nine
 2396        ˇten
 2397        ˇ"#
 2398        .unindent(),
 2399    );
 2400}
 2401
 2402#[gpui::test]
 2403async fn test_delete_to_beginning_of_line(cx: &mut TestAppContext) {
 2404    init_test(cx, |_| {});
 2405    let mut cx = EditorTestContext::new(cx).await;
 2406    cx.set_state("one «two threeˇ» four");
 2407    cx.update_editor(|editor, window, cx| {
 2408        editor.delete_to_beginning_of_line(
 2409            &DeleteToBeginningOfLine {
 2410                stop_at_indent: false,
 2411            },
 2412            window,
 2413            cx,
 2414        );
 2415        assert_eq!(editor.text(cx), " four");
 2416    });
 2417}
 2418
 2419#[gpui::test]
 2420fn test_delete_to_word_boundary(cx: &mut TestAppContext) {
 2421    init_test(cx, |_| {});
 2422
 2423    let editor = cx.add_window(|window, cx| {
 2424        let buffer = MultiBuffer::build_simple("one two three four", cx);
 2425        build_editor(buffer.clone(), window, cx)
 2426    });
 2427
 2428    _ = editor.update(cx, |editor, window, cx| {
 2429        editor.change_selections(None, window, cx, |s| {
 2430            s.select_display_ranges([
 2431                // an empty selection - the preceding word fragment is deleted
 2432                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 2),
 2433                // characters selected - they are deleted
 2434                DisplayPoint::new(DisplayRow(0), 9)..DisplayPoint::new(DisplayRow(0), 12),
 2435            ])
 2436        });
 2437        editor.delete_to_previous_word_start(
 2438            &DeleteToPreviousWordStart {
 2439                ignore_newlines: false,
 2440            },
 2441            window,
 2442            cx,
 2443        );
 2444        assert_eq!(editor.buffer.read(cx).read(cx).text(), "e two te four");
 2445    });
 2446
 2447    _ = editor.update(cx, |editor, window, cx| {
 2448        editor.change_selections(None, window, cx, |s| {
 2449            s.select_display_ranges([
 2450                // an empty selection - the following word fragment is deleted
 2451                DisplayPoint::new(DisplayRow(0), 3)..DisplayPoint::new(DisplayRow(0), 3),
 2452                // characters selected - they are deleted
 2453                DisplayPoint::new(DisplayRow(0), 9)..DisplayPoint::new(DisplayRow(0), 10),
 2454            ])
 2455        });
 2456        editor.delete_to_next_word_end(
 2457            &DeleteToNextWordEnd {
 2458                ignore_newlines: false,
 2459            },
 2460            window,
 2461            cx,
 2462        );
 2463        assert_eq!(editor.buffer.read(cx).read(cx).text(), "e t te our");
 2464    });
 2465}
 2466
 2467#[gpui::test]
 2468fn test_delete_to_previous_word_start_or_newline(cx: &mut TestAppContext) {
 2469    init_test(cx, |_| {});
 2470
 2471    let editor = cx.add_window(|window, cx| {
 2472        let buffer = MultiBuffer::build_simple("one\n2\nthree\n4", cx);
 2473        build_editor(buffer.clone(), window, cx)
 2474    });
 2475    let del_to_prev_word_start = DeleteToPreviousWordStart {
 2476        ignore_newlines: false,
 2477    };
 2478    let del_to_prev_word_start_ignore_newlines = DeleteToPreviousWordStart {
 2479        ignore_newlines: true,
 2480    };
 2481
 2482    _ = editor.update(cx, |editor, window, cx| {
 2483        editor.change_selections(None, window, cx, |s| {
 2484            s.select_display_ranges([
 2485                DisplayPoint::new(DisplayRow(3), 1)..DisplayPoint::new(DisplayRow(3), 1)
 2486            ])
 2487        });
 2488        editor.delete_to_previous_word_start(&del_to_prev_word_start, window, cx);
 2489        assert_eq!(editor.buffer.read(cx).read(cx).text(), "one\n2\nthree\n");
 2490        editor.delete_to_previous_word_start(&del_to_prev_word_start, window, cx);
 2491        assert_eq!(editor.buffer.read(cx).read(cx).text(), "one\n2\nthree");
 2492        editor.delete_to_previous_word_start(&del_to_prev_word_start, window, cx);
 2493        assert_eq!(editor.buffer.read(cx).read(cx).text(), "one\n2\n");
 2494        editor.delete_to_previous_word_start(&del_to_prev_word_start, window, cx);
 2495        assert_eq!(editor.buffer.read(cx).read(cx).text(), "one\n2");
 2496        editor.delete_to_previous_word_start(&del_to_prev_word_start_ignore_newlines, window, cx);
 2497        assert_eq!(editor.buffer.read(cx).read(cx).text(), "one\n");
 2498        editor.delete_to_previous_word_start(&del_to_prev_word_start_ignore_newlines, window, cx);
 2499        assert_eq!(editor.buffer.read(cx).read(cx).text(), "");
 2500    });
 2501}
 2502
 2503#[gpui::test]
 2504fn test_delete_to_next_word_end_or_newline(cx: &mut TestAppContext) {
 2505    init_test(cx, |_| {});
 2506
 2507    let editor = cx.add_window(|window, cx| {
 2508        let buffer = MultiBuffer::build_simple("\none\n   two\nthree\n   four", cx);
 2509        build_editor(buffer.clone(), window, cx)
 2510    });
 2511    let del_to_next_word_end = DeleteToNextWordEnd {
 2512        ignore_newlines: false,
 2513    };
 2514    let del_to_next_word_end_ignore_newlines = DeleteToNextWordEnd {
 2515        ignore_newlines: true,
 2516    };
 2517
 2518    _ = editor.update(cx, |editor, window, cx| {
 2519        editor.change_selections(None, window, cx, |s| {
 2520            s.select_display_ranges([
 2521                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0)
 2522            ])
 2523        });
 2524        editor.delete_to_next_word_end(&del_to_next_word_end, window, cx);
 2525        assert_eq!(
 2526            editor.buffer.read(cx).read(cx).text(),
 2527            "one\n   two\nthree\n   four"
 2528        );
 2529        editor.delete_to_next_word_end(&del_to_next_word_end, window, cx);
 2530        assert_eq!(
 2531            editor.buffer.read(cx).read(cx).text(),
 2532            "\n   two\nthree\n   four"
 2533        );
 2534        editor.delete_to_next_word_end(&del_to_next_word_end, window, cx);
 2535        assert_eq!(
 2536            editor.buffer.read(cx).read(cx).text(),
 2537            "two\nthree\n   four"
 2538        );
 2539        editor.delete_to_next_word_end(&del_to_next_word_end, window, cx);
 2540        assert_eq!(editor.buffer.read(cx).read(cx).text(), "\nthree\n   four");
 2541        editor.delete_to_next_word_end(&del_to_next_word_end_ignore_newlines, window, cx);
 2542        assert_eq!(editor.buffer.read(cx).read(cx).text(), "\n   four");
 2543        editor.delete_to_next_word_end(&del_to_next_word_end_ignore_newlines, window, cx);
 2544        assert_eq!(editor.buffer.read(cx).read(cx).text(), "");
 2545    });
 2546}
 2547
 2548#[gpui::test]
 2549fn test_newline(cx: &mut TestAppContext) {
 2550    init_test(cx, |_| {});
 2551
 2552    let editor = cx.add_window(|window, cx| {
 2553        let buffer = MultiBuffer::build_simple("aaaa\n    bbbb\n", cx);
 2554        build_editor(buffer.clone(), window, cx)
 2555    });
 2556
 2557    _ = editor.update(cx, |editor, window, cx| {
 2558        editor.change_selections(None, window, cx, |s| {
 2559            s.select_display_ranges([
 2560                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 2),
 2561                DisplayPoint::new(DisplayRow(1), 2)..DisplayPoint::new(DisplayRow(1), 2),
 2562                DisplayPoint::new(DisplayRow(1), 6)..DisplayPoint::new(DisplayRow(1), 6),
 2563            ])
 2564        });
 2565
 2566        editor.newline(&Newline, window, cx);
 2567        assert_eq!(editor.text(cx), "aa\naa\n  \n    bb\n    bb\n");
 2568    });
 2569}
 2570
 2571#[gpui::test]
 2572fn test_newline_with_old_selections(cx: &mut TestAppContext) {
 2573    init_test(cx, |_| {});
 2574
 2575    let editor = cx.add_window(|window, cx| {
 2576        let buffer = MultiBuffer::build_simple(
 2577            "
 2578                a
 2579                b(
 2580                    X
 2581                )
 2582                c(
 2583                    X
 2584                )
 2585            "
 2586            .unindent()
 2587            .as_str(),
 2588            cx,
 2589        );
 2590        let mut editor = build_editor(buffer.clone(), window, cx);
 2591        editor.change_selections(None, window, cx, |s| {
 2592            s.select_ranges([
 2593                Point::new(2, 4)..Point::new(2, 5),
 2594                Point::new(5, 4)..Point::new(5, 5),
 2595            ])
 2596        });
 2597        editor
 2598    });
 2599
 2600    _ = editor.update(cx, |editor, window, cx| {
 2601        // Edit the buffer directly, deleting ranges surrounding the editor's selections
 2602        editor.buffer.update(cx, |buffer, cx| {
 2603            buffer.edit(
 2604                [
 2605                    (Point::new(1, 2)..Point::new(3, 0), ""),
 2606                    (Point::new(4, 2)..Point::new(6, 0), ""),
 2607                ],
 2608                None,
 2609                cx,
 2610            );
 2611            assert_eq!(
 2612                buffer.read(cx).text(),
 2613                "
 2614                    a
 2615                    b()
 2616                    c()
 2617                "
 2618                .unindent()
 2619            );
 2620        });
 2621        assert_eq!(
 2622            editor.selections.ranges(cx),
 2623            &[
 2624                Point::new(1, 2)..Point::new(1, 2),
 2625                Point::new(2, 2)..Point::new(2, 2),
 2626            ],
 2627        );
 2628
 2629        editor.newline(&Newline, window, cx);
 2630        assert_eq!(
 2631            editor.text(cx),
 2632            "
 2633                a
 2634                b(
 2635                )
 2636                c(
 2637                )
 2638            "
 2639            .unindent()
 2640        );
 2641
 2642        // The selections are moved after the inserted newlines
 2643        assert_eq!(
 2644            editor.selections.ranges(cx),
 2645            &[
 2646                Point::new(2, 0)..Point::new(2, 0),
 2647                Point::new(4, 0)..Point::new(4, 0),
 2648            ],
 2649        );
 2650    });
 2651}
 2652
 2653#[gpui::test]
 2654async fn test_newline_above(cx: &mut TestAppContext) {
 2655    init_test(cx, |settings| {
 2656        settings.defaults.tab_size = NonZeroU32::new(4)
 2657    });
 2658
 2659    let language = Arc::new(
 2660        Language::new(
 2661            LanguageConfig::default(),
 2662            Some(tree_sitter_rust::LANGUAGE.into()),
 2663        )
 2664        .with_indents_query(r#"(_ "(" ")" @end) @indent"#)
 2665        .unwrap(),
 2666    );
 2667
 2668    let mut cx = EditorTestContext::new(cx).await;
 2669    cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
 2670    cx.set_state(indoc! {"
 2671        const a: ˇA = (
 2672 2673                «const_functionˇ»(ˇ),
 2674                so«mˇ»et«hˇ»ing_ˇelse,ˇ
 2675 2676        ˇ);ˇ
 2677    "});
 2678
 2679    cx.update_editor(|e, window, cx| e.newline_above(&NewlineAbove, window, cx));
 2680    cx.assert_editor_state(indoc! {"
 2681        ˇ
 2682        const a: A = (
 2683            ˇ
 2684            (
 2685                ˇ
 2686                ˇ
 2687                const_function(),
 2688                ˇ
 2689                ˇ
 2690                ˇ
 2691                ˇ
 2692                something_else,
 2693                ˇ
 2694            )
 2695            ˇ
 2696            ˇ
 2697        );
 2698    "});
 2699}
 2700
 2701#[gpui::test]
 2702async fn test_newline_below(cx: &mut TestAppContext) {
 2703    init_test(cx, |settings| {
 2704        settings.defaults.tab_size = NonZeroU32::new(4)
 2705    });
 2706
 2707    let language = Arc::new(
 2708        Language::new(
 2709            LanguageConfig::default(),
 2710            Some(tree_sitter_rust::LANGUAGE.into()),
 2711        )
 2712        .with_indents_query(r#"(_ "(" ")" @end) @indent"#)
 2713        .unwrap(),
 2714    );
 2715
 2716    let mut cx = EditorTestContext::new(cx).await;
 2717    cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
 2718    cx.set_state(indoc! {"
 2719        const a: ˇA = (
 2720 2721                «const_functionˇ»(ˇ),
 2722                so«mˇ»et«hˇ»ing_ˇelse,ˇ
 2723 2724        ˇ);ˇ
 2725    "});
 2726
 2727    cx.update_editor(|e, window, cx| e.newline_below(&NewlineBelow, window, cx));
 2728    cx.assert_editor_state(indoc! {"
 2729        const a: A = (
 2730            ˇ
 2731            (
 2732                ˇ
 2733                const_function(),
 2734                ˇ
 2735                ˇ
 2736                something_else,
 2737                ˇ
 2738                ˇ
 2739                ˇ
 2740                ˇ
 2741            )
 2742            ˇ
 2743        );
 2744        ˇ
 2745        ˇ
 2746    "});
 2747}
 2748
 2749#[gpui::test]
 2750async fn test_newline_comments(cx: &mut TestAppContext) {
 2751    init_test(cx, |settings| {
 2752        settings.defaults.tab_size = NonZeroU32::new(4)
 2753    });
 2754
 2755    let language = Arc::new(Language::new(
 2756        LanguageConfig {
 2757            line_comments: vec!["//".into()],
 2758            ..LanguageConfig::default()
 2759        },
 2760        None,
 2761    ));
 2762    {
 2763        let mut cx = EditorTestContext::new(cx).await;
 2764        cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
 2765        cx.set_state(indoc! {"
 2766        // Fooˇ
 2767    "});
 2768
 2769        cx.update_editor(|e, window, cx| e.newline(&Newline, window, cx));
 2770        cx.assert_editor_state(indoc! {"
 2771        // Foo
 2772        //ˇ
 2773    "});
 2774        // Ensure that if cursor is before the comment start, we do not actually insert a comment prefix.
 2775        cx.set_state(indoc! {"
 2776        ˇ// Foo
 2777    "});
 2778        cx.update_editor(|e, window, cx| e.newline(&Newline, window, cx));
 2779        cx.assert_editor_state(indoc! {"
 2780
 2781        ˇ// Foo
 2782    "});
 2783    }
 2784    // Ensure that comment continuations can be disabled.
 2785    update_test_language_settings(cx, |settings| {
 2786        settings.defaults.extend_comment_on_newline = Some(false);
 2787    });
 2788    let mut cx = EditorTestContext::new(cx).await;
 2789    cx.set_state(indoc! {"
 2790        // Fooˇ
 2791    "});
 2792    cx.update_editor(|e, window, cx| e.newline(&Newline, window, cx));
 2793    cx.assert_editor_state(indoc! {"
 2794        // Foo
 2795        ˇ
 2796    "});
 2797}
 2798
 2799#[gpui::test]
 2800fn test_insert_with_old_selections(cx: &mut TestAppContext) {
 2801    init_test(cx, |_| {});
 2802
 2803    let editor = cx.add_window(|window, cx| {
 2804        let buffer = MultiBuffer::build_simple("a( X ), b( Y ), c( Z )", cx);
 2805        let mut editor = build_editor(buffer.clone(), window, cx);
 2806        editor.change_selections(None, window, cx, |s| {
 2807            s.select_ranges([3..4, 11..12, 19..20])
 2808        });
 2809        editor
 2810    });
 2811
 2812    _ = editor.update(cx, |editor, window, cx| {
 2813        // Edit the buffer directly, deleting ranges surrounding the editor's selections
 2814        editor.buffer.update(cx, |buffer, cx| {
 2815            buffer.edit([(2..5, ""), (10..13, ""), (18..21, "")], None, cx);
 2816            assert_eq!(buffer.read(cx).text(), "a(), b(), c()".unindent());
 2817        });
 2818        assert_eq!(editor.selections.ranges(cx), &[2..2, 7..7, 12..12],);
 2819
 2820        editor.insert("Z", window, cx);
 2821        assert_eq!(editor.text(cx), "a(Z), b(Z), c(Z)");
 2822
 2823        // The selections are moved after the inserted characters
 2824        assert_eq!(editor.selections.ranges(cx), &[3..3, 9..9, 15..15],);
 2825    });
 2826}
 2827
 2828#[gpui::test]
 2829async fn test_tab(cx: &mut TestAppContext) {
 2830    init_test(cx, |settings| {
 2831        settings.defaults.tab_size = NonZeroU32::new(3)
 2832    });
 2833
 2834    let mut cx = EditorTestContext::new(cx).await;
 2835    cx.set_state(indoc! {"
 2836        ˇabˇc
 2837        ˇ🏀ˇ🏀ˇefg
 2838 2839    "});
 2840    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 2841    cx.assert_editor_state(indoc! {"
 2842           ˇab ˇc
 2843           ˇ🏀  ˇ🏀  ˇefg
 2844        d  ˇ
 2845    "});
 2846
 2847    cx.set_state(indoc! {"
 2848        a
 2849        «🏀ˇ»🏀«🏀ˇ»🏀«🏀ˇ»
 2850    "});
 2851    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 2852    cx.assert_editor_state(indoc! {"
 2853        a
 2854           «🏀ˇ»🏀«🏀ˇ»🏀«🏀ˇ»
 2855    "});
 2856}
 2857
 2858#[gpui::test]
 2859async fn test_tab_in_leading_whitespace_auto_indents_lines(cx: &mut TestAppContext) {
 2860    init_test(cx, |_| {});
 2861
 2862    let mut cx = EditorTestContext::new(cx).await;
 2863    let language = Arc::new(
 2864        Language::new(
 2865            LanguageConfig::default(),
 2866            Some(tree_sitter_rust::LANGUAGE.into()),
 2867        )
 2868        .with_indents_query(r#"(_ "(" ")" @end) @indent"#)
 2869        .unwrap(),
 2870    );
 2871    cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
 2872
 2873    // cursors that are already at the suggested indent level insert
 2874    // a soft tab. cursors that are to the left of the suggested indent
 2875    // auto-indent their line.
 2876    cx.set_state(indoc! {"
 2877        ˇ
 2878        const a: B = (
 2879            c(
 2880                d(
 2881        ˇ
 2882                )
 2883        ˇ
 2884        ˇ    )
 2885        );
 2886    "});
 2887    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 2888    cx.assert_editor_state(indoc! {"
 2889            ˇ
 2890        const a: B = (
 2891            c(
 2892                d(
 2893                    ˇ
 2894                )
 2895                ˇ
 2896            ˇ)
 2897        );
 2898    "});
 2899
 2900    // handle auto-indent when there are multiple cursors on the same line
 2901    cx.set_state(indoc! {"
 2902        const a: B = (
 2903            c(
 2904        ˇ    ˇ
 2905        ˇ    )
 2906        );
 2907    "});
 2908    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 2909    cx.assert_editor_state(indoc! {"
 2910        const a: B = (
 2911            c(
 2912                ˇ
 2913            ˇ)
 2914        );
 2915    "});
 2916}
 2917
 2918#[gpui::test]
 2919async fn test_tab_with_mixed_whitespace_txt(cx: &mut TestAppContext) {
 2920    init_test(cx, |settings| {
 2921        settings.defaults.tab_size = NonZeroU32::new(3)
 2922    });
 2923
 2924    let mut cx = EditorTestContext::new(cx).await;
 2925    cx.set_state(indoc! {"
 2926         ˇ
 2927        \t ˇ
 2928        \t  ˇ
 2929        \t   ˇ
 2930         \t  \t\t \t      \t\t   \t\t    \t \t ˇ
 2931    "});
 2932
 2933    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 2934    cx.assert_editor_state(indoc! {"
 2935           ˇ
 2936        \t   ˇ
 2937        \t   ˇ
 2938        \t      ˇ
 2939         \t  \t\t \t      \t\t   \t\t    \t \t   ˇ
 2940    "});
 2941}
 2942
 2943#[gpui::test]
 2944async fn test_tab_with_mixed_whitespace_rust(cx: &mut TestAppContext) {
 2945    init_test(cx, |settings| {
 2946        settings.defaults.tab_size = NonZeroU32::new(4)
 2947    });
 2948
 2949    let language = Arc::new(
 2950        Language::new(
 2951            LanguageConfig::default(),
 2952            Some(tree_sitter_rust::LANGUAGE.into()),
 2953        )
 2954        .with_indents_query(r#"(_ "{" "}" @end) @indent"#)
 2955        .unwrap(),
 2956    );
 2957
 2958    let mut cx = EditorTestContext::new(cx).await;
 2959    cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
 2960    cx.set_state(indoc! {"
 2961        fn a() {
 2962            if b {
 2963        \t ˇc
 2964            }
 2965        }
 2966    "});
 2967
 2968    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 2969    cx.assert_editor_state(indoc! {"
 2970        fn a() {
 2971            if b {
 2972                ˇc
 2973            }
 2974        }
 2975    "});
 2976}
 2977
 2978#[gpui::test]
 2979async fn test_indent_outdent(cx: &mut TestAppContext) {
 2980    init_test(cx, |settings| {
 2981        settings.defaults.tab_size = NonZeroU32::new(4);
 2982    });
 2983
 2984    let mut cx = EditorTestContext::new(cx).await;
 2985
 2986    cx.set_state(indoc! {"
 2987          «oneˇ» «twoˇ»
 2988        three
 2989         four
 2990    "});
 2991    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 2992    cx.assert_editor_state(indoc! {"
 2993            «oneˇ» «twoˇ»
 2994        three
 2995         four
 2996    "});
 2997
 2998    cx.update_editor(|e, window, cx| e.backtab(&Backtab, window, cx));
 2999    cx.assert_editor_state(indoc! {"
 3000        «oneˇ» «twoˇ»
 3001        three
 3002         four
 3003    "});
 3004
 3005    // select across line ending
 3006    cx.set_state(indoc! {"
 3007        one two
 3008        t«hree
 3009        ˇ» four
 3010    "});
 3011    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 3012    cx.assert_editor_state(indoc! {"
 3013        one two
 3014            t«hree
 3015        ˇ» four
 3016    "});
 3017
 3018    cx.update_editor(|e, window, cx| e.backtab(&Backtab, window, cx));
 3019    cx.assert_editor_state(indoc! {"
 3020        one two
 3021        t«hree
 3022        ˇ» four
 3023    "});
 3024
 3025    // Ensure that indenting/outdenting works when the cursor is at column 0.
 3026    cx.set_state(indoc! {"
 3027        one two
 3028        ˇthree
 3029            four
 3030    "});
 3031    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 3032    cx.assert_editor_state(indoc! {"
 3033        one two
 3034            ˇthree
 3035            four
 3036    "});
 3037
 3038    cx.set_state(indoc! {"
 3039        one two
 3040        ˇ    three
 3041            four
 3042    "});
 3043    cx.update_editor(|e, window, cx| e.backtab(&Backtab, window, cx));
 3044    cx.assert_editor_state(indoc! {"
 3045        one two
 3046        ˇthree
 3047            four
 3048    "});
 3049}
 3050
 3051#[gpui::test]
 3052async fn test_indent_outdent_with_hard_tabs(cx: &mut TestAppContext) {
 3053    init_test(cx, |settings| {
 3054        settings.defaults.hard_tabs = Some(true);
 3055    });
 3056
 3057    let mut cx = EditorTestContext::new(cx).await;
 3058
 3059    // select two ranges on one line
 3060    cx.set_state(indoc! {"
 3061        «oneˇ» «twoˇ»
 3062        three
 3063        four
 3064    "});
 3065    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 3066    cx.assert_editor_state(indoc! {"
 3067        \t«oneˇ» «twoˇ»
 3068        three
 3069        four
 3070    "});
 3071    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 3072    cx.assert_editor_state(indoc! {"
 3073        \t\t«oneˇ» «twoˇ»
 3074        three
 3075        four
 3076    "});
 3077    cx.update_editor(|e, window, cx| e.backtab(&Backtab, window, cx));
 3078    cx.assert_editor_state(indoc! {"
 3079        \t«oneˇ» «twoˇ»
 3080        three
 3081        four
 3082    "});
 3083    cx.update_editor(|e, window, cx| e.backtab(&Backtab, window, cx));
 3084    cx.assert_editor_state(indoc! {"
 3085        «oneˇ» «twoˇ»
 3086        three
 3087        four
 3088    "});
 3089
 3090    // select across a line ending
 3091    cx.set_state(indoc! {"
 3092        one two
 3093        t«hree
 3094        ˇ»four
 3095    "});
 3096    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 3097    cx.assert_editor_state(indoc! {"
 3098        one two
 3099        \tt«hree
 3100        ˇ»four
 3101    "});
 3102    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 3103    cx.assert_editor_state(indoc! {"
 3104        one two
 3105        \t\tt«hree
 3106        ˇ»four
 3107    "});
 3108    cx.update_editor(|e, window, cx| e.backtab(&Backtab, window, cx));
 3109    cx.assert_editor_state(indoc! {"
 3110        one two
 3111        \tt«hree
 3112        ˇ»four
 3113    "});
 3114    cx.update_editor(|e, window, cx| e.backtab(&Backtab, window, cx));
 3115    cx.assert_editor_state(indoc! {"
 3116        one two
 3117        t«hree
 3118        ˇ»four
 3119    "});
 3120
 3121    // Ensure that indenting/outdenting works when the cursor is at column 0.
 3122    cx.set_state(indoc! {"
 3123        one two
 3124        ˇthree
 3125        four
 3126    "});
 3127    cx.update_editor(|e, window, cx| e.backtab(&Backtab, window, cx));
 3128    cx.assert_editor_state(indoc! {"
 3129        one two
 3130        ˇthree
 3131        four
 3132    "});
 3133    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 3134    cx.assert_editor_state(indoc! {"
 3135        one two
 3136        \tˇthree
 3137        four
 3138    "});
 3139    cx.update_editor(|e, window, cx| e.backtab(&Backtab, window, cx));
 3140    cx.assert_editor_state(indoc! {"
 3141        one two
 3142        ˇthree
 3143        four
 3144    "});
 3145}
 3146
 3147#[gpui::test]
 3148fn test_indent_outdent_with_excerpts(cx: &mut TestAppContext) {
 3149    init_test(cx, |settings| {
 3150        settings.languages.extend([
 3151            (
 3152                "TOML".into(),
 3153                LanguageSettingsContent {
 3154                    tab_size: NonZeroU32::new(2),
 3155                    ..Default::default()
 3156                },
 3157            ),
 3158            (
 3159                "Rust".into(),
 3160                LanguageSettingsContent {
 3161                    tab_size: NonZeroU32::new(4),
 3162                    ..Default::default()
 3163                },
 3164            ),
 3165        ]);
 3166    });
 3167
 3168    let toml_language = Arc::new(Language::new(
 3169        LanguageConfig {
 3170            name: "TOML".into(),
 3171            ..Default::default()
 3172        },
 3173        None,
 3174    ));
 3175    let rust_language = Arc::new(Language::new(
 3176        LanguageConfig {
 3177            name: "Rust".into(),
 3178            ..Default::default()
 3179        },
 3180        None,
 3181    ));
 3182
 3183    let toml_buffer =
 3184        cx.new(|cx| Buffer::local("a = 1\nb = 2\n", cx).with_language(toml_language, cx));
 3185    let rust_buffer =
 3186        cx.new(|cx| Buffer::local("const c: usize = 3;\n", cx).with_language(rust_language, cx));
 3187    let multibuffer = cx.new(|cx| {
 3188        let mut multibuffer = MultiBuffer::new(ReadWrite);
 3189        multibuffer.push_excerpts(
 3190            toml_buffer.clone(),
 3191            [ExcerptRange::new(Point::new(0, 0)..Point::new(2, 0))],
 3192            cx,
 3193        );
 3194        multibuffer.push_excerpts(
 3195            rust_buffer.clone(),
 3196            [ExcerptRange::new(Point::new(0, 0)..Point::new(1, 0))],
 3197            cx,
 3198        );
 3199        multibuffer
 3200    });
 3201
 3202    cx.add_window(|window, cx| {
 3203        let mut editor = build_editor(multibuffer, window, cx);
 3204
 3205        assert_eq!(
 3206            editor.text(cx),
 3207            indoc! {"
 3208                a = 1
 3209                b = 2
 3210
 3211                const c: usize = 3;
 3212            "}
 3213        );
 3214
 3215        select_ranges(
 3216            &mut editor,
 3217            indoc! {"
 3218                «aˇ» = 1
 3219                b = 2
 3220
 3221                «const c:ˇ» usize = 3;
 3222            "},
 3223            window,
 3224            cx,
 3225        );
 3226
 3227        editor.tab(&Tab, window, cx);
 3228        assert_text_with_selections(
 3229            &mut editor,
 3230            indoc! {"
 3231                  «aˇ» = 1
 3232                b = 2
 3233
 3234                    «const c:ˇ» usize = 3;
 3235            "},
 3236            cx,
 3237        );
 3238        editor.backtab(&Backtab, window, cx);
 3239        assert_text_with_selections(
 3240            &mut editor,
 3241            indoc! {"
 3242                «aˇ» = 1
 3243                b = 2
 3244
 3245                «const c:ˇ» usize = 3;
 3246            "},
 3247            cx,
 3248        );
 3249
 3250        editor
 3251    });
 3252}
 3253
 3254#[gpui::test]
 3255async fn test_backspace(cx: &mut TestAppContext) {
 3256    init_test(cx, |_| {});
 3257
 3258    let mut cx = EditorTestContext::new(cx).await;
 3259
 3260    // Basic backspace
 3261    cx.set_state(indoc! {"
 3262        onˇe two three
 3263        fou«rˇ» five six
 3264        seven «ˇeight nine
 3265        »ten
 3266    "});
 3267    cx.update_editor(|e, window, cx| e.backspace(&Backspace, window, cx));
 3268    cx.assert_editor_state(indoc! {"
 3269        oˇe two three
 3270        fouˇ five six
 3271        seven ˇten
 3272    "});
 3273
 3274    // Test backspace inside and around indents
 3275    cx.set_state(indoc! {"
 3276        zero
 3277            ˇone
 3278                ˇtwo
 3279            ˇ ˇ ˇ  three
 3280        ˇ  ˇ  four
 3281    "});
 3282    cx.update_editor(|e, window, cx| e.backspace(&Backspace, window, cx));
 3283    cx.assert_editor_state(indoc! {"
 3284        zero
 3285        ˇone
 3286            ˇtwo
 3287        ˇ  threeˇ  four
 3288    "});
 3289}
 3290
 3291#[gpui::test]
 3292async fn test_delete(cx: &mut TestAppContext) {
 3293    init_test(cx, |_| {});
 3294
 3295    let mut cx = EditorTestContext::new(cx).await;
 3296    cx.set_state(indoc! {"
 3297        onˇe two three
 3298        fou«rˇ» five six
 3299        seven «ˇeight nine
 3300        »ten
 3301    "});
 3302    cx.update_editor(|e, window, cx| e.delete(&Delete, window, cx));
 3303    cx.assert_editor_state(indoc! {"
 3304        onˇ two three
 3305        fouˇ five six
 3306        seven ˇten
 3307    "});
 3308}
 3309
 3310#[gpui::test]
 3311fn test_delete_line(cx: &mut TestAppContext) {
 3312    init_test(cx, |_| {});
 3313
 3314    let editor = cx.add_window(|window, cx| {
 3315        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
 3316        build_editor(buffer, window, cx)
 3317    });
 3318    _ = editor.update(cx, |editor, window, cx| {
 3319        editor.change_selections(None, window, cx, |s| {
 3320            s.select_display_ranges([
 3321                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 1),
 3322                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 1),
 3323                DisplayPoint::new(DisplayRow(3), 0)..DisplayPoint::new(DisplayRow(3), 0),
 3324            ])
 3325        });
 3326        editor.delete_line(&DeleteLine, window, cx);
 3327        assert_eq!(editor.display_text(cx), "ghi");
 3328        assert_eq!(
 3329            editor.selections.display_ranges(cx),
 3330            vec![
 3331                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0),
 3332                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 1)
 3333            ]
 3334        );
 3335    });
 3336
 3337    let editor = cx.add_window(|window, cx| {
 3338        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
 3339        build_editor(buffer, window, cx)
 3340    });
 3341    _ = editor.update(cx, |editor, window, cx| {
 3342        editor.change_selections(None, window, cx, |s| {
 3343            s.select_display_ranges([
 3344                DisplayPoint::new(DisplayRow(2), 0)..DisplayPoint::new(DisplayRow(0), 1)
 3345            ])
 3346        });
 3347        editor.delete_line(&DeleteLine, window, cx);
 3348        assert_eq!(editor.display_text(cx), "ghi\n");
 3349        assert_eq!(
 3350            editor.selections.display_ranges(cx),
 3351            vec![DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 1)]
 3352        );
 3353    });
 3354}
 3355
 3356#[gpui::test]
 3357fn test_join_lines_with_single_selection(cx: &mut TestAppContext) {
 3358    init_test(cx, |_| {});
 3359
 3360    cx.add_window(|window, cx| {
 3361        let buffer = MultiBuffer::build_simple("aaa\nbbb\nccc\nddd\n\n", cx);
 3362        let mut editor = build_editor(buffer.clone(), window, cx);
 3363        let buffer = buffer.read(cx).as_singleton().unwrap();
 3364
 3365        assert_eq!(
 3366            editor.selections.ranges::<Point>(cx),
 3367            &[Point::new(0, 0)..Point::new(0, 0)]
 3368        );
 3369
 3370        // When on single line, replace newline at end by space
 3371        editor.join_lines(&JoinLines, window, cx);
 3372        assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd\n\n");
 3373        assert_eq!(
 3374            editor.selections.ranges::<Point>(cx),
 3375            &[Point::new(0, 3)..Point::new(0, 3)]
 3376        );
 3377
 3378        // When multiple lines are selected, remove newlines that are spanned by the selection
 3379        editor.change_selections(None, window, cx, |s| {
 3380            s.select_ranges([Point::new(0, 5)..Point::new(2, 2)])
 3381        });
 3382        editor.join_lines(&JoinLines, window, cx);
 3383        assert_eq!(buffer.read(cx).text(), "aaa bbb ccc ddd\n\n");
 3384        assert_eq!(
 3385            editor.selections.ranges::<Point>(cx),
 3386            &[Point::new(0, 11)..Point::new(0, 11)]
 3387        );
 3388
 3389        // Undo should be transactional
 3390        editor.undo(&Undo, window, cx);
 3391        assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd\n\n");
 3392        assert_eq!(
 3393            editor.selections.ranges::<Point>(cx),
 3394            &[Point::new(0, 5)..Point::new(2, 2)]
 3395        );
 3396
 3397        // When joining an empty line don't insert a space
 3398        editor.change_selections(None, window, cx, |s| {
 3399            s.select_ranges([Point::new(2, 1)..Point::new(2, 2)])
 3400        });
 3401        editor.join_lines(&JoinLines, window, cx);
 3402        assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd\n");
 3403        assert_eq!(
 3404            editor.selections.ranges::<Point>(cx),
 3405            [Point::new(2, 3)..Point::new(2, 3)]
 3406        );
 3407
 3408        // We can remove trailing newlines
 3409        editor.join_lines(&JoinLines, window, cx);
 3410        assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd");
 3411        assert_eq!(
 3412            editor.selections.ranges::<Point>(cx),
 3413            [Point::new(2, 3)..Point::new(2, 3)]
 3414        );
 3415
 3416        // We don't blow up on the last line
 3417        editor.join_lines(&JoinLines, window, cx);
 3418        assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd");
 3419        assert_eq!(
 3420            editor.selections.ranges::<Point>(cx),
 3421            [Point::new(2, 3)..Point::new(2, 3)]
 3422        );
 3423
 3424        // reset to test indentation
 3425        editor.buffer.update(cx, |buffer, cx| {
 3426            buffer.edit(
 3427                [
 3428                    (Point::new(1, 0)..Point::new(1, 2), "  "),
 3429                    (Point::new(2, 0)..Point::new(2, 3), "  \n\td"),
 3430                ],
 3431                None,
 3432                cx,
 3433            )
 3434        });
 3435
 3436        // We remove any leading spaces
 3437        assert_eq!(buffer.read(cx).text(), "aaa bbb\n  c\n  \n\td");
 3438        editor.change_selections(None, window, cx, |s| {
 3439            s.select_ranges([Point::new(0, 1)..Point::new(0, 1)])
 3440        });
 3441        editor.join_lines(&JoinLines, window, cx);
 3442        assert_eq!(buffer.read(cx).text(), "aaa bbb c\n  \n\td");
 3443
 3444        // We don't insert a space for a line containing only spaces
 3445        editor.join_lines(&JoinLines, window, cx);
 3446        assert_eq!(buffer.read(cx).text(), "aaa bbb c\n\td");
 3447
 3448        // We ignore any leading tabs
 3449        editor.join_lines(&JoinLines, window, cx);
 3450        assert_eq!(buffer.read(cx).text(), "aaa bbb c d");
 3451
 3452        editor
 3453    });
 3454}
 3455
 3456#[gpui::test]
 3457fn test_join_lines_with_multi_selection(cx: &mut TestAppContext) {
 3458    init_test(cx, |_| {});
 3459
 3460    cx.add_window(|window, cx| {
 3461        let buffer = MultiBuffer::build_simple("aaa\nbbb\nccc\nddd\n\n", cx);
 3462        let mut editor = build_editor(buffer.clone(), window, cx);
 3463        let buffer = buffer.read(cx).as_singleton().unwrap();
 3464
 3465        editor.change_selections(None, window, cx, |s| {
 3466            s.select_ranges([
 3467                Point::new(0, 2)..Point::new(1, 1),
 3468                Point::new(1, 2)..Point::new(1, 2),
 3469                Point::new(3, 1)..Point::new(3, 2),
 3470            ])
 3471        });
 3472
 3473        editor.join_lines(&JoinLines, window, cx);
 3474        assert_eq!(buffer.read(cx).text(), "aaa bbb ccc\nddd\n");
 3475
 3476        assert_eq!(
 3477            editor.selections.ranges::<Point>(cx),
 3478            [
 3479                Point::new(0, 7)..Point::new(0, 7),
 3480                Point::new(1, 3)..Point::new(1, 3)
 3481            ]
 3482        );
 3483        editor
 3484    });
 3485}
 3486
 3487#[gpui::test]
 3488async fn test_join_lines_with_git_diff_base(executor: BackgroundExecutor, cx: &mut TestAppContext) {
 3489    init_test(cx, |_| {});
 3490
 3491    let mut cx = EditorTestContext::new(cx).await;
 3492
 3493    let diff_base = r#"
 3494        Line 0
 3495        Line 1
 3496        Line 2
 3497        Line 3
 3498        "#
 3499    .unindent();
 3500
 3501    cx.set_state(
 3502        &r#"
 3503        ˇLine 0
 3504        Line 1
 3505        Line 2
 3506        Line 3
 3507        "#
 3508        .unindent(),
 3509    );
 3510
 3511    cx.set_head_text(&diff_base);
 3512    executor.run_until_parked();
 3513
 3514    // Join lines
 3515    cx.update_editor(|editor, window, cx| {
 3516        editor.join_lines(&JoinLines, window, cx);
 3517    });
 3518    executor.run_until_parked();
 3519
 3520    cx.assert_editor_state(
 3521        &r#"
 3522        Line 0ˇ Line 1
 3523        Line 2
 3524        Line 3
 3525        "#
 3526        .unindent(),
 3527    );
 3528    // Join again
 3529    cx.update_editor(|editor, window, cx| {
 3530        editor.join_lines(&JoinLines, window, cx);
 3531    });
 3532    executor.run_until_parked();
 3533
 3534    cx.assert_editor_state(
 3535        &r#"
 3536        Line 0 Line 1ˇ Line 2
 3537        Line 3
 3538        "#
 3539        .unindent(),
 3540    );
 3541}
 3542
 3543#[gpui::test]
 3544async fn test_custom_newlines_cause_no_false_positive_diffs(
 3545    executor: BackgroundExecutor,
 3546    cx: &mut TestAppContext,
 3547) {
 3548    init_test(cx, |_| {});
 3549    let mut cx = EditorTestContext::new(cx).await;
 3550    cx.set_state("Line 0\r\nLine 1\rˇ\nLine 2\r\nLine 3");
 3551    cx.set_head_text("Line 0\r\nLine 1\r\nLine 2\r\nLine 3");
 3552    executor.run_until_parked();
 3553
 3554    cx.update_editor(|editor, window, cx| {
 3555        let snapshot = editor.snapshot(window, cx);
 3556        assert_eq!(
 3557            snapshot
 3558                .buffer_snapshot
 3559                .diff_hunks_in_range(0..snapshot.buffer_snapshot.len())
 3560                .collect::<Vec<_>>(),
 3561            Vec::new(),
 3562            "Should not have any diffs for files with custom newlines"
 3563        );
 3564    });
 3565}
 3566
 3567#[gpui::test]
 3568async fn test_manipulate_lines_with_single_selection(cx: &mut TestAppContext) {
 3569    init_test(cx, |_| {});
 3570
 3571    let mut cx = EditorTestContext::new(cx).await;
 3572
 3573    // Test sort_lines_case_insensitive()
 3574    cx.set_state(indoc! {"
 3575        «z
 3576        y
 3577        x
 3578        Z
 3579        Y
 3580        Xˇ»
 3581    "});
 3582    cx.update_editor(|e, window, cx| {
 3583        e.sort_lines_case_insensitive(&SortLinesCaseInsensitive, window, cx)
 3584    });
 3585    cx.assert_editor_state(indoc! {"
 3586        «x
 3587        X
 3588        y
 3589        Y
 3590        z
 3591        Zˇ»
 3592    "});
 3593
 3594    // Test reverse_lines()
 3595    cx.set_state(indoc! {"
 3596        «5
 3597        4
 3598        3
 3599        2
 3600        1ˇ»
 3601    "});
 3602    cx.update_editor(|e, window, cx| e.reverse_lines(&ReverseLines, window, cx));
 3603    cx.assert_editor_state(indoc! {"
 3604        «1
 3605        2
 3606        3
 3607        4
 3608        5ˇ»
 3609    "});
 3610
 3611    // Skip testing shuffle_line()
 3612
 3613    // From here on out, test more complex cases of manipulate_lines() with a single driver method: sort_lines_case_sensitive()
 3614    // Since all methods calling manipulate_lines() are doing the exact same general thing (reordering lines)
 3615
 3616    // Don't manipulate when cursor is on single line, but expand the selection
 3617    cx.set_state(indoc! {"
 3618        ddˇdd
 3619        ccc
 3620        bb
 3621        a
 3622    "});
 3623    cx.update_editor(|e, window, cx| {
 3624        e.sort_lines_case_sensitive(&SortLinesCaseSensitive, window, cx)
 3625    });
 3626    cx.assert_editor_state(indoc! {"
 3627        «ddddˇ»
 3628        ccc
 3629        bb
 3630        a
 3631    "});
 3632
 3633    // Basic manipulate case
 3634    // Start selection moves to column 0
 3635    // End of selection shrinks to fit shorter line
 3636    cx.set_state(indoc! {"
 3637        dd«d
 3638        ccc
 3639        bb
 3640        aaaaaˇ»
 3641    "});
 3642    cx.update_editor(|e, window, cx| {
 3643        e.sort_lines_case_sensitive(&SortLinesCaseSensitive, window, cx)
 3644    });
 3645    cx.assert_editor_state(indoc! {"
 3646        «aaaaa
 3647        bb
 3648        ccc
 3649        dddˇ»
 3650    "});
 3651
 3652    // Manipulate case with newlines
 3653    cx.set_state(indoc! {"
 3654        dd«d
 3655        ccc
 3656
 3657        bb
 3658        aaaaa
 3659
 3660        ˇ»
 3661    "});
 3662    cx.update_editor(|e, window, cx| {
 3663        e.sort_lines_case_sensitive(&SortLinesCaseSensitive, window, cx)
 3664    });
 3665    cx.assert_editor_state(indoc! {"
 3666        «
 3667
 3668        aaaaa
 3669        bb
 3670        ccc
 3671        dddˇ»
 3672
 3673    "});
 3674
 3675    // Adding new line
 3676    cx.set_state(indoc! {"
 3677        aa«a
 3678        bbˇ»b
 3679    "});
 3680    cx.update_editor(|e, window, cx| {
 3681        e.manipulate_lines(window, cx, |lines| lines.push("added_line"))
 3682    });
 3683    cx.assert_editor_state(indoc! {"
 3684        «aaa
 3685        bbb
 3686        added_lineˇ»
 3687    "});
 3688
 3689    // Removing line
 3690    cx.set_state(indoc! {"
 3691        aa«a
 3692        bbbˇ»
 3693    "});
 3694    cx.update_editor(|e, window, cx| {
 3695        e.manipulate_lines(window, cx, |lines| {
 3696            lines.pop();
 3697        })
 3698    });
 3699    cx.assert_editor_state(indoc! {"
 3700        «aaaˇ»
 3701    "});
 3702
 3703    // Removing all lines
 3704    cx.set_state(indoc! {"
 3705        aa«a
 3706        bbbˇ»
 3707    "});
 3708    cx.update_editor(|e, window, cx| {
 3709        e.manipulate_lines(window, cx, |lines| {
 3710            lines.drain(..);
 3711        })
 3712    });
 3713    cx.assert_editor_state(indoc! {"
 3714        ˇ
 3715    "});
 3716}
 3717
 3718#[gpui::test]
 3719async fn test_unique_lines_multi_selection(cx: &mut TestAppContext) {
 3720    init_test(cx, |_| {});
 3721
 3722    let mut cx = EditorTestContext::new(cx).await;
 3723
 3724    // Consider continuous selection as single selection
 3725    cx.set_state(indoc! {"
 3726        Aaa«aa
 3727        cˇ»c«c
 3728        bb
 3729        aaaˇ»aa
 3730    "});
 3731    cx.update_editor(|e, window, cx| {
 3732        e.unique_lines_case_sensitive(&UniqueLinesCaseSensitive, window, cx)
 3733    });
 3734    cx.assert_editor_state(indoc! {"
 3735        «Aaaaa
 3736        ccc
 3737        bb
 3738        aaaaaˇ»
 3739    "});
 3740
 3741    cx.set_state(indoc! {"
 3742        Aaa«aa
 3743        cˇ»c«c
 3744        bb
 3745        aaaˇ»aa
 3746    "});
 3747    cx.update_editor(|e, window, cx| {
 3748        e.unique_lines_case_insensitive(&UniqueLinesCaseInsensitive, window, cx)
 3749    });
 3750    cx.assert_editor_state(indoc! {"
 3751        «Aaaaa
 3752        ccc
 3753        bbˇ»
 3754    "});
 3755
 3756    // Consider non continuous selection as distinct dedup operations
 3757    cx.set_state(indoc! {"
 3758        «aaaaa
 3759        bb
 3760        aaaaa
 3761        aaaaaˇ»
 3762
 3763        aaa«aaˇ»
 3764    "});
 3765    cx.update_editor(|e, window, cx| {
 3766        e.unique_lines_case_sensitive(&UniqueLinesCaseSensitive, window, cx)
 3767    });
 3768    cx.assert_editor_state(indoc! {"
 3769        «aaaaa
 3770        bbˇ»
 3771
 3772        «aaaaaˇ»
 3773    "});
 3774}
 3775
 3776#[gpui::test]
 3777async fn test_unique_lines_single_selection(cx: &mut TestAppContext) {
 3778    init_test(cx, |_| {});
 3779
 3780    let mut cx = EditorTestContext::new(cx).await;
 3781
 3782    cx.set_state(indoc! {"
 3783        «Aaa
 3784        aAa
 3785        Aaaˇ»
 3786    "});
 3787    cx.update_editor(|e, window, cx| {
 3788        e.unique_lines_case_sensitive(&UniqueLinesCaseSensitive, window, cx)
 3789    });
 3790    cx.assert_editor_state(indoc! {"
 3791        «Aaa
 3792        aAaˇ»
 3793    "});
 3794
 3795    cx.set_state(indoc! {"
 3796        «Aaa
 3797        aAa
 3798        aaAˇ»
 3799    "});
 3800    cx.update_editor(|e, window, cx| {
 3801        e.unique_lines_case_insensitive(&UniqueLinesCaseInsensitive, window, cx)
 3802    });
 3803    cx.assert_editor_state(indoc! {"
 3804        «Aaaˇ»
 3805    "});
 3806}
 3807
 3808#[gpui::test]
 3809async fn test_manipulate_lines_with_multi_selection(cx: &mut TestAppContext) {
 3810    init_test(cx, |_| {});
 3811
 3812    let mut cx = EditorTestContext::new(cx).await;
 3813
 3814    // Manipulate with multiple selections on a single line
 3815    cx.set_state(indoc! {"
 3816        dd«dd
 3817        cˇ»c«c
 3818        bb
 3819        aaaˇ»aa
 3820    "});
 3821    cx.update_editor(|e, window, cx| {
 3822        e.sort_lines_case_sensitive(&SortLinesCaseSensitive, window, cx)
 3823    });
 3824    cx.assert_editor_state(indoc! {"
 3825        «aaaaa
 3826        bb
 3827        ccc
 3828        ddddˇ»
 3829    "});
 3830
 3831    // Manipulate with multiple disjoin selections
 3832    cx.set_state(indoc! {"
 3833 3834        4
 3835        3
 3836        2
 3837        1ˇ»
 3838
 3839        dd«dd
 3840        ccc
 3841        bb
 3842        aaaˇ»aa
 3843    "});
 3844    cx.update_editor(|e, window, cx| {
 3845        e.sort_lines_case_sensitive(&SortLinesCaseSensitive, window, cx)
 3846    });
 3847    cx.assert_editor_state(indoc! {"
 3848        «1
 3849        2
 3850        3
 3851        4
 3852        5ˇ»
 3853
 3854        «aaaaa
 3855        bb
 3856        ccc
 3857        ddddˇ»
 3858    "});
 3859
 3860    // Adding lines on each selection
 3861    cx.set_state(indoc! {"
 3862 3863        1ˇ»
 3864
 3865        bb«bb
 3866        aaaˇ»aa
 3867    "});
 3868    cx.update_editor(|e, window, cx| {
 3869        e.manipulate_lines(window, cx, |lines| lines.push("added line"))
 3870    });
 3871    cx.assert_editor_state(indoc! {"
 3872        «2
 3873        1
 3874        added lineˇ»
 3875
 3876        «bbbb
 3877        aaaaa
 3878        added lineˇ»
 3879    "});
 3880
 3881    // Removing lines on each selection
 3882    cx.set_state(indoc! {"
 3883 3884        1ˇ»
 3885
 3886        bb«bb
 3887        aaaˇ»aa
 3888    "});
 3889    cx.update_editor(|e, window, cx| {
 3890        e.manipulate_lines(window, cx, |lines| {
 3891            lines.pop();
 3892        })
 3893    });
 3894    cx.assert_editor_state(indoc! {"
 3895        «2ˇ»
 3896
 3897        «bbbbˇ»
 3898    "});
 3899}
 3900
 3901#[gpui::test]
 3902async fn test_toggle_case(cx: &mut TestAppContext) {
 3903    init_test(cx, |_| {});
 3904
 3905    let mut cx = EditorTestContext::new(cx).await;
 3906
 3907    // If all lower case -> upper case
 3908    cx.set_state(indoc! {"
 3909        «hello worldˇ»
 3910    "});
 3911    cx.update_editor(|e, window, cx| e.toggle_case(&ToggleCase, window, cx));
 3912    cx.assert_editor_state(indoc! {"
 3913        «HELLO WORLDˇ»
 3914    "});
 3915
 3916    // If all upper case -> lower case
 3917    cx.set_state(indoc! {"
 3918        «HELLO WORLDˇ»
 3919    "});
 3920    cx.update_editor(|e, window, cx| e.toggle_case(&ToggleCase, window, cx));
 3921    cx.assert_editor_state(indoc! {"
 3922        «hello worldˇ»
 3923    "});
 3924
 3925    // If any upper case characters are identified -> lower case
 3926    // This matches JetBrains IDEs
 3927    cx.set_state(indoc! {"
 3928        «hEllo worldˇ»
 3929    "});
 3930    cx.update_editor(|e, window, cx| e.toggle_case(&ToggleCase, window, cx));
 3931    cx.assert_editor_state(indoc! {"
 3932        «hello worldˇ»
 3933    "});
 3934}
 3935
 3936#[gpui::test]
 3937async fn test_manipulate_text(cx: &mut TestAppContext) {
 3938    init_test(cx, |_| {});
 3939
 3940    let mut cx = EditorTestContext::new(cx).await;
 3941
 3942    // Test convert_to_upper_case()
 3943    cx.set_state(indoc! {"
 3944        «hello worldˇ»
 3945    "});
 3946    cx.update_editor(|e, window, cx| e.convert_to_upper_case(&ConvertToUpperCase, window, cx));
 3947    cx.assert_editor_state(indoc! {"
 3948        «HELLO WORLDˇ»
 3949    "});
 3950
 3951    // Test convert_to_lower_case()
 3952    cx.set_state(indoc! {"
 3953        «HELLO WORLDˇ»
 3954    "});
 3955    cx.update_editor(|e, window, cx| e.convert_to_lower_case(&ConvertToLowerCase, window, cx));
 3956    cx.assert_editor_state(indoc! {"
 3957        «hello worldˇ»
 3958    "});
 3959
 3960    // Test multiple line, single selection case
 3961    cx.set_state(indoc! {"
 3962        «The quick brown
 3963        fox jumps over
 3964        the lazy dogˇ»
 3965    "});
 3966    cx.update_editor(|e, window, cx| e.convert_to_title_case(&ConvertToTitleCase, window, cx));
 3967    cx.assert_editor_state(indoc! {"
 3968        «The Quick Brown
 3969        Fox Jumps Over
 3970        The Lazy Dogˇ»
 3971    "});
 3972
 3973    // Test multiple line, single selection case
 3974    cx.set_state(indoc! {"
 3975        «The quick brown
 3976        fox jumps over
 3977        the lazy dogˇ»
 3978    "});
 3979    cx.update_editor(|e, window, cx| {
 3980        e.convert_to_upper_camel_case(&ConvertToUpperCamelCase, window, cx)
 3981    });
 3982    cx.assert_editor_state(indoc! {"
 3983        «TheQuickBrown
 3984        FoxJumpsOver
 3985        TheLazyDogˇ»
 3986    "});
 3987
 3988    // From here on out, test more complex cases of manipulate_text()
 3989
 3990    // Test no selection case - should affect words cursors are in
 3991    // Cursor at beginning, middle, and end of word
 3992    cx.set_state(indoc! {"
 3993        ˇhello big beauˇtiful worldˇ
 3994    "});
 3995    cx.update_editor(|e, window, cx| e.convert_to_upper_case(&ConvertToUpperCase, window, cx));
 3996    cx.assert_editor_state(indoc! {"
 3997        «HELLOˇ» big «BEAUTIFULˇ» «WORLDˇ»
 3998    "});
 3999
 4000    // Test multiple selections on a single line and across multiple lines
 4001    cx.set_state(indoc! {"
 4002        «Theˇ» quick «brown
 4003        foxˇ» jumps «overˇ»
 4004        the «lazyˇ» dog
 4005    "});
 4006    cx.update_editor(|e, window, cx| e.convert_to_upper_case(&ConvertToUpperCase, window, cx));
 4007    cx.assert_editor_state(indoc! {"
 4008        «THEˇ» quick «BROWN
 4009        FOXˇ» jumps «OVERˇ»
 4010        the «LAZYˇ» dog
 4011    "});
 4012
 4013    // Test case where text length grows
 4014    cx.set_state(indoc! {"
 4015        «tschüߡ»
 4016    "});
 4017    cx.update_editor(|e, window, cx| e.convert_to_upper_case(&ConvertToUpperCase, window, cx));
 4018    cx.assert_editor_state(indoc! {"
 4019        «TSCHÜSSˇ»
 4020    "});
 4021
 4022    // Test to make sure we don't crash when text shrinks
 4023    cx.set_state(indoc! {"
 4024        aaa_bbbˇ
 4025    "});
 4026    cx.update_editor(|e, window, cx| {
 4027        e.convert_to_lower_camel_case(&ConvertToLowerCamelCase, window, cx)
 4028    });
 4029    cx.assert_editor_state(indoc! {"
 4030        «aaaBbbˇ»
 4031    "});
 4032
 4033    // Test to make sure we all aware of the fact that each word can grow and shrink
 4034    // Final selections should be aware of this fact
 4035    cx.set_state(indoc! {"
 4036        aaa_bˇbb bbˇb_ccc ˇccc_ddd
 4037    "});
 4038    cx.update_editor(|e, window, cx| {
 4039        e.convert_to_lower_camel_case(&ConvertToLowerCamelCase, window, cx)
 4040    });
 4041    cx.assert_editor_state(indoc! {"
 4042        «aaaBbbˇ» «bbbCccˇ» «cccDddˇ»
 4043    "});
 4044
 4045    cx.set_state(indoc! {"
 4046        «hElLo, WoRld!ˇ»
 4047    "});
 4048    cx.update_editor(|e, window, cx| {
 4049        e.convert_to_opposite_case(&ConvertToOppositeCase, window, cx)
 4050    });
 4051    cx.assert_editor_state(indoc! {"
 4052        «HeLlO, wOrLD!ˇ»
 4053    "});
 4054}
 4055
 4056#[gpui::test]
 4057fn test_duplicate_line(cx: &mut TestAppContext) {
 4058    init_test(cx, |_| {});
 4059
 4060    let editor = cx.add_window(|window, cx| {
 4061        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
 4062        build_editor(buffer, window, cx)
 4063    });
 4064    _ = editor.update(cx, |editor, window, cx| {
 4065        editor.change_selections(None, window, cx, |s| {
 4066            s.select_display_ranges([
 4067                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 1),
 4068                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 2),
 4069                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0),
 4070                DisplayPoint::new(DisplayRow(3), 0)..DisplayPoint::new(DisplayRow(3), 0),
 4071            ])
 4072        });
 4073        editor.duplicate_line_down(&DuplicateLineDown, window, cx);
 4074        assert_eq!(editor.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
 4075        assert_eq!(
 4076            editor.selections.display_ranges(cx),
 4077            vec![
 4078                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 1),
 4079                DisplayPoint::new(DisplayRow(1), 2)..DisplayPoint::new(DisplayRow(1), 2),
 4080                DisplayPoint::new(DisplayRow(3), 0)..DisplayPoint::new(DisplayRow(3), 0),
 4081                DisplayPoint::new(DisplayRow(6), 0)..DisplayPoint::new(DisplayRow(6), 0),
 4082            ]
 4083        );
 4084    });
 4085
 4086    let editor = cx.add_window(|window, cx| {
 4087        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
 4088        build_editor(buffer, window, cx)
 4089    });
 4090    _ = editor.update(cx, |editor, window, cx| {
 4091        editor.change_selections(None, window, cx, |s| {
 4092            s.select_display_ranges([
 4093                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(1), 1),
 4094                DisplayPoint::new(DisplayRow(1), 2)..DisplayPoint::new(DisplayRow(2), 1),
 4095            ])
 4096        });
 4097        editor.duplicate_line_down(&DuplicateLineDown, window, cx);
 4098        assert_eq!(editor.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
 4099        assert_eq!(
 4100            editor.selections.display_ranges(cx),
 4101            vec![
 4102                DisplayPoint::new(DisplayRow(3), 1)..DisplayPoint::new(DisplayRow(4), 1),
 4103                DisplayPoint::new(DisplayRow(4), 2)..DisplayPoint::new(DisplayRow(5), 1),
 4104            ]
 4105        );
 4106    });
 4107
 4108    // With `move_upwards` the selections stay in place, except for
 4109    // the lines inserted above them
 4110    let editor = cx.add_window(|window, cx| {
 4111        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
 4112        build_editor(buffer, window, cx)
 4113    });
 4114    _ = editor.update(cx, |editor, window, cx| {
 4115        editor.change_selections(None, window, cx, |s| {
 4116            s.select_display_ranges([
 4117                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 1),
 4118                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 2),
 4119                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0),
 4120                DisplayPoint::new(DisplayRow(3), 0)..DisplayPoint::new(DisplayRow(3), 0),
 4121            ])
 4122        });
 4123        editor.duplicate_line_up(&DuplicateLineUp, window, cx);
 4124        assert_eq!(editor.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
 4125        assert_eq!(
 4126            editor.selections.display_ranges(cx),
 4127            vec![
 4128                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 1),
 4129                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 2),
 4130                DisplayPoint::new(DisplayRow(2), 0)..DisplayPoint::new(DisplayRow(2), 0),
 4131                DisplayPoint::new(DisplayRow(6), 0)..DisplayPoint::new(DisplayRow(6), 0),
 4132            ]
 4133        );
 4134    });
 4135
 4136    let editor = cx.add_window(|window, cx| {
 4137        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
 4138        build_editor(buffer, window, cx)
 4139    });
 4140    _ = editor.update(cx, |editor, window, cx| {
 4141        editor.change_selections(None, window, cx, |s| {
 4142            s.select_display_ranges([
 4143                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(1), 1),
 4144                DisplayPoint::new(DisplayRow(1), 2)..DisplayPoint::new(DisplayRow(2), 1),
 4145            ])
 4146        });
 4147        editor.duplicate_line_up(&DuplicateLineUp, window, cx);
 4148        assert_eq!(editor.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
 4149        assert_eq!(
 4150            editor.selections.display_ranges(cx),
 4151            vec![
 4152                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(1), 1),
 4153                DisplayPoint::new(DisplayRow(1), 2)..DisplayPoint::new(DisplayRow(2), 1),
 4154            ]
 4155        );
 4156    });
 4157
 4158    let editor = cx.add_window(|window, cx| {
 4159        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
 4160        build_editor(buffer, window, cx)
 4161    });
 4162    _ = editor.update(cx, |editor, window, cx| {
 4163        editor.change_selections(None, window, cx, |s| {
 4164            s.select_display_ranges([
 4165                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(1), 1),
 4166                DisplayPoint::new(DisplayRow(1), 2)..DisplayPoint::new(DisplayRow(2), 1),
 4167            ])
 4168        });
 4169        editor.duplicate_selection(&DuplicateSelection, window, cx);
 4170        assert_eq!(editor.display_text(cx), "abc\ndbc\ndef\ngf\nghi\n");
 4171        assert_eq!(
 4172            editor.selections.display_ranges(cx),
 4173            vec![
 4174                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(1), 1),
 4175                DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(3), 1),
 4176            ]
 4177        );
 4178    });
 4179}
 4180
 4181#[gpui::test]
 4182fn test_move_line_up_down(cx: &mut TestAppContext) {
 4183    init_test(cx, |_| {});
 4184
 4185    let editor = cx.add_window(|window, cx| {
 4186        let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
 4187        build_editor(buffer, window, cx)
 4188    });
 4189    _ = editor.update(cx, |editor, window, cx| {
 4190        editor.fold_creases(
 4191            vec![
 4192                Crease::simple(Point::new(0, 2)..Point::new(1, 2), FoldPlaceholder::test()),
 4193                Crease::simple(Point::new(2, 3)..Point::new(4, 1), FoldPlaceholder::test()),
 4194                Crease::simple(Point::new(7, 0)..Point::new(8, 4), FoldPlaceholder::test()),
 4195            ],
 4196            true,
 4197            window,
 4198            cx,
 4199        );
 4200        editor.change_selections(None, window, cx, |s| {
 4201            s.select_display_ranges([
 4202                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 1),
 4203                DisplayPoint::new(DisplayRow(3), 1)..DisplayPoint::new(DisplayRow(3), 1),
 4204                DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(4), 3),
 4205                DisplayPoint::new(DisplayRow(5), 0)..DisplayPoint::new(DisplayRow(5), 2),
 4206            ])
 4207        });
 4208        assert_eq!(
 4209            editor.display_text(cx),
 4210            "aa⋯bbb\nccc⋯eeee\nfffff\nggggg\n⋯i\njjjjj"
 4211        );
 4212
 4213        editor.move_line_up(&MoveLineUp, window, cx);
 4214        assert_eq!(
 4215            editor.display_text(cx),
 4216            "aa⋯bbb\nccc⋯eeee\nggggg\n⋯i\njjjjj\nfffff"
 4217        );
 4218        assert_eq!(
 4219            editor.selections.display_ranges(cx),
 4220            vec![
 4221                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 1),
 4222                DisplayPoint::new(DisplayRow(2), 1)..DisplayPoint::new(DisplayRow(2), 1),
 4223                DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(3), 3),
 4224                DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(4), 2)
 4225            ]
 4226        );
 4227    });
 4228
 4229    _ = editor.update(cx, |editor, window, cx| {
 4230        editor.move_line_down(&MoveLineDown, window, cx);
 4231        assert_eq!(
 4232            editor.display_text(cx),
 4233            "ccc⋯eeee\naa⋯bbb\nfffff\nggggg\n⋯i\njjjjj"
 4234        );
 4235        assert_eq!(
 4236            editor.selections.display_ranges(cx),
 4237            vec![
 4238                DisplayPoint::new(DisplayRow(1), 1)..DisplayPoint::new(DisplayRow(1), 1),
 4239                DisplayPoint::new(DisplayRow(3), 1)..DisplayPoint::new(DisplayRow(3), 1),
 4240                DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(4), 3),
 4241                DisplayPoint::new(DisplayRow(5), 0)..DisplayPoint::new(DisplayRow(5), 2)
 4242            ]
 4243        );
 4244    });
 4245
 4246    _ = editor.update(cx, |editor, window, cx| {
 4247        editor.move_line_down(&MoveLineDown, window, cx);
 4248        assert_eq!(
 4249            editor.display_text(cx),
 4250            "ccc⋯eeee\nfffff\naa⋯bbb\nggggg\n⋯i\njjjjj"
 4251        );
 4252        assert_eq!(
 4253            editor.selections.display_ranges(cx),
 4254            vec![
 4255                DisplayPoint::new(DisplayRow(2), 1)..DisplayPoint::new(DisplayRow(2), 1),
 4256                DisplayPoint::new(DisplayRow(3), 1)..DisplayPoint::new(DisplayRow(3), 1),
 4257                DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(4), 3),
 4258                DisplayPoint::new(DisplayRow(5), 0)..DisplayPoint::new(DisplayRow(5), 2)
 4259            ]
 4260        );
 4261    });
 4262
 4263    _ = editor.update(cx, |editor, window, cx| {
 4264        editor.move_line_up(&MoveLineUp, window, cx);
 4265        assert_eq!(
 4266            editor.display_text(cx),
 4267            "ccc⋯eeee\naa⋯bbb\nggggg\n⋯i\njjjjj\nfffff"
 4268        );
 4269        assert_eq!(
 4270            editor.selections.display_ranges(cx),
 4271            vec![
 4272                DisplayPoint::new(DisplayRow(1), 1)..DisplayPoint::new(DisplayRow(1), 1),
 4273                DisplayPoint::new(DisplayRow(2), 1)..DisplayPoint::new(DisplayRow(2), 1),
 4274                DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(3), 3),
 4275                DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(4), 2)
 4276            ]
 4277        );
 4278    });
 4279}
 4280
 4281#[gpui::test]
 4282fn test_move_line_up_down_with_blocks(cx: &mut TestAppContext) {
 4283    init_test(cx, |_| {});
 4284
 4285    let editor = cx.add_window(|window, cx| {
 4286        let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
 4287        build_editor(buffer, window, cx)
 4288    });
 4289    _ = editor.update(cx, |editor, window, cx| {
 4290        let snapshot = editor.buffer.read(cx).snapshot(cx);
 4291        editor.insert_blocks(
 4292            [BlockProperties {
 4293                style: BlockStyle::Fixed,
 4294                placement: BlockPlacement::Below(snapshot.anchor_after(Point::new(2, 0))),
 4295                height: Some(1),
 4296                render: Arc::new(|_| div().into_any()),
 4297                priority: 0,
 4298            }],
 4299            Some(Autoscroll::fit()),
 4300            cx,
 4301        );
 4302        editor.change_selections(None, window, cx, |s| {
 4303            s.select_ranges([Point::new(2, 0)..Point::new(2, 0)])
 4304        });
 4305        editor.move_line_down(&MoveLineDown, window, cx);
 4306    });
 4307}
 4308
 4309#[gpui::test]
 4310async fn test_selections_and_replace_blocks(cx: &mut TestAppContext) {
 4311    init_test(cx, |_| {});
 4312
 4313    let mut cx = EditorTestContext::new(cx).await;
 4314    cx.set_state(
 4315        &"
 4316            ˇzero
 4317            one
 4318            two
 4319            three
 4320            four
 4321            five
 4322        "
 4323        .unindent(),
 4324    );
 4325
 4326    // Create a four-line block that replaces three lines of text.
 4327    cx.update_editor(|editor, window, cx| {
 4328        let snapshot = editor.snapshot(window, cx);
 4329        let snapshot = &snapshot.buffer_snapshot;
 4330        let placement = BlockPlacement::Replace(
 4331            snapshot.anchor_after(Point::new(1, 0))..=snapshot.anchor_after(Point::new(3, 0)),
 4332        );
 4333        editor.insert_blocks(
 4334            [BlockProperties {
 4335                placement,
 4336                height: Some(4),
 4337                style: BlockStyle::Sticky,
 4338                render: Arc::new(|_| gpui::div().into_any_element()),
 4339                priority: 0,
 4340            }],
 4341            None,
 4342            cx,
 4343        );
 4344    });
 4345
 4346    // Move down so that the cursor touches the block.
 4347    cx.update_editor(|editor, window, cx| {
 4348        editor.move_down(&Default::default(), window, cx);
 4349    });
 4350    cx.assert_editor_state(
 4351        &"
 4352            zero
 4353            «one
 4354            two
 4355            threeˇ»
 4356            four
 4357            five
 4358        "
 4359        .unindent(),
 4360    );
 4361
 4362    // Move down past the block.
 4363    cx.update_editor(|editor, window, cx| {
 4364        editor.move_down(&Default::default(), window, cx);
 4365    });
 4366    cx.assert_editor_state(
 4367        &"
 4368            zero
 4369            one
 4370            two
 4371            three
 4372            ˇfour
 4373            five
 4374        "
 4375        .unindent(),
 4376    );
 4377}
 4378
 4379#[gpui::test]
 4380fn test_transpose(cx: &mut TestAppContext) {
 4381    init_test(cx, |_| {});
 4382
 4383    _ = cx.add_window(|window, cx| {
 4384        let mut editor = build_editor(MultiBuffer::build_simple("abc", cx), window, cx);
 4385        editor.set_style(EditorStyle::default(), window, cx);
 4386        editor.change_selections(None, window, cx, |s| s.select_ranges([1..1]));
 4387        editor.transpose(&Default::default(), window, cx);
 4388        assert_eq!(editor.text(cx), "bac");
 4389        assert_eq!(editor.selections.ranges(cx), [2..2]);
 4390
 4391        editor.transpose(&Default::default(), window, cx);
 4392        assert_eq!(editor.text(cx), "bca");
 4393        assert_eq!(editor.selections.ranges(cx), [3..3]);
 4394
 4395        editor.transpose(&Default::default(), window, cx);
 4396        assert_eq!(editor.text(cx), "bac");
 4397        assert_eq!(editor.selections.ranges(cx), [3..3]);
 4398
 4399        editor
 4400    });
 4401
 4402    _ = cx.add_window(|window, cx| {
 4403        let mut editor = build_editor(MultiBuffer::build_simple("abc\nde", cx), window, cx);
 4404        editor.set_style(EditorStyle::default(), window, cx);
 4405        editor.change_selections(None, window, cx, |s| s.select_ranges([3..3]));
 4406        editor.transpose(&Default::default(), window, cx);
 4407        assert_eq!(editor.text(cx), "acb\nde");
 4408        assert_eq!(editor.selections.ranges(cx), [3..3]);
 4409
 4410        editor.change_selections(None, window, cx, |s| s.select_ranges([4..4]));
 4411        editor.transpose(&Default::default(), window, cx);
 4412        assert_eq!(editor.text(cx), "acbd\ne");
 4413        assert_eq!(editor.selections.ranges(cx), [5..5]);
 4414
 4415        editor.transpose(&Default::default(), window, cx);
 4416        assert_eq!(editor.text(cx), "acbde\n");
 4417        assert_eq!(editor.selections.ranges(cx), [6..6]);
 4418
 4419        editor.transpose(&Default::default(), window, cx);
 4420        assert_eq!(editor.text(cx), "acbd\ne");
 4421        assert_eq!(editor.selections.ranges(cx), [6..6]);
 4422
 4423        editor
 4424    });
 4425
 4426    _ = cx.add_window(|window, cx| {
 4427        let mut editor = build_editor(MultiBuffer::build_simple("abc\nde", cx), window, cx);
 4428        editor.set_style(EditorStyle::default(), window, cx);
 4429        editor.change_selections(None, window, cx, |s| s.select_ranges([1..1, 2..2, 4..4]));
 4430        editor.transpose(&Default::default(), window, cx);
 4431        assert_eq!(editor.text(cx), "bacd\ne");
 4432        assert_eq!(editor.selections.ranges(cx), [2..2, 3..3, 5..5]);
 4433
 4434        editor.transpose(&Default::default(), window, cx);
 4435        assert_eq!(editor.text(cx), "bcade\n");
 4436        assert_eq!(editor.selections.ranges(cx), [3..3, 4..4, 6..6]);
 4437
 4438        editor.transpose(&Default::default(), window, cx);
 4439        assert_eq!(editor.text(cx), "bcda\ne");
 4440        assert_eq!(editor.selections.ranges(cx), [4..4, 6..6]);
 4441
 4442        editor.transpose(&Default::default(), window, cx);
 4443        assert_eq!(editor.text(cx), "bcade\n");
 4444        assert_eq!(editor.selections.ranges(cx), [4..4, 6..6]);
 4445
 4446        editor.transpose(&Default::default(), window, cx);
 4447        assert_eq!(editor.text(cx), "bcaed\n");
 4448        assert_eq!(editor.selections.ranges(cx), [5..5, 6..6]);
 4449
 4450        editor
 4451    });
 4452
 4453    _ = cx.add_window(|window, cx| {
 4454        let mut editor = build_editor(MultiBuffer::build_simple("🍐🏀✋", cx), window, cx);
 4455        editor.set_style(EditorStyle::default(), window, cx);
 4456        editor.change_selections(None, window, cx, |s| s.select_ranges([4..4]));
 4457        editor.transpose(&Default::default(), window, cx);
 4458        assert_eq!(editor.text(cx), "🏀🍐✋");
 4459        assert_eq!(editor.selections.ranges(cx), [8..8]);
 4460
 4461        editor.transpose(&Default::default(), window, cx);
 4462        assert_eq!(editor.text(cx), "🏀✋🍐");
 4463        assert_eq!(editor.selections.ranges(cx), [11..11]);
 4464
 4465        editor.transpose(&Default::default(), window, cx);
 4466        assert_eq!(editor.text(cx), "🏀🍐✋");
 4467        assert_eq!(editor.selections.ranges(cx), [11..11]);
 4468
 4469        editor
 4470    });
 4471}
 4472
 4473#[gpui::test]
 4474async fn test_rewrap(cx: &mut TestAppContext) {
 4475    init_test(cx, |settings| {
 4476        settings.languages.extend([
 4477            (
 4478                "Markdown".into(),
 4479                LanguageSettingsContent {
 4480                    allow_rewrap: Some(language_settings::RewrapBehavior::Anywhere),
 4481                    ..Default::default()
 4482                },
 4483            ),
 4484            (
 4485                "Plain Text".into(),
 4486                LanguageSettingsContent {
 4487                    allow_rewrap: Some(language_settings::RewrapBehavior::Anywhere),
 4488                    ..Default::default()
 4489                },
 4490            ),
 4491        ])
 4492    });
 4493
 4494    let mut cx = EditorTestContext::new(cx).await;
 4495
 4496    let language_with_c_comments = Arc::new(Language::new(
 4497        LanguageConfig {
 4498            line_comments: vec!["// ".into()],
 4499            ..LanguageConfig::default()
 4500        },
 4501        None,
 4502    ));
 4503    let language_with_pound_comments = Arc::new(Language::new(
 4504        LanguageConfig {
 4505            line_comments: vec!["# ".into()],
 4506            ..LanguageConfig::default()
 4507        },
 4508        None,
 4509    ));
 4510    let markdown_language = Arc::new(Language::new(
 4511        LanguageConfig {
 4512            name: "Markdown".into(),
 4513            ..LanguageConfig::default()
 4514        },
 4515        None,
 4516    ));
 4517    let language_with_doc_comments = Arc::new(Language::new(
 4518        LanguageConfig {
 4519            line_comments: vec!["// ".into(), "/// ".into()],
 4520            ..LanguageConfig::default()
 4521        },
 4522        Some(tree_sitter_rust::LANGUAGE.into()),
 4523    ));
 4524
 4525    let plaintext_language = Arc::new(Language::new(
 4526        LanguageConfig {
 4527            name: "Plain Text".into(),
 4528            ..LanguageConfig::default()
 4529        },
 4530        None,
 4531    ));
 4532
 4533    assert_rewrap(
 4534        indoc! {"
 4535            // ˇLorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mollis elit purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus auctor, eu lacinia sapien scelerisque. Vivamus sit amet neque et quam tincidunt hendrerit. Praesent semper egestas tellus id dignissim. Pellentesque odio lectus, iaculis ac volutpat et, blandit quis urna. Sed vestibulum nisi sit amet nisl venenatis tempus. Donec molestie blandit quam, et porta nunc laoreet in. Integer sit amet scelerisque nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras egestas porta metus, eu viverra ipsum efficitur quis. Donec luctus eros turpis, id vulputate turpis porttitor id. Aliquam id accumsan eros.
 4536        "},
 4537        indoc! {"
 4538            // ˇLorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mollis elit
 4539            // purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus
 4540            // auctor, eu lacinia sapien scelerisque. Vivamus sit amet neque et quam
 4541            // tincidunt hendrerit. Praesent semper egestas tellus id dignissim.
 4542            // Pellentesque odio lectus, iaculis ac volutpat et, blandit quis urna. Sed
 4543            // vestibulum nisi sit amet nisl venenatis tempus. Donec molestie blandit quam,
 4544            // et porta nunc laoreet in. Integer sit amet scelerisque nisi. Lorem ipsum
 4545            // dolor sit amet, consectetur adipiscing elit. Cras egestas porta metus, eu
 4546            // viverra ipsum efficitur quis. Donec luctus eros turpis, id vulputate turpis
 4547            // porttitor id. Aliquam id accumsan eros.
 4548        "},
 4549        language_with_c_comments.clone(),
 4550        &mut cx,
 4551    );
 4552
 4553    // Test that rewrapping works inside of a selection
 4554    assert_rewrap(
 4555        indoc! {"
 4556            «// Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mollis elit purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus auctor, eu lacinia sapien scelerisque. Vivamus sit amet neque et quam tincidunt hendrerit. Praesent semper egestas tellus id dignissim. Pellentesque odio lectus, iaculis ac volutpat et, blandit quis urna. Sed vestibulum nisi sit amet nisl venenatis tempus. Donec molestie blandit quam, et porta nunc laoreet in. Integer sit amet scelerisque nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras egestas porta metus, eu viverra ipsum efficitur quis. Donec luctus eros turpis, id vulputate turpis porttitor id. Aliquam id accumsan eros.ˇ»
 4557        "},
 4558        indoc! {"
 4559            «// Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mollis elit
 4560            // purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus
 4561            // auctor, eu lacinia sapien scelerisque. Vivamus sit amet neque et quam
 4562            // tincidunt hendrerit. Praesent semper egestas tellus id dignissim.
 4563            // Pellentesque odio lectus, iaculis ac volutpat et, blandit quis urna. Sed
 4564            // vestibulum nisi sit amet nisl venenatis tempus. Donec molestie blandit quam,
 4565            // et porta nunc laoreet in. Integer sit amet scelerisque nisi. Lorem ipsum
 4566            // dolor sit amet, consectetur adipiscing elit. Cras egestas porta metus, eu
 4567            // viverra ipsum efficitur quis. Donec luctus eros turpis, id vulputate turpis
 4568            // porttitor id. Aliquam id accumsan eros.ˇ»
 4569        "},
 4570        language_with_c_comments.clone(),
 4571        &mut cx,
 4572    );
 4573
 4574    // Test that cursors that expand to the same region are collapsed.
 4575    assert_rewrap(
 4576        indoc! {"
 4577            // ˇLorem ipsum dolor sit amet, consectetur adipiscing elit.
 4578            // ˇVivamus mollis elit purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus auctor, eu lacinia sapien scelerisque.
 4579            // ˇVivamus sit amet neque et quam tincidunt hendrerit. Praesent semper egestas tellus id dignissim. Pellentesque odio lectus, iaculis ac volutpat et,
 4580            // ˇblandit quis urna. Sed vestibulum nisi sit amet nisl venenatis tempus. Donec molestie blandit quam, et porta nunc laoreet in. Integer sit amet scelerisque nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras egestas porta metus, eu viverra ipsum efficitur quis. Donec luctus eros turpis, id vulputate turpis porttitor id. Aliquam id accumsan eros.
 4581        "},
 4582        indoc! {"
 4583            // ˇLorem ipsum dolor sit amet, consectetur adipiscing elit. ˇVivamus mollis elit
 4584            // purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus
 4585            // auctor, eu lacinia sapien scelerisque. ˇVivamus sit amet neque et quam
 4586            // tincidunt hendrerit. Praesent semper egestas tellus id dignissim.
 4587            // Pellentesque odio lectus, iaculis ac volutpat et, ˇblandit quis urna. Sed
 4588            // vestibulum nisi sit amet nisl venenatis tempus. Donec molestie blandit quam,
 4589            // et porta nunc laoreet in. Integer sit amet scelerisque nisi. Lorem ipsum
 4590            // dolor sit amet, consectetur adipiscing elit. Cras egestas porta metus, eu
 4591            // viverra ipsum efficitur quis. Donec luctus eros turpis, id vulputate turpis
 4592            // porttitor id. Aliquam id accumsan eros.
 4593        "},
 4594        language_with_c_comments.clone(),
 4595        &mut cx,
 4596    );
 4597
 4598    // Test that non-contiguous selections are treated separately.
 4599    assert_rewrap(
 4600        indoc! {"
 4601            // ˇLorem ipsum dolor sit amet, consectetur adipiscing elit.
 4602            // ˇVivamus mollis elit purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus auctor, eu lacinia sapien scelerisque.
 4603            //
 4604            // ˇVivamus sit amet neque et quam tincidunt hendrerit. Praesent semper egestas tellus id dignissim. Pellentesque odio lectus, iaculis ac volutpat et,
 4605            // ˇblandit quis urna. Sed vestibulum nisi sit amet nisl venenatis tempus. Donec molestie blandit quam, et porta nunc laoreet in. Integer sit amet scelerisque nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras egestas porta metus, eu viverra ipsum efficitur quis. Donec luctus eros turpis, id vulputate turpis porttitor id. Aliquam id accumsan eros.
 4606        "},
 4607        indoc! {"
 4608            // ˇLorem ipsum dolor sit amet, consectetur adipiscing elit. ˇVivamus mollis elit
 4609            // purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus
 4610            // auctor, eu lacinia sapien scelerisque.
 4611            //
 4612            // ˇVivamus sit amet neque et quam tincidunt hendrerit. Praesent semper egestas
 4613            // tellus id dignissim. Pellentesque odio lectus, iaculis ac volutpat et,
 4614            // ˇblandit quis urna. Sed vestibulum nisi sit amet nisl venenatis tempus. Donec
 4615            // molestie blandit quam, et porta nunc laoreet in. Integer sit amet scelerisque
 4616            // nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras egestas
 4617            // porta metus, eu viverra ipsum efficitur quis. Donec luctus eros turpis, id
 4618            // vulputate turpis porttitor id. Aliquam id accumsan eros.
 4619        "},
 4620        language_with_c_comments.clone(),
 4621        &mut cx,
 4622    );
 4623
 4624    // Test that different comment prefixes are supported.
 4625    assert_rewrap(
 4626        indoc! {"
 4627            # ˇLorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mollis elit purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus auctor, eu lacinia sapien scelerisque. Vivamus sit amet neque et quam tincidunt hendrerit. Praesent semper egestas tellus id dignissim. Pellentesque odio lectus, iaculis ac volutpat et, blandit quis urna. Sed vestibulum nisi sit amet nisl venenatis tempus. Donec molestie blandit quam, et porta nunc laoreet in. Integer sit amet scelerisque nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras egestas porta metus, eu viverra ipsum efficitur quis. Donec luctus eros turpis, id vulputate turpis porttitor id. Aliquam id accumsan eros.
 4628        "},
 4629        indoc! {"
 4630            # ˇLorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mollis elit
 4631            # purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus auctor,
 4632            # eu lacinia sapien scelerisque. Vivamus sit amet neque et quam tincidunt
 4633            # hendrerit. Praesent semper egestas tellus id dignissim. Pellentesque odio
 4634            # lectus, iaculis ac volutpat et, blandit quis urna. Sed vestibulum nisi sit
 4635            # amet nisl venenatis tempus. Donec molestie blandit quam, et porta nunc laoreet
 4636            # in. Integer sit amet scelerisque nisi. Lorem ipsum dolor sit amet, consectetur
 4637            # adipiscing elit. Cras egestas porta metus, eu viverra ipsum efficitur quis.
 4638            # Donec luctus eros turpis, id vulputate turpis porttitor id. Aliquam id
 4639            # accumsan eros.
 4640        "},
 4641        language_with_pound_comments.clone(),
 4642        &mut cx,
 4643    );
 4644
 4645    // Test that rewrapping is ignored outside of comments in most languages.
 4646    assert_rewrap(
 4647        indoc! {"
 4648            /// Adds two numbers.
 4649            /// Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mollis elit purus, a ornare lacus gravida vitae.ˇ
 4650            fn add(a: u32, b: u32) -> u32 {
 4651                a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + bˇ
 4652            }
 4653        "},
 4654        indoc! {"
 4655            /// Adds two numbers. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 4656            /// Vivamus mollis elit purus, a ornare lacus gravida vitae.ˇ
 4657            fn add(a: u32, b: u32) -> u32 {
 4658                a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + bˇ
 4659            }
 4660        "},
 4661        language_with_doc_comments.clone(),
 4662        &mut cx,
 4663    );
 4664
 4665    // Test that rewrapping works in Markdown and Plain Text languages.
 4666    assert_rewrap(
 4667        indoc! {"
 4668            # Hello
 4669
 4670            Lorem ipsum dolor sit amet, ˇconsectetur adipiscing elit. Vivamus mollis elit purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus auctor, eu lacinia sapien scelerisque. Vivamus sit amet neque et quam tincidunt hendrerit. Praesent semper egestas tellus id dignissim. Pellentesque odio lectus, iaculis ac volutpat et, blandit quis urna. Sed vestibulum nisi sit amet nisl venenatis tempus. Donec molestie blandit quam, et porta nunc laoreet in. Integer sit amet scelerisque nisi.
 4671        "},
 4672        indoc! {"
 4673            # Hello
 4674
 4675            Lorem ipsum dolor sit amet, ˇconsectetur adipiscing elit. Vivamus mollis elit
 4676            purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus auctor,
 4677            eu lacinia sapien scelerisque. Vivamus sit amet neque et quam tincidunt
 4678            hendrerit. Praesent semper egestas tellus id dignissim. Pellentesque odio
 4679            lectus, iaculis ac volutpat et, blandit quis urna. Sed vestibulum nisi sit amet
 4680            nisl venenatis tempus. Donec molestie blandit quam, et porta nunc laoreet in.
 4681            Integer sit amet scelerisque nisi.
 4682        "},
 4683        markdown_language,
 4684        &mut cx,
 4685    );
 4686
 4687    assert_rewrap(
 4688        indoc! {"
 4689            Lorem ipsum dolor sit amet, ˇconsectetur adipiscing elit. Vivamus mollis elit purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus auctor, eu lacinia sapien scelerisque. Vivamus sit amet neque et quam tincidunt hendrerit. Praesent semper egestas tellus id dignissim. Pellentesque odio lectus, iaculis ac volutpat et, blandit quis urna. Sed vestibulum nisi sit amet nisl venenatis tempus. Donec molestie blandit quam, et porta nunc laoreet in. Integer sit amet scelerisque nisi.
 4690        "},
 4691        indoc! {"
 4692            Lorem ipsum dolor sit amet, ˇconsectetur adipiscing elit. Vivamus mollis elit
 4693            purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus auctor,
 4694            eu lacinia sapien scelerisque. Vivamus sit amet neque et quam tincidunt
 4695            hendrerit. Praesent semper egestas tellus id dignissim. Pellentesque odio
 4696            lectus, iaculis ac volutpat et, blandit quis urna. Sed vestibulum nisi sit amet
 4697            nisl venenatis tempus. Donec molestie blandit quam, et porta nunc laoreet in.
 4698            Integer sit amet scelerisque nisi.
 4699        "},
 4700        plaintext_language,
 4701        &mut cx,
 4702    );
 4703
 4704    // Test rewrapping unaligned comments in a selection.
 4705    assert_rewrap(
 4706        indoc! {"
 4707            fn foo() {
 4708                if true {
 4709            «        // Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mollis elit purus, a ornare lacus gravida vitae.
 4710            // Praesent semper egestas tellus id dignissim.ˇ»
 4711                    do_something();
 4712                } else {
 4713                    //
 4714                }
 4715            }
 4716        "},
 4717        indoc! {"
 4718            fn foo() {
 4719                if true {
 4720            «        // Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus
 4721                    // mollis elit purus, a ornare lacus gravida vitae. Praesent semper
 4722                    // egestas tellus id dignissim.ˇ»
 4723                    do_something();
 4724                } else {
 4725                    //
 4726                }
 4727            }
 4728        "},
 4729        language_with_doc_comments.clone(),
 4730        &mut cx,
 4731    );
 4732
 4733    assert_rewrap(
 4734        indoc! {"
 4735            fn foo() {
 4736                if true {
 4737            «ˇ        // Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mollis elit purus, a ornare lacus gravida vitae.
 4738            // Praesent semper egestas tellus id dignissim.»
 4739                    do_something();
 4740                } else {
 4741                    //
 4742                }
 4743
 4744            }
 4745        "},
 4746        indoc! {"
 4747            fn foo() {
 4748                if true {
 4749            «ˇ        // Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus
 4750                    // mollis elit purus, a ornare lacus gravida vitae. Praesent semper
 4751                    // egestas tellus id dignissim.»
 4752                    do_something();
 4753                } else {
 4754                    //
 4755                }
 4756
 4757            }
 4758        "},
 4759        language_with_doc_comments.clone(),
 4760        &mut cx,
 4761    );
 4762
 4763    #[track_caller]
 4764    fn assert_rewrap(
 4765        unwrapped_text: &str,
 4766        wrapped_text: &str,
 4767        language: Arc<Language>,
 4768        cx: &mut EditorTestContext,
 4769    ) {
 4770        cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
 4771        cx.set_state(unwrapped_text);
 4772        cx.update_editor(|e, window, cx| e.rewrap(&Rewrap, window, cx));
 4773        cx.assert_editor_state(wrapped_text);
 4774    }
 4775}
 4776
 4777#[gpui::test]
 4778async fn test_hard_wrap(cx: &mut TestAppContext) {
 4779    init_test(cx, |_| {});
 4780    let mut cx = EditorTestContext::new(cx).await;
 4781
 4782    cx.update_buffer(|buffer, cx| buffer.set_language(Some(git_commit_lang()), cx));
 4783    cx.update_editor(|editor, _, cx| {
 4784        editor.set_hard_wrap(Some(14), cx);
 4785    });
 4786
 4787    cx.set_state(indoc!(
 4788        "
 4789        one two three ˇ
 4790        "
 4791    ));
 4792    cx.simulate_input("four");
 4793    cx.run_until_parked();
 4794
 4795    cx.assert_editor_state(indoc!(
 4796        "
 4797        one two three
 4798        fourˇ
 4799        "
 4800    ));
 4801
 4802    cx.update_editor(|editor, window, cx| {
 4803        editor.newline(&Default::default(), window, cx);
 4804    });
 4805    cx.run_until_parked();
 4806    cx.assert_editor_state(indoc!(
 4807        "
 4808        one two three
 4809        four
 4810        ˇ
 4811        "
 4812    ));
 4813
 4814    cx.simulate_input("five");
 4815    cx.run_until_parked();
 4816    cx.assert_editor_state(indoc!(
 4817        "
 4818        one two three
 4819        four
 4820        fiveˇ
 4821        "
 4822    ));
 4823
 4824    cx.update_editor(|editor, window, cx| {
 4825        editor.newline(&Default::default(), window, cx);
 4826    });
 4827    cx.run_until_parked();
 4828    cx.simulate_input("# ");
 4829    cx.run_until_parked();
 4830    cx.assert_editor_state(indoc!(
 4831        "
 4832        one two three
 4833        four
 4834        five
 4835        # ˇ
 4836        "
 4837    ));
 4838
 4839    cx.update_editor(|editor, window, cx| {
 4840        editor.newline(&Default::default(), window, cx);
 4841    });
 4842    cx.run_until_parked();
 4843    cx.assert_editor_state(indoc!(
 4844        "
 4845        one two three
 4846        four
 4847        five
 4848        #\x20
 4849 4850        "
 4851    ));
 4852
 4853    cx.simulate_input(" 6");
 4854    cx.run_until_parked();
 4855    cx.assert_editor_state(indoc!(
 4856        "
 4857        one two three
 4858        four
 4859        five
 4860        #
 4861        # 6ˇ
 4862        "
 4863    ));
 4864}
 4865
 4866#[gpui::test]
 4867async fn test_clipboard(cx: &mut TestAppContext) {
 4868    init_test(cx, |_| {});
 4869
 4870    let mut cx = EditorTestContext::new(cx).await;
 4871
 4872    cx.set_state("«one✅ ˇ»two «three ˇ»four «five ˇ»six ");
 4873    cx.update_editor(|e, window, cx| e.cut(&Cut, window, cx));
 4874    cx.assert_editor_state("ˇtwo ˇfour ˇsix ");
 4875
 4876    // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
 4877    cx.set_state("two ˇfour ˇsix ˇ");
 4878    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 4879    cx.assert_editor_state("two one✅ ˇfour three ˇsix five ˇ");
 4880
 4881    // Paste again but with only two cursors. Since the number of cursors doesn't
 4882    // match the number of slices in the clipboard, the entire clipboard text
 4883    // is pasted at each cursor.
 4884    cx.set_state("ˇtwo one✅ four three six five ˇ");
 4885    cx.update_editor(|e, window, cx| {
 4886        e.handle_input("( ", window, cx);
 4887        e.paste(&Paste, window, cx);
 4888        e.handle_input(") ", window, cx);
 4889    });
 4890    cx.assert_editor_state(
 4891        &([
 4892            "( one✅ ",
 4893            "three ",
 4894            "five ) ˇtwo one✅ four three six five ( one✅ ",
 4895            "three ",
 4896            "five ) ˇ",
 4897        ]
 4898        .join("\n")),
 4899    );
 4900
 4901    // Cut with three selections, one of which is full-line.
 4902    cx.set_state(indoc! {"
 4903        1«2ˇ»3
 4904        4ˇ567
 4905        «8ˇ»9"});
 4906    cx.update_editor(|e, window, cx| e.cut(&Cut, window, cx));
 4907    cx.assert_editor_state(indoc! {"
 4908        1ˇ3
 4909        ˇ9"});
 4910
 4911    // Paste with three selections, noticing how the copied selection that was full-line
 4912    // gets inserted before the second cursor.
 4913    cx.set_state(indoc! {"
 4914        1ˇ3
 4915 4916        «oˇ»ne"});
 4917    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 4918    cx.assert_editor_state(indoc! {"
 4919        12ˇ3
 4920        4567
 4921 4922        8ˇne"});
 4923
 4924    // Copy with a single cursor only, which writes the whole line into the clipboard.
 4925    cx.set_state(indoc! {"
 4926        The quick brown
 4927        fox juˇmps over
 4928        the lazy dog"});
 4929    cx.update_editor(|e, window, cx| e.copy(&Copy, window, cx));
 4930    assert_eq!(
 4931        cx.read_from_clipboard()
 4932            .and_then(|item| item.text().as_deref().map(str::to_string)),
 4933        Some("fox jumps over\n".to_string())
 4934    );
 4935
 4936    // Paste with three selections, noticing how the copied full-line selection is inserted
 4937    // before the empty selections but replaces the selection that is non-empty.
 4938    cx.set_state(indoc! {"
 4939        Tˇhe quick brown
 4940        «foˇ»x jumps over
 4941        tˇhe lazy dog"});
 4942    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 4943    cx.assert_editor_state(indoc! {"
 4944        fox jumps over
 4945        Tˇhe quick brown
 4946        fox jumps over
 4947        ˇx jumps over
 4948        fox jumps over
 4949        tˇhe lazy dog"});
 4950}
 4951
 4952#[gpui::test]
 4953async fn test_copy_trim(cx: &mut TestAppContext) {
 4954    init_test(cx, |_| {});
 4955
 4956    let mut cx = EditorTestContext::new(cx).await;
 4957    cx.set_state(
 4958        r#"            «for selection in selections.iter() {
 4959            let mut start = selection.start;
 4960            let mut end = selection.end;
 4961            let is_entire_line = selection.is_empty();
 4962            if is_entire_line {
 4963                start = Point::new(start.row, 0);ˇ»
 4964                end = cmp::min(max_point, Point::new(end.row + 1, 0));
 4965            }
 4966        "#,
 4967    );
 4968    cx.update_editor(|e, window, cx| e.copy(&Copy, window, cx));
 4969    assert_eq!(
 4970        cx.read_from_clipboard()
 4971            .and_then(|item| item.text().as_deref().map(str::to_string)),
 4972        Some(
 4973            "for selection in selections.iter() {
 4974            let mut start = selection.start;
 4975            let mut end = selection.end;
 4976            let is_entire_line = selection.is_empty();
 4977            if is_entire_line {
 4978                start = Point::new(start.row, 0);"
 4979                .to_string()
 4980        ),
 4981        "Regular copying preserves all indentation selected",
 4982    );
 4983    cx.update_editor(|e, window, cx| e.copy_and_trim(&CopyAndTrim, window, cx));
 4984    assert_eq!(
 4985        cx.read_from_clipboard()
 4986            .and_then(|item| item.text().as_deref().map(str::to_string)),
 4987        Some(
 4988            "for selection in selections.iter() {
 4989let mut start = selection.start;
 4990let mut end = selection.end;
 4991let is_entire_line = selection.is_empty();
 4992if is_entire_line {
 4993    start = Point::new(start.row, 0);"
 4994                .to_string()
 4995        ),
 4996        "Copying with stripping should strip all leading whitespaces"
 4997    );
 4998
 4999    cx.set_state(
 5000        r#"       «     for selection in selections.iter() {
 5001            let mut start = selection.start;
 5002            let mut end = selection.end;
 5003            let is_entire_line = selection.is_empty();
 5004            if is_entire_line {
 5005                start = Point::new(start.row, 0);ˇ»
 5006                end = cmp::min(max_point, Point::new(end.row + 1, 0));
 5007            }
 5008        "#,
 5009    );
 5010    cx.update_editor(|e, window, cx| e.copy(&Copy, window, cx));
 5011    assert_eq!(
 5012        cx.read_from_clipboard()
 5013            .and_then(|item| item.text().as_deref().map(str::to_string)),
 5014        Some(
 5015            "     for selection in selections.iter() {
 5016            let mut start = selection.start;
 5017            let mut end = selection.end;
 5018            let is_entire_line = selection.is_empty();
 5019            if is_entire_line {
 5020                start = Point::new(start.row, 0);"
 5021                .to_string()
 5022        ),
 5023        "Regular copying preserves all indentation selected",
 5024    );
 5025    cx.update_editor(|e, window, cx| e.copy_and_trim(&CopyAndTrim, window, cx));
 5026    assert_eq!(
 5027        cx.read_from_clipboard()
 5028            .and_then(|item| item.text().as_deref().map(str::to_string)),
 5029        Some(
 5030            "for selection in selections.iter() {
 5031let mut start = selection.start;
 5032let mut end = selection.end;
 5033let is_entire_line = selection.is_empty();
 5034if is_entire_line {
 5035    start = Point::new(start.row, 0);"
 5036                .to_string()
 5037        ),
 5038        "Copying with stripping should strip all leading whitespaces, even if some of it was selected"
 5039    );
 5040
 5041    cx.set_state(
 5042        r#"       «ˇ     for selection in selections.iter() {
 5043            let mut start = selection.start;
 5044            let mut end = selection.end;
 5045            let is_entire_line = selection.is_empty();
 5046            if is_entire_line {
 5047                start = Point::new(start.row, 0);»
 5048                end = cmp::min(max_point, Point::new(end.row + 1, 0));
 5049            }
 5050        "#,
 5051    );
 5052    cx.update_editor(|e, window, cx| e.copy(&Copy, window, cx));
 5053    assert_eq!(
 5054        cx.read_from_clipboard()
 5055            .and_then(|item| item.text().as_deref().map(str::to_string)),
 5056        Some(
 5057            "     for selection in selections.iter() {
 5058            let mut start = selection.start;
 5059            let mut end = selection.end;
 5060            let is_entire_line = selection.is_empty();
 5061            if is_entire_line {
 5062                start = Point::new(start.row, 0);"
 5063                .to_string()
 5064        ),
 5065        "Regular copying for reverse selection works the same",
 5066    );
 5067    cx.update_editor(|e, window, cx| e.copy_and_trim(&CopyAndTrim, window, cx));
 5068    assert_eq!(
 5069        cx.read_from_clipboard()
 5070            .and_then(|item| item.text().as_deref().map(str::to_string)),
 5071        Some(
 5072            "for selection in selections.iter() {
 5073let mut start = selection.start;
 5074let mut end = selection.end;
 5075let is_entire_line = selection.is_empty();
 5076if is_entire_line {
 5077    start = Point::new(start.row, 0);"
 5078                .to_string()
 5079        ),
 5080        "Copying with stripping for reverse selection works the same"
 5081    );
 5082
 5083    cx.set_state(
 5084        r#"            for selection «in selections.iter() {
 5085            let mut start = selection.start;
 5086            let mut end = selection.end;
 5087            let is_entire_line = selection.is_empty();
 5088            if is_entire_line {
 5089                start = Point::new(start.row, 0);ˇ»
 5090                end = cmp::min(max_point, Point::new(end.row + 1, 0));
 5091            }
 5092        "#,
 5093    );
 5094    cx.update_editor(|e, window, cx| e.copy(&Copy, window, cx));
 5095    assert_eq!(
 5096        cx.read_from_clipboard()
 5097            .and_then(|item| item.text().as_deref().map(str::to_string)),
 5098        Some(
 5099            "in selections.iter() {
 5100            let mut start = selection.start;
 5101            let mut end = selection.end;
 5102            let is_entire_line = selection.is_empty();
 5103            if is_entire_line {
 5104                start = Point::new(start.row, 0);"
 5105                .to_string()
 5106        ),
 5107        "When selecting past the indent, the copying works as usual",
 5108    );
 5109    cx.update_editor(|e, window, cx| e.copy_and_trim(&CopyAndTrim, window, cx));
 5110    assert_eq!(
 5111        cx.read_from_clipboard()
 5112            .and_then(|item| item.text().as_deref().map(str::to_string)),
 5113        Some(
 5114            "in selections.iter() {
 5115            let mut start = selection.start;
 5116            let mut end = selection.end;
 5117            let is_entire_line = selection.is_empty();
 5118            if is_entire_line {
 5119                start = Point::new(start.row, 0);"
 5120                .to_string()
 5121        ),
 5122        "When selecting past the indent, nothing is trimmed"
 5123    );
 5124
 5125    cx.set_state(
 5126        r#"            «for selection in selections.iter() {
 5127            let mut start = selection.start;
 5128
 5129            let mut end = selection.end;
 5130            let is_entire_line = selection.is_empty();
 5131            if is_entire_line {
 5132                start = Point::new(start.row, 0);
 5133ˇ»                end = cmp::min(max_point, Point::new(end.row + 1, 0));
 5134            }
 5135        "#,
 5136    );
 5137    cx.update_editor(|e, window, cx| e.copy_and_trim(&CopyAndTrim, window, cx));
 5138    assert_eq!(
 5139        cx.read_from_clipboard()
 5140            .and_then(|item| item.text().as_deref().map(str::to_string)),
 5141        Some(
 5142            "for selection in selections.iter() {
 5143let mut start = selection.start;
 5144
 5145let mut end = selection.end;
 5146let is_entire_line = selection.is_empty();
 5147if is_entire_line {
 5148    start = Point::new(start.row, 0);
 5149"
 5150            .to_string()
 5151        ),
 5152        "Copying with stripping should ignore empty lines"
 5153    );
 5154}
 5155
 5156#[gpui::test]
 5157async fn test_paste_multiline(cx: &mut TestAppContext) {
 5158    init_test(cx, |_| {});
 5159
 5160    let mut cx = EditorTestContext::new(cx).await;
 5161    cx.update_buffer(|buffer, cx| buffer.set_language(Some(rust_lang()), cx));
 5162
 5163    // Cut an indented block, without the leading whitespace.
 5164    cx.set_state(indoc! {"
 5165        const a: B = (
 5166            c(),
 5167            «d(
 5168                e,
 5169                f
 5170            )ˇ»
 5171        );
 5172    "});
 5173    cx.update_editor(|e, window, cx| e.cut(&Cut, window, cx));
 5174    cx.assert_editor_state(indoc! {"
 5175        const a: B = (
 5176            c(),
 5177            ˇ
 5178        );
 5179    "});
 5180
 5181    // Paste it at the same position.
 5182    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 5183    cx.assert_editor_state(indoc! {"
 5184        const a: B = (
 5185            c(),
 5186            d(
 5187                e,
 5188                f
 5189 5190        );
 5191    "});
 5192
 5193    // Paste it at a line with a lower indent level.
 5194    cx.set_state(indoc! {"
 5195        ˇ
 5196        const a: B = (
 5197            c(),
 5198        );
 5199    "});
 5200    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 5201    cx.assert_editor_state(indoc! {"
 5202        d(
 5203            e,
 5204            f
 5205 5206        const a: B = (
 5207            c(),
 5208        );
 5209    "});
 5210
 5211    // Cut an indented block, with the leading whitespace.
 5212    cx.set_state(indoc! {"
 5213        const a: B = (
 5214            c(),
 5215        «    d(
 5216                e,
 5217                f
 5218            )
 5219        ˇ»);
 5220    "});
 5221    cx.update_editor(|e, window, cx| e.cut(&Cut, window, cx));
 5222    cx.assert_editor_state(indoc! {"
 5223        const a: B = (
 5224            c(),
 5225        ˇ);
 5226    "});
 5227
 5228    // Paste it at the same position.
 5229    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 5230    cx.assert_editor_state(indoc! {"
 5231        const a: B = (
 5232            c(),
 5233            d(
 5234                e,
 5235                f
 5236            )
 5237        ˇ);
 5238    "});
 5239
 5240    // Paste it at a line with a higher indent level.
 5241    cx.set_state(indoc! {"
 5242        const a: B = (
 5243            c(),
 5244            d(
 5245                e,
 5246 5247            )
 5248        );
 5249    "});
 5250    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 5251    cx.assert_editor_state(indoc! {"
 5252        const a: B = (
 5253            c(),
 5254            d(
 5255                e,
 5256                f    d(
 5257                    e,
 5258                    f
 5259                )
 5260        ˇ
 5261            )
 5262        );
 5263    "});
 5264
 5265    // Copy an indented block, starting mid-line
 5266    cx.set_state(indoc! {"
 5267        const a: B = (
 5268            c(),
 5269            somethin«g(
 5270                e,
 5271                f
 5272            )ˇ»
 5273        );
 5274    "});
 5275    cx.update_editor(|e, window, cx| e.copy(&Copy, window, cx));
 5276
 5277    // Paste it on a line with a lower indent level
 5278    cx.update_editor(|e, window, cx| e.move_to_end(&Default::default(), window, cx));
 5279    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 5280    cx.assert_editor_state(indoc! {"
 5281        const a: B = (
 5282            c(),
 5283            something(
 5284                e,
 5285                f
 5286            )
 5287        );
 5288        g(
 5289            e,
 5290            f
 5291"});
 5292}
 5293
 5294#[gpui::test]
 5295async fn test_paste_content_from_other_app(cx: &mut TestAppContext) {
 5296    init_test(cx, |_| {});
 5297
 5298    cx.write_to_clipboard(ClipboardItem::new_string(
 5299        "    d(\n        e\n    );\n".into(),
 5300    ));
 5301
 5302    let mut cx = EditorTestContext::new(cx).await;
 5303    cx.update_buffer(|buffer, cx| buffer.set_language(Some(rust_lang()), cx));
 5304
 5305    cx.set_state(indoc! {"
 5306        fn a() {
 5307            b();
 5308            if c() {
 5309                ˇ
 5310            }
 5311        }
 5312    "});
 5313
 5314    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 5315    cx.assert_editor_state(indoc! {"
 5316        fn a() {
 5317            b();
 5318            if c() {
 5319                d(
 5320                    e
 5321                );
 5322        ˇ
 5323            }
 5324        }
 5325    "});
 5326
 5327    cx.set_state(indoc! {"
 5328        fn a() {
 5329            b();
 5330            ˇ
 5331        }
 5332    "});
 5333
 5334    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 5335    cx.assert_editor_state(indoc! {"
 5336        fn a() {
 5337            b();
 5338            d(
 5339                e
 5340            );
 5341        ˇ
 5342        }
 5343    "});
 5344}
 5345
 5346#[gpui::test]
 5347fn test_select_all(cx: &mut TestAppContext) {
 5348    init_test(cx, |_| {});
 5349
 5350    let editor = cx.add_window(|window, cx| {
 5351        let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
 5352        build_editor(buffer, window, cx)
 5353    });
 5354    _ = editor.update(cx, |editor, window, cx| {
 5355        editor.select_all(&SelectAll, window, cx);
 5356        assert_eq!(
 5357            editor.selections.display_ranges(cx),
 5358            &[DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(2), 3)]
 5359        );
 5360    });
 5361}
 5362
 5363#[gpui::test]
 5364fn test_select_line(cx: &mut TestAppContext) {
 5365    init_test(cx, |_| {});
 5366
 5367    let editor = cx.add_window(|window, cx| {
 5368        let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
 5369        build_editor(buffer, window, cx)
 5370    });
 5371    _ = editor.update(cx, |editor, window, cx| {
 5372        editor.change_selections(None, window, cx, |s| {
 5373            s.select_display_ranges([
 5374                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 1),
 5375                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 2),
 5376                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0),
 5377                DisplayPoint::new(DisplayRow(4), 2)..DisplayPoint::new(DisplayRow(4), 2),
 5378            ])
 5379        });
 5380        editor.select_line(&SelectLine, window, cx);
 5381        assert_eq!(
 5382            editor.selections.display_ranges(cx),
 5383            vec![
 5384                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(2), 0),
 5385                DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(5), 0),
 5386            ]
 5387        );
 5388    });
 5389
 5390    _ = editor.update(cx, |editor, window, cx| {
 5391        editor.select_line(&SelectLine, window, cx);
 5392        assert_eq!(
 5393            editor.selections.display_ranges(cx),
 5394            vec![
 5395                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(3), 0),
 5396                DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(5), 5),
 5397            ]
 5398        );
 5399    });
 5400
 5401    _ = editor.update(cx, |editor, window, cx| {
 5402        editor.select_line(&SelectLine, window, cx);
 5403        assert_eq!(
 5404            editor.selections.display_ranges(cx),
 5405            vec![DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(5), 5)]
 5406        );
 5407    });
 5408}
 5409
 5410#[gpui::test]
 5411async fn test_split_selection_into_lines(cx: &mut TestAppContext) {
 5412    init_test(cx, |_| {});
 5413    let mut cx = EditorTestContext::new(cx).await;
 5414
 5415    #[track_caller]
 5416    fn test(cx: &mut EditorTestContext, initial_state: &'static str, expected_state: &'static str) {
 5417        cx.set_state(initial_state);
 5418        cx.update_editor(|e, window, cx| {
 5419            e.split_selection_into_lines(&SplitSelectionIntoLines, window, cx)
 5420        });
 5421        cx.assert_editor_state(expected_state);
 5422    }
 5423
 5424    // Selection starts and ends at the middle of lines, left-to-right
 5425    test(
 5426        &mut cx,
 5427        "aa\nb«ˇb\ncc\ndd\ne»e\nff",
 5428        "aa\nbbˇ\nccˇ\nddˇ\neˇe\nff",
 5429    );
 5430    // Same thing, right-to-left
 5431    test(
 5432        &mut cx,
 5433        "aa\nb«b\ncc\ndd\neˇ»e\nff",
 5434        "aa\nbbˇ\nccˇ\nddˇ\neˇe\nff",
 5435    );
 5436
 5437    // Whole buffer, left-to-right, last line *doesn't* end with newline
 5438    test(
 5439        &mut cx,
 5440        "«ˇaa\nbb\ncc\ndd\nee\nff»",
 5441        "aaˇ\nbbˇ\nccˇ\nddˇ\neeˇ\nffˇ",
 5442    );
 5443    // Same thing, right-to-left
 5444    test(
 5445        &mut cx,
 5446        "«aa\nbb\ncc\ndd\nee\nffˇ»",
 5447        "aaˇ\nbbˇ\nccˇ\nddˇ\neeˇ\nffˇ",
 5448    );
 5449
 5450    // Whole buffer, left-to-right, last line ends with newline
 5451    test(
 5452        &mut cx,
 5453        "«ˇaa\nbb\ncc\ndd\nee\nff\n»",
 5454        "aaˇ\nbbˇ\nccˇ\nddˇ\neeˇ\nffˇ\n",
 5455    );
 5456    // Same thing, right-to-left
 5457    test(
 5458        &mut cx,
 5459        "«aa\nbb\ncc\ndd\nee\nff\nˇ»",
 5460        "aaˇ\nbbˇ\nccˇ\nddˇ\neeˇ\nffˇ\n",
 5461    );
 5462
 5463    // Starts at the end of a line, ends at the start of another
 5464    test(
 5465        &mut cx,
 5466        "aa\nbb«ˇ\ncc\ndd\nee\n»ff\n",
 5467        "aa\nbbˇ\nccˇ\nddˇ\neeˇ\nff\n",
 5468    );
 5469}
 5470
 5471#[gpui::test]
 5472async fn test_split_selection_into_lines_interacting_with_creases(cx: &mut TestAppContext) {
 5473    init_test(cx, |_| {});
 5474
 5475    let editor = cx.add_window(|window, cx| {
 5476        let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
 5477        build_editor(buffer, window, cx)
 5478    });
 5479
 5480    // setup
 5481    _ = editor.update(cx, |editor, window, cx| {
 5482        editor.fold_creases(
 5483            vec![
 5484                Crease::simple(Point::new(0, 2)..Point::new(1, 2), FoldPlaceholder::test()),
 5485                Crease::simple(Point::new(2, 3)..Point::new(4, 1), FoldPlaceholder::test()),
 5486                Crease::simple(Point::new(7, 0)..Point::new(8, 4), FoldPlaceholder::test()),
 5487            ],
 5488            true,
 5489            window,
 5490            cx,
 5491        );
 5492        assert_eq!(
 5493            editor.display_text(cx),
 5494            "aa⋯bbb\nccc⋯eeee\nfffff\nggggg\n⋯i"
 5495        );
 5496    });
 5497
 5498    _ = editor.update(cx, |editor, window, cx| {
 5499        editor.change_selections(None, window, cx, |s| {
 5500            s.select_display_ranges([
 5501                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 1),
 5502                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 2),
 5503                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0),
 5504                DisplayPoint::new(DisplayRow(4), 4)..DisplayPoint::new(DisplayRow(4), 4),
 5505            ])
 5506        });
 5507        editor.split_selection_into_lines(&SplitSelectionIntoLines, window, cx);
 5508        assert_eq!(
 5509            editor.display_text(cx),
 5510            "aaaaa\nbbbbb\nccc⋯eeee\nfffff\nggggg\n⋯i"
 5511        );
 5512    });
 5513    EditorTestContext::for_editor(editor, cx)
 5514        .await
 5515        .assert_editor_state("aˇaˇaaa\nbbbbb\nˇccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiiiˇ");
 5516
 5517    _ = editor.update(cx, |editor, window, cx| {
 5518        editor.change_selections(None, window, cx, |s| {
 5519            s.select_display_ranges([
 5520                DisplayPoint::new(DisplayRow(5), 0)..DisplayPoint::new(DisplayRow(0), 1)
 5521            ])
 5522        });
 5523        editor.split_selection_into_lines(&SplitSelectionIntoLines, window, cx);
 5524        assert_eq!(
 5525            editor.display_text(cx),
 5526            "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
 5527        );
 5528        assert_eq!(
 5529            editor.selections.display_ranges(cx),
 5530            [
 5531                DisplayPoint::new(DisplayRow(0), 5)..DisplayPoint::new(DisplayRow(0), 5),
 5532                DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(1), 5),
 5533                DisplayPoint::new(DisplayRow(2), 5)..DisplayPoint::new(DisplayRow(2), 5),
 5534                DisplayPoint::new(DisplayRow(3), 5)..DisplayPoint::new(DisplayRow(3), 5),
 5535                DisplayPoint::new(DisplayRow(4), 5)..DisplayPoint::new(DisplayRow(4), 5),
 5536                DisplayPoint::new(DisplayRow(5), 5)..DisplayPoint::new(DisplayRow(5), 5),
 5537                DisplayPoint::new(DisplayRow(6), 5)..DisplayPoint::new(DisplayRow(6), 5)
 5538            ]
 5539        );
 5540    });
 5541    EditorTestContext::for_editor(editor, cx)
 5542        .await
 5543        .assert_editor_state(
 5544            "aaaaaˇ\nbbbbbˇ\ncccccˇ\ndddddˇ\neeeeeˇ\nfffffˇ\ngggggˇ\nhhhhh\niiiii",
 5545        );
 5546}
 5547
 5548#[gpui::test]
 5549async fn test_add_selection_above_below(cx: &mut TestAppContext) {
 5550    init_test(cx, |_| {});
 5551
 5552    let mut cx = EditorTestContext::new(cx).await;
 5553
 5554    cx.set_state(indoc!(
 5555        r#"abc
 5556           defˇghi
 5557
 5558           jk
 5559           nlmo
 5560           "#
 5561    ));
 5562
 5563    cx.update_editor(|editor, window, cx| {
 5564        editor.add_selection_above(&Default::default(), window, cx);
 5565    });
 5566
 5567    cx.assert_editor_state(indoc!(
 5568        r#"abcˇ
 5569           defˇghi
 5570
 5571           jk
 5572           nlmo
 5573           "#
 5574    ));
 5575
 5576    cx.update_editor(|editor, window, cx| {
 5577        editor.add_selection_above(&Default::default(), window, cx);
 5578    });
 5579
 5580    cx.assert_editor_state(indoc!(
 5581        r#"abcˇ
 5582            defˇghi
 5583
 5584            jk
 5585            nlmo
 5586            "#
 5587    ));
 5588
 5589    cx.update_editor(|editor, window, cx| {
 5590        editor.add_selection_below(&Default::default(), window, cx);
 5591    });
 5592
 5593    cx.assert_editor_state(indoc!(
 5594        r#"abc
 5595           defˇghi
 5596
 5597           jk
 5598           nlmo
 5599           "#
 5600    ));
 5601
 5602    cx.update_editor(|editor, window, cx| {
 5603        editor.undo_selection(&Default::default(), window, cx);
 5604    });
 5605
 5606    cx.assert_editor_state(indoc!(
 5607        r#"abcˇ
 5608           defˇghi
 5609
 5610           jk
 5611           nlmo
 5612           "#
 5613    ));
 5614
 5615    cx.update_editor(|editor, window, cx| {
 5616        editor.redo_selection(&Default::default(), window, cx);
 5617    });
 5618
 5619    cx.assert_editor_state(indoc!(
 5620        r#"abc
 5621           defˇghi
 5622
 5623           jk
 5624           nlmo
 5625           "#
 5626    ));
 5627
 5628    cx.update_editor(|editor, window, cx| {
 5629        editor.add_selection_below(&Default::default(), window, cx);
 5630    });
 5631
 5632    cx.assert_editor_state(indoc!(
 5633        r#"abc
 5634           defˇghi
 5635
 5636           jk
 5637           nlmˇo
 5638           "#
 5639    ));
 5640
 5641    cx.update_editor(|editor, window, cx| {
 5642        editor.add_selection_below(&Default::default(), window, cx);
 5643    });
 5644
 5645    cx.assert_editor_state(indoc!(
 5646        r#"abc
 5647           defˇghi
 5648
 5649           jk
 5650           nlmˇo
 5651           "#
 5652    ));
 5653
 5654    // change selections
 5655    cx.set_state(indoc!(
 5656        r#"abc
 5657           def«ˇg»hi
 5658
 5659           jk
 5660           nlmo
 5661           "#
 5662    ));
 5663
 5664    cx.update_editor(|editor, window, cx| {
 5665        editor.add_selection_below(&Default::default(), window, cx);
 5666    });
 5667
 5668    cx.assert_editor_state(indoc!(
 5669        r#"abc
 5670           def«ˇg»hi
 5671
 5672           jk
 5673           nlm«ˇo»
 5674           "#
 5675    ));
 5676
 5677    cx.update_editor(|editor, window, cx| {
 5678        editor.add_selection_below(&Default::default(), window, cx);
 5679    });
 5680
 5681    cx.assert_editor_state(indoc!(
 5682        r#"abc
 5683           def«ˇg»hi
 5684
 5685           jk
 5686           nlm«ˇo»
 5687           "#
 5688    ));
 5689
 5690    cx.update_editor(|editor, window, cx| {
 5691        editor.add_selection_above(&Default::default(), window, cx);
 5692    });
 5693
 5694    cx.assert_editor_state(indoc!(
 5695        r#"abc
 5696           def«ˇg»hi
 5697
 5698           jk
 5699           nlmo
 5700           "#
 5701    ));
 5702
 5703    cx.update_editor(|editor, window, cx| {
 5704        editor.add_selection_above(&Default::default(), window, cx);
 5705    });
 5706
 5707    cx.assert_editor_state(indoc!(
 5708        r#"abc
 5709           def«ˇg»hi
 5710
 5711           jk
 5712           nlmo
 5713           "#
 5714    ));
 5715
 5716    // Change selections again
 5717    cx.set_state(indoc!(
 5718        r#"a«bc
 5719           defgˇ»hi
 5720
 5721           jk
 5722           nlmo
 5723           "#
 5724    ));
 5725
 5726    cx.update_editor(|editor, window, cx| {
 5727        editor.add_selection_below(&Default::default(), window, cx);
 5728    });
 5729
 5730    cx.assert_editor_state(indoc!(
 5731        r#"a«bcˇ»
 5732           d«efgˇ»hi
 5733
 5734           j«kˇ»
 5735           nlmo
 5736           "#
 5737    ));
 5738
 5739    cx.update_editor(|editor, window, cx| {
 5740        editor.add_selection_below(&Default::default(), window, cx);
 5741    });
 5742    cx.assert_editor_state(indoc!(
 5743        r#"a«bcˇ»
 5744           d«efgˇ»hi
 5745
 5746           j«kˇ»
 5747           n«lmoˇ»
 5748           "#
 5749    ));
 5750    cx.update_editor(|editor, window, cx| {
 5751        editor.add_selection_above(&Default::default(), window, cx);
 5752    });
 5753
 5754    cx.assert_editor_state(indoc!(
 5755        r#"a«bcˇ»
 5756           d«efgˇ»hi
 5757
 5758           j«kˇ»
 5759           nlmo
 5760           "#
 5761    ));
 5762
 5763    // Change selections again
 5764    cx.set_state(indoc!(
 5765        r#"abc
 5766           d«ˇefghi
 5767
 5768           jk
 5769           nlm»o
 5770           "#
 5771    ));
 5772
 5773    cx.update_editor(|editor, window, cx| {
 5774        editor.add_selection_above(&Default::default(), window, cx);
 5775    });
 5776
 5777    cx.assert_editor_state(indoc!(
 5778        r#"a«ˇbc»
 5779           d«ˇef»ghi
 5780
 5781           j«ˇk»
 5782           n«ˇlm»o
 5783           "#
 5784    ));
 5785
 5786    cx.update_editor(|editor, window, cx| {
 5787        editor.add_selection_below(&Default::default(), window, cx);
 5788    });
 5789
 5790    cx.assert_editor_state(indoc!(
 5791        r#"abc
 5792           d«ˇef»ghi
 5793
 5794           j«ˇk»
 5795           n«ˇlm»o
 5796           "#
 5797    ));
 5798}
 5799
 5800#[gpui::test]
 5801async fn test_select_next(cx: &mut TestAppContext) {
 5802    init_test(cx, |_| {});
 5803
 5804    let mut cx = EditorTestContext::new(cx).await;
 5805    cx.set_state("abc\nˇabc abc\ndefabc\nabc");
 5806
 5807    cx.update_editor(|e, window, cx| e.select_next(&SelectNext::default(), window, cx))
 5808        .unwrap();
 5809    cx.assert_editor_state("abc\n«abcˇ» abc\ndefabc\nabc");
 5810
 5811    cx.update_editor(|e, window, cx| e.select_next(&SelectNext::default(), window, cx))
 5812        .unwrap();
 5813    cx.assert_editor_state("abc\n«abcˇ» «abcˇ»\ndefabc\nabc");
 5814
 5815    cx.update_editor(|editor, window, cx| editor.undo_selection(&UndoSelection, window, cx));
 5816    cx.assert_editor_state("abc\n«abcˇ» abc\ndefabc\nabc");
 5817
 5818    cx.update_editor(|editor, window, cx| editor.redo_selection(&RedoSelection, window, cx));
 5819    cx.assert_editor_state("abc\n«abcˇ» «abcˇ»\ndefabc\nabc");
 5820
 5821    cx.update_editor(|e, window, cx| e.select_next(&SelectNext::default(), window, cx))
 5822        .unwrap();
 5823    cx.assert_editor_state("abc\n«abcˇ» «abcˇ»\ndefabc\n«abcˇ»");
 5824
 5825    cx.update_editor(|e, window, cx| e.select_next(&SelectNext::default(), window, cx))
 5826        .unwrap();
 5827    cx.assert_editor_state("«abcˇ»\n«abcˇ» «abcˇ»\ndefabc\n«abcˇ»");
 5828}
 5829
 5830#[gpui::test]
 5831async fn test_select_all_matches(cx: &mut TestAppContext) {
 5832    init_test(cx, |_| {});
 5833
 5834    let mut cx = EditorTestContext::new(cx).await;
 5835
 5836    // Test caret-only selections
 5837    cx.set_state("abc\nˇabc abc\ndefabc\nabc");
 5838    cx.update_editor(|e, window, cx| e.select_all_matches(&SelectAllMatches, window, cx))
 5839        .unwrap();
 5840    cx.assert_editor_state("«abcˇ»\n«abcˇ» «abcˇ»\ndefabc\n«abcˇ»");
 5841
 5842    // Test left-to-right selections
 5843    cx.set_state("abc\n«abcˇ»\nabc");
 5844    cx.update_editor(|e, window, cx| e.select_all_matches(&SelectAllMatches, window, cx))
 5845        .unwrap();
 5846    cx.assert_editor_state("«abcˇ»\n«abcˇ»\n«abcˇ»");
 5847
 5848    // Test right-to-left selections
 5849    cx.set_state("abc\n«ˇabc»\nabc");
 5850    cx.update_editor(|e, window, cx| e.select_all_matches(&SelectAllMatches, window, cx))
 5851        .unwrap();
 5852    cx.assert_editor_state("«ˇabc»\n«ˇabc»\n«ˇabc»");
 5853
 5854    // Test selecting whitespace with caret selection
 5855    cx.set_state("abc\nˇ   abc\nabc");
 5856    cx.update_editor(|e, window, cx| e.select_all_matches(&SelectAllMatches, window, cx))
 5857        .unwrap();
 5858    cx.assert_editor_state("abc\n«   ˇ»abc\nabc");
 5859
 5860    // Test selecting whitespace with left-to-right selection
 5861    cx.set_state("abc\n«ˇ  »abc\nabc");
 5862    cx.update_editor(|e, window, cx| e.select_all_matches(&SelectAllMatches, window, cx))
 5863        .unwrap();
 5864    cx.assert_editor_state("abc\n«ˇ  »abc\nabc");
 5865
 5866    // Test no matches with right-to-left selection
 5867    cx.set_state("abc\n«  ˇ»abc\nabc");
 5868    cx.update_editor(|e, window, cx| e.select_all_matches(&SelectAllMatches, window, cx))
 5869        .unwrap();
 5870    cx.assert_editor_state("abc\n«  ˇ»abc\nabc");
 5871}
 5872
 5873#[gpui::test]
 5874async fn test_select_all_matches_does_not_scroll(cx: &mut TestAppContext) {
 5875    init_test(cx, |_| {});
 5876
 5877    let mut cx = EditorTestContext::new(cx).await;
 5878
 5879    let large_body_1 = "\nd".repeat(200);
 5880    let large_body_2 = "\ne".repeat(200);
 5881
 5882    cx.set_state(&format!(
 5883        "abc\nabc{large_body_1} «ˇa»bc{large_body_2}\nefabc\nabc"
 5884    ));
 5885    let initial_scroll_position = cx.update_editor(|editor, _, cx| {
 5886        let scroll_position = editor.scroll_position(cx);
 5887        assert!(scroll_position.y > 0.0, "Initial selection is between two large bodies and should have the editor scrolled to it");
 5888        scroll_position
 5889    });
 5890
 5891    cx.update_editor(|e, window, cx| e.select_all_matches(&SelectAllMatches, window, cx))
 5892        .unwrap();
 5893    cx.assert_editor_state(&format!(
 5894        "«ˇa»bc\n«ˇa»bc{large_body_1} «ˇa»bc{large_body_2}\nef«ˇa»bc\n«ˇa»bc"
 5895    ));
 5896    let scroll_position_after_selection =
 5897        cx.update_editor(|editor, _, cx| editor.scroll_position(cx));
 5898    assert_eq!(
 5899        initial_scroll_position, scroll_position_after_selection,
 5900        "Scroll position should not change after selecting all matches"
 5901    );
 5902}
 5903
 5904#[gpui::test]
 5905async fn test_undo_format_scrolls_to_last_edit_pos(cx: &mut TestAppContext) {
 5906    init_test(cx, |_| {});
 5907
 5908    let mut cx = EditorLspTestContext::new_rust(
 5909        lsp::ServerCapabilities {
 5910            document_formatting_provider: Some(lsp::OneOf::Left(true)),
 5911            ..Default::default()
 5912        },
 5913        cx,
 5914    )
 5915    .await;
 5916
 5917    cx.set_state(indoc! {"
 5918        line 1
 5919        line 2
 5920        linˇe 3
 5921        line 4
 5922        line 5
 5923    "});
 5924
 5925    // Make an edit
 5926    cx.update_editor(|editor, window, cx| {
 5927        editor.handle_input("X", window, cx);
 5928    });
 5929
 5930    // Move cursor to a different position
 5931    cx.update_editor(|editor, window, cx| {
 5932        editor.change_selections(None, window, cx, |s| {
 5933            s.select_ranges([Point::new(4, 2)..Point::new(4, 2)]);
 5934        });
 5935    });
 5936
 5937    cx.assert_editor_state(indoc! {"
 5938        line 1
 5939        line 2
 5940        linXe 3
 5941        line 4
 5942        liˇne 5
 5943    "});
 5944
 5945    cx.lsp
 5946        .set_request_handler::<lsp::request::Formatting, _, _>(move |_, _| async move {
 5947            Ok(Some(vec![lsp::TextEdit::new(
 5948                lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
 5949                "PREFIX ".to_string(),
 5950            )]))
 5951        });
 5952
 5953    cx.update_editor(|editor, window, cx| editor.format(&Default::default(), window, cx))
 5954        .unwrap()
 5955        .await
 5956        .unwrap();
 5957
 5958    cx.assert_editor_state(indoc! {"
 5959        PREFIX line 1
 5960        line 2
 5961        linXe 3
 5962        line 4
 5963        liˇne 5
 5964    "});
 5965
 5966    // Undo formatting
 5967    cx.update_editor(|editor, window, cx| {
 5968        editor.undo(&Default::default(), window, cx);
 5969    });
 5970
 5971    // Verify cursor moved back to position after edit
 5972    cx.assert_editor_state(indoc! {"
 5973        line 1
 5974        line 2
 5975        linXˇe 3
 5976        line 4
 5977        line 5
 5978    "});
 5979}
 5980
 5981#[gpui::test]
 5982async fn test_select_next_with_multiple_carets(cx: &mut TestAppContext) {
 5983    init_test(cx, |_| {});
 5984
 5985    let mut cx = EditorTestContext::new(cx).await;
 5986    cx.set_state(
 5987        r#"let foo = 2;
 5988lˇet foo = 2;
 5989let fooˇ = 2;
 5990let foo = 2;
 5991let foo = ˇ2;"#,
 5992    );
 5993
 5994    cx.update_editor(|e, window, cx| e.select_next(&SelectNext::default(), window, cx))
 5995        .unwrap();
 5996    cx.assert_editor_state(
 5997        r#"let foo = 2;
 5998«letˇ» foo = 2;
 5999let «fooˇ» = 2;
 6000let foo = 2;
 6001let foo = «2ˇ»;"#,
 6002    );
 6003
 6004    // noop for multiple selections with different contents
 6005    cx.update_editor(|e, window, cx| e.select_next(&SelectNext::default(), window, cx))
 6006        .unwrap();
 6007    cx.assert_editor_state(
 6008        r#"let foo = 2;
 6009«letˇ» foo = 2;
 6010let «fooˇ» = 2;
 6011let foo = 2;
 6012let foo = «2ˇ»;"#,
 6013    );
 6014}
 6015
 6016#[gpui::test]
 6017async fn test_select_previous_multibuffer(cx: &mut TestAppContext) {
 6018    init_test(cx, |_| {});
 6019
 6020    let mut cx =
 6021        EditorTestContext::new_multibuffer(cx, ["aaa\n«bbb\nccc\n»ddd", "aaa\n«bbb\nccc\n»ddd"]);
 6022
 6023    cx.assert_editor_state(indoc! {"
 6024        ˇbbb
 6025        ccc
 6026
 6027        bbb
 6028        ccc
 6029        "});
 6030    cx.dispatch_action(SelectPrevious::default());
 6031    cx.assert_editor_state(indoc! {"
 6032                «bbbˇ»
 6033                ccc
 6034
 6035                bbb
 6036                ccc
 6037                "});
 6038    cx.dispatch_action(SelectPrevious::default());
 6039    cx.assert_editor_state(indoc! {"
 6040                «bbbˇ»
 6041                ccc
 6042
 6043                «bbbˇ»
 6044                ccc
 6045                "});
 6046}
 6047
 6048#[gpui::test]
 6049async fn test_select_previous_with_single_caret(cx: &mut TestAppContext) {
 6050    init_test(cx, |_| {});
 6051
 6052    let mut cx = EditorTestContext::new(cx).await;
 6053    cx.set_state("abc\nˇabc abc\ndefabc\nabc");
 6054
 6055    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6056        .unwrap();
 6057    cx.assert_editor_state("abc\n«abcˇ» abc\ndefabc\nabc");
 6058
 6059    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6060        .unwrap();
 6061    cx.assert_editor_state("«abcˇ»\n«abcˇ» abc\ndefabc\nabc");
 6062
 6063    cx.update_editor(|editor, window, cx| editor.undo_selection(&UndoSelection, window, cx));
 6064    cx.assert_editor_state("abc\n«abcˇ» abc\ndefabc\nabc");
 6065
 6066    cx.update_editor(|editor, window, cx| editor.redo_selection(&RedoSelection, window, cx));
 6067    cx.assert_editor_state("«abcˇ»\n«abcˇ» abc\ndefabc\nabc");
 6068
 6069    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6070        .unwrap();
 6071    cx.assert_editor_state("«abcˇ»\n«abcˇ» abc\ndefabc\n«abcˇ»");
 6072
 6073    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6074        .unwrap();
 6075    cx.assert_editor_state("«abcˇ»\n«abcˇ» abc\ndef«abcˇ»\n«abcˇ»");
 6076
 6077    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6078        .unwrap();
 6079    cx.assert_editor_state("«abcˇ»\n«abcˇ» «abcˇ»\ndef«abcˇ»\n«abcˇ»");
 6080}
 6081
 6082#[gpui::test]
 6083async fn test_select_previous_empty_buffer(cx: &mut TestAppContext) {
 6084    init_test(cx, |_| {});
 6085
 6086    let mut cx = EditorTestContext::new(cx).await;
 6087    cx.set_state("");
 6088
 6089    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6090        .unwrap();
 6091    cx.assert_editor_state("«aˇ»");
 6092    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6093        .unwrap();
 6094    cx.assert_editor_state("«aˇ»");
 6095}
 6096
 6097#[gpui::test]
 6098async fn test_select_previous_with_multiple_carets(cx: &mut TestAppContext) {
 6099    init_test(cx, |_| {});
 6100
 6101    let mut cx = EditorTestContext::new(cx).await;
 6102    cx.set_state(
 6103        r#"let foo = 2;
 6104lˇet foo = 2;
 6105let fooˇ = 2;
 6106let foo = 2;
 6107let foo = ˇ2;"#,
 6108    );
 6109
 6110    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6111        .unwrap();
 6112    cx.assert_editor_state(
 6113        r#"let foo = 2;
 6114«letˇ» foo = 2;
 6115let «fooˇ» = 2;
 6116let foo = 2;
 6117let foo = «2ˇ»;"#,
 6118    );
 6119
 6120    // noop for multiple selections with different contents
 6121    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6122        .unwrap();
 6123    cx.assert_editor_state(
 6124        r#"let foo = 2;
 6125«letˇ» foo = 2;
 6126let «fooˇ» = 2;
 6127let foo = 2;
 6128let foo = «2ˇ»;"#,
 6129    );
 6130}
 6131
 6132#[gpui::test]
 6133async fn test_select_previous_with_single_selection(cx: &mut TestAppContext) {
 6134    init_test(cx, |_| {});
 6135
 6136    let mut cx = EditorTestContext::new(cx).await;
 6137    cx.set_state("abc\n«ˇabc» abc\ndefabc\nabc");
 6138
 6139    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6140        .unwrap();
 6141    cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndefabc\nabc");
 6142
 6143    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6144        .unwrap();
 6145    cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndefabc\n«abcˇ»");
 6146
 6147    cx.update_editor(|editor, window, cx| editor.undo_selection(&UndoSelection, window, cx));
 6148    cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndefabc\nabc");
 6149
 6150    cx.update_editor(|editor, window, cx| editor.redo_selection(&RedoSelection, window, cx));
 6151    cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndefabc\n«abcˇ»");
 6152
 6153    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6154        .unwrap();
 6155    cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndef«abcˇ»\n«abcˇ»");
 6156
 6157    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6158        .unwrap();
 6159    cx.assert_editor_state("«abcˇ»\n«ˇabc» «abcˇ»\ndef«abcˇ»\n«abcˇ»");
 6160}
 6161
 6162#[gpui::test]
 6163async fn test_select_larger_smaller_syntax_node(cx: &mut TestAppContext) {
 6164    init_test(cx, |_| {});
 6165
 6166    let language = Arc::new(Language::new(
 6167        LanguageConfig::default(),
 6168        Some(tree_sitter_rust::LANGUAGE.into()),
 6169    ));
 6170
 6171    let text = r#"
 6172        use mod1::mod2::{mod3, mod4};
 6173
 6174        fn fn_1(param1: bool, param2: &str) {
 6175            let var1 = "text";
 6176        }
 6177    "#
 6178    .unindent();
 6179
 6180    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
 6181    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 6182    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
 6183
 6184    editor
 6185        .condition::<crate::EditorEvent>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
 6186        .await;
 6187
 6188    editor.update_in(cx, |editor, window, cx| {
 6189        editor.change_selections(None, window, cx, |s| {
 6190            s.select_display_ranges([
 6191                DisplayPoint::new(DisplayRow(0), 25)..DisplayPoint::new(DisplayRow(0), 25),
 6192                DisplayPoint::new(DisplayRow(2), 24)..DisplayPoint::new(DisplayRow(2), 12),
 6193                DisplayPoint::new(DisplayRow(3), 18)..DisplayPoint::new(DisplayRow(3), 18),
 6194            ]);
 6195        });
 6196        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6197    });
 6198    editor.update(cx, |editor, cx| {
 6199        assert_text_with_selections(
 6200            editor,
 6201            indoc! {r#"
 6202                use mod1::mod2::{mod3, «mod4ˇ»};
 6203
 6204                fn fn_1«ˇ(param1: bool, param2: &str)» {
 6205                    let var1 = "«ˇtext»";
 6206                }
 6207            "#},
 6208            cx,
 6209        );
 6210    });
 6211
 6212    editor.update_in(cx, |editor, window, cx| {
 6213        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6214    });
 6215    editor.update(cx, |editor, cx| {
 6216        assert_text_with_selections(
 6217            editor,
 6218            indoc! {r#"
 6219                use mod1::mod2::«{mod3, mod4}ˇ»;
 6220
 6221                «ˇfn fn_1(param1: bool, param2: &str) {
 6222                    let var1 = "text";
 6223 6224            "#},
 6225            cx,
 6226        );
 6227    });
 6228
 6229    editor.update_in(cx, |editor, window, cx| {
 6230        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6231    });
 6232    assert_eq!(
 6233        editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
 6234        &[DisplayPoint::new(DisplayRow(5), 0)..DisplayPoint::new(DisplayRow(0), 0)]
 6235    );
 6236
 6237    // Trying to expand the selected syntax node one more time has no effect.
 6238    editor.update_in(cx, |editor, window, cx| {
 6239        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6240    });
 6241    assert_eq!(
 6242        editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
 6243        &[DisplayPoint::new(DisplayRow(5), 0)..DisplayPoint::new(DisplayRow(0), 0)]
 6244    );
 6245
 6246    editor.update_in(cx, |editor, window, cx| {
 6247        editor.select_smaller_syntax_node(&SelectSmallerSyntaxNode, window, cx);
 6248    });
 6249    editor.update(cx, |editor, cx| {
 6250        assert_text_with_selections(
 6251            editor,
 6252            indoc! {r#"
 6253                use mod1::mod2::«{mod3, mod4}ˇ»;
 6254
 6255                «ˇfn fn_1(param1: bool, param2: &str) {
 6256                    let var1 = "text";
 6257 6258            "#},
 6259            cx,
 6260        );
 6261    });
 6262
 6263    editor.update_in(cx, |editor, window, cx| {
 6264        editor.select_smaller_syntax_node(&SelectSmallerSyntaxNode, window, cx);
 6265    });
 6266    editor.update(cx, |editor, cx| {
 6267        assert_text_with_selections(
 6268            editor,
 6269            indoc! {r#"
 6270                use mod1::mod2::{mod3, «mod4ˇ»};
 6271
 6272                fn fn_1«ˇ(param1: bool, param2: &str)» {
 6273                    let var1 = "«ˇtext»";
 6274                }
 6275            "#},
 6276            cx,
 6277        );
 6278    });
 6279
 6280    editor.update_in(cx, |editor, window, cx| {
 6281        editor.select_smaller_syntax_node(&SelectSmallerSyntaxNode, window, cx);
 6282    });
 6283    editor.update(cx, |editor, cx| {
 6284        assert_text_with_selections(
 6285            editor,
 6286            indoc! {r#"
 6287                use mod1::mod2::{mod3, mo«ˇ»d4};
 6288
 6289                fn fn_1(para«ˇm1: bool, pa»ram2: &str) {
 6290                    let var1 = "te«ˇ»xt";
 6291                }
 6292            "#},
 6293            cx,
 6294        );
 6295    });
 6296
 6297    // Trying to shrink the selected syntax node one more time has no effect.
 6298    editor.update_in(cx, |editor, window, cx| {
 6299        editor.select_smaller_syntax_node(&SelectSmallerSyntaxNode, window, cx);
 6300    });
 6301    editor.update_in(cx, |editor, _, cx| {
 6302        assert_text_with_selections(
 6303            editor,
 6304            indoc! {r#"
 6305                use mod1::mod2::{mod3, mo«ˇ»d4};
 6306
 6307                fn fn_1(para«ˇm1: bool, pa»ram2: &str) {
 6308                    let var1 = "te«ˇ»xt";
 6309                }
 6310            "#},
 6311            cx,
 6312        );
 6313    });
 6314
 6315    // Ensure that we keep expanding the selection if the larger selection starts or ends within
 6316    // a fold.
 6317    editor.update_in(cx, |editor, window, cx| {
 6318        editor.fold_creases(
 6319            vec![
 6320                Crease::simple(
 6321                    Point::new(0, 21)..Point::new(0, 24),
 6322                    FoldPlaceholder::test(),
 6323                ),
 6324                Crease::simple(
 6325                    Point::new(3, 20)..Point::new(3, 22),
 6326                    FoldPlaceholder::test(),
 6327                ),
 6328            ],
 6329            true,
 6330            window,
 6331            cx,
 6332        );
 6333        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6334    });
 6335    editor.update(cx, |editor, cx| {
 6336        assert_text_with_selections(
 6337            editor,
 6338            indoc! {r#"
 6339                use mod1::mod2::«{mod3, mod4}ˇ»;
 6340
 6341                fn fn_1«ˇ(param1: bool, param2: &str)» {
 6342                    let var1 = "«ˇtext»";
 6343                }
 6344            "#},
 6345            cx,
 6346        );
 6347    });
 6348}
 6349
 6350#[gpui::test]
 6351async fn test_select_larger_smaller_syntax_node_for_string(cx: &mut TestAppContext) {
 6352    init_test(cx, |_| {});
 6353
 6354    let language = Arc::new(Language::new(
 6355        LanguageConfig::default(),
 6356        Some(tree_sitter_rust::LANGUAGE.into()),
 6357    ));
 6358
 6359    let text = r#"
 6360        use mod1::mod2::{mod3, mod4};
 6361
 6362        fn fn_1(param1: bool, param2: &str) {
 6363            let var1 = "hello world";
 6364        }
 6365    "#
 6366    .unindent();
 6367
 6368    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
 6369    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 6370    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
 6371
 6372    editor
 6373        .condition::<crate::EditorEvent>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
 6374        .await;
 6375
 6376    // Test 1: Cursor on a letter of a string word
 6377    editor.update_in(cx, |editor, window, cx| {
 6378        editor.change_selections(None, window, cx, |s| {
 6379            s.select_display_ranges([
 6380                DisplayPoint::new(DisplayRow(3), 17)..DisplayPoint::new(DisplayRow(3), 17)
 6381            ]);
 6382        });
 6383    });
 6384    editor.update_in(cx, |editor, window, cx| {
 6385        assert_text_with_selections(
 6386            editor,
 6387            indoc! {r#"
 6388                use mod1::mod2::{mod3, mod4};
 6389
 6390                fn fn_1(param1: bool, param2: &str) {
 6391                    let var1 = "hˇello world";
 6392                }
 6393            "#},
 6394            cx,
 6395        );
 6396        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6397        assert_text_with_selections(
 6398            editor,
 6399            indoc! {r#"
 6400                use mod1::mod2::{mod3, mod4};
 6401
 6402                fn fn_1(param1: bool, param2: &str) {
 6403                    let var1 = "«ˇhello» world";
 6404                }
 6405            "#},
 6406            cx,
 6407        );
 6408    });
 6409
 6410    // Test 2: Partial selection within a word
 6411    editor.update_in(cx, |editor, window, cx| {
 6412        editor.change_selections(None, window, cx, |s| {
 6413            s.select_display_ranges([
 6414                DisplayPoint::new(DisplayRow(3), 17)..DisplayPoint::new(DisplayRow(3), 19)
 6415            ]);
 6416        });
 6417    });
 6418    editor.update_in(cx, |editor, window, cx| {
 6419        assert_text_with_selections(
 6420            editor,
 6421            indoc! {r#"
 6422                use mod1::mod2::{mod3, mod4};
 6423
 6424                fn fn_1(param1: bool, param2: &str) {
 6425                    let var1 = "h«elˇ»lo world";
 6426                }
 6427            "#},
 6428            cx,
 6429        );
 6430        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6431        assert_text_with_selections(
 6432            editor,
 6433            indoc! {r#"
 6434                use mod1::mod2::{mod3, mod4};
 6435
 6436                fn fn_1(param1: bool, param2: &str) {
 6437                    let var1 = "«ˇhello» world";
 6438                }
 6439            "#},
 6440            cx,
 6441        );
 6442    });
 6443
 6444    // Test 3: Complete word already selected
 6445    editor.update_in(cx, |editor, window, cx| {
 6446        editor.change_selections(None, window, cx, |s| {
 6447            s.select_display_ranges([
 6448                DisplayPoint::new(DisplayRow(3), 16)..DisplayPoint::new(DisplayRow(3), 21)
 6449            ]);
 6450        });
 6451    });
 6452    editor.update_in(cx, |editor, window, cx| {
 6453        assert_text_with_selections(
 6454            editor,
 6455            indoc! {r#"
 6456                use mod1::mod2::{mod3, mod4};
 6457
 6458                fn fn_1(param1: bool, param2: &str) {
 6459                    let var1 = "«helloˇ» world";
 6460                }
 6461            "#},
 6462            cx,
 6463        );
 6464        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6465        assert_text_with_selections(
 6466            editor,
 6467            indoc! {r#"
 6468                use mod1::mod2::{mod3, mod4};
 6469
 6470                fn fn_1(param1: bool, param2: &str) {
 6471                    let var1 = "«hello worldˇ»";
 6472                }
 6473            "#},
 6474            cx,
 6475        );
 6476    });
 6477
 6478    // Test 4: Selection spanning across words
 6479    editor.update_in(cx, |editor, window, cx| {
 6480        editor.change_selections(None, window, cx, |s| {
 6481            s.select_display_ranges([
 6482                DisplayPoint::new(DisplayRow(3), 19)..DisplayPoint::new(DisplayRow(3), 24)
 6483            ]);
 6484        });
 6485    });
 6486    editor.update_in(cx, |editor, window, cx| {
 6487        assert_text_with_selections(
 6488            editor,
 6489            indoc! {r#"
 6490                use mod1::mod2::{mod3, mod4};
 6491
 6492                fn fn_1(param1: bool, param2: &str) {
 6493                    let var1 = "hel«lo woˇ»rld";
 6494                }
 6495            "#},
 6496            cx,
 6497        );
 6498        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6499        assert_text_with_selections(
 6500            editor,
 6501            indoc! {r#"
 6502                use mod1::mod2::{mod3, mod4};
 6503
 6504                fn fn_1(param1: bool, param2: &str) {
 6505                    let var1 = "«ˇhello world»";
 6506                }
 6507            "#},
 6508            cx,
 6509        );
 6510    });
 6511
 6512    // Test 5: Expansion beyond string
 6513    editor.update_in(cx, |editor, window, cx| {
 6514        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6515        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6516        assert_text_with_selections(
 6517            editor,
 6518            indoc! {r#"
 6519                use mod1::mod2::{mod3, mod4};
 6520
 6521                fn fn_1(param1: bool, param2: &str) {
 6522                    «ˇlet var1 = "hello world";»
 6523                }
 6524            "#},
 6525            cx,
 6526        );
 6527    });
 6528}
 6529
 6530#[gpui::test]
 6531async fn test_fold_function_bodies(cx: &mut TestAppContext) {
 6532    init_test(cx, |_| {});
 6533
 6534    let base_text = r#"
 6535        impl A {
 6536            // this is an uncommitted comment
 6537
 6538            fn b() {
 6539                c();
 6540            }
 6541
 6542            // this is another uncommitted comment
 6543
 6544            fn d() {
 6545                // e
 6546                // f
 6547            }
 6548        }
 6549
 6550        fn g() {
 6551            // h
 6552        }
 6553    "#
 6554    .unindent();
 6555
 6556    let text = r#"
 6557        ˇimpl A {
 6558
 6559            fn b() {
 6560                c();
 6561            }
 6562
 6563            fn d() {
 6564                // e
 6565                // f
 6566            }
 6567        }
 6568
 6569        fn g() {
 6570            // h
 6571        }
 6572    "#
 6573    .unindent();
 6574
 6575    let mut cx = EditorLspTestContext::new_rust(Default::default(), cx).await;
 6576    cx.set_state(&text);
 6577    cx.set_head_text(&base_text);
 6578    cx.update_editor(|editor, window, cx| {
 6579        editor.expand_all_diff_hunks(&Default::default(), window, cx);
 6580    });
 6581
 6582    cx.assert_state_with_diff(
 6583        "
 6584        ˇimpl A {
 6585      -     // this is an uncommitted comment
 6586
 6587            fn b() {
 6588                c();
 6589            }
 6590
 6591      -     // this is another uncommitted comment
 6592      -
 6593            fn d() {
 6594                // e
 6595                // f
 6596            }
 6597        }
 6598
 6599        fn g() {
 6600            // h
 6601        }
 6602    "
 6603        .unindent(),
 6604    );
 6605
 6606    let expected_display_text = "
 6607        impl A {
 6608            // this is an uncommitted comment
 6609
 6610            fn b() {
 6611 6612            }
 6613
 6614            // this is another uncommitted comment
 6615
 6616            fn d() {
 6617 6618            }
 6619        }
 6620
 6621        fn g() {
 6622 6623        }
 6624        "
 6625    .unindent();
 6626
 6627    cx.update_editor(|editor, window, cx| {
 6628        editor.fold_function_bodies(&FoldFunctionBodies, window, cx);
 6629        assert_eq!(editor.display_text(cx), expected_display_text);
 6630    });
 6631}
 6632
 6633#[gpui::test]
 6634async fn test_autoindent(cx: &mut TestAppContext) {
 6635    init_test(cx, |_| {});
 6636
 6637    let language = Arc::new(
 6638        Language::new(
 6639            LanguageConfig {
 6640                brackets: BracketPairConfig {
 6641                    pairs: vec![
 6642                        BracketPair {
 6643                            start: "{".to_string(),
 6644                            end: "}".to_string(),
 6645                            close: false,
 6646                            surround: false,
 6647                            newline: true,
 6648                        },
 6649                        BracketPair {
 6650                            start: "(".to_string(),
 6651                            end: ")".to_string(),
 6652                            close: false,
 6653                            surround: false,
 6654                            newline: true,
 6655                        },
 6656                    ],
 6657                    ..Default::default()
 6658                },
 6659                ..Default::default()
 6660            },
 6661            Some(tree_sitter_rust::LANGUAGE.into()),
 6662        )
 6663        .with_indents_query(
 6664            r#"
 6665                (_ "(" ")" @end) @indent
 6666                (_ "{" "}" @end) @indent
 6667            "#,
 6668        )
 6669        .unwrap(),
 6670    );
 6671
 6672    let text = "fn a() {}";
 6673
 6674    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
 6675    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 6676    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
 6677    editor
 6678        .condition::<crate::EditorEvent>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
 6679        .await;
 6680
 6681    editor.update_in(cx, |editor, window, cx| {
 6682        editor.change_selections(None, window, cx, |s| s.select_ranges([5..5, 8..8, 9..9]));
 6683        editor.newline(&Newline, window, cx);
 6684        assert_eq!(editor.text(cx), "fn a(\n    \n) {\n    \n}\n");
 6685        assert_eq!(
 6686            editor.selections.ranges(cx),
 6687            &[
 6688                Point::new(1, 4)..Point::new(1, 4),
 6689                Point::new(3, 4)..Point::new(3, 4),
 6690                Point::new(5, 0)..Point::new(5, 0)
 6691            ]
 6692        );
 6693    });
 6694}
 6695
 6696#[gpui::test]
 6697async fn test_autoindent_selections(cx: &mut TestAppContext) {
 6698    init_test(cx, |_| {});
 6699
 6700    {
 6701        let mut cx = EditorLspTestContext::new_rust(Default::default(), cx).await;
 6702        cx.set_state(indoc! {"
 6703            impl A {
 6704
 6705                fn b() {}
 6706
 6707            «fn c() {
 6708
 6709            }ˇ»
 6710            }
 6711        "});
 6712
 6713        cx.update_editor(|editor, window, cx| {
 6714            editor.autoindent(&Default::default(), window, cx);
 6715        });
 6716
 6717        cx.assert_editor_state(indoc! {"
 6718            impl A {
 6719
 6720                fn b() {}
 6721
 6722                «fn c() {
 6723
 6724                }ˇ»
 6725            }
 6726        "});
 6727    }
 6728
 6729    {
 6730        let mut cx = EditorTestContext::new_multibuffer(
 6731            cx,
 6732            [indoc! { "
 6733                impl A {
 6734                «
 6735                // a
 6736                fn b(){}
 6737                »
 6738                «
 6739                    }
 6740                    fn c(){}
 6741                »
 6742            "}],
 6743        );
 6744
 6745        let buffer = cx.update_editor(|editor, _, cx| {
 6746            let buffer = editor.buffer().update(cx, |buffer, _| {
 6747                buffer.all_buffers().iter().next().unwrap().clone()
 6748            });
 6749            buffer.update(cx, |buffer, cx| buffer.set_language(Some(rust_lang()), cx));
 6750            buffer
 6751        });
 6752
 6753        cx.run_until_parked();
 6754        cx.update_editor(|editor, window, cx| {
 6755            editor.select_all(&Default::default(), window, cx);
 6756            editor.autoindent(&Default::default(), window, cx)
 6757        });
 6758        cx.run_until_parked();
 6759
 6760        cx.update(|_, cx| {
 6761            assert_eq!(
 6762                buffer.read(cx).text(),
 6763                indoc! { "
 6764                    impl A {
 6765
 6766                        // a
 6767                        fn b(){}
 6768
 6769
 6770                    }
 6771                    fn c(){}
 6772
 6773                " }
 6774            )
 6775        });
 6776    }
 6777}
 6778
 6779#[gpui::test]
 6780async fn test_autoclose_and_auto_surround_pairs(cx: &mut TestAppContext) {
 6781    init_test(cx, |_| {});
 6782
 6783    let mut cx = EditorTestContext::new(cx).await;
 6784
 6785    let language = Arc::new(Language::new(
 6786        LanguageConfig {
 6787            brackets: BracketPairConfig {
 6788                pairs: vec![
 6789                    BracketPair {
 6790                        start: "{".to_string(),
 6791                        end: "}".to_string(),
 6792                        close: true,
 6793                        surround: true,
 6794                        newline: true,
 6795                    },
 6796                    BracketPair {
 6797                        start: "(".to_string(),
 6798                        end: ")".to_string(),
 6799                        close: true,
 6800                        surround: true,
 6801                        newline: true,
 6802                    },
 6803                    BracketPair {
 6804                        start: "/*".to_string(),
 6805                        end: " */".to_string(),
 6806                        close: true,
 6807                        surround: true,
 6808                        newline: true,
 6809                    },
 6810                    BracketPair {
 6811                        start: "[".to_string(),
 6812                        end: "]".to_string(),
 6813                        close: false,
 6814                        surround: false,
 6815                        newline: true,
 6816                    },
 6817                    BracketPair {
 6818                        start: "\"".to_string(),
 6819                        end: "\"".to_string(),
 6820                        close: true,
 6821                        surround: true,
 6822                        newline: false,
 6823                    },
 6824                    BracketPair {
 6825                        start: "<".to_string(),
 6826                        end: ">".to_string(),
 6827                        close: false,
 6828                        surround: true,
 6829                        newline: true,
 6830                    },
 6831                ],
 6832                ..Default::default()
 6833            },
 6834            autoclose_before: "})]".to_string(),
 6835            ..Default::default()
 6836        },
 6837        Some(tree_sitter_rust::LANGUAGE.into()),
 6838    ));
 6839
 6840    cx.language_registry().add(language.clone());
 6841    cx.update_buffer(|buffer, cx| {
 6842        buffer.set_language(Some(language), cx);
 6843    });
 6844
 6845    cx.set_state(
 6846        &r#"
 6847            🏀ˇ
 6848            εˇ
 6849            ❤️ˇ
 6850        "#
 6851        .unindent(),
 6852    );
 6853
 6854    // autoclose multiple nested brackets at multiple cursors
 6855    cx.update_editor(|editor, window, cx| {
 6856        editor.handle_input("{", window, cx);
 6857        editor.handle_input("{", window, cx);
 6858        editor.handle_input("{", window, cx);
 6859    });
 6860    cx.assert_editor_state(
 6861        &"
 6862            🏀{{{ˇ}}}
 6863            ε{{{ˇ}}}
 6864            ❤️{{{ˇ}}}
 6865        "
 6866        .unindent(),
 6867    );
 6868
 6869    // insert a different closing bracket
 6870    cx.update_editor(|editor, window, cx| {
 6871        editor.handle_input(")", window, cx);
 6872    });
 6873    cx.assert_editor_state(
 6874        &"
 6875            🏀{{{)ˇ}}}
 6876            ε{{{)ˇ}}}
 6877            ❤️{{{)ˇ}}}
 6878        "
 6879        .unindent(),
 6880    );
 6881
 6882    // skip over the auto-closed brackets when typing a closing bracket
 6883    cx.update_editor(|editor, window, cx| {
 6884        editor.move_right(&MoveRight, window, cx);
 6885        editor.handle_input("}", window, cx);
 6886        editor.handle_input("}", window, cx);
 6887        editor.handle_input("}", window, cx);
 6888    });
 6889    cx.assert_editor_state(
 6890        &"
 6891            🏀{{{)}}}}ˇ
 6892            ε{{{)}}}}ˇ
 6893            ❤️{{{)}}}}ˇ
 6894        "
 6895        .unindent(),
 6896    );
 6897
 6898    // autoclose multi-character pairs
 6899    cx.set_state(
 6900        &"
 6901            ˇ
 6902            ˇ
 6903        "
 6904        .unindent(),
 6905    );
 6906    cx.update_editor(|editor, window, cx| {
 6907        editor.handle_input("/", window, cx);
 6908        editor.handle_input("*", window, cx);
 6909    });
 6910    cx.assert_editor_state(
 6911        &"
 6912            /*ˇ */
 6913            /*ˇ */
 6914        "
 6915        .unindent(),
 6916    );
 6917
 6918    // one cursor autocloses a multi-character pair, one cursor
 6919    // does not autoclose.
 6920    cx.set_state(
 6921        &"
 6922 6923            ˇ
 6924        "
 6925        .unindent(),
 6926    );
 6927    cx.update_editor(|editor, window, cx| editor.handle_input("*", window, cx));
 6928    cx.assert_editor_state(
 6929        &"
 6930            /*ˇ */
 6931 6932        "
 6933        .unindent(),
 6934    );
 6935
 6936    // Don't autoclose if the next character isn't whitespace and isn't
 6937    // listed in the language's "autoclose_before" section.
 6938    cx.set_state("ˇa b");
 6939    cx.update_editor(|editor, window, cx| editor.handle_input("{", window, cx));
 6940    cx.assert_editor_state("{ˇa b");
 6941
 6942    // Don't autoclose if `close` is false for the bracket pair
 6943    cx.set_state("ˇ");
 6944    cx.update_editor(|editor, window, cx| editor.handle_input("[", window, cx));
 6945    cx.assert_editor_state("");
 6946
 6947    // Surround with brackets if text is selected
 6948    cx.set_state("«aˇ» b");
 6949    cx.update_editor(|editor, window, cx| editor.handle_input("{", window, cx));
 6950    cx.assert_editor_state("{«aˇ»} b");
 6951
 6952    // Autoclose when not immediately after a word character
 6953    cx.set_state("a ˇ");
 6954    cx.update_editor(|editor, window, cx| editor.handle_input("\"", window, cx));
 6955    cx.assert_editor_state("a \"ˇ\"");
 6956
 6957    // Autoclose pair where the start and end characters are the same
 6958    cx.update_editor(|editor, window, cx| editor.handle_input("\"", window, cx));
 6959    cx.assert_editor_state("a \"\"ˇ");
 6960
 6961    // Don't autoclose when immediately after a word character
 6962    cx.set_state("");
 6963    cx.update_editor(|editor, window, cx| editor.handle_input("\"", window, cx));
 6964    cx.assert_editor_state("a\"ˇ");
 6965
 6966    // Do autoclose when after a non-word character
 6967    cx.set_state("");
 6968    cx.update_editor(|editor, window, cx| editor.handle_input("\"", window, cx));
 6969    cx.assert_editor_state("{\"ˇ\"");
 6970
 6971    // Non identical pairs autoclose regardless of preceding character
 6972    cx.set_state("");
 6973    cx.update_editor(|editor, window, cx| editor.handle_input("{", window, cx));
 6974    cx.assert_editor_state("a{ˇ}");
 6975
 6976    // Don't autoclose pair if autoclose is disabled
 6977    cx.set_state("ˇ");
 6978    cx.update_editor(|editor, window, cx| editor.handle_input("<", window, cx));
 6979    cx.assert_editor_state("");
 6980
 6981    // Surround with brackets if text is selected and auto_surround is enabled, even if autoclose is disabled
 6982    cx.set_state("«aˇ» b");
 6983    cx.update_editor(|editor, window, cx| editor.handle_input("<", window, cx));
 6984    cx.assert_editor_state("<«aˇ»> b");
 6985}
 6986
 6987#[gpui::test]
 6988async fn test_always_treat_brackets_as_autoclosed_skip_over(cx: &mut TestAppContext) {
 6989    init_test(cx, |settings| {
 6990        settings.defaults.always_treat_brackets_as_autoclosed = Some(true);
 6991    });
 6992
 6993    let mut cx = EditorTestContext::new(cx).await;
 6994
 6995    let language = Arc::new(Language::new(
 6996        LanguageConfig {
 6997            brackets: BracketPairConfig {
 6998                pairs: vec![
 6999                    BracketPair {
 7000                        start: "{".to_string(),
 7001                        end: "}".to_string(),
 7002                        close: true,
 7003                        surround: true,
 7004                        newline: true,
 7005                    },
 7006                    BracketPair {
 7007                        start: "(".to_string(),
 7008                        end: ")".to_string(),
 7009                        close: true,
 7010                        surround: true,
 7011                        newline: true,
 7012                    },
 7013                    BracketPair {
 7014                        start: "[".to_string(),
 7015                        end: "]".to_string(),
 7016                        close: false,
 7017                        surround: false,
 7018                        newline: true,
 7019                    },
 7020                ],
 7021                ..Default::default()
 7022            },
 7023            autoclose_before: "})]".to_string(),
 7024            ..Default::default()
 7025        },
 7026        Some(tree_sitter_rust::LANGUAGE.into()),
 7027    ));
 7028
 7029    cx.language_registry().add(language.clone());
 7030    cx.update_buffer(|buffer, cx| {
 7031        buffer.set_language(Some(language), cx);
 7032    });
 7033
 7034    cx.set_state(
 7035        &"
 7036            ˇ
 7037            ˇ
 7038            ˇ
 7039        "
 7040        .unindent(),
 7041    );
 7042
 7043    // ensure only matching closing brackets are skipped over
 7044    cx.update_editor(|editor, window, cx| {
 7045        editor.handle_input("}", window, cx);
 7046        editor.move_left(&MoveLeft, window, cx);
 7047        editor.handle_input(")", window, cx);
 7048        editor.move_left(&MoveLeft, window, cx);
 7049    });
 7050    cx.assert_editor_state(
 7051        &"
 7052            ˇ)}
 7053            ˇ)}
 7054            ˇ)}
 7055        "
 7056        .unindent(),
 7057    );
 7058
 7059    // skip-over closing brackets at multiple cursors
 7060    cx.update_editor(|editor, window, cx| {
 7061        editor.handle_input(")", window, cx);
 7062        editor.handle_input("}", window, cx);
 7063    });
 7064    cx.assert_editor_state(
 7065        &"
 7066            )}ˇ
 7067            )}ˇ
 7068            )}ˇ
 7069        "
 7070        .unindent(),
 7071    );
 7072
 7073    // ignore non-close brackets
 7074    cx.update_editor(|editor, window, cx| {
 7075        editor.handle_input("]", window, cx);
 7076        editor.move_left(&MoveLeft, window, cx);
 7077        editor.handle_input("]", window, cx);
 7078    });
 7079    cx.assert_editor_state(
 7080        &"
 7081            )}]ˇ]
 7082            )}]ˇ]
 7083            )}]ˇ]
 7084        "
 7085        .unindent(),
 7086    );
 7087}
 7088
 7089#[gpui::test]
 7090async fn test_autoclose_with_embedded_language(cx: &mut TestAppContext) {
 7091    init_test(cx, |_| {});
 7092
 7093    let mut cx = EditorTestContext::new(cx).await;
 7094
 7095    let html_language = Arc::new(
 7096        Language::new(
 7097            LanguageConfig {
 7098                name: "HTML".into(),
 7099                brackets: BracketPairConfig {
 7100                    pairs: vec![
 7101                        BracketPair {
 7102                            start: "<".into(),
 7103                            end: ">".into(),
 7104                            close: true,
 7105                            ..Default::default()
 7106                        },
 7107                        BracketPair {
 7108                            start: "{".into(),
 7109                            end: "}".into(),
 7110                            close: true,
 7111                            ..Default::default()
 7112                        },
 7113                        BracketPair {
 7114                            start: "(".into(),
 7115                            end: ")".into(),
 7116                            close: true,
 7117                            ..Default::default()
 7118                        },
 7119                    ],
 7120                    ..Default::default()
 7121                },
 7122                autoclose_before: "})]>".into(),
 7123                ..Default::default()
 7124            },
 7125            Some(tree_sitter_html::LANGUAGE.into()),
 7126        )
 7127        .with_injection_query(
 7128            r#"
 7129            (script_element
 7130                (raw_text) @injection.content
 7131                (#set! injection.language "javascript"))
 7132            "#,
 7133        )
 7134        .unwrap(),
 7135    );
 7136
 7137    let javascript_language = Arc::new(Language::new(
 7138        LanguageConfig {
 7139            name: "JavaScript".into(),
 7140            brackets: BracketPairConfig {
 7141                pairs: vec![
 7142                    BracketPair {
 7143                        start: "/*".into(),
 7144                        end: " */".into(),
 7145                        close: true,
 7146                        ..Default::default()
 7147                    },
 7148                    BracketPair {
 7149                        start: "{".into(),
 7150                        end: "}".into(),
 7151                        close: true,
 7152                        ..Default::default()
 7153                    },
 7154                    BracketPair {
 7155                        start: "(".into(),
 7156                        end: ")".into(),
 7157                        close: true,
 7158                        ..Default::default()
 7159                    },
 7160                ],
 7161                ..Default::default()
 7162            },
 7163            autoclose_before: "})]>".into(),
 7164            ..Default::default()
 7165        },
 7166        Some(tree_sitter_typescript::LANGUAGE_TSX.into()),
 7167    ));
 7168
 7169    cx.language_registry().add(html_language.clone());
 7170    cx.language_registry().add(javascript_language.clone());
 7171
 7172    cx.update_buffer(|buffer, cx| {
 7173        buffer.set_language(Some(html_language), cx);
 7174    });
 7175
 7176    cx.set_state(
 7177        &r#"
 7178            <body>ˇ
 7179                <script>
 7180                    var x = 1;ˇ
 7181                </script>
 7182            </body>ˇ
 7183        "#
 7184        .unindent(),
 7185    );
 7186
 7187    // Precondition: different languages are active at different locations.
 7188    cx.update_editor(|editor, window, cx| {
 7189        let snapshot = editor.snapshot(window, cx);
 7190        let cursors = editor.selections.ranges::<usize>(cx);
 7191        let languages = cursors
 7192            .iter()
 7193            .map(|c| snapshot.language_at(c.start).unwrap().name())
 7194            .collect::<Vec<_>>();
 7195        assert_eq!(
 7196            languages,
 7197            &["HTML".into(), "JavaScript".into(), "HTML".into()]
 7198        );
 7199    });
 7200
 7201    // Angle brackets autoclose in HTML, but not JavaScript.
 7202    cx.update_editor(|editor, window, cx| {
 7203        editor.handle_input("<", window, cx);
 7204        editor.handle_input("a", window, cx);
 7205    });
 7206    cx.assert_editor_state(
 7207        &r#"
 7208            <body><aˇ>
 7209                <script>
 7210                    var x = 1;<aˇ
 7211                </script>
 7212            </body><aˇ>
 7213        "#
 7214        .unindent(),
 7215    );
 7216
 7217    // Curly braces and parens autoclose in both HTML and JavaScript.
 7218    cx.update_editor(|editor, window, cx| {
 7219        editor.handle_input(" b=", window, cx);
 7220        editor.handle_input("{", window, cx);
 7221        editor.handle_input("c", window, cx);
 7222        editor.handle_input("(", window, cx);
 7223    });
 7224    cx.assert_editor_state(
 7225        &r#"
 7226            <body><a b={c(ˇ)}>
 7227                <script>
 7228                    var x = 1;<a b={c(ˇ)}
 7229                </script>
 7230            </body><a b={c(ˇ)}>
 7231        "#
 7232        .unindent(),
 7233    );
 7234
 7235    // Brackets that were already autoclosed are skipped.
 7236    cx.update_editor(|editor, window, cx| {
 7237        editor.handle_input(")", window, cx);
 7238        editor.handle_input("d", window, cx);
 7239        editor.handle_input("}", window, cx);
 7240    });
 7241    cx.assert_editor_state(
 7242        &r#"
 7243            <body><a b={c()d}ˇ>
 7244                <script>
 7245                    var x = 1;<a b={c()d}ˇ
 7246                </script>
 7247            </body><a b={c()d}ˇ>
 7248        "#
 7249        .unindent(),
 7250    );
 7251    cx.update_editor(|editor, window, cx| {
 7252        editor.handle_input(">", window, cx);
 7253    });
 7254    cx.assert_editor_state(
 7255        &r#"
 7256            <body><a b={c()d}>ˇ
 7257                <script>
 7258                    var x = 1;<a b={c()d}>ˇ
 7259                </script>
 7260            </body><a b={c()d}>ˇ
 7261        "#
 7262        .unindent(),
 7263    );
 7264
 7265    // Reset
 7266    cx.set_state(
 7267        &r#"
 7268            <body>ˇ
 7269                <script>
 7270                    var x = 1;ˇ
 7271                </script>
 7272            </body>ˇ
 7273        "#
 7274        .unindent(),
 7275    );
 7276
 7277    cx.update_editor(|editor, window, cx| {
 7278        editor.handle_input("<", window, cx);
 7279    });
 7280    cx.assert_editor_state(
 7281        &r#"
 7282            <body><ˇ>
 7283                <script>
 7284                    var x = 1;<ˇ
 7285                </script>
 7286            </body><ˇ>
 7287        "#
 7288        .unindent(),
 7289    );
 7290
 7291    // When backspacing, the closing angle brackets are removed.
 7292    cx.update_editor(|editor, window, cx| {
 7293        editor.backspace(&Backspace, window, cx);
 7294    });
 7295    cx.assert_editor_state(
 7296        &r#"
 7297            <body>ˇ
 7298                <script>
 7299                    var x = 1;ˇ
 7300                </script>
 7301            </body>ˇ
 7302        "#
 7303        .unindent(),
 7304    );
 7305
 7306    // Block comments autoclose in JavaScript, but not HTML.
 7307    cx.update_editor(|editor, window, cx| {
 7308        editor.handle_input("/", window, cx);
 7309        editor.handle_input("*", window, cx);
 7310    });
 7311    cx.assert_editor_state(
 7312        &r#"
 7313            <body>/*ˇ
 7314                <script>
 7315                    var x = 1;/*ˇ */
 7316                </script>
 7317            </body>/*ˇ
 7318        "#
 7319        .unindent(),
 7320    );
 7321}
 7322
 7323#[gpui::test]
 7324async fn test_autoclose_with_overrides(cx: &mut TestAppContext) {
 7325    init_test(cx, |_| {});
 7326
 7327    let mut cx = EditorTestContext::new(cx).await;
 7328
 7329    let rust_language = Arc::new(
 7330        Language::new(
 7331            LanguageConfig {
 7332                name: "Rust".into(),
 7333                brackets: serde_json::from_value(json!([
 7334                    { "start": "{", "end": "}", "close": true, "newline": true },
 7335                    { "start": "\"", "end": "\"", "close": true, "newline": false, "not_in": ["string"] },
 7336                ]))
 7337                .unwrap(),
 7338                autoclose_before: "})]>".into(),
 7339                ..Default::default()
 7340            },
 7341            Some(tree_sitter_rust::LANGUAGE.into()),
 7342        )
 7343        .with_override_query("(string_literal) @string")
 7344        .unwrap(),
 7345    );
 7346
 7347    cx.language_registry().add(rust_language.clone());
 7348    cx.update_buffer(|buffer, cx| {
 7349        buffer.set_language(Some(rust_language), cx);
 7350    });
 7351
 7352    cx.set_state(
 7353        &r#"
 7354            let x = ˇ
 7355        "#
 7356        .unindent(),
 7357    );
 7358
 7359    // Inserting a quotation mark. A closing quotation mark is automatically inserted.
 7360    cx.update_editor(|editor, window, cx| {
 7361        editor.handle_input("\"", window, cx);
 7362    });
 7363    cx.assert_editor_state(
 7364        &r#"
 7365            let x = "ˇ"
 7366        "#
 7367        .unindent(),
 7368    );
 7369
 7370    // Inserting another quotation mark. The cursor moves across the existing
 7371    // automatically-inserted quotation mark.
 7372    cx.update_editor(|editor, window, cx| {
 7373        editor.handle_input("\"", window, cx);
 7374    });
 7375    cx.assert_editor_state(
 7376        &r#"
 7377            let x = ""ˇ
 7378        "#
 7379        .unindent(),
 7380    );
 7381
 7382    // Reset
 7383    cx.set_state(
 7384        &r#"
 7385            let x = ˇ
 7386        "#
 7387        .unindent(),
 7388    );
 7389
 7390    // Inserting a quotation mark inside of a string. A second quotation mark is not inserted.
 7391    cx.update_editor(|editor, window, cx| {
 7392        editor.handle_input("\"", window, cx);
 7393        editor.handle_input(" ", window, cx);
 7394        editor.move_left(&Default::default(), window, cx);
 7395        editor.handle_input("\\", window, cx);
 7396        editor.handle_input("\"", window, cx);
 7397    });
 7398    cx.assert_editor_state(
 7399        &r#"
 7400            let x = "\"ˇ "
 7401        "#
 7402        .unindent(),
 7403    );
 7404
 7405    // Inserting a closing quotation mark at the position of an automatically-inserted quotation
 7406    // mark. Nothing is inserted.
 7407    cx.update_editor(|editor, window, cx| {
 7408        editor.move_right(&Default::default(), window, cx);
 7409        editor.handle_input("\"", window, cx);
 7410    });
 7411    cx.assert_editor_state(
 7412        &r#"
 7413            let x = "\" "ˇ
 7414        "#
 7415        .unindent(),
 7416    );
 7417}
 7418
 7419#[gpui::test]
 7420async fn test_surround_with_pair(cx: &mut TestAppContext) {
 7421    init_test(cx, |_| {});
 7422
 7423    let language = Arc::new(Language::new(
 7424        LanguageConfig {
 7425            brackets: BracketPairConfig {
 7426                pairs: vec![
 7427                    BracketPair {
 7428                        start: "{".to_string(),
 7429                        end: "}".to_string(),
 7430                        close: true,
 7431                        surround: true,
 7432                        newline: true,
 7433                    },
 7434                    BracketPair {
 7435                        start: "/* ".to_string(),
 7436                        end: "*/".to_string(),
 7437                        close: true,
 7438                        surround: true,
 7439                        ..Default::default()
 7440                    },
 7441                ],
 7442                ..Default::default()
 7443            },
 7444            ..Default::default()
 7445        },
 7446        Some(tree_sitter_rust::LANGUAGE.into()),
 7447    ));
 7448
 7449    let text = r#"
 7450        a
 7451        b
 7452        c
 7453    "#
 7454    .unindent();
 7455
 7456    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
 7457    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 7458    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
 7459    editor
 7460        .condition::<crate::EditorEvent>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
 7461        .await;
 7462
 7463    editor.update_in(cx, |editor, window, cx| {
 7464        editor.change_selections(None, window, cx, |s| {
 7465            s.select_display_ranges([
 7466                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 1),
 7467                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 1),
 7468                DisplayPoint::new(DisplayRow(2), 0)..DisplayPoint::new(DisplayRow(2), 1),
 7469            ])
 7470        });
 7471
 7472        editor.handle_input("{", window, cx);
 7473        editor.handle_input("{", window, cx);
 7474        editor.handle_input("{", window, cx);
 7475        assert_eq!(
 7476            editor.text(cx),
 7477            "
 7478                {{{a}}}
 7479                {{{b}}}
 7480                {{{c}}}
 7481            "
 7482            .unindent()
 7483        );
 7484        assert_eq!(
 7485            editor.selections.display_ranges(cx),
 7486            [
 7487                DisplayPoint::new(DisplayRow(0), 3)..DisplayPoint::new(DisplayRow(0), 4),
 7488                DisplayPoint::new(DisplayRow(1), 3)..DisplayPoint::new(DisplayRow(1), 4),
 7489                DisplayPoint::new(DisplayRow(2), 3)..DisplayPoint::new(DisplayRow(2), 4)
 7490            ]
 7491        );
 7492
 7493        editor.undo(&Undo, window, cx);
 7494        editor.undo(&Undo, window, cx);
 7495        editor.undo(&Undo, window, cx);
 7496        assert_eq!(
 7497            editor.text(cx),
 7498            "
 7499                a
 7500                b
 7501                c
 7502            "
 7503            .unindent()
 7504        );
 7505        assert_eq!(
 7506            editor.selections.display_ranges(cx),
 7507            [
 7508                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 1),
 7509                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 1),
 7510                DisplayPoint::new(DisplayRow(2), 0)..DisplayPoint::new(DisplayRow(2), 1)
 7511            ]
 7512        );
 7513
 7514        // Ensure inserting the first character of a multi-byte bracket pair
 7515        // doesn't surround the selections with the bracket.
 7516        editor.handle_input("/", window, cx);
 7517        assert_eq!(
 7518            editor.text(cx),
 7519            "
 7520                /
 7521                /
 7522                /
 7523            "
 7524            .unindent()
 7525        );
 7526        assert_eq!(
 7527            editor.selections.display_ranges(cx),
 7528            [
 7529                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 1),
 7530                DisplayPoint::new(DisplayRow(1), 1)..DisplayPoint::new(DisplayRow(1), 1),
 7531                DisplayPoint::new(DisplayRow(2), 1)..DisplayPoint::new(DisplayRow(2), 1)
 7532            ]
 7533        );
 7534
 7535        editor.undo(&Undo, window, cx);
 7536        assert_eq!(
 7537            editor.text(cx),
 7538            "
 7539                a
 7540                b
 7541                c
 7542            "
 7543            .unindent()
 7544        );
 7545        assert_eq!(
 7546            editor.selections.display_ranges(cx),
 7547            [
 7548                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 1),
 7549                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 1),
 7550                DisplayPoint::new(DisplayRow(2), 0)..DisplayPoint::new(DisplayRow(2), 1)
 7551            ]
 7552        );
 7553
 7554        // Ensure inserting the last character of a multi-byte bracket pair
 7555        // doesn't surround the selections with the bracket.
 7556        editor.handle_input("*", window, cx);
 7557        assert_eq!(
 7558            editor.text(cx),
 7559            "
 7560                *
 7561                *
 7562                *
 7563            "
 7564            .unindent()
 7565        );
 7566        assert_eq!(
 7567            editor.selections.display_ranges(cx),
 7568            [
 7569                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 1),
 7570                DisplayPoint::new(DisplayRow(1), 1)..DisplayPoint::new(DisplayRow(1), 1),
 7571                DisplayPoint::new(DisplayRow(2), 1)..DisplayPoint::new(DisplayRow(2), 1)
 7572            ]
 7573        );
 7574    });
 7575}
 7576
 7577#[gpui::test]
 7578async fn test_delete_autoclose_pair(cx: &mut TestAppContext) {
 7579    init_test(cx, |_| {});
 7580
 7581    let language = Arc::new(Language::new(
 7582        LanguageConfig {
 7583            brackets: BracketPairConfig {
 7584                pairs: vec![BracketPair {
 7585                    start: "{".to_string(),
 7586                    end: "}".to_string(),
 7587                    close: true,
 7588                    surround: true,
 7589                    newline: true,
 7590                }],
 7591                ..Default::default()
 7592            },
 7593            autoclose_before: "}".to_string(),
 7594            ..Default::default()
 7595        },
 7596        Some(tree_sitter_rust::LANGUAGE.into()),
 7597    ));
 7598
 7599    let text = r#"
 7600        a
 7601        b
 7602        c
 7603    "#
 7604    .unindent();
 7605
 7606    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
 7607    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 7608    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
 7609    editor
 7610        .condition::<crate::EditorEvent>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
 7611        .await;
 7612
 7613    editor.update_in(cx, |editor, window, cx| {
 7614        editor.change_selections(None, window, cx, |s| {
 7615            s.select_ranges([
 7616                Point::new(0, 1)..Point::new(0, 1),
 7617                Point::new(1, 1)..Point::new(1, 1),
 7618                Point::new(2, 1)..Point::new(2, 1),
 7619            ])
 7620        });
 7621
 7622        editor.handle_input("{", window, cx);
 7623        editor.handle_input("{", window, cx);
 7624        editor.handle_input("_", window, cx);
 7625        assert_eq!(
 7626            editor.text(cx),
 7627            "
 7628                a{{_}}
 7629                b{{_}}
 7630                c{{_}}
 7631            "
 7632            .unindent()
 7633        );
 7634        assert_eq!(
 7635            editor.selections.ranges::<Point>(cx),
 7636            [
 7637                Point::new(0, 4)..Point::new(0, 4),
 7638                Point::new(1, 4)..Point::new(1, 4),
 7639                Point::new(2, 4)..Point::new(2, 4)
 7640            ]
 7641        );
 7642
 7643        editor.backspace(&Default::default(), window, cx);
 7644        editor.backspace(&Default::default(), window, cx);
 7645        assert_eq!(
 7646            editor.text(cx),
 7647            "
 7648                a{}
 7649                b{}
 7650                c{}
 7651            "
 7652            .unindent()
 7653        );
 7654        assert_eq!(
 7655            editor.selections.ranges::<Point>(cx),
 7656            [
 7657                Point::new(0, 2)..Point::new(0, 2),
 7658                Point::new(1, 2)..Point::new(1, 2),
 7659                Point::new(2, 2)..Point::new(2, 2)
 7660            ]
 7661        );
 7662
 7663        editor.delete_to_previous_word_start(&Default::default(), window, cx);
 7664        assert_eq!(
 7665            editor.text(cx),
 7666            "
 7667                a
 7668                b
 7669                c
 7670            "
 7671            .unindent()
 7672        );
 7673        assert_eq!(
 7674            editor.selections.ranges::<Point>(cx),
 7675            [
 7676                Point::new(0, 1)..Point::new(0, 1),
 7677                Point::new(1, 1)..Point::new(1, 1),
 7678                Point::new(2, 1)..Point::new(2, 1)
 7679            ]
 7680        );
 7681    });
 7682}
 7683
 7684#[gpui::test]
 7685async fn test_always_treat_brackets_as_autoclosed_delete(cx: &mut TestAppContext) {
 7686    init_test(cx, |settings| {
 7687        settings.defaults.always_treat_brackets_as_autoclosed = Some(true);
 7688    });
 7689
 7690    let mut cx = EditorTestContext::new(cx).await;
 7691
 7692    let language = Arc::new(Language::new(
 7693        LanguageConfig {
 7694            brackets: BracketPairConfig {
 7695                pairs: vec![
 7696                    BracketPair {
 7697                        start: "{".to_string(),
 7698                        end: "}".to_string(),
 7699                        close: true,
 7700                        surround: true,
 7701                        newline: true,
 7702                    },
 7703                    BracketPair {
 7704                        start: "(".to_string(),
 7705                        end: ")".to_string(),
 7706                        close: true,
 7707                        surround: true,
 7708                        newline: true,
 7709                    },
 7710                    BracketPair {
 7711                        start: "[".to_string(),
 7712                        end: "]".to_string(),
 7713                        close: false,
 7714                        surround: true,
 7715                        newline: true,
 7716                    },
 7717                ],
 7718                ..Default::default()
 7719            },
 7720            autoclose_before: "})]".to_string(),
 7721            ..Default::default()
 7722        },
 7723        Some(tree_sitter_rust::LANGUAGE.into()),
 7724    ));
 7725
 7726    cx.language_registry().add(language.clone());
 7727    cx.update_buffer(|buffer, cx| {
 7728        buffer.set_language(Some(language), cx);
 7729    });
 7730
 7731    cx.set_state(
 7732        &"
 7733            {(ˇ)}
 7734            [[ˇ]]
 7735            {(ˇ)}
 7736        "
 7737        .unindent(),
 7738    );
 7739
 7740    cx.update_editor(|editor, window, cx| {
 7741        editor.backspace(&Default::default(), window, cx);
 7742        editor.backspace(&Default::default(), window, cx);
 7743    });
 7744
 7745    cx.assert_editor_state(
 7746        &"
 7747            ˇ
 7748            ˇ]]
 7749            ˇ
 7750        "
 7751        .unindent(),
 7752    );
 7753
 7754    cx.update_editor(|editor, window, cx| {
 7755        editor.handle_input("{", window, cx);
 7756        editor.handle_input("{", window, cx);
 7757        editor.move_right(&MoveRight, window, cx);
 7758        editor.move_right(&MoveRight, window, cx);
 7759        editor.move_left(&MoveLeft, window, cx);
 7760        editor.move_left(&MoveLeft, window, cx);
 7761        editor.backspace(&Default::default(), window, cx);
 7762    });
 7763
 7764    cx.assert_editor_state(
 7765        &"
 7766            {ˇ}
 7767            {ˇ}]]
 7768            {ˇ}
 7769        "
 7770        .unindent(),
 7771    );
 7772
 7773    cx.update_editor(|editor, window, cx| {
 7774        editor.backspace(&Default::default(), window, cx);
 7775    });
 7776
 7777    cx.assert_editor_state(
 7778        &"
 7779            ˇ
 7780            ˇ]]
 7781            ˇ
 7782        "
 7783        .unindent(),
 7784    );
 7785}
 7786
 7787#[gpui::test]
 7788async fn test_auto_replace_emoji_shortcode(cx: &mut TestAppContext) {
 7789    init_test(cx, |_| {});
 7790
 7791    let language = Arc::new(Language::new(
 7792        LanguageConfig::default(),
 7793        Some(tree_sitter_rust::LANGUAGE.into()),
 7794    ));
 7795
 7796    let buffer = cx.new(|cx| Buffer::local("", cx).with_language(language, cx));
 7797    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 7798    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
 7799    editor
 7800        .condition::<crate::EditorEvent>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
 7801        .await;
 7802
 7803    editor.update_in(cx, |editor, window, cx| {
 7804        editor.set_auto_replace_emoji_shortcode(true);
 7805
 7806        editor.handle_input("Hello ", window, cx);
 7807        editor.handle_input(":wave", window, cx);
 7808        assert_eq!(editor.text(cx), "Hello :wave".unindent());
 7809
 7810        editor.handle_input(":", window, cx);
 7811        assert_eq!(editor.text(cx), "Hello 👋".unindent());
 7812
 7813        editor.handle_input(" :smile", window, cx);
 7814        assert_eq!(editor.text(cx), "Hello 👋 :smile".unindent());
 7815
 7816        editor.handle_input(":", window, cx);
 7817        assert_eq!(editor.text(cx), "Hello 👋 😄".unindent());
 7818
 7819        // Ensure shortcode gets replaced when it is part of a word that only consists of emojis
 7820        editor.handle_input(":wave", window, cx);
 7821        assert_eq!(editor.text(cx), "Hello 👋 😄:wave".unindent());
 7822
 7823        editor.handle_input(":", window, cx);
 7824        assert_eq!(editor.text(cx), "Hello 👋 😄👋".unindent());
 7825
 7826        editor.handle_input(":1", window, cx);
 7827        assert_eq!(editor.text(cx), "Hello 👋 😄👋:1".unindent());
 7828
 7829        editor.handle_input(":", window, cx);
 7830        assert_eq!(editor.text(cx), "Hello 👋 😄👋:1:".unindent());
 7831
 7832        // Ensure shortcode does not get replaced when it is part of a word
 7833        editor.handle_input(" Test:wave", window, cx);
 7834        assert_eq!(editor.text(cx), "Hello 👋 😄👋:1: Test:wave".unindent());
 7835
 7836        editor.handle_input(":", window, cx);
 7837        assert_eq!(editor.text(cx), "Hello 👋 😄👋:1: Test:wave:".unindent());
 7838
 7839        editor.set_auto_replace_emoji_shortcode(false);
 7840
 7841        // Ensure shortcode does not get replaced when auto replace is off
 7842        editor.handle_input(" :wave", window, cx);
 7843        assert_eq!(
 7844            editor.text(cx),
 7845            "Hello 👋 😄👋:1: Test:wave: :wave".unindent()
 7846        );
 7847
 7848        editor.handle_input(":", window, cx);
 7849        assert_eq!(
 7850            editor.text(cx),
 7851            "Hello 👋 😄👋:1: Test:wave: :wave:".unindent()
 7852        );
 7853    });
 7854}
 7855
 7856#[gpui::test]
 7857async fn test_snippet_placeholder_choices(cx: &mut TestAppContext) {
 7858    init_test(cx, |_| {});
 7859
 7860    let (text, insertion_ranges) = marked_text_ranges(
 7861        indoc! {"
 7862            ˇ
 7863        "},
 7864        false,
 7865    );
 7866
 7867    let buffer = cx.update(|cx| MultiBuffer::build_simple(&text, cx));
 7868    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
 7869
 7870    _ = editor.update_in(cx, |editor, window, cx| {
 7871        let snippet = Snippet::parse("type ${1|,i32,u32|} = $2").unwrap();
 7872
 7873        editor
 7874            .insert_snippet(&insertion_ranges, snippet, window, cx)
 7875            .unwrap();
 7876
 7877        fn assert(editor: &mut Editor, cx: &mut Context<Editor>, marked_text: &str) {
 7878            let (expected_text, selection_ranges) = marked_text_ranges(marked_text, false);
 7879            assert_eq!(editor.text(cx), expected_text);
 7880            assert_eq!(editor.selections.ranges::<usize>(cx), selection_ranges);
 7881        }
 7882
 7883        assert(
 7884            editor,
 7885            cx,
 7886            indoc! {"
 7887            type «» =•
 7888            "},
 7889        );
 7890
 7891        assert!(editor.context_menu_visible(), "There should be a matches");
 7892    });
 7893}
 7894
 7895#[gpui::test]
 7896async fn test_snippets(cx: &mut TestAppContext) {
 7897    init_test(cx, |_| {});
 7898
 7899    let (text, insertion_ranges) = marked_text_ranges(
 7900        indoc! {"
 7901            a.ˇ b
 7902            a.ˇ b
 7903            a.ˇ b
 7904        "},
 7905        false,
 7906    );
 7907
 7908    let buffer = cx.update(|cx| MultiBuffer::build_simple(&text, cx));
 7909    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
 7910
 7911    editor.update_in(cx, |editor, window, cx| {
 7912        let snippet = Snippet::parse("f(${1:one}, ${2:two}, ${1:three})$0").unwrap();
 7913
 7914        editor
 7915            .insert_snippet(&insertion_ranges, snippet, window, cx)
 7916            .unwrap();
 7917
 7918        fn assert(editor: &mut Editor, cx: &mut Context<Editor>, marked_text: &str) {
 7919            let (expected_text, selection_ranges) = marked_text_ranges(marked_text, false);
 7920            assert_eq!(editor.text(cx), expected_text);
 7921            assert_eq!(editor.selections.ranges::<usize>(cx), selection_ranges);
 7922        }
 7923
 7924        assert(
 7925            editor,
 7926            cx,
 7927            indoc! {"
 7928                a.f(«one», two, «three») b
 7929                a.f(«one», two, «three») b
 7930                a.f(«one», two, «three») b
 7931            "},
 7932        );
 7933
 7934        // Can't move earlier than the first tab stop
 7935        assert!(!editor.move_to_prev_snippet_tabstop(window, cx));
 7936        assert(
 7937            editor,
 7938            cx,
 7939            indoc! {"
 7940                a.f(«one», two, «three») b
 7941                a.f(«one», two, «three») b
 7942                a.f(«one», two, «three») b
 7943            "},
 7944        );
 7945
 7946        assert!(editor.move_to_next_snippet_tabstop(window, cx));
 7947        assert(
 7948            editor,
 7949            cx,
 7950            indoc! {"
 7951                a.f(one, «two», three) b
 7952                a.f(one, «two», three) b
 7953                a.f(one, «two», three) b
 7954            "},
 7955        );
 7956
 7957        editor.move_to_prev_snippet_tabstop(window, cx);
 7958        assert(
 7959            editor,
 7960            cx,
 7961            indoc! {"
 7962                a.f(«one», two, «three») b
 7963                a.f(«one», two, «three») b
 7964                a.f(«one», two, «three») b
 7965            "},
 7966        );
 7967
 7968        assert!(editor.move_to_next_snippet_tabstop(window, cx));
 7969        assert(
 7970            editor,
 7971            cx,
 7972            indoc! {"
 7973                a.f(one, «two», three) b
 7974                a.f(one, «two», three) b
 7975                a.f(one, «two», three) b
 7976            "},
 7977        );
 7978        assert!(editor.move_to_next_snippet_tabstop(window, cx));
 7979        assert(
 7980            editor,
 7981            cx,
 7982            indoc! {"
 7983                a.f(one, two, three)ˇ b
 7984                a.f(one, two, three)ˇ b
 7985                a.f(one, two, three)ˇ b
 7986            "},
 7987        );
 7988
 7989        // As soon as the last tab stop is reached, snippet state is gone
 7990        editor.move_to_prev_snippet_tabstop(window, cx);
 7991        assert(
 7992            editor,
 7993            cx,
 7994            indoc! {"
 7995                a.f(one, two, three)ˇ b
 7996                a.f(one, two, three)ˇ b
 7997                a.f(one, two, three)ˇ b
 7998            "},
 7999        );
 8000    });
 8001}
 8002
 8003#[gpui::test]
 8004async fn test_document_format_during_save(cx: &mut TestAppContext) {
 8005    init_test(cx, |_| {});
 8006
 8007    let fs = FakeFs::new(cx.executor());
 8008    fs.insert_file(path!("/file.rs"), Default::default()).await;
 8009
 8010    let project = Project::test(fs, [path!("/file.rs").as_ref()], cx).await;
 8011
 8012    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
 8013    language_registry.add(rust_lang());
 8014    let mut fake_servers = language_registry.register_fake_lsp(
 8015        "Rust",
 8016        FakeLspAdapter {
 8017            capabilities: lsp::ServerCapabilities {
 8018                document_formatting_provider: Some(lsp::OneOf::Left(true)),
 8019                ..Default::default()
 8020            },
 8021            ..Default::default()
 8022        },
 8023    );
 8024
 8025    let buffer = project
 8026        .update(cx, |project, cx| {
 8027            project.open_local_buffer(path!("/file.rs"), cx)
 8028        })
 8029        .await
 8030        .unwrap();
 8031
 8032    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 8033    let (editor, cx) = cx.add_window_view(|window, cx| {
 8034        build_editor_with_project(project.clone(), buffer, window, cx)
 8035    });
 8036    editor.update_in(cx, |editor, window, cx| {
 8037        editor.set_text("one\ntwo\nthree\n", window, cx)
 8038    });
 8039    assert!(cx.read(|cx| editor.is_dirty(cx)));
 8040
 8041    cx.executor().start_waiting();
 8042    let fake_server = fake_servers.next().await.unwrap();
 8043
 8044    {
 8045        fake_server.set_request_handler::<lsp::request::Formatting, _, _>(
 8046            move |params, _| async move {
 8047                assert_eq!(
 8048                    params.text_document.uri,
 8049                    lsp::Url::from_file_path(path!("/file.rs")).unwrap()
 8050                );
 8051                assert_eq!(params.options.tab_size, 4);
 8052                Ok(Some(vec![lsp::TextEdit::new(
 8053                    lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(1, 0)),
 8054                    ", ".to_string(),
 8055                )]))
 8056            },
 8057        );
 8058        let save = editor
 8059            .update_in(cx, |editor, window, cx| {
 8060                editor.save(true, project.clone(), window, cx)
 8061            })
 8062            .unwrap();
 8063        cx.executor().start_waiting();
 8064        save.await;
 8065
 8066        assert_eq!(
 8067            editor.update(cx, |editor, cx| editor.text(cx)),
 8068            "one, two\nthree\n"
 8069        );
 8070        assert!(!cx.read(|cx| editor.is_dirty(cx)));
 8071    }
 8072
 8073    {
 8074        editor.update_in(cx, |editor, window, cx| {
 8075            editor.set_text("one\ntwo\nthree\n", window, cx)
 8076        });
 8077        assert!(cx.read(|cx| editor.is_dirty(cx)));
 8078
 8079        // Ensure we can still save even if formatting hangs.
 8080        fake_server.set_request_handler::<lsp::request::Formatting, _, _>(
 8081            move |params, _| async move {
 8082                assert_eq!(
 8083                    params.text_document.uri,
 8084                    lsp::Url::from_file_path(path!("/file.rs")).unwrap()
 8085                );
 8086                futures::future::pending::<()>().await;
 8087                unreachable!()
 8088            },
 8089        );
 8090        let save = editor
 8091            .update_in(cx, |editor, window, cx| {
 8092                editor.save(true, project.clone(), window, cx)
 8093            })
 8094            .unwrap();
 8095        cx.executor().advance_clock(super::FORMAT_TIMEOUT);
 8096        cx.executor().start_waiting();
 8097        save.await;
 8098        assert_eq!(
 8099            editor.update(cx, |editor, cx| editor.text(cx)),
 8100            "one\ntwo\nthree\n"
 8101        );
 8102    }
 8103
 8104    // For non-dirty buffer, no formatting request should be sent
 8105    {
 8106        assert!(!cx.read(|cx| editor.is_dirty(cx)));
 8107
 8108        fake_server.set_request_handler::<lsp::request::Formatting, _, _>(move |_, _| async move {
 8109            panic!("Should not be invoked on non-dirty buffer");
 8110        });
 8111        let save = editor
 8112            .update_in(cx, |editor, window, cx| {
 8113                editor.save(true, project.clone(), window, cx)
 8114            })
 8115            .unwrap();
 8116        cx.executor().start_waiting();
 8117        save.await;
 8118    }
 8119
 8120    // Set rust language override and assert overridden tabsize is sent to language server
 8121    update_test_language_settings(cx, |settings| {
 8122        settings.languages.insert(
 8123            "Rust".into(),
 8124            LanguageSettingsContent {
 8125                tab_size: NonZeroU32::new(8),
 8126                ..Default::default()
 8127            },
 8128        );
 8129    });
 8130
 8131    {
 8132        editor.update_in(cx, |editor, window, cx| {
 8133            editor.set_text("somehting_new\n", window, cx)
 8134        });
 8135        assert!(cx.read(|cx| editor.is_dirty(cx)));
 8136        let _formatting_request_signal = fake_server
 8137            .set_request_handler::<lsp::request::Formatting, _, _>(move |params, _| async move {
 8138                assert_eq!(
 8139                    params.text_document.uri,
 8140                    lsp::Url::from_file_path(path!("/file.rs")).unwrap()
 8141                );
 8142                assert_eq!(params.options.tab_size, 8);
 8143                Ok(Some(vec![]))
 8144            });
 8145        let save = editor
 8146            .update_in(cx, |editor, window, cx| {
 8147                editor.save(true, project.clone(), window, cx)
 8148            })
 8149            .unwrap();
 8150        cx.executor().start_waiting();
 8151        save.await;
 8152    }
 8153}
 8154
 8155#[gpui::test]
 8156async fn test_multibuffer_format_during_save(cx: &mut TestAppContext) {
 8157    init_test(cx, |_| {});
 8158
 8159    let cols = 4;
 8160    let rows = 10;
 8161    let sample_text_1 = sample_text(rows, cols, 'a');
 8162    assert_eq!(
 8163        sample_text_1,
 8164        "aaaa\nbbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj"
 8165    );
 8166    let sample_text_2 = sample_text(rows, cols, 'l');
 8167    assert_eq!(
 8168        sample_text_2,
 8169        "llll\nmmmm\nnnnn\noooo\npppp\nqqqq\nrrrr\nssss\ntttt\nuuuu"
 8170    );
 8171    let sample_text_3 = sample_text(rows, cols, 'v');
 8172    assert_eq!(
 8173        sample_text_3,
 8174        "vvvv\nwwww\nxxxx\nyyyy\nzzzz\n{{{{\n||||\n}}}}\n~~~~\n\u{7f}\u{7f}\u{7f}\u{7f}"
 8175    );
 8176
 8177    let fs = FakeFs::new(cx.executor());
 8178    fs.insert_tree(
 8179        path!("/a"),
 8180        json!({
 8181            "main.rs": sample_text_1,
 8182            "other.rs": sample_text_2,
 8183            "lib.rs": sample_text_3,
 8184        }),
 8185    )
 8186    .await;
 8187
 8188    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
 8189    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8190    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
 8191
 8192    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
 8193    language_registry.add(rust_lang());
 8194    let mut fake_servers = language_registry.register_fake_lsp(
 8195        "Rust",
 8196        FakeLspAdapter {
 8197            capabilities: lsp::ServerCapabilities {
 8198                document_formatting_provider: Some(lsp::OneOf::Left(true)),
 8199                ..Default::default()
 8200            },
 8201            ..Default::default()
 8202        },
 8203    );
 8204
 8205    let worktree = project.update(cx, |project, cx| {
 8206        let mut worktrees = project.worktrees(cx).collect::<Vec<_>>();
 8207        assert_eq!(worktrees.len(), 1);
 8208        worktrees.pop().unwrap()
 8209    });
 8210    let worktree_id = worktree.update(cx, |worktree, _| worktree.id());
 8211
 8212    let buffer_1 = project
 8213        .update(cx, |project, cx| {
 8214            project.open_buffer((worktree_id, "main.rs"), cx)
 8215        })
 8216        .await
 8217        .unwrap();
 8218    let buffer_2 = project
 8219        .update(cx, |project, cx| {
 8220            project.open_buffer((worktree_id, "other.rs"), cx)
 8221        })
 8222        .await
 8223        .unwrap();
 8224    let buffer_3 = project
 8225        .update(cx, |project, cx| {
 8226            project.open_buffer((worktree_id, "lib.rs"), cx)
 8227        })
 8228        .await
 8229        .unwrap();
 8230
 8231    let multi_buffer = cx.new(|cx| {
 8232        let mut multi_buffer = MultiBuffer::new(ReadWrite);
 8233        multi_buffer.push_excerpts(
 8234            buffer_1.clone(),
 8235            [
 8236                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
 8237                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
 8238                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
 8239            ],
 8240            cx,
 8241        );
 8242        multi_buffer.push_excerpts(
 8243            buffer_2.clone(),
 8244            [
 8245                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
 8246                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
 8247                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
 8248            ],
 8249            cx,
 8250        );
 8251        multi_buffer.push_excerpts(
 8252            buffer_3.clone(),
 8253            [
 8254                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
 8255                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
 8256                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
 8257            ],
 8258            cx,
 8259        );
 8260        multi_buffer
 8261    });
 8262    let multi_buffer_editor = cx.new_window_entity(|window, cx| {
 8263        Editor::new(
 8264            EditorMode::full(),
 8265            multi_buffer,
 8266            Some(project.clone()),
 8267            window,
 8268            cx,
 8269        )
 8270    });
 8271
 8272    multi_buffer_editor.update_in(cx, |editor, window, cx| {
 8273        editor.change_selections(Some(Autoscroll::Next), window, cx, |s| {
 8274            s.select_ranges(Some(1..2))
 8275        });
 8276        editor.insert("|one|two|three|", window, cx);
 8277    });
 8278    assert!(cx.read(|cx| multi_buffer_editor.is_dirty(cx)));
 8279    multi_buffer_editor.update_in(cx, |editor, window, cx| {
 8280        editor.change_selections(Some(Autoscroll::Next), window, cx, |s| {
 8281            s.select_ranges(Some(60..70))
 8282        });
 8283        editor.insert("|four|five|six|", window, cx);
 8284    });
 8285    assert!(cx.read(|cx| multi_buffer_editor.is_dirty(cx)));
 8286
 8287    // First two buffers should be edited, but not the third one.
 8288    assert_eq!(
 8289        multi_buffer_editor.update(cx, |editor, cx| editor.text(cx)),
 8290        "a|one|two|three|aa\nbbbb\ncccc\n\nffff\ngggg\n\njjjj\nllll\nmmmm\nnnnn|four|five|six|\nr\n\nuuuu\nvvvv\nwwww\nxxxx\n\n{{{{\n||||\n\n\u{7f}\u{7f}\u{7f}\u{7f}",
 8291    );
 8292    buffer_1.update(cx, |buffer, _| {
 8293        assert!(buffer.is_dirty());
 8294        assert_eq!(
 8295            buffer.text(),
 8296            "a|one|two|three|aa\nbbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj",
 8297        )
 8298    });
 8299    buffer_2.update(cx, |buffer, _| {
 8300        assert!(buffer.is_dirty());
 8301        assert_eq!(
 8302            buffer.text(),
 8303            "llll\nmmmm\nnnnn|four|five|six|oooo\npppp\nr\nssss\ntttt\nuuuu",
 8304        )
 8305    });
 8306    buffer_3.update(cx, |buffer, _| {
 8307        assert!(!buffer.is_dirty());
 8308        assert_eq!(buffer.text(), sample_text_3,)
 8309    });
 8310    cx.executor().run_until_parked();
 8311
 8312    cx.executor().start_waiting();
 8313    let save = multi_buffer_editor
 8314        .update_in(cx, |editor, window, cx| {
 8315            editor.save(true, project.clone(), window, cx)
 8316        })
 8317        .unwrap();
 8318
 8319    let fake_server = fake_servers.next().await.unwrap();
 8320    fake_server
 8321        .server
 8322        .on_request::<lsp::request::Formatting, _, _>(move |params, _| async move {
 8323            Ok(Some(vec![lsp::TextEdit::new(
 8324                lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(1, 0)),
 8325                format!("[{} formatted]", params.text_document.uri),
 8326            )]))
 8327        })
 8328        .detach();
 8329    save.await;
 8330
 8331    // After multibuffer saving, only first two buffers should be reformatted, but not the third one (as it was not dirty).
 8332    assert!(cx.read(|cx| !multi_buffer_editor.is_dirty(cx)));
 8333    assert_eq!(
 8334        multi_buffer_editor.update(cx, |editor, cx| editor.text(cx)),
 8335        uri!(
 8336            "a|o[file:///a/main.rs formatted]bbbb\ncccc\n\nffff\ngggg\n\njjjj\n\nlll[file:///a/other.rs formatted]mmmm\nnnnn|four|five|six|\nr\n\nuuuu\n\nvvvv\nwwww\nxxxx\n\n{{{{\n||||\n\n\u{7f}\u{7f}\u{7f}\u{7f}"
 8337        ),
 8338    );
 8339    buffer_1.update(cx, |buffer, _| {
 8340        assert!(!buffer.is_dirty());
 8341        assert_eq!(
 8342            buffer.text(),
 8343            uri!("a|o[file:///a/main.rs formatted]bbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj\n"),
 8344        )
 8345    });
 8346    buffer_2.update(cx, |buffer, _| {
 8347        assert!(!buffer.is_dirty());
 8348        assert_eq!(
 8349            buffer.text(),
 8350            uri!("lll[file:///a/other.rs formatted]mmmm\nnnnn|four|five|six|oooo\npppp\nr\nssss\ntttt\nuuuu\n"),
 8351        )
 8352    });
 8353    buffer_3.update(cx, |buffer, _| {
 8354        assert!(!buffer.is_dirty());
 8355        assert_eq!(buffer.text(), sample_text_3,)
 8356    });
 8357}
 8358
 8359#[gpui::test]
 8360async fn test_range_format_during_save(cx: &mut TestAppContext) {
 8361    init_test(cx, |_| {});
 8362
 8363    let fs = FakeFs::new(cx.executor());
 8364    fs.insert_file(path!("/file.rs"), Default::default()).await;
 8365
 8366    let project = Project::test(fs, [path!("/").as_ref()], cx).await;
 8367
 8368    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
 8369    language_registry.add(rust_lang());
 8370    let mut fake_servers = language_registry.register_fake_lsp(
 8371        "Rust",
 8372        FakeLspAdapter {
 8373            capabilities: lsp::ServerCapabilities {
 8374                document_range_formatting_provider: Some(lsp::OneOf::Left(true)),
 8375                ..Default::default()
 8376            },
 8377            ..Default::default()
 8378        },
 8379    );
 8380
 8381    let buffer = project
 8382        .update(cx, |project, cx| {
 8383            project.open_local_buffer(path!("/file.rs"), cx)
 8384        })
 8385        .await
 8386        .unwrap();
 8387
 8388    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 8389    let (editor, cx) = cx.add_window_view(|window, cx| {
 8390        build_editor_with_project(project.clone(), buffer, window, cx)
 8391    });
 8392    editor.update_in(cx, |editor, window, cx| {
 8393        editor.set_text("one\ntwo\nthree\n", window, cx)
 8394    });
 8395    assert!(cx.read(|cx| editor.is_dirty(cx)));
 8396
 8397    cx.executor().start_waiting();
 8398    let fake_server = fake_servers.next().await.unwrap();
 8399
 8400    let save = editor
 8401        .update_in(cx, |editor, window, cx| {
 8402            editor.save(true, project.clone(), window, cx)
 8403        })
 8404        .unwrap();
 8405    fake_server
 8406        .set_request_handler::<lsp::request::RangeFormatting, _, _>(move |params, _| async move {
 8407            assert_eq!(
 8408                params.text_document.uri,
 8409                lsp::Url::from_file_path(path!("/file.rs")).unwrap()
 8410            );
 8411            assert_eq!(params.options.tab_size, 4);
 8412            Ok(Some(vec![lsp::TextEdit::new(
 8413                lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(1, 0)),
 8414                ", ".to_string(),
 8415            )]))
 8416        })
 8417        .next()
 8418        .await;
 8419    cx.executor().start_waiting();
 8420    save.await;
 8421    assert_eq!(
 8422        editor.update(cx, |editor, cx| editor.text(cx)),
 8423        "one, two\nthree\n"
 8424    );
 8425    assert!(!cx.read(|cx| editor.is_dirty(cx)));
 8426
 8427    editor.update_in(cx, |editor, window, cx| {
 8428        editor.set_text("one\ntwo\nthree\n", window, cx)
 8429    });
 8430    assert!(cx.read(|cx| editor.is_dirty(cx)));
 8431
 8432    // Ensure we can still save even if formatting hangs.
 8433    fake_server.set_request_handler::<lsp::request::RangeFormatting, _, _>(
 8434        move |params, _| async move {
 8435            assert_eq!(
 8436                params.text_document.uri,
 8437                lsp::Url::from_file_path(path!("/file.rs")).unwrap()
 8438            );
 8439            futures::future::pending::<()>().await;
 8440            unreachable!()
 8441        },
 8442    );
 8443    let save = editor
 8444        .update_in(cx, |editor, window, cx| {
 8445            editor.save(true, project.clone(), window, cx)
 8446        })
 8447        .unwrap();
 8448    cx.executor().advance_clock(super::FORMAT_TIMEOUT);
 8449    cx.executor().start_waiting();
 8450    save.await;
 8451    assert_eq!(
 8452        editor.update(cx, |editor, cx| editor.text(cx)),
 8453        "one\ntwo\nthree\n"
 8454    );
 8455    assert!(!cx.read(|cx| editor.is_dirty(cx)));
 8456
 8457    // For non-dirty buffer, no formatting request should be sent
 8458    let save = editor
 8459        .update_in(cx, |editor, window, cx| {
 8460            editor.save(true, project.clone(), window, cx)
 8461        })
 8462        .unwrap();
 8463    let _pending_format_request = fake_server
 8464        .set_request_handler::<lsp::request::RangeFormatting, _, _>(move |_, _| async move {
 8465            panic!("Should not be invoked on non-dirty buffer");
 8466        })
 8467        .next();
 8468    cx.executor().start_waiting();
 8469    save.await;
 8470
 8471    // Set Rust language override and assert overridden tabsize is sent to language server
 8472    update_test_language_settings(cx, |settings| {
 8473        settings.languages.insert(
 8474            "Rust".into(),
 8475            LanguageSettingsContent {
 8476                tab_size: NonZeroU32::new(8),
 8477                ..Default::default()
 8478            },
 8479        );
 8480    });
 8481
 8482    editor.update_in(cx, |editor, window, cx| {
 8483        editor.set_text("somehting_new\n", window, cx)
 8484    });
 8485    assert!(cx.read(|cx| editor.is_dirty(cx)));
 8486    let save = editor
 8487        .update_in(cx, |editor, window, cx| {
 8488            editor.save(true, project.clone(), window, cx)
 8489        })
 8490        .unwrap();
 8491    fake_server
 8492        .set_request_handler::<lsp::request::RangeFormatting, _, _>(move |params, _| async move {
 8493            assert_eq!(
 8494                params.text_document.uri,
 8495                lsp::Url::from_file_path(path!("/file.rs")).unwrap()
 8496            );
 8497            assert_eq!(params.options.tab_size, 8);
 8498            Ok(Some(vec![]))
 8499        })
 8500        .next()
 8501        .await;
 8502    cx.executor().start_waiting();
 8503    save.await;
 8504}
 8505
 8506#[gpui::test]
 8507async fn test_document_format_manual_trigger(cx: &mut TestAppContext) {
 8508    init_test(cx, |settings| {
 8509        settings.defaults.formatter = Some(language_settings::SelectedFormatter::List(
 8510            FormatterList(vec![Formatter::LanguageServer { name: None }].into()),
 8511        ))
 8512    });
 8513
 8514    let fs = FakeFs::new(cx.executor());
 8515    fs.insert_file(path!("/file.rs"), Default::default()).await;
 8516
 8517    let project = Project::test(fs, [path!("/").as_ref()], cx).await;
 8518
 8519    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
 8520    language_registry.add(Arc::new(Language::new(
 8521        LanguageConfig {
 8522            name: "Rust".into(),
 8523            matcher: LanguageMatcher {
 8524                path_suffixes: vec!["rs".to_string()],
 8525                ..Default::default()
 8526            },
 8527            ..LanguageConfig::default()
 8528        },
 8529        Some(tree_sitter_rust::LANGUAGE.into()),
 8530    )));
 8531    update_test_language_settings(cx, |settings| {
 8532        // Enable Prettier formatting for the same buffer, and ensure
 8533        // LSP is called instead of Prettier.
 8534        settings.defaults.prettier = Some(PrettierSettings {
 8535            allowed: true,
 8536            ..PrettierSettings::default()
 8537        });
 8538    });
 8539    let mut fake_servers = language_registry.register_fake_lsp(
 8540        "Rust",
 8541        FakeLspAdapter {
 8542            capabilities: lsp::ServerCapabilities {
 8543                document_formatting_provider: Some(lsp::OneOf::Left(true)),
 8544                ..Default::default()
 8545            },
 8546            ..Default::default()
 8547        },
 8548    );
 8549
 8550    let buffer = project
 8551        .update(cx, |project, cx| {
 8552            project.open_local_buffer(path!("/file.rs"), cx)
 8553        })
 8554        .await
 8555        .unwrap();
 8556
 8557    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 8558    let (editor, cx) = cx.add_window_view(|window, cx| {
 8559        build_editor_with_project(project.clone(), buffer, window, cx)
 8560    });
 8561    editor.update_in(cx, |editor, window, cx| {
 8562        editor.set_text("one\ntwo\nthree\n", window, cx)
 8563    });
 8564
 8565    cx.executor().start_waiting();
 8566    let fake_server = fake_servers.next().await.unwrap();
 8567
 8568    let format = editor
 8569        .update_in(cx, |editor, window, cx| {
 8570            editor.perform_format(
 8571                project.clone(),
 8572                FormatTrigger::Manual,
 8573                FormatTarget::Buffers,
 8574                window,
 8575                cx,
 8576            )
 8577        })
 8578        .unwrap();
 8579    fake_server
 8580        .set_request_handler::<lsp::request::Formatting, _, _>(move |params, _| async move {
 8581            assert_eq!(
 8582                params.text_document.uri,
 8583                lsp::Url::from_file_path(path!("/file.rs")).unwrap()
 8584            );
 8585            assert_eq!(params.options.tab_size, 4);
 8586            Ok(Some(vec![lsp::TextEdit::new(
 8587                lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(1, 0)),
 8588                ", ".to_string(),
 8589            )]))
 8590        })
 8591        .next()
 8592        .await;
 8593    cx.executor().start_waiting();
 8594    format.await;
 8595    assert_eq!(
 8596        editor.update(cx, |editor, cx| editor.text(cx)),
 8597        "one, two\nthree\n"
 8598    );
 8599
 8600    editor.update_in(cx, |editor, window, cx| {
 8601        editor.set_text("one\ntwo\nthree\n", window, cx)
 8602    });
 8603    // Ensure we don't lock if formatting hangs.
 8604    fake_server.set_request_handler::<lsp::request::Formatting, _, _>(
 8605        move |params, _| async move {
 8606            assert_eq!(
 8607                params.text_document.uri,
 8608                lsp::Url::from_file_path(path!("/file.rs")).unwrap()
 8609            );
 8610            futures::future::pending::<()>().await;
 8611            unreachable!()
 8612        },
 8613    );
 8614    let format = editor
 8615        .update_in(cx, |editor, window, cx| {
 8616            editor.perform_format(
 8617                project,
 8618                FormatTrigger::Manual,
 8619                FormatTarget::Buffers,
 8620                window,
 8621                cx,
 8622            )
 8623        })
 8624        .unwrap();
 8625    cx.executor().advance_clock(super::FORMAT_TIMEOUT);
 8626    cx.executor().start_waiting();
 8627    format.await;
 8628    assert_eq!(
 8629        editor.update(cx, |editor, cx| editor.text(cx)),
 8630        "one\ntwo\nthree\n"
 8631    );
 8632}
 8633
 8634#[gpui::test]
 8635async fn test_multiple_formatters(cx: &mut TestAppContext) {
 8636    init_test(cx, |settings| {
 8637        settings.defaults.remove_trailing_whitespace_on_save = Some(true);
 8638        settings.defaults.formatter =
 8639            Some(language_settings::SelectedFormatter::List(FormatterList(
 8640                vec![
 8641                    Formatter::LanguageServer { name: None },
 8642                    Formatter::CodeActions(
 8643                        [
 8644                            ("code-action-1".into(), true),
 8645                            ("code-action-2".into(), true),
 8646                        ]
 8647                        .into_iter()
 8648                        .collect(),
 8649                    ),
 8650                ]
 8651                .into(),
 8652            )))
 8653    });
 8654
 8655    let fs = FakeFs::new(cx.executor());
 8656    fs.insert_file(path!("/file.rs"), "one  \ntwo   \nthree".into())
 8657        .await;
 8658
 8659    let project = Project::test(fs, [path!("/").as_ref()], cx).await;
 8660    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
 8661    language_registry.add(rust_lang());
 8662
 8663    let mut fake_servers = language_registry.register_fake_lsp(
 8664        "Rust",
 8665        FakeLspAdapter {
 8666            capabilities: lsp::ServerCapabilities {
 8667                document_formatting_provider: Some(lsp::OneOf::Left(true)),
 8668                execute_command_provider: Some(lsp::ExecuteCommandOptions {
 8669                    commands: vec!["the-command-for-code-action-1".into()],
 8670                    ..Default::default()
 8671                }),
 8672                code_action_provider: Some(lsp::CodeActionProviderCapability::Simple(true)),
 8673                ..Default::default()
 8674            },
 8675            ..Default::default()
 8676        },
 8677    );
 8678
 8679    let buffer = project
 8680        .update(cx, |project, cx| {
 8681            project.open_local_buffer(path!("/file.rs"), cx)
 8682        })
 8683        .await
 8684        .unwrap();
 8685
 8686    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 8687    let (editor, cx) = cx.add_window_view(|window, cx| {
 8688        build_editor_with_project(project.clone(), buffer, window, cx)
 8689    });
 8690
 8691    cx.executor().start_waiting();
 8692
 8693    let fake_server = fake_servers.next().await.unwrap();
 8694    fake_server.set_request_handler::<lsp::request::Formatting, _, _>(
 8695        move |_params, _| async move {
 8696            Ok(Some(vec![lsp::TextEdit::new(
 8697                lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
 8698                "applied-formatting\n".to_string(),
 8699            )]))
 8700        },
 8701    );
 8702    fake_server.set_request_handler::<lsp::request::CodeActionRequest, _, _>(
 8703        move |params, _| async move {
 8704            assert_eq!(
 8705                params.context.only,
 8706                Some(vec!["code-action-1".into(), "code-action-2".into()])
 8707            );
 8708            let uri = lsp::Url::from_file_path(path!("/file.rs")).unwrap();
 8709            Ok(Some(vec![
 8710                lsp::CodeActionOrCommand::CodeAction(lsp::CodeAction {
 8711                    kind: Some("code-action-1".into()),
 8712                    edit: Some(lsp::WorkspaceEdit::new(
 8713                        [(
 8714                            uri.clone(),
 8715                            vec![lsp::TextEdit::new(
 8716                                lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
 8717                                "applied-code-action-1-edit\n".to_string(),
 8718                            )],
 8719                        )]
 8720                        .into_iter()
 8721                        .collect(),
 8722                    )),
 8723                    command: Some(lsp::Command {
 8724                        command: "the-command-for-code-action-1".into(),
 8725                        ..Default::default()
 8726                    }),
 8727                    ..Default::default()
 8728                }),
 8729                lsp::CodeActionOrCommand::CodeAction(lsp::CodeAction {
 8730                    kind: Some("code-action-2".into()),
 8731                    edit: Some(lsp::WorkspaceEdit::new(
 8732                        [(
 8733                            uri.clone(),
 8734                            vec![lsp::TextEdit::new(
 8735                                lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
 8736                                "applied-code-action-2-edit\n".to_string(),
 8737                            )],
 8738                        )]
 8739                        .into_iter()
 8740                        .collect(),
 8741                    )),
 8742                    ..Default::default()
 8743                }),
 8744            ]))
 8745        },
 8746    );
 8747
 8748    fake_server.set_request_handler::<lsp::request::CodeActionResolveRequest, _, _>({
 8749        move |params, _| async move { Ok(params) }
 8750    });
 8751
 8752    let command_lock = Arc::new(futures::lock::Mutex::new(()));
 8753    fake_server.set_request_handler::<lsp::request::ExecuteCommand, _, _>({
 8754        let fake = fake_server.clone();
 8755        let lock = command_lock.clone();
 8756        move |params, _| {
 8757            assert_eq!(params.command, "the-command-for-code-action-1");
 8758            let fake = fake.clone();
 8759            let lock = lock.clone();
 8760            async move {
 8761                lock.lock().await;
 8762                fake.server
 8763                    .request::<lsp::request::ApplyWorkspaceEdit>(lsp::ApplyWorkspaceEditParams {
 8764                        label: None,
 8765                        edit: lsp::WorkspaceEdit {
 8766                            changes: Some(
 8767                                [(
 8768                                    lsp::Url::from_file_path(path!("/file.rs")).unwrap(),
 8769                                    vec![lsp::TextEdit {
 8770                                        range: lsp::Range::new(
 8771                                            lsp::Position::new(0, 0),
 8772                                            lsp::Position::new(0, 0),
 8773                                        ),
 8774                                        new_text: "applied-code-action-1-command\n".into(),
 8775                                    }],
 8776                                )]
 8777                                .into_iter()
 8778                                .collect(),
 8779                            ),
 8780                            ..Default::default()
 8781                        },
 8782                    })
 8783                    .await
 8784                    .unwrap();
 8785                Ok(Some(json!(null)))
 8786            }
 8787        }
 8788    });
 8789
 8790    cx.executor().start_waiting();
 8791    editor
 8792        .update_in(cx, |editor, window, cx| {
 8793            editor.perform_format(
 8794                project.clone(),
 8795                FormatTrigger::Manual,
 8796                FormatTarget::Buffers,
 8797                window,
 8798                cx,
 8799            )
 8800        })
 8801        .unwrap()
 8802        .await;
 8803    editor.update(cx, |editor, cx| {
 8804        assert_eq!(
 8805            editor.text(cx),
 8806            r#"
 8807                applied-code-action-2-edit
 8808                applied-code-action-1-command
 8809                applied-code-action-1-edit
 8810                applied-formatting
 8811                one
 8812                two
 8813                three
 8814            "#
 8815            .unindent()
 8816        );
 8817    });
 8818
 8819    editor.update_in(cx, |editor, window, cx| {
 8820        editor.undo(&Default::default(), window, cx);
 8821        assert_eq!(editor.text(cx), "one  \ntwo   \nthree");
 8822    });
 8823
 8824    // Perform a manual edit while waiting for an LSP command
 8825    // that's being run as part of a formatting code action.
 8826    let lock_guard = command_lock.lock().await;
 8827    let format = editor
 8828        .update_in(cx, |editor, window, cx| {
 8829            editor.perform_format(
 8830                project.clone(),
 8831                FormatTrigger::Manual,
 8832                FormatTarget::Buffers,
 8833                window,
 8834                cx,
 8835            )
 8836        })
 8837        .unwrap();
 8838    cx.run_until_parked();
 8839    editor.update(cx, |editor, cx| {
 8840        assert_eq!(
 8841            editor.text(cx),
 8842            r#"
 8843                applied-code-action-1-edit
 8844                applied-formatting
 8845                one
 8846                two
 8847                three
 8848            "#
 8849            .unindent()
 8850        );
 8851
 8852        editor.buffer.update(cx, |buffer, cx| {
 8853            let ix = buffer.len(cx);
 8854            buffer.edit([(ix..ix, "edited\n")], None, cx);
 8855        });
 8856    });
 8857
 8858    // Allow the LSP command to proceed. Because the buffer was edited,
 8859    // the second code action will not be run.
 8860    drop(lock_guard);
 8861    format.await;
 8862    editor.update_in(cx, |editor, window, cx| {
 8863        assert_eq!(
 8864            editor.text(cx),
 8865            r#"
 8866                applied-code-action-1-command
 8867                applied-code-action-1-edit
 8868                applied-formatting
 8869                one
 8870                two
 8871                three
 8872                edited
 8873            "#
 8874            .unindent()
 8875        );
 8876
 8877        // The manual edit is undone first, because it is the last thing the user did
 8878        // (even though the command completed afterwards).
 8879        editor.undo(&Default::default(), window, cx);
 8880        assert_eq!(
 8881            editor.text(cx),
 8882            r#"
 8883                applied-code-action-1-command
 8884                applied-code-action-1-edit
 8885                applied-formatting
 8886                one
 8887                two
 8888                three
 8889            "#
 8890            .unindent()
 8891        );
 8892
 8893        // All the formatting (including the command, which completed after the manual edit)
 8894        // is undone together.
 8895        editor.undo(&Default::default(), window, cx);
 8896        assert_eq!(editor.text(cx), "one  \ntwo   \nthree");
 8897    });
 8898}
 8899
 8900#[gpui::test]
 8901async fn test_organize_imports_manual_trigger(cx: &mut TestAppContext) {
 8902    init_test(cx, |settings| {
 8903        settings.defaults.formatter = Some(language_settings::SelectedFormatter::List(
 8904            FormatterList(vec![Formatter::LanguageServer { name: None }].into()),
 8905        ))
 8906    });
 8907
 8908    let fs = FakeFs::new(cx.executor());
 8909    fs.insert_file(path!("/file.ts"), Default::default()).await;
 8910
 8911    let project = Project::test(fs, [path!("/").as_ref()], cx).await;
 8912
 8913    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
 8914    language_registry.add(Arc::new(Language::new(
 8915        LanguageConfig {
 8916            name: "TypeScript".into(),
 8917            matcher: LanguageMatcher {
 8918                path_suffixes: vec!["ts".to_string()],
 8919                ..Default::default()
 8920            },
 8921            ..LanguageConfig::default()
 8922        },
 8923        Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
 8924    )));
 8925    update_test_language_settings(cx, |settings| {
 8926        settings.defaults.prettier = Some(PrettierSettings {
 8927            allowed: true,
 8928            ..PrettierSettings::default()
 8929        });
 8930    });
 8931    let mut fake_servers = language_registry.register_fake_lsp(
 8932        "TypeScript",
 8933        FakeLspAdapter {
 8934            capabilities: lsp::ServerCapabilities {
 8935                code_action_provider: Some(lsp::CodeActionProviderCapability::Simple(true)),
 8936                ..Default::default()
 8937            },
 8938            ..Default::default()
 8939        },
 8940    );
 8941
 8942    let buffer = project
 8943        .update(cx, |project, cx| {
 8944            project.open_local_buffer(path!("/file.ts"), cx)
 8945        })
 8946        .await
 8947        .unwrap();
 8948
 8949    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 8950    let (editor, cx) = cx.add_window_view(|window, cx| {
 8951        build_editor_with_project(project.clone(), buffer, window, cx)
 8952    });
 8953    editor.update_in(cx, |editor, window, cx| {
 8954        editor.set_text(
 8955            "import { a } from 'module';\nimport { b } from 'module';\n\nconst x = a;\n",
 8956            window,
 8957            cx,
 8958        )
 8959    });
 8960
 8961    cx.executor().start_waiting();
 8962    let fake_server = fake_servers.next().await.unwrap();
 8963
 8964    let format = editor
 8965        .update_in(cx, |editor, window, cx| {
 8966            editor.perform_code_action_kind(
 8967                project.clone(),
 8968                CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
 8969                window,
 8970                cx,
 8971            )
 8972        })
 8973        .unwrap();
 8974    fake_server
 8975        .set_request_handler::<lsp::request::CodeActionRequest, _, _>(move |params, _| async move {
 8976            assert_eq!(
 8977                params.text_document.uri,
 8978                lsp::Url::from_file_path(path!("/file.ts")).unwrap()
 8979            );
 8980            Ok(Some(vec![lsp::CodeActionOrCommand::CodeAction(
 8981                lsp::CodeAction {
 8982                    title: "Organize Imports".to_string(),
 8983                    kind: Some(lsp::CodeActionKind::SOURCE_ORGANIZE_IMPORTS),
 8984                    edit: Some(lsp::WorkspaceEdit {
 8985                        changes: Some(
 8986                            [(
 8987                                params.text_document.uri.clone(),
 8988                                vec![lsp::TextEdit::new(
 8989                                    lsp::Range::new(
 8990                                        lsp::Position::new(1, 0),
 8991                                        lsp::Position::new(2, 0),
 8992                                    ),
 8993                                    "".to_string(),
 8994                                )],
 8995                            )]
 8996                            .into_iter()
 8997                            .collect(),
 8998                        ),
 8999                        ..Default::default()
 9000                    }),
 9001                    ..Default::default()
 9002                },
 9003            )]))
 9004        })
 9005        .next()
 9006        .await;
 9007    cx.executor().start_waiting();
 9008    format.await;
 9009    assert_eq!(
 9010        editor.update(cx, |editor, cx| editor.text(cx)),
 9011        "import { a } from 'module';\n\nconst x = a;\n"
 9012    );
 9013
 9014    editor.update_in(cx, |editor, window, cx| {
 9015        editor.set_text(
 9016            "import { a } from 'module';\nimport { b } from 'module';\n\nconst x = a;\n",
 9017            window,
 9018            cx,
 9019        )
 9020    });
 9021    // Ensure we don't lock if code action hangs.
 9022    fake_server.set_request_handler::<lsp::request::CodeActionRequest, _, _>(
 9023        move |params, _| async move {
 9024            assert_eq!(
 9025                params.text_document.uri,
 9026                lsp::Url::from_file_path(path!("/file.ts")).unwrap()
 9027            );
 9028            futures::future::pending::<()>().await;
 9029            unreachable!()
 9030        },
 9031    );
 9032    let format = editor
 9033        .update_in(cx, |editor, window, cx| {
 9034            editor.perform_code_action_kind(
 9035                project,
 9036                CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
 9037                window,
 9038                cx,
 9039            )
 9040        })
 9041        .unwrap();
 9042    cx.executor().advance_clock(super::CODE_ACTION_TIMEOUT);
 9043    cx.executor().start_waiting();
 9044    format.await;
 9045    assert_eq!(
 9046        editor.update(cx, |editor, cx| editor.text(cx)),
 9047        "import { a } from 'module';\nimport { b } from 'module';\n\nconst x = a;\n"
 9048    );
 9049}
 9050
 9051#[gpui::test]
 9052async fn test_concurrent_format_requests(cx: &mut TestAppContext) {
 9053    init_test(cx, |_| {});
 9054
 9055    let mut cx = EditorLspTestContext::new_rust(
 9056        lsp::ServerCapabilities {
 9057            document_formatting_provider: Some(lsp::OneOf::Left(true)),
 9058            ..Default::default()
 9059        },
 9060        cx,
 9061    )
 9062    .await;
 9063
 9064    cx.set_state(indoc! {"
 9065        one.twoˇ
 9066    "});
 9067
 9068    // The format request takes a long time. When it completes, it inserts
 9069    // a newline and an indent before the `.`
 9070    cx.lsp
 9071        .set_request_handler::<lsp::request::Formatting, _, _>(move |_, cx| {
 9072            let executor = cx.background_executor().clone();
 9073            async move {
 9074                executor.timer(Duration::from_millis(100)).await;
 9075                Ok(Some(vec![lsp::TextEdit {
 9076                    range: lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(0, 3)),
 9077                    new_text: "\n    ".into(),
 9078                }]))
 9079            }
 9080        });
 9081
 9082    // Submit a format request.
 9083    let format_1 = cx
 9084        .update_editor(|editor, window, cx| editor.format(&Format, window, cx))
 9085        .unwrap();
 9086    cx.executor().run_until_parked();
 9087
 9088    // Submit a second format request.
 9089    let format_2 = cx
 9090        .update_editor(|editor, window, cx| editor.format(&Format, window, cx))
 9091        .unwrap();
 9092    cx.executor().run_until_parked();
 9093
 9094    // Wait for both format requests to complete
 9095    cx.executor().advance_clock(Duration::from_millis(200));
 9096    cx.executor().start_waiting();
 9097    format_1.await.unwrap();
 9098    cx.executor().start_waiting();
 9099    format_2.await.unwrap();
 9100
 9101    // The formatting edits only happens once.
 9102    cx.assert_editor_state(indoc! {"
 9103        one
 9104            .twoˇ
 9105    "});
 9106}
 9107
 9108#[gpui::test]
 9109async fn test_strip_whitespace_and_format_via_lsp(cx: &mut TestAppContext) {
 9110    init_test(cx, |settings| {
 9111        settings.defaults.formatter = Some(language_settings::SelectedFormatter::Auto)
 9112    });
 9113
 9114    let mut cx = EditorLspTestContext::new_rust(
 9115        lsp::ServerCapabilities {
 9116            document_formatting_provider: Some(lsp::OneOf::Left(true)),
 9117            ..Default::default()
 9118        },
 9119        cx,
 9120    )
 9121    .await;
 9122
 9123    // Set up a buffer white some trailing whitespace and no trailing newline.
 9124    cx.set_state(
 9125        &[
 9126            "one ",   //
 9127            "twoˇ",   //
 9128            "three ", //
 9129            "four",   //
 9130        ]
 9131        .join("\n"),
 9132    );
 9133
 9134    // Submit a format request.
 9135    let format = cx
 9136        .update_editor(|editor, window, cx| editor.format(&Format, window, cx))
 9137        .unwrap();
 9138
 9139    // Record which buffer changes have been sent to the language server
 9140    let buffer_changes = Arc::new(Mutex::new(Vec::new()));
 9141    cx.lsp
 9142        .handle_notification::<lsp::notification::DidChangeTextDocument, _>({
 9143            let buffer_changes = buffer_changes.clone();
 9144            move |params, _| {
 9145                buffer_changes.lock().extend(
 9146                    params
 9147                        .content_changes
 9148                        .into_iter()
 9149                        .map(|e| (e.range.unwrap(), e.text)),
 9150                );
 9151            }
 9152        });
 9153
 9154    // Handle formatting requests to the language server.
 9155    cx.lsp
 9156        .set_request_handler::<lsp::request::Formatting, _, _>({
 9157            let buffer_changes = buffer_changes.clone();
 9158            move |_, _| {
 9159                // When formatting is requested, trailing whitespace has already been stripped,
 9160                // and the trailing newline has already been added.
 9161                assert_eq!(
 9162                    &buffer_changes.lock()[1..],
 9163                    &[
 9164                        (
 9165                            lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(0, 4)),
 9166                            "".into()
 9167                        ),
 9168                        (
 9169                            lsp::Range::new(lsp::Position::new(2, 5), lsp::Position::new(2, 6)),
 9170                            "".into()
 9171                        ),
 9172                        (
 9173                            lsp::Range::new(lsp::Position::new(3, 4), lsp::Position::new(3, 4)),
 9174                            "\n".into()
 9175                        ),
 9176                    ]
 9177                );
 9178
 9179                // Insert blank lines between each line of the buffer.
 9180                async move {
 9181                    Ok(Some(vec![
 9182                        lsp::TextEdit {
 9183                            range: lsp::Range::new(
 9184                                lsp::Position::new(1, 0),
 9185                                lsp::Position::new(1, 0),
 9186                            ),
 9187                            new_text: "\n".into(),
 9188                        },
 9189                        lsp::TextEdit {
 9190                            range: lsp::Range::new(
 9191                                lsp::Position::new(2, 0),
 9192                                lsp::Position::new(2, 0),
 9193                            ),
 9194                            new_text: "\n".into(),
 9195                        },
 9196                    ]))
 9197                }
 9198            }
 9199        });
 9200
 9201    // After formatting the buffer, the trailing whitespace is stripped,
 9202    // a newline is appended, and the edits provided by the language server
 9203    // have been applied.
 9204    format.await.unwrap();
 9205    cx.assert_editor_state(
 9206        &[
 9207            "one",   //
 9208            "",      //
 9209            "twoˇ",  //
 9210            "",      //
 9211            "three", //
 9212            "four",  //
 9213            "",      //
 9214        ]
 9215        .join("\n"),
 9216    );
 9217
 9218    // Undoing the formatting undoes the trailing whitespace removal, the
 9219    // trailing newline, and the LSP edits.
 9220    cx.update_buffer(|buffer, cx| buffer.undo(cx));
 9221    cx.assert_editor_state(
 9222        &[
 9223            "one ",   //
 9224            "twoˇ",   //
 9225            "three ", //
 9226            "four",   //
 9227        ]
 9228        .join("\n"),
 9229    );
 9230}
 9231
 9232#[gpui::test]
 9233async fn test_handle_input_for_show_signature_help_auto_signature_help_true(
 9234    cx: &mut TestAppContext,
 9235) {
 9236    init_test(cx, |_| {});
 9237
 9238    cx.update(|cx| {
 9239        cx.update_global::<SettingsStore, _>(|settings, cx| {
 9240            settings.update_user_settings::<EditorSettings>(cx, |settings| {
 9241                settings.auto_signature_help = Some(true);
 9242            });
 9243        });
 9244    });
 9245
 9246    let mut cx = EditorLspTestContext::new_rust(
 9247        lsp::ServerCapabilities {
 9248            signature_help_provider: Some(lsp::SignatureHelpOptions {
 9249                ..Default::default()
 9250            }),
 9251            ..Default::default()
 9252        },
 9253        cx,
 9254    )
 9255    .await;
 9256
 9257    let language = Language::new(
 9258        LanguageConfig {
 9259            name: "Rust".into(),
 9260            brackets: BracketPairConfig {
 9261                pairs: vec![
 9262                    BracketPair {
 9263                        start: "{".to_string(),
 9264                        end: "}".to_string(),
 9265                        close: true,
 9266                        surround: true,
 9267                        newline: true,
 9268                    },
 9269                    BracketPair {
 9270                        start: "(".to_string(),
 9271                        end: ")".to_string(),
 9272                        close: true,
 9273                        surround: true,
 9274                        newline: true,
 9275                    },
 9276                    BracketPair {
 9277                        start: "/*".to_string(),
 9278                        end: " */".to_string(),
 9279                        close: true,
 9280                        surround: true,
 9281                        newline: true,
 9282                    },
 9283                    BracketPair {
 9284                        start: "[".to_string(),
 9285                        end: "]".to_string(),
 9286                        close: false,
 9287                        surround: false,
 9288                        newline: true,
 9289                    },
 9290                    BracketPair {
 9291                        start: "\"".to_string(),
 9292                        end: "\"".to_string(),
 9293                        close: true,
 9294                        surround: true,
 9295                        newline: false,
 9296                    },
 9297                    BracketPair {
 9298                        start: "<".to_string(),
 9299                        end: ">".to_string(),
 9300                        close: false,
 9301                        surround: true,
 9302                        newline: true,
 9303                    },
 9304                ],
 9305                ..Default::default()
 9306            },
 9307            autoclose_before: "})]".to_string(),
 9308            ..Default::default()
 9309        },
 9310        Some(tree_sitter_rust::LANGUAGE.into()),
 9311    );
 9312    let language = Arc::new(language);
 9313
 9314    cx.language_registry().add(language.clone());
 9315    cx.update_buffer(|buffer, cx| {
 9316        buffer.set_language(Some(language), cx);
 9317    });
 9318
 9319    cx.set_state(
 9320        &r#"
 9321            fn main() {
 9322                sampleˇ
 9323            }
 9324        "#
 9325        .unindent(),
 9326    );
 9327
 9328    cx.update_editor(|editor, window, cx| {
 9329        editor.handle_input("(", window, cx);
 9330    });
 9331    cx.assert_editor_state(
 9332        &"
 9333            fn main() {
 9334                sample(ˇ)
 9335            }
 9336        "
 9337        .unindent(),
 9338    );
 9339
 9340    let mocked_response = lsp::SignatureHelp {
 9341        signatures: vec![lsp::SignatureInformation {
 9342            label: "fn sample(param1: u8, param2: u8)".to_string(),
 9343            documentation: None,
 9344            parameters: Some(vec![
 9345                lsp::ParameterInformation {
 9346                    label: lsp::ParameterLabel::Simple("param1: u8".to_string()),
 9347                    documentation: None,
 9348                },
 9349                lsp::ParameterInformation {
 9350                    label: lsp::ParameterLabel::Simple("param2: u8".to_string()),
 9351                    documentation: None,
 9352                },
 9353            ]),
 9354            active_parameter: None,
 9355        }],
 9356        active_signature: Some(0),
 9357        active_parameter: Some(0),
 9358    };
 9359    handle_signature_help_request(&mut cx, mocked_response).await;
 9360
 9361    cx.condition(|editor, _| editor.signature_help_state.is_shown())
 9362        .await;
 9363
 9364    cx.editor(|editor, _, _| {
 9365        let signature_help_state = editor.signature_help_state.popover().cloned();
 9366        assert_eq!(
 9367            signature_help_state.unwrap().label,
 9368            "param1: u8, param2: u8"
 9369        );
 9370    });
 9371}
 9372
 9373#[gpui::test]
 9374async fn test_handle_input_with_different_show_signature_settings(cx: &mut TestAppContext) {
 9375    init_test(cx, |_| {});
 9376
 9377    cx.update(|cx| {
 9378        cx.update_global::<SettingsStore, _>(|settings, cx| {
 9379            settings.update_user_settings::<EditorSettings>(cx, |settings| {
 9380                settings.auto_signature_help = Some(false);
 9381                settings.show_signature_help_after_edits = Some(false);
 9382            });
 9383        });
 9384    });
 9385
 9386    let mut cx = EditorLspTestContext::new_rust(
 9387        lsp::ServerCapabilities {
 9388            signature_help_provider: Some(lsp::SignatureHelpOptions {
 9389                ..Default::default()
 9390            }),
 9391            ..Default::default()
 9392        },
 9393        cx,
 9394    )
 9395    .await;
 9396
 9397    let language = Language::new(
 9398        LanguageConfig {
 9399            name: "Rust".into(),
 9400            brackets: BracketPairConfig {
 9401                pairs: vec![
 9402                    BracketPair {
 9403                        start: "{".to_string(),
 9404                        end: "}".to_string(),
 9405                        close: true,
 9406                        surround: true,
 9407                        newline: true,
 9408                    },
 9409                    BracketPair {
 9410                        start: "(".to_string(),
 9411                        end: ")".to_string(),
 9412                        close: true,
 9413                        surround: true,
 9414                        newline: true,
 9415                    },
 9416                    BracketPair {
 9417                        start: "/*".to_string(),
 9418                        end: " */".to_string(),
 9419                        close: true,
 9420                        surround: true,
 9421                        newline: true,
 9422                    },
 9423                    BracketPair {
 9424                        start: "[".to_string(),
 9425                        end: "]".to_string(),
 9426                        close: false,
 9427                        surround: false,
 9428                        newline: true,
 9429                    },
 9430                    BracketPair {
 9431                        start: "\"".to_string(),
 9432                        end: "\"".to_string(),
 9433                        close: true,
 9434                        surround: true,
 9435                        newline: false,
 9436                    },
 9437                    BracketPair {
 9438                        start: "<".to_string(),
 9439                        end: ">".to_string(),
 9440                        close: false,
 9441                        surround: true,
 9442                        newline: true,
 9443                    },
 9444                ],
 9445                ..Default::default()
 9446            },
 9447            autoclose_before: "})]".to_string(),
 9448            ..Default::default()
 9449        },
 9450        Some(tree_sitter_rust::LANGUAGE.into()),
 9451    );
 9452    let language = Arc::new(language);
 9453
 9454    cx.language_registry().add(language.clone());
 9455    cx.update_buffer(|buffer, cx| {
 9456        buffer.set_language(Some(language), cx);
 9457    });
 9458
 9459    // Ensure that signature_help is not called when no signature help is enabled.
 9460    cx.set_state(
 9461        &r#"
 9462            fn main() {
 9463                sampleˇ
 9464            }
 9465        "#
 9466        .unindent(),
 9467    );
 9468    cx.update_editor(|editor, window, cx| {
 9469        editor.handle_input("(", window, cx);
 9470    });
 9471    cx.assert_editor_state(
 9472        &"
 9473            fn main() {
 9474                sample(ˇ)
 9475            }
 9476        "
 9477        .unindent(),
 9478    );
 9479    cx.editor(|editor, _, _| {
 9480        assert!(editor.signature_help_state.task().is_none());
 9481    });
 9482
 9483    let mocked_response = lsp::SignatureHelp {
 9484        signatures: vec![lsp::SignatureInformation {
 9485            label: "fn sample(param1: u8, param2: u8)".to_string(),
 9486            documentation: None,
 9487            parameters: Some(vec![
 9488                lsp::ParameterInformation {
 9489                    label: lsp::ParameterLabel::Simple("param1: u8".to_string()),
 9490                    documentation: None,
 9491                },
 9492                lsp::ParameterInformation {
 9493                    label: lsp::ParameterLabel::Simple("param2: u8".to_string()),
 9494                    documentation: None,
 9495                },
 9496            ]),
 9497            active_parameter: None,
 9498        }],
 9499        active_signature: Some(0),
 9500        active_parameter: Some(0),
 9501    };
 9502
 9503    // Ensure that signature_help is called when enabled afte edits
 9504    cx.update(|_, cx| {
 9505        cx.update_global::<SettingsStore, _>(|settings, cx| {
 9506            settings.update_user_settings::<EditorSettings>(cx, |settings| {
 9507                settings.auto_signature_help = Some(false);
 9508                settings.show_signature_help_after_edits = Some(true);
 9509            });
 9510        });
 9511    });
 9512    cx.set_state(
 9513        &r#"
 9514            fn main() {
 9515                sampleˇ
 9516            }
 9517        "#
 9518        .unindent(),
 9519    );
 9520    cx.update_editor(|editor, window, cx| {
 9521        editor.handle_input("(", window, cx);
 9522    });
 9523    cx.assert_editor_state(
 9524        &"
 9525            fn main() {
 9526                sample(ˇ)
 9527            }
 9528        "
 9529        .unindent(),
 9530    );
 9531    handle_signature_help_request(&mut cx, mocked_response.clone()).await;
 9532    cx.condition(|editor, _| editor.signature_help_state.is_shown())
 9533        .await;
 9534    cx.update_editor(|editor, _, _| {
 9535        let signature_help_state = editor.signature_help_state.popover().cloned();
 9536        assert!(signature_help_state.is_some());
 9537        assert_eq!(
 9538            signature_help_state.unwrap().label,
 9539            "param1: u8, param2: u8"
 9540        );
 9541        editor.signature_help_state = SignatureHelpState::default();
 9542    });
 9543
 9544    // Ensure that signature_help is called when auto signature help override is enabled
 9545    cx.update(|_, cx| {
 9546        cx.update_global::<SettingsStore, _>(|settings, cx| {
 9547            settings.update_user_settings::<EditorSettings>(cx, |settings| {
 9548                settings.auto_signature_help = Some(true);
 9549                settings.show_signature_help_after_edits = Some(false);
 9550            });
 9551        });
 9552    });
 9553    cx.set_state(
 9554        &r#"
 9555            fn main() {
 9556                sampleˇ
 9557            }
 9558        "#
 9559        .unindent(),
 9560    );
 9561    cx.update_editor(|editor, window, cx| {
 9562        editor.handle_input("(", window, cx);
 9563    });
 9564    cx.assert_editor_state(
 9565        &"
 9566            fn main() {
 9567                sample(ˇ)
 9568            }
 9569        "
 9570        .unindent(),
 9571    );
 9572    handle_signature_help_request(&mut cx, mocked_response).await;
 9573    cx.condition(|editor, _| editor.signature_help_state.is_shown())
 9574        .await;
 9575    cx.editor(|editor, _, _| {
 9576        let signature_help_state = editor.signature_help_state.popover().cloned();
 9577        assert!(signature_help_state.is_some());
 9578        assert_eq!(
 9579            signature_help_state.unwrap().label,
 9580            "param1: u8, param2: u8"
 9581        );
 9582    });
 9583}
 9584
 9585#[gpui::test]
 9586async fn test_signature_help(cx: &mut TestAppContext) {
 9587    init_test(cx, |_| {});
 9588    cx.update(|cx| {
 9589        cx.update_global::<SettingsStore, _>(|settings, cx| {
 9590            settings.update_user_settings::<EditorSettings>(cx, |settings| {
 9591                settings.auto_signature_help = Some(true);
 9592            });
 9593        });
 9594    });
 9595
 9596    let mut cx = EditorLspTestContext::new_rust(
 9597        lsp::ServerCapabilities {
 9598            signature_help_provider: Some(lsp::SignatureHelpOptions {
 9599                ..Default::default()
 9600            }),
 9601            ..Default::default()
 9602        },
 9603        cx,
 9604    )
 9605    .await;
 9606
 9607    // A test that directly calls `show_signature_help`
 9608    cx.update_editor(|editor, window, cx| {
 9609        editor.show_signature_help(&ShowSignatureHelp, window, cx);
 9610    });
 9611
 9612    let mocked_response = lsp::SignatureHelp {
 9613        signatures: vec![lsp::SignatureInformation {
 9614            label: "fn sample(param1: u8, param2: u8)".to_string(),
 9615            documentation: None,
 9616            parameters: Some(vec![
 9617                lsp::ParameterInformation {
 9618                    label: lsp::ParameterLabel::Simple("param1: u8".to_string()),
 9619                    documentation: None,
 9620                },
 9621                lsp::ParameterInformation {
 9622                    label: lsp::ParameterLabel::Simple("param2: u8".to_string()),
 9623                    documentation: None,
 9624                },
 9625            ]),
 9626            active_parameter: None,
 9627        }],
 9628        active_signature: Some(0),
 9629        active_parameter: Some(0),
 9630    };
 9631    handle_signature_help_request(&mut cx, mocked_response).await;
 9632
 9633    cx.condition(|editor, _| editor.signature_help_state.is_shown())
 9634        .await;
 9635
 9636    cx.editor(|editor, _, _| {
 9637        let signature_help_state = editor.signature_help_state.popover().cloned();
 9638        assert!(signature_help_state.is_some());
 9639        assert_eq!(
 9640            signature_help_state.unwrap().label,
 9641            "param1: u8, param2: u8"
 9642        );
 9643    });
 9644
 9645    // When exiting outside from inside the brackets, `signature_help` is closed.
 9646    cx.set_state(indoc! {"
 9647        fn main() {
 9648            sample(ˇ);
 9649        }
 9650
 9651        fn sample(param1: u8, param2: u8) {}
 9652    "});
 9653
 9654    cx.update_editor(|editor, window, cx| {
 9655        editor.change_selections(None, window, cx, |s| s.select_ranges([0..0]));
 9656    });
 9657
 9658    let mocked_response = lsp::SignatureHelp {
 9659        signatures: Vec::new(),
 9660        active_signature: None,
 9661        active_parameter: None,
 9662    };
 9663    handle_signature_help_request(&mut cx, mocked_response).await;
 9664
 9665    cx.condition(|editor, _| !editor.signature_help_state.is_shown())
 9666        .await;
 9667
 9668    cx.editor(|editor, _, _| {
 9669        assert!(!editor.signature_help_state.is_shown());
 9670    });
 9671
 9672    // When entering inside the brackets from outside, `show_signature_help` is automatically called.
 9673    cx.set_state(indoc! {"
 9674        fn main() {
 9675            sample(ˇ);
 9676        }
 9677
 9678        fn sample(param1: u8, param2: u8) {}
 9679    "});
 9680
 9681    let mocked_response = lsp::SignatureHelp {
 9682        signatures: vec![lsp::SignatureInformation {
 9683            label: "fn sample(param1: u8, param2: u8)".to_string(),
 9684            documentation: None,
 9685            parameters: Some(vec![
 9686                lsp::ParameterInformation {
 9687                    label: lsp::ParameterLabel::Simple("param1: u8".to_string()),
 9688                    documentation: None,
 9689                },
 9690                lsp::ParameterInformation {
 9691                    label: lsp::ParameterLabel::Simple("param2: u8".to_string()),
 9692                    documentation: None,
 9693                },
 9694            ]),
 9695            active_parameter: None,
 9696        }],
 9697        active_signature: Some(0),
 9698        active_parameter: Some(0),
 9699    };
 9700    handle_signature_help_request(&mut cx, mocked_response.clone()).await;
 9701    cx.condition(|editor, _| editor.signature_help_state.is_shown())
 9702        .await;
 9703    cx.editor(|editor, _, _| {
 9704        assert!(editor.signature_help_state.is_shown());
 9705    });
 9706
 9707    // Restore the popover with more parameter input
 9708    cx.set_state(indoc! {"
 9709        fn main() {
 9710            sample(param1, param2ˇ);
 9711        }
 9712
 9713        fn sample(param1: u8, param2: u8) {}
 9714    "});
 9715
 9716    let mocked_response = lsp::SignatureHelp {
 9717        signatures: vec![lsp::SignatureInformation {
 9718            label: "fn sample(param1: u8, param2: u8)".to_string(),
 9719            documentation: None,
 9720            parameters: Some(vec![
 9721                lsp::ParameterInformation {
 9722                    label: lsp::ParameterLabel::Simple("param1: u8".to_string()),
 9723                    documentation: None,
 9724                },
 9725                lsp::ParameterInformation {
 9726                    label: lsp::ParameterLabel::Simple("param2: u8".to_string()),
 9727                    documentation: None,
 9728                },
 9729            ]),
 9730            active_parameter: None,
 9731        }],
 9732        active_signature: Some(0),
 9733        active_parameter: Some(1),
 9734    };
 9735    handle_signature_help_request(&mut cx, mocked_response.clone()).await;
 9736    cx.condition(|editor, _| editor.signature_help_state.is_shown())
 9737        .await;
 9738
 9739    // When selecting a range, the popover is gone.
 9740    // Avoid using `cx.set_state` to not actually edit the document, just change its selections.
 9741    cx.update_editor(|editor, window, cx| {
 9742        editor.change_selections(None, window, cx, |s| {
 9743            s.select_ranges(Some(Point::new(1, 25)..Point::new(1, 19)));
 9744        })
 9745    });
 9746    cx.assert_editor_state(indoc! {"
 9747        fn main() {
 9748            sample(param1, «ˇparam2»);
 9749        }
 9750
 9751        fn sample(param1: u8, param2: u8) {}
 9752    "});
 9753    cx.editor(|editor, _, _| {
 9754        assert!(!editor.signature_help_state.is_shown());
 9755    });
 9756
 9757    // When unselecting again, the popover is back if within the brackets.
 9758    cx.update_editor(|editor, window, cx| {
 9759        editor.change_selections(None, window, cx, |s| {
 9760            s.select_ranges(Some(Point::new(1, 19)..Point::new(1, 19)));
 9761        })
 9762    });
 9763    cx.assert_editor_state(indoc! {"
 9764        fn main() {
 9765            sample(param1, ˇparam2);
 9766        }
 9767
 9768        fn sample(param1: u8, param2: u8) {}
 9769    "});
 9770    handle_signature_help_request(&mut cx, mocked_response).await;
 9771    cx.condition(|editor, _| editor.signature_help_state.is_shown())
 9772        .await;
 9773    cx.editor(|editor, _, _| {
 9774        assert!(editor.signature_help_state.is_shown());
 9775    });
 9776
 9777    // Test to confirm that SignatureHelp does not appear after deselecting multiple ranges when it was hidden by pressing Escape.
 9778    cx.update_editor(|editor, window, cx| {
 9779        editor.change_selections(None, window, cx, |s| {
 9780            s.select_ranges(Some(Point::new(0, 0)..Point::new(0, 0)));
 9781            s.select_ranges(Some(Point::new(1, 19)..Point::new(1, 19)));
 9782        })
 9783    });
 9784    cx.assert_editor_state(indoc! {"
 9785        fn main() {
 9786            sample(param1, ˇparam2);
 9787        }
 9788
 9789        fn sample(param1: u8, param2: u8) {}
 9790    "});
 9791
 9792    let mocked_response = lsp::SignatureHelp {
 9793        signatures: vec![lsp::SignatureInformation {
 9794            label: "fn sample(param1: u8, param2: u8)".to_string(),
 9795            documentation: None,
 9796            parameters: Some(vec![
 9797                lsp::ParameterInformation {
 9798                    label: lsp::ParameterLabel::Simple("param1: u8".to_string()),
 9799                    documentation: None,
 9800                },
 9801                lsp::ParameterInformation {
 9802                    label: lsp::ParameterLabel::Simple("param2: u8".to_string()),
 9803                    documentation: None,
 9804                },
 9805            ]),
 9806            active_parameter: None,
 9807        }],
 9808        active_signature: Some(0),
 9809        active_parameter: Some(1),
 9810    };
 9811    handle_signature_help_request(&mut cx, mocked_response.clone()).await;
 9812    cx.condition(|editor, _| editor.signature_help_state.is_shown())
 9813        .await;
 9814    cx.update_editor(|editor, _, cx| {
 9815        editor.hide_signature_help(cx, SignatureHelpHiddenBy::Escape);
 9816    });
 9817    cx.condition(|editor, _| !editor.signature_help_state.is_shown())
 9818        .await;
 9819    cx.update_editor(|editor, window, cx| {
 9820        editor.change_selections(None, window, cx, |s| {
 9821            s.select_ranges(Some(Point::new(1, 25)..Point::new(1, 19)));
 9822        })
 9823    });
 9824    cx.assert_editor_state(indoc! {"
 9825        fn main() {
 9826            sample(param1, «ˇparam2»);
 9827        }
 9828
 9829        fn sample(param1: u8, param2: u8) {}
 9830    "});
 9831    cx.update_editor(|editor, window, cx| {
 9832        editor.change_selections(None, window, cx, |s| {
 9833            s.select_ranges(Some(Point::new(1, 19)..Point::new(1, 19)));
 9834        })
 9835    });
 9836    cx.assert_editor_state(indoc! {"
 9837        fn main() {
 9838            sample(param1, ˇparam2);
 9839        }
 9840
 9841        fn sample(param1: u8, param2: u8) {}
 9842    "});
 9843    cx.condition(|editor, _| !editor.signature_help_state.is_shown()) // because hidden by escape
 9844        .await;
 9845}
 9846
 9847#[gpui::test]
 9848async fn test_completion_mode(cx: &mut TestAppContext) {
 9849    init_test(cx, |_| {});
 9850    let mut cx = EditorLspTestContext::new_rust(
 9851        lsp::ServerCapabilities {
 9852            completion_provider: Some(lsp::CompletionOptions {
 9853                resolve_provider: Some(true),
 9854                ..Default::default()
 9855            }),
 9856            ..Default::default()
 9857        },
 9858        cx,
 9859    )
 9860    .await;
 9861
 9862    struct Run {
 9863        run_description: &'static str,
 9864        initial_state: String,
 9865        buffer_marked_text: String,
 9866        completion_text: &'static str,
 9867        expected_with_insert_mode: String,
 9868        expected_with_replace_mode: String,
 9869        expected_with_replace_subsequence_mode: String,
 9870        expected_with_replace_suffix_mode: String,
 9871    }
 9872
 9873    let runs = [
 9874        Run {
 9875            run_description: "Start of word matches completion text",
 9876            initial_state: "before ediˇ after".into(),
 9877            buffer_marked_text: "before <edi|> after".into(),
 9878            completion_text: "editor",
 9879            expected_with_insert_mode: "before editorˇ after".into(),
 9880            expected_with_replace_mode: "before editorˇ after".into(),
 9881            expected_with_replace_subsequence_mode: "before editorˇ after".into(),
 9882            expected_with_replace_suffix_mode: "before editorˇ after".into(),
 9883        },
 9884        Run {
 9885            run_description: "Accept same text at the middle of the word",
 9886            initial_state: "before ediˇtor after".into(),
 9887            buffer_marked_text: "before <edi|tor> after".into(),
 9888            completion_text: "editor",
 9889            expected_with_insert_mode: "before editorˇtor after".into(),
 9890            expected_with_replace_mode: "before editorˇ after".into(),
 9891            expected_with_replace_subsequence_mode: "before editorˇ after".into(),
 9892            expected_with_replace_suffix_mode: "before editorˇ after".into(),
 9893        },
 9894        Run {
 9895            run_description: "End of word matches completion text -- cursor at end",
 9896            initial_state: "before torˇ after".into(),
 9897            buffer_marked_text: "before <tor|> after".into(),
 9898            completion_text: "editor",
 9899            expected_with_insert_mode: "before editorˇ after".into(),
 9900            expected_with_replace_mode: "before editorˇ after".into(),
 9901            expected_with_replace_subsequence_mode: "before editorˇ after".into(),
 9902            expected_with_replace_suffix_mode: "before editorˇ after".into(),
 9903        },
 9904        Run {
 9905            run_description: "End of word matches completion text -- cursor at start",
 9906            initial_state: "before ˇtor after".into(),
 9907            buffer_marked_text: "before <|tor> after".into(),
 9908            completion_text: "editor",
 9909            expected_with_insert_mode: "before editorˇtor after".into(),
 9910            expected_with_replace_mode: "before editorˇ after".into(),
 9911            expected_with_replace_subsequence_mode: "before editorˇ after".into(),
 9912            expected_with_replace_suffix_mode: "before editorˇ after".into(),
 9913        },
 9914        Run {
 9915            run_description: "Prepend text containing whitespace",
 9916            initial_state: "pˇfield: bool".into(),
 9917            buffer_marked_text: "<p|field>: bool".into(),
 9918            completion_text: "pub ",
 9919            expected_with_insert_mode: "pub ˇfield: bool".into(),
 9920            expected_with_replace_mode: "pub ˇ: bool".into(),
 9921            expected_with_replace_subsequence_mode: "pub ˇfield: bool".into(),
 9922            expected_with_replace_suffix_mode: "pub ˇfield: bool".into(),
 9923        },
 9924        Run {
 9925            run_description: "Add element to start of list",
 9926            initial_state: "[element_ˇelement_2]".into(),
 9927            buffer_marked_text: "[<element_|element_2>]".into(),
 9928            completion_text: "element_1",
 9929            expected_with_insert_mode: "[element_1ˇelement_2]".into(),
 9930            expected_with_replace_mode: "[element_1ˇ]".into(),
 9931            expected_with_replace_subsequence_mode: "[element_1ˇelement_2]".into(),
 9932            expected_with_replace_suffix_mode: "[element_1ˇelement_2]".into(),
 9933        },
 9934        Run {
 9935            run_description: "Add element to start of list -- first and second elements are equal",
 9936            initial_state: "[elˇelement]".into(),
 9937            buffer_marked_text: "[<el|element>]".into(),
 9938            completion_text: "element",
 9939            expected_with_insert_mode: "[elementˇelement]".into(),
 9940            expected_with_replace_mode: "[elementˇ]".into(),
 9941            expected_with_replace_subsequence_mode: "[elementˇelement]".into(),
 9942            expected_with_replace_suffix_mode: "[elementˇ]".into(),
 9943        },
 9944        Run {
 9945            run_description: "Ends with matching suffix",
 9946            initial_state: "SubˇError".into(),
 9947            buffer_marked_text: "<Sub|Error>".into(),
 9948            completion_text: "SubscriptionError",
 9949            expected_with_insert_mode: "SubscriptionErrorˇError".into(),
 9950            expected_with_replace_mode: "SubscriptionErrorˇ".into(),
 9951            expected_with_replace_subsequence_mode: "SubscriptionErrorˇ".into(),
 9952            expected_with_replace_suffix_mode: "SubscriptionErrorˇ".into(),
 9953        },
 9954        Run {
 9955            run_description: "Suffix is a subsequence -- contiguous",
 9956            initial_state: "SubˇErr".into(),
 9957            buffer_marked_text: "<Sub|Err>".into(),
 9958            completion_text: "SubscriptionError",
 9959            expected_with_insert_mode: "SubscriptionErrorˇErr".into(),
 9960            expected_with_replace_mode: "SubscriptionErrorˇ".into(),
 9961            expected_with_replace_subsequence_mode: "SubscriptionErrorˇ".into(),
 9962            expected_with_replace_suffix_mode: "SubscriptionErrorˇErr".into(),
 9963        },
 9964        Run {
 9965            run_description: "Suffix is a subsequence -- non-contiguous -- replace intended",
 9966            initial_state: "Suˇscrirr".into(),
 9967            buffer_marked_text: "<Su|scrirr>".into(),
 9968            completion_text: "SubscriptionError",
 9969            expected_with_insert_mode: "SubscriptionErrorˇscrirr".into(),
 9970            expected_with_replace_mode: "SubscriptionErrorˇ".into(),
 9971            expected_with_replace_subsequence_mode: "SubscriptionErrorˇ".into(),
 9972            expected_with_replace_suffix_mode: "SubscriptionErrorˇscrirr".into(),
 9973        },
 9974        Run {
 9975            run_description: "Suffix is a subsequence -- non-contiguous -- replace unintended",
 9976            initial_state: "foo(indˇix)".into(),
 9977            buffer_marked_text: "foo(<ind|ix>)".into(),
 9978            completion_text: "node_index",
 9979            expected_with_insert_mode: "foo(node_indexˇix)".into(),
 9980            expected_with_replace_mode: "foo(node_indexˇ)".into(),
 9981            expected_with_replace_subsequence_mode: "foo(node_indexˇix)".into(),
 9982            expected_with_replace_suffix_mode: "foo(node_indexˇix)".into(),
 9983        },
 9984    ];
 9985
 9986    for run in runs {
 9987        let run_variations = [
 9988            (LspInsertMode::Insert, run.expected_with_insert_mode),
 9989            (LspInsertMode::Replace, run.expected_with_replace_mode),
 9990            (
 9991                LspInsertMode::ReplaceSubsequence,
 9992                run.expected_with_replace_subsequence_mode,
 9993            ),
 9994            (
 9995                LspInsertMode::ReplaceSuffix,
 9996                run.expected_with_replace_suffix_mode,
 9997            ),
 9998        ];
 9999
10000        for (lsp_insert_mode, expected_text) in run_variations {
10001            eprintln!(
10002                "run = {:?}, mode = {lsp_insert_mode:.?}",
10003                run.run_description,
10004            );
10005
10006            update_test_language_settings(&mut cx, |settings| {
10007                settings.defaults.completions = Some(CompletionSettings {
10008                    lsp_insert_mode,
10009                    words: WordsCompletionMode::Disabled,
10010                    lsp: true,
10011                    lsp_fetch_timeout_ms: 0,
10012                });
10013            });
10014
10015            cx.set_state(&run.initial_state);
10016            cx.update_editor(|editor, window, cx| {
10017                editor.show_completions(&ShowCompletions { trigger: None }, window, cx);
10018            });
10019
10020            let counter = Arc::new(AtomicUsize::new(0));
10021            handle_completion_request_with_insert_and_replace(
10022                &mut cx,
10023                &run.buffer_marked_text,
10024                vec![run.completion_text],
10025                counter.clone(),
10026            )
10027            .await;
10028            cx.condition(|editor, _| editor.context_menu_visible())
10029                .await;
10030            assert_eq!(counter.load(atomic::Ordering::Acquire), 1);
10031
10032            let apply_additional_edits = cx.update_editor(|editor, window, cx| {
10033                editor
10034                    .confirm_completion(&ConfirmCompletion::default(), window, cx)
10035                    .unwrap()
10036            });
10037            cx.assert_editor_state(&expected_text);
10038            handle_resolve_completion_request(&mut cx, None).await;
10039            apply_additional_edits.await.unwrap();
10040        }
10041    }
10042}
10043
10044#[gpui::test]
10045async fn test_completion_with_mode_specified_by_action(cx: &mut TestAppContext) {
10046    init_test(cx, |_| {});
10047    let mut cx = EditorLspTestContext::new_rust(
10048        lsp::ServerCapabilities {
10049            completion_provider: Some(lsp::CompletionOptions {
10050                resolve_provider: Some(true),
10051                ..Default::default()
10052            }),
10053            ..Default::default()
10054        },
10055        cx,
10056    )
10057    .await;
10058
10059    let initial_state = "SubˇError";
10060    let buffer_marked_text = "<Sub|Error>";
10061    let completion_text = "SubscriptionError";
10062    let expected_with_insert_mode = "SubscriptionErrorˇError";
10063    let expected_with_replace_mode = "SubscriptionErrorˇ";
10064
10065    update_test_language_settings(&mut cx, |settings| {
10066        settings.defaults.completions = Some(CompletionSettings {
10067            words: WordsCompletionMode::Disabled,
10068            // set the opposite here to ensure that the action is overriding the default behavior
10069            lsp_insert_mode: LspInsertMode::Insert,
10070            lsp: true,
10071            lsp_fetch_timeout_ms: 0,
10072        });
10073    });
10074
10075    cx.set_state(initial_state);
10076    cx.update_editor(|editor, window, cx| {
10077        editor.show_completions(&ShowCompletions { trigger: None }, window, cx);
10078    });
10079
10080    let counter = Arc::new(AtomicUsize::new(0));
10081    handle_completion_request_with_insert_and_replace(
10082        &mut cx,
10083        &buffer_marked_text,
10084        vec![completion_text],
10085        counter.clone(),
10086    )
10087    .await;
10088    cx.condition(|editor, _| editor.context_menu_visible())
10089        .await;
10090    assert_eq!(counter.load(atomic::Ordering::Acquire), 1);
10091
10092    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
10093        editor
10094            .confirm_completion_replace(&ConfirmCompletionReplace, window, cx)
10095            .unwrap()
10096    });
10097    cx.assert_editor_state(&expected_with_replace_mode);
10098    handle_resolve_completion_request(&mut cx, None).await;
10099    apply_additional_edits.await.unwrap();
10100
10101    update_test_language_settings(&mut cx, |settings| {
10102        settings.defaults.completions = Some(CompletionSettings {
10103            words: WordsCompletionMode::Disabled,
10104            // set the opposite here to ensure that the action is overriding the default behavior
10105            lsp_insert_mode: LspInsertMode::Replace,
10106            lsp: true,
10107            lsp_fetch_timeout_ms: 0,
10108        });
10109    });
10110
10111    cx.set_state(initial_state);
10112    cx.update_editor(|editor, window, cx| {
10113        editor.show_completions(&ShowCompletions { trigger: None }, window, cx);
10114    });
10115    handle_completion_request_with_insert_and_replace(
10116        &mut cx,
10117        &buffer_marked_text,
10118        vec![completion_text],
10119        counter.clone(),
10120    )
10121    .await;
10122    cx.condition(|editor, _| editor.context_menu_visible())
10123        .await;
10124    assert_eq!(counter.load(atomic::Ordering::Acquire), 2);
10125
10126    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
10127        editor
10128            .confirm_completion_insert(&ConfirmCompletionInsert, window, cx)
10129            .unwrap()
10130    });
10131    cx.assert_editor_state(&expected_with_insert_mode);
10132    handle_resolve_completion_request(&mut cx, None).await;
10133    apply_additional_edits.await.unwrap();
10134}
10135
10136#[gpui::test]
10137async fn test_completion_replacing_surrounding_text_with_multicursors(cx: &mut TestAppContext) {
10138    init_test(cx, |_| {});
10139    let mut cx = EditorLspTestContext::new_rust(
10140        lsp::ServerCapabilities {
10141            completion_provider: Some(lsp::CompletionOptions {
10142                resolve_provider: Some(true),
10143                ..Default::default()
10144            }),
10145            ..Default::default()
10146        },
10147        cx,
10148    )
10149    .await;
10150
10151    // scenario: surrounding text matches completion text
10152    let completion_text = "to_offset";
10153    let initial_state = indoc! {"
10154        1. buf.to_offˇsuffix
10155        2. buf.to_offˇsuf
10156        3. buf.to_offˇfix
10157        4. buf.to_offˇ
10158        5. into_offˇensive
10159        6. ˇsuffix
10160        7. let ˇ //
10161        8. aaˇzz
10162        9. buf.to_off«zzzzzˇ»suffix
10163        10. buf.«ˇzzzzz»suffix
10164        11. to_off«ˇzzzzz»
10165
10166        buf.to_offˇsuffix  // newest cursor
10167    "};
10168    let completion_marked_buffer = indoc! {"
10169        1. buf.to_offsuffix
10170        2. buf.to_offsuf
10171        3. buf.to_offfix
10172        4. buf.to_off
10173        5. into_offensive
10174        6. suffix
10175        7. let  //
10176        8. aazz
10177        9. buf.to_offzzzzzsuffix
10178        10. buf.zzzzzsuffix
10179        11. to_offzzzzz
10180
10181        buf.<to_off|suffix>  // newest cursor
10182    "};
10183    let expected = indoc! {"
10184        1. buf.to_offsetˇ
10185        2. buf.to_offsetˇsuf
10186        3. buf.to_offsetˇfix
10187        4. buf.to_offsetˇ
10188        5. into_offsetˇensive
10189        6. to_offsetˇsuffix
10190        7. let to_offsetˇ //
10191        8. aato_offsetˇzz
10192        9. buf.to_offsetˇ
10193        10. buf.to_offsetˇsuffix
10194        11. to_offsetˇ
10195
10196        buf.to_offsetˇ  // newest cursor
10197    "};
10198    cx.set_state(initial_state);
10199    cx.update_editor(|editor, window, cx| {
10200        editor.show_completions(&ShowCompletions { trigger: None }, window, cx);
10201    });
10202    handle_completion_request_with_insert_and_replace(
10203        &mut cx,
10204        completion_marked_buffer,
10205        vec![completion_text],
10206        Arc::new(AtomicUsize::new(0)),
10207    )
10208    .await;
10209    cx.condition(|editor, _| editor.context_menu_visible())
10210        .await;
10211    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
10212        editor
10213            .confirm_completion_replace(&ConfirmCompletionReplace, window, cx)
10214            .unwrap()
10215    });
10216    cx.assert_editor_state(expected);
10217    handle_resolve_completion_request(&mut cx, None).await;
10218    apply_additional_edits.await.unwrap();
10219
10220    // scenario: surrounding text matches surroundings of newest cursor, inserting at the end
10221    let completion_text = "foo_and_bar";
10222    let initial_state = indoc! {"
10223        1. ooanbˇ
10224        2. zooanbˇ
10225        3. ooanbˇz
10226        4. zooanbˇz
10227        5. ooanˇ
10228        6. oanbˇ
10229
10230        ooanbˇ
10231    "};
10232    let completion_marked_buffer = indoc! {"
10233        1. ooanb
10234        2. zooanb
10235        3. ooanbz
10236        4. zooanbz
10237        5. ooan
10238        6. oanb
10239
10240        <ooanb|>
10241    "};
10242    let expected = indoc! {"
10243        1. foo_and_barˇ
10244        2. zfoo_and_barˇ
10245        3. foo_and_barˇz
10246        4. zfoo_and_barˇz
10247        5. ooanfoo_and_barˇ
10248        6. oanbfoo_and_barˇ
10249
10250        foo_and_barˇ
10251    "};
10252    cx.set_state(initial_state);
10253    cx.update_editor(|editor, window, cx| {
10254        editor.show_completions(&ShowCompletions { trigger: None }, window, cx);
10255    });
10256    handle_completion_request_with_insert_and_replace(
10257        &mut cx,
10258        completion_marked_buffer,
10259        vec![completion_text],
10260        Arc::new(AtomicUsize::new(0)),
10261    )
10262    .await;
10263    cx.condition(|editor, _| editor.context_menu_visible())
10264        .await;
10265    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
10266        editor
10267            .confirm_completion_replace(&ConfirmCompletionReplace, window, cx)
10268            .unwrap()
10269    });
10270    cx.assert_editor_state(expected);
10271    handle_resolve_completion_request(&mut cx, None).await;
10272    apply_additional_edits.await.unwrap();
10273
10274    // scenario: surrounding text matches surroundings of newest cursor, inserted at the middle
10275    // (expects the same as if it was inserted at the end)
10276    let completion_text = "foo_and_bar";
10277    let initial_state = indoc! {"
10278        1. ooˇanb
10279        2. zooˇanb
10280        3. ooˇanbz
10281        4. zooˇanbz
10282
10283        ooˇanb
10284    "};
10285    let completion_marked_buffer = indoc! {"
10286        1. ooanb
10287        2. zooanb
10288        3. ooanbz
10289        4. zooanbz
10290
10291        <oo|anb>
10292    "};
10293    let expected = indoc! {"
10294        1. foo_and_barˇ
10295        2. zfoo_and_barˇ
10296        3. foo_and_barˇz
10297        4. zfoo_and_barˇz
10298
10299        foo_and_barˇ
10300    "};
10301    cx.set_state(initial_state);
10302    cx.update_editor(|editor, window, cx| {
10303        editor.show_completions(&ShowCompletions { trigger: None }, window, cx);
10304    });
10305    handle_completion_request_with_insert_and_replace(
10306        &mut cx,
10307        completion_marked_buffer,
10308        vec![completion_text],
10309        Arc::new(AtomicUsize::new(0)),
10310    )
10311    .await;
10312    cx.condition(|editor, _| editor.context_menu_visible())
10313        .await;
10314    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
10315        editor
10316            .confirm_completion_replace(&ConfirmCompletionReplace, window, cx)
10317            .unwrap()
10318    });
10319    cx.assert_editor_state(expected);
10320    handle_resolve_completion_request(&mut cx, None).await;
10321    apply_additional_edits.await.unwrap();
10322}
10323
10324// This used to crash
10325#[gpui::test]
10326async fn test_completion_in_multibuffer_with_replace_range(cx: &mut TestAppContext) {
10327    init_test(cx, |_| {});
10328
10329    let buffer_text = indoc! {"
10330        fn main() {
10331            10.satu;
10332
10333            //
10334            // separate cursors so they open in different excerpts (manually reproducible)
10335            //
10336
10337            10.satu20;
10338        }
10339    "};
10340    let multibuffer_text_with_selections = indoc! {"
10341        fn main() {
10342            10.satuˇ;
10343
10344            //
10345
10346            //
10347
10348            10.satuˇ20;
10349        }
10350    "};
10351    let expected_multibuffer = indoc! {"
10352        fn main() {
10353            10.saturating_sub()ˇ;
10354
10355            //
10356
10357            //
10358
10359            10.saturating_sub()ˇ;
10360        }
10361    "};
10362
10363    let first_excerpt_end = buffer_text.find("//").unwrap() + 3;
10364    let second_excerpt_end = buffer_text.rfind("//").unwrap() - 4;
10365
10366    let fs = FakeFs::new(cx.executor());
10367    fs.insert_tree(
10368        path!("/a"),
10369        json!({
10370            "main.rs": buffer_text,
10371        }),
10372    )
10373    .await;
10374
10375    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
10376    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
10377    language_registry.add(rust_lang());
10378    let mut fake_servers = language_registry.register_fake_lsp(
10379        "Rust",
10380        FakeLspAdapter {
10381            capabilities: lsp::ServerCapabilities {
10382                completion_provider: Some(lsp::CompletionOptions {
10383                    resolve_provider: None,
10384                    ..lsp::CompletionOptions::default()
10385                }),
10386                ..lsp::ServerCapabilities::default()
10387            },
10388            ..FakeLspAdapter::default()
10389        },
10390    );
10391    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
10392    let cx = &mut VisualTestContext::from_window(*workspace, cx);
10393    let buffer = project
10394        .update(cx, |project, cx| {
10395            project.open_local_buffer(path!("/a/main.rs"), cx)
10396        })
10397        .await
10398        .unwrap();
10399
10400    let multi_buffer = cx.new(|cx| {
10401        let mut multi_buffer = MultiBuffer::new(Capability::ReadWrite);
10402        multi_buffer.push_excerpts(
10403            buffer.clone(),
10404            [ExcerptRange::new(0..first_excerpt_end)],
10405            cx,
10406        );
10407        multi_buffer.push_excerpts(
10408            buffer.clone(),
10409            [ExcerptRange::new(second_excerpt_end..buffer_text.len())],
10410            cx,
10411        );
10412        multi_buffer
10413    });
10414
10415    let editor = workspace
10416        .update(cx, |_, window, cx| {
10417            cx.new(|cx| {
10418                Editor::new(
10419                    EditorMode::Full {
10420                        scale_ui_elements_with_buffer_font_size: false,
10421                        show_active_line_background: false,
10422                    },
10423                    multi_buffer.clone(),
10424                    Some(project.clone()),
10425                    window,
10426                    cx,
10427                )
10428            })
10429        })
10430        .unwrap();
10431
10432    let pane = workspace
10433        .update(cx, |workspace, _, _| workspace.active_pane().clone())
10434        .unwrap();
10435    pane.update_in(cx, |pane, window, cx| {
10436        pane.add_item(Box::new(editor.clone()), true, true, None, window, cx);
10437    });
10438
10439    let fake_server = fake_servers.next().await.unwrap();
10440
10441    editor.update_in(cx, |editor, window, cx| {
10442        editor.change_selections(None, window, cx, |s| {
10443            s.select_ranges([
10444                Point::new(1, 11)..Point::new(1, 11),
10445                Point::new(7, 11)..Point::new(7, 11),
10446            ])
10447        });
10448
10449        assert_text_with_selections(editor, multibuffer_text_with_selections, cx);
10450    });
10451
10452    editor.update_in(cx, |editor, window, cx| {
10453        editor.show_completions(&ShowCompletions { trigger: None }, window, cx);
10454    });
10455
10456    fake_server
10457        .set_request_handler::<lsp::request::Completion, _, _>(move |_, _| async move {
10458            let completion_item = lsp::CompletionItem {
10459                label: "saturating_sub()".into(),
10460                text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
10461                    lsp::InsertReplaceEdit {
10462                        new_text: "saturating_sub()".to_owned(),
10463                        insert: lsp::Range::new(
10464                            lsp::Position::new(7, 7),
10465                            lsp::Position::new(7, 11),
10466                        ),
10467                        replace: lsp::Range::new(
10468                            lsp::Position::new(7, 7),
10469                            lsp::Position::new(7, 13),
10470                        ),
10471                    },
10472                )),
10473                ..lsp::CompletionItem::default()
10474            };
10475
10476            Ok(Some(lsp::CompletionResponse::Array(vec![completion_item])))
10477        })
10478        .next()
10479        .await
10480        .unwrap();
10481
10482    cx.condition(&editor, |editor, _| editor.context_menu_visible())
10483        .await;
10484
10485    editor
10486        .update_in(cx, |editor, window, cx| {
10487            editor
10488                .confirm_completion_replace(&ConfirmCompletionReplace, window, cx)
10489                .unwrap()
10490        })
10491        .await
10492        .unwrap();
10493
10494    editor.update(cx, |editor, cx| {
10495        assert_text_with_selections(editor, expected_multibuffer, cx);
10496    })
10497}
10498
10499#[gpui::test]
10500async fn test_completion(cx: &mut TestAppContext) {
10501    init_test(cx, |_| {});
10502
10503    let mut cx = EditorLspTestContext::new_rust(
10504        lsp::ServerCapabilities {
10505            completion_provider: Some(lsp::CompletionOptions {
10506                trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
10507                resolve_provider: Some(true),
10508                ..Default::default()
10509            }),
10510            signature_help_provider: Some(lsp::SignatureHelpOptions::default()),
10511            ..Default::default()
10512        },
10513        cx,
10514    )
10515    .await;
10516    let counter = Arc::new(AtomicUsize::new(0));
10517
10518    cx.set_state(indoc! {"
10519        oneˇ
10520        two
10521        three
10522    "});
10523    cx.simulate_keystroke(".");
10524    handle_completion_request(
10525        &mut cx,
10526        indoc! {"
10527            one.|<>
10528            two
10529            three
10530        "},
10531        vec!["first_completion", "second_completion"],
10532        counter.clone(),
10533    )
10534    .await;
10535    cx.condition(|editor, _| editor.context_menu_visible())
10536        .await;
10537    assert_eq!(counter.load(atomic::Ordering::Acquire), 1);
10538
10539    let _handler = handle_signature_help_request(
10540        &mut cx,
10541        lsp::SignatureHelp {
10542            signatures: vec![lsp::SignatureInformation {
10543                label: "test signature".to_string(),
10544                documentation: None,
10545                parameters: Some(vec![lsp::ParameterInformation {
10546                    label: lsp::ParameterLabel::Simple("foo: u8".to_string()),
10547                    documentation: None,
10548                }]),
10549                active_parameter: None,
10550            }],
10551            active_signature: None,
10552            active_parameter: None,
10553        },
10554    );
10555    cx.update_editor(|editor, window, cx| {
10556        assert!(
10557            !editor.signature_help_state.is_shown(),
10558            "No signature help was called for"
10559        );
10560        editor.show_signature_help(&ShowSignatureHelp, window, cx);
10561    });
10562    cx.run_until_parked();
10563    cx.update_editor(|editor, _, _| {
10564        assert!(
10565            !editor.signature_help_state.is_shown(),
10566            "No signature help should be shown when completions menu is open"
10567        );
10568    });
10569
10570    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
10571        editor.context_menu_next(&Default::default(), window, cx);
10572        editor
10573            .confirm_completion(&ConfirmCompletion::default(), window, cx)
10574            .unwrap()
10575    });
10576    cx.assert_editor_state(indoc! {"
10577        one.second_completionˇ
10578        two
10579        three
10580    "});
10581
10582    handle_resolve_completion_request(
10583        &mut cx,
10584        Some(vec![
10585            (
10586                //This overlaps with the primary completion edit which is
10587                //misbehavior from the LSP spec, test that we filter it out
10588                indoc! {"
10589                    one.second_ˇcompletion
10590                    two
10591                    threeˇ
10592                "},
10593                "overlapping additional edit",
10594            ),
10595            (
10596                indoc! {"
10597                    one.second_completion
10598                    two
10599                    threeˇ
10600                "},
10601                "\nadditional edit",
10602            ),
10603        ]),
10604    )
10605    .await;
10606    apply_additional_edits.await.unwrap();
10607    cx.assert_editor_state(indoc! {"
10608        one.second_completionˇ
10609        two
10610        three
10611        additional edit
10612    "});
10613
10614    cx.set_state(indoc! {"
10615        one.second_completion
10616        twoˇ
10617        threeˇ
10618        additional edit
10619    "});
10620    cx.simulate_keystroke(" ");
10621    assert!(cx.editor(|e, _, _| e.context_menu.borrow_mut().is_none()));
10622    cx.simulate_keystroke("s");
10623    assert!(cx.editor(|e, _, _| e.context_menu.borrow_mut().is_none()));
10624
10625    cx.assert_editor_state(indoc! {"
10626        one.second_completion
10627        two sˇ
10628        three sˇ
10629        additional edit
10630    "});
10631    handle_completion_request(
10632        &mut cx,
10633        indoc! {"
10634            one.second_completion
10635            two s
10636            three <s|>
10637            additional edit
10638        "},
10639        vec!["fourth_completion", "fifth_completion", "sixth_completion"],
10640        counter.clone(),
10641    )
10642    .await;
10643    cx.condition(|editor, _| editor.context_menu_visible())
10644        .await;
10645    assert_eq!(counter.load(atomic::Ordering::Acquire), 2);
10646
10647    cx.simulate_keystroke("i");
10648
10649    handle_completion_request(
10650        &mut cx,
10651        indoc! {"
10652            one.second_completion
10653            two si
10654            three <si|>
10655            additional edit
10656        "},
10657        vec!["fourth_completion", "fifth_completion", "sixth_completion"],
10658        counter.clone(),
10659    )
10660    .await;
10661    cx.condition(|editor, _| editor.context_menu_visible())
10662        .await;
10663    assert_eq!(counter.load(atomic::Ordering::Acquire), 3);
10664
10665    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
10666        editor
10667            .confirm_completion(&ConfirmCompletion::default(), window, cx)
10668            .unwrap()
10669    });
10670    cx.assert_editor_state(indoc! {"
10671        one.second_completion
10672        two sixth_completionˇ
10673        three sixth_completionˇ
10674        additional edit
10675    "});
10676
10677    apply_additional_edits.await.unwrap();
10678
10679    update_test_language_settings(&mut cx, |settings| {
10680        settings.defaults.show_completions_on_input = Some(false);
10681    });
10682    cx.set_state("editorˇ");
10683    cx.simulate_keystroke(".");
10684    assert!(cx.editor(|e, _, _| e.context_menu.borrow_mut().is_none()));
10685    cx.simulate_keystrokes("c l o");
10686    cx.assert_editor_state("editor.cloˇ");
10687    assert!(cx.editor(|e, _, _| e.context_menu.borrow_mut().is_none()));
10688    cx.update_editor(|editor, window, cx| {
10689        editor.show_completions(&ShowCompletions { trigger: None }, window, cx);
10690    });
10691    handle_completion_request(
10692        &mut cx,
10693        "editor.<clo|>",
10694        vec!["close", "clobber"],
10695        counter.clone(),
10696    )
10697    .await;
10698    cx.condition(|editor, _| editor.context_menu_visible())
10699        .await;
10700    assert_eq!(counter.load(atomic::Ordering::Acquire), 4);
10701
10702    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
10703        editor
10704            .confirm_completion(&ConfirmCompletion::default(), window, cx)
10705            .unwrap()
10706    });
10707    cx.assert_editor_state("editor.clobberˇ");
10708    handle_resolve_completion_request(&mut cx, None).await;
10709    apply_additional_edits.await.unwrap();
10710}
10711
10712#[gpui::test]
10713async fn test_word_completion(cx: &mut TestAppContext) {
10714    let lsp_fetch_timeout_ms = 10;
10715    init_test(cx, |language_settings| {
10716        language_settings.defaults.completions = Some(CompletionSettings {
10717            words: WordsCompletionMode::Fallback,
10718            lsp: true,
10719            lsp_fetch_timeout_ms: 10,
10720            lsp_insert_mode: LspInsertMode::Insert,
10721        });
10722    });
10723
10724    let mut cx = EditorLspTestContext::new_rust(
10725        lsp::ServerCapabilities {
10726            completion_provider: Some(lsp::CompletionOptions {
10727                trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
10728                ..lsp::CompletionOptions::default()
10729            }),
10730            signature_help_provider: Some(lsp::SignatureHelpOptions::default()),
10731            ..lsp::ServerCapabilities::default()
10732        },
10733        cx,
10734    )
10735    .await;
10736
10737    let throttle_completions = Arc::new(AtomicBool::new(false));
10738
10739    let lsp_throttle_completions = throttle_completions.clone();
10740    let _completion_requests_handler =
10741        cx.lsp
10742            .server
10743            .on_request::<lsp::request::Completion, _, _>(move |_, cx| {
10744                let lsp_throttle_completions = lsp_throttle_completions.clone();
10745                let cx = cx.clone();
10746                async move {
10747                    if lsp_throttle_completions.load(atomic::Ordering::Acquire) {
10748                        cx.background_executor()
10749                            .timer(Duration::from_millis(lsp_fetch_timeout_ms * 10))
10750                            .await;
10751                    }
10752                    Ok(Some(lsp::CompletionResponse::Array(vec![
10753                        lsp::CompletionItem {
10754                            label: "first".into(),
10755                            ..lsp::CompletionItem::default()
10756                        },
10757                        lsp::CompletionItem {
10758                            label: "last".into(),
10759                            ..lsp::CompletionItem::default()
10760                        },
10761                    ])))
10762                }
10763            });
10764
10765    cx.set_state(indoc! {"
10766        oneˇ
10767        two
10768        three
10769    "});
10770    cx.simulate_keystroke(".");
10771    cx.executor().run_until_parked();
10772    cx.condition(|editor, _| editor.context_menu_visible())
10773        .await;
10774    cx.update_editor(|editor, window, cx| {
10775        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10776        {
10777            assert_eq!(
10778                completion_menu_entries(&menu),
10779                &["first", "last"],
10780                "When LSP server is fast to reply, no fallback word completions are used"
10781            );
10782        } else {
10783            panic!("expected completion menu to be open");
10784        }
10785        editor.cancel(&Cancel, window, cx);
10786    });
10787    cx.executor().run_until_parked();
10788    cx.condition(|editor, _| !editor.context_menu_visible())
10789        .await;
10790
10791    throttle_completions.store(true, atomic::Ordering::Release);
10792    cx.simulate_keystroke(".");
10793    cx.executor()
10794        .advance_clock(Duration::from_millis(lsp_fetch_timeout_ms * 2));
10795    cx.executor().run_until_parked();
10796    cx.condition(|editor, _| editor.context_menu_visible())
10797        .await;
10798    cx.update_editor(|editor, _, _| {
10799        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10800        {
10801            assert_eq!(completion_menu_entries(&menu), &["one", "three", "two"],
10802                "When LSP server is slow, document words can be shown instead, if configured accordingly");
10803        } else {
10804            panic!("expected completion menu to be open");
10805        }
10806    });
10807}
10808
10809#[gpui::test]
10810async fn test_word_completions_do_not_duplicate_lsp_ones(cx: &mut TestAppContext) {
10811    init_test(cx, |language_settings| {
10812        language_settings.defaults.completions = Some(CompletionSettings {
10813            words: WordsCompletionMode::Enabled,
10814            lsp: true,
10815            lsp_fetch_timeout_ms: 0,
10816            lsp_insert_mode: LspInsertMode::Insert,
10817        });
10818    });
10819
10820    let mut cx = EditorLspTestContext::new_rust(
10821        lsp::ServerCapabilities {
10822            completion_provider: Some(lsp::CompletionOptions {
10823                trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
10824                ..lsp::CompletionOptions::default()
10825            }),
10826            signature_help_provider: Some(lsp::SignatureHelpOptions::default()),
10827            ..lsp::ServerCapabilities::default()
10828        },
10829        cx,
10830    )
10831    .await;
10832
10833    let _completion_requests_handler =
10834        cx.lsp
10835            .server
10836            .on_request::<lsp::request::Completion, _, _>(move |_, _| async move {
10837                Ok(Some(lsp::CompletionResponse::Array(vec![
10838                    lsp::CompletionItem {
10839                        label: "first".into(),
10840                        ..lsp::CompletionItem::default()
10841                    },
10842                    lsp::CompletionItem {
10843                        label: "last".into(),
10844                        ..lsp::CompletionItem::default()
10845                    },
10846                ])))
10847            });
10848
10849    cx.set_state(indoc! {"ˇ
10850        first
10851        last
10852        second
10853    "});
10854    cx.simulate_keystroke(".");
10855    cx.executor().run_until_parked();
10856    cx.condition(|editor, _| editor.context_menu_visible())
10857        .await;
10858    cx.update_editor(|editor, _, _| {
10859        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10860        {
10861            assert_eq!(
10862                completion_menu_entries(&menu),
10863                &["first", "last", "second"],
10864                "Word completions that has the same edit as the any of the LSP ones, should not be proposed"
10865            );
10866        } else {
10867            panic!("expected completion menu to be open");
10868        }
10869    });
10870}
10871
10872#[gpui::test]
10873async fn test_word_completions_continue_on_typing(cx: &mut TestAppContext) {
10874    init_test(cx, |language_settings| {
10875        language_settings.defaults.completions = Some(CompletionSettings {
10876            words: WordsCompletionMode::Disabled,
10877            lsp: true,
10878            lsp_fetch_timeout_ms: 0,
10879            lsp_insert_mode: LspInsertMode::Insert,
10880        });
10881    });
10882
10883    let mut cx = EditorLspTestContext::new_rust(
10884        lsp::ServerCapabilities {
10885            completion_provider: Some(lsp::CompletionOptions {
10886                trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
10887                ..lsp::CompletionOptions::default()
10888            }),
10889            signature_help_provider: Some(lsp::SignatureHelpOptions::default()),
10890            ..lsp::ServerCapabilities::default()
10891        },
10892        cx,
10893    )
10894    .await;
10895
10896    let _completion_requests_handler =
10897        cx.lsp
10898            .server
10899            .on_request::<lsp::request::Completion, _, _>(move |_, _| async move {
10900                panic!("LSP completions should not be queried when dealing with word completions")
10901            });
10902
10903    cx.set_state(indoc! {"ˇ
10904        first
10905        last
10906        second
10907    "});
10908    cx.update_editor(|editor, window, cx| {
10909        editor.show_word_completions(&ShowWordCompletions, window, cx);
10910    });
10911    cx.executor().run_until_parked();
10912    cx.condition(|editor, _| editor.context_menu_visible())
10913        .await;
10914    cx.update_editor(|editor, _, _| {
10915        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10916        {
10917            assert_eq!(
10918                completion_menu_entries(&menu),
10919                &["first", "last", "second"],
10920                "`ShowWordCompletions` action should show word completions"
10921            );
10922        } else {
10923            panic!("expected completion menu to be open");
10924        }
10925    });
10926
10927    cx.simulate_keystroke("l");
10928    cx.executor().run_until_parked();
10929    cx.condition(|editor, _| editor.context_menu_visible())
10930        .await;
10931    cx.update_editor(|editor, _, _| {
10932        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10933        {
10934            assert_eq!(
10935                completion_menu_entries(&menu),
10936                &["last"],
10937                "After showing word completions, further editing should filter them and not query the LSP"
10938            );
10939        } else {
10940            panic!("expected completion menu to be open");
10941        }
10942    });
10943}
10944
10945#[gpui::test]
10946async fn test_word_completions_usually_skip_digits(cx: &mut TestAppContext) {
10947    init_test(cx, |language_settings| {
10948        language_settings.defaults.completions = Some(CompletionSettings {
10949            words: WordsCompletionMode::Fallback,
10950            lsp: false,
10951            lsp_fetch_timeout_ms: 0,
10952            lsp_insert_mode: LspInsertMode::Insert,
10953        });
10954    });
10955
10956    let mut cx = EditorLspTestContext::new_rust(lsp::ServerCapabilities::default(), cx).await;
10957
10958    cx.set_state(indoc! {"ˇ
10959        0_usize
10960        let
10961        33
10962        4.5f32
10963    "});
10964    cx.update_editor(|editor, window, cx| {
10965        editor.show_completions(&ShowCompletions::default(), window, cx);
10966    });
10967    cx.executor().run_until_parked();
10968    cx.condition(|editor, _| editor.context_menu_visible())
10969        .await;
10970    cx.update_editor(|editor, window, cx| {
10971        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10972        {
10973            assert_eq!(
10974                completion_menu_entries(&menu),
10975                &["let"],
10976                "With no digits in the completion query, no digits should be in the word completions"
10977            );
10978        } else {
10979            panic!("expected completion menu to be open");
10980        }
10981        editor.cancel(&Cancel, window, cx);
10982    });
10983
10984    cx.set_state(indoc! {"10985        0_usize
10986        let
10987        3
10988        33.35f32
10989    "});
10990    cx.update_editor(|editor, window, cx| {
10991        editor.show_completions(&ShowCompletions::default(), window, cx);
10992    });
10993    cx.executor().run_until_parked();
10994    cx.condition(|editor, _| editor.context_menu_visible())
10995        .await;
10996    cx.update_editor(|editor, _, _| {
10997        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10998        {
10999            assert_eq!(completion_menu_entries(&menu), &["33", "35f32"], "The digit is in the completion query, \
11000                return matching words with digits (`33`, `35f32`) but exclude query duplicates (`3`)");
11001        } else {
11002            panic!("expected completion menu to be open");
11003        }
11004    });
11005}
11006
11007fn gen_text_edit(params: &CompletionParams, text: &str) -> Option<lsp::CompletionTextEdit> {
11008    let position = || lsp::Position {
11009        line: params.text_document_position.position.line,
11010        character: params.text_document_position.position.character,
11011    };
11012    Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
11013        range: lsp::Range {
11014            start: position(),
11015            end: position(),
11016        },
11017        new_text: text.to_string(),
11018    }))
11019}
11020
11021#[gpui::test]
11022async fn test_multiline_completion(cx: &mut TestAppContext) {
11023    init_test(cx, |_| {});
11024
11025    let fs = FakeFs::new(cx.executor());
11026    fs.insert_tree(
11027        path!("/a"),
11028        json!({
11029            "main.ts": "a",
11030        }),
11031    )
11032    .await;
11033
11034    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
11035    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
11036    let typescript_language = Arc::new(Language::new(
11037        LanguageConfig {
11038            name: "TypeScript".into(),
11039            matcher: LanguageMatcher {
11040                path_suffixes: vec!["ts".to_string()],
11041                ..LanguageMatcher::default()
11042            },
11043            line_comments: vec!["// ".into()],
11044            ..LanguageConfig::default()
11045        },
11046        Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
11047    ));
11048    language_registry.add(typescript_language.clone());
11049    let mut fake_servers = language_registry.register_fake_lsp(
11050        "TypeScript",
11051        FakeLspAdapter {
11052            capabilities: lsp::ServerCapabilities {
11053                completion_provider: Some(lsp::CompletionOptions {
11054                    trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
11055                    ..lsp::CompletionOptions::default()
11056                }),
11057                signature_help_provider: Some(lsp::SignatureHelpOptions::default()),
11058                ..lsp::ServerCapabilities::default()
11059            },
11060            // Emulate vtsls label generation
11061            label_for_completion: Some(Box::new(|item, _| {
11062                let text = if let Some(description) = item
11063                    .label_details
11064                    .as_ref()
11065                    .and_then(|label_details| label_details.description.as_ref())
11066                {
11067                    format!("{} {}", item.label, description)
11068                } else if let Some(detail) = &item.detail {
11069                    format!("{} {}", item.label, detail)
11070                } else {
11071                    item.label.clone()
11072                };
11073                let len = text.len();
11074                Some(language::CodeLabel {
11075                    text,
11076                    runs: Vec::new(),
11077                    filter_range: 0..len,
11078                })
11079            })),
11080            ..FakeLspAdapter::default()
11081        },
11082    );
11083    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
11084    let cx = &mut VisualTestContext::from_window(*workspace, cx);
11085    let worktree_id = workspace
11086        .update(cx, |workspace, _window, cx| {
11087            workspace.project().update(cx, |project, cx| {
11088                project.worktrees(cx).next().unwrap().read(cx).id()
11089            })
11090        })
11091        .unwrap();
11092    let _buffer = project
11093        .update(cx, |project, cx| {
11094            project.open_local_buffer_with_lsp(path!("/a/main.ts"), cx)
11095        })
11096        .await
11097        .unwrap();
11098    let editor = workspace
11099        .update(cx, |workspace, window, cx| {
11100            workspace.open_path((worktree_id, "main.ts"), None, true, window, cx)
11101        })
11102        .unwrap()
11103        .await
11104        .unwrap()
11105        .downcast::<Editor>()
11106        .unwrap();
11107    let fake_server = fake_servers.next().await.unwrap();
11108
11109    let multiline_label = "StickyHeaderExcerpt {\n            excerpt,\n            next_excerpt_controls_present,\n            next_buffer_row,\n        }: StickyHeaderExcerpt<'_>,";
11110    let multiline_label_2 = "a\nb\nc\n";
11111    let multiline_detail = "[]struct {\n\tSignerId\tstruct {\n\t\tIssuer\t\t\tstring\t`json:\"issuer\"`\n\t\tSubjectSerialNumber\"`\n}}";
11112    let multiline_description = "d\ne\nf\n";
11113    let multiline_detail_2 = "g\nh\ni\n";
11114
11115    let mut completion_handle = fake_server.set_request_handler::<lsp::request::Completion, _, _>(
11116        move |params, _| async move {
11117            Ok(Some(lsp::CompletionResponse::Array(vec![
11118                lsp::CompletionItem {
11119                    label: multiline_label.to_string(),
11120                    text_edit: gen_text_edit(&params, "new_text_1"),
11121                    ..lsp::CompletionItem::default()
11122                },
11123                lsp::CompletionItem {
11124                    label: "single line label 1".to_string(),
11125                    detail: Some(multiline_detail.to_string()),
11126                    text_edit: gen_text_edit(&params, "new_text_2"),
11127                    ..lsp::CompletionItem::default()
11128                },
11129                lsp::CompletionItem {
11130                    label: "single line label 2".to_string(),
11131                    label_details: Some(lsp::CompletionItemLabelDetails {
11132                        description: Some(multiline_description.to_string()),
11133                        detail: None,
11134                    }),
11135                    text_edit: gen_text_edit(&params, "new_text_2"),
11136                    ..lsp::CompletionItem::default()
11137                },
11138                lsp::CompletionItem {
11139                    label: multiline_label_2.to_string(),
11140                    detail: Some(multiline_detail_2.to_string()),
11141                    text_edit: gen_text_edit(&params, "new_text_3"),
11142                    ..lsp::CompletionItem::default()
11143                },
11144                lsp::CompletionItem {
11145                    label: "Label with many     spaces and \t but without newlines".to_string(),
11146                    detail: Some(
11147                        "Details with many     spaces and \t but without newlines".to_string(),
11148                    ),
11149                    text_edit: gen_text_edit(&params, "new_text_4"),
11150                    ..lsp::CompletionItem::default()
11151                },
11152            ])))
11153        },
11154    );
11155
11156    editor.update_in(cx, |editor, window, cx| {
11157        cx.focus_self(window);
11158        editor.move_to_end(&MoveToEnd, window, cx);
11159        editor.handle_input(".", window, cx);
11160    });
11161    cx.run_until_parked();
11162    completion_handle.next().await.unwrap();
11163
11164    editor.update(cx, |editor, _| {
11165        assert!(editor.context_menu_visible());
11166        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
11167        {
11168            let completion_labels = menu
11169                .completions
11170                .borrow()
11171                .iter()
11172                .map(|c| c.label.text.clone())
11173                .collect::<Vec<_>>();
11174            assert_eq!(
11175                completion_labels,
11176                &[
11177                    "StickyHeaderExcerpt { excerpt, next_excerpt_controls_present, next_buffer_row, }: StickyHeaderExcerpt<'_>,",
11178                    "single line label 1 []struct { SignerId struct { Issuer string `json:\"issuer\"` SubjectSerialNumber\"` }}",
11179                    "single line label 2 d e f ",
11180                    "a b c g h i ",
11181                    "Label with many     spaces and \t but without newlines Details with many     spaces and \t but without newlines",
11182                ],
11183                "Completion items should have their labels without newlines, also replacing excessive whitespaces. Completion items without newlines should not be altered.",
11184            );
11185
11186            for completion in menu
11187                .completions
11188                .borrow()
11189                .iter() {
11190                    assert_eq!(
11191                        completion.label.filter_range,
11192                        0..completion.label.text.len(),
11193                        "Adjusted completion items should still keep their filter ranges for the entire label. Item: {completion:?}"
11194                    );
11195                }
11196        } else {
11197            panic!("expected completion menu to be open");
11198        }
11199    });
11200}
11201
11202#[gpui::test]
11203async fn test_completion_page_up_down_keys(cx: &mut TestAppContext) {
11204    init_test(cx, |_| {});
11205    let mut cx = EditorLspTestContext::new_rust(
11206        lsp::ServerCapabilities {
11207            completion_provider: Some(lsp::CompletionOptions {
11208                trigger_characters: Some(vec![".".to_string()]),
11209                ..Default::default()
11210            }),
11211            ..Default::default()
11212        },
11213        cx,
11214    )
11215    .await;
11216    cx.lsp
11217        .set_request_handler::<lsp::request::Completion, _, _>(move |_, _| async move {
11218            Ok(Some(lsp::CompletionResponse::Array(vec![
11219                lsp::CompletionItem {
11220                    label: "first".into(),
11221                    ..Default::default()
11222                },
11223                lsp::CompletionItem {
11224                    label: "last".into(),
11225                    ..Default::default()
11226                },
11227            ])))
11228        });
11229    cx.set_state("variableˇ");
11230    cx.simulate_keystroke(".");
11231    cx.executor().run_until_parked();
11232
11233    cx.update_editor(|editor, _, _| {
11234        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
11235        {
11236            assert_eq!(completion_menu_entries(&menu), &["first", "last"]);
11237        } else {
11238            panic!("expected completion menu to be open");
11239        }
11240    });
11241
11242    cx.update_editor(|editor, window, cx| {
11243        editor.move_page_down(&MovePageDown::default(), window, cx);
11244        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
11245        {
11246            assert!(
11247                menu.selected_item == 1,
11248                "expected PageDown to select the last item from the context menu"
11249            );
11250        } else {
11251            panic!("expected completion menu to stay open after PageDown");
11252        }
11253    });
11254
11255    cx.update_editor(|editor, window, cx| {
11256        editor.move_page_up(&MovePageUp::default(), window, cx);
11257        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
11258        {
11259            assert!(
11260                menu.selected_item == 0,
11261                "expected PageUp to select the first item from the context menu"
11262            );
11263        } else {
11264            panic!("expected completion menu to stay open after PageUp");
11265        }
11266    });
11267}
11268
11269#[gpui::test]
11270async fn test_as_is_completions(cx: &mut TestAppContext) {
11271    init_test(cx, |_| {});
11272    let mut cx = EditorLspTestContext::new_rust(
11273        lsp::ServerCapabilities {
11274            completion_provider: Some(lsp::CompletionOptions {
11275                ..Default::default()
11276            }),
11277            ..Default::default()
11278        },
11279        cx,
11280    )
11281    .await;
11282    cx.lsp
11283        .set_request_handler::<lsp::request::Completion, _, _>(move |_, _| async move {
11284            Ok(Some(lsp::CompletionResponse::Array(vec![
11285                lsp::CompletionItem {
11286                    label: "unsafe".into(),
11287                    text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
11288                        range: lsp::Range {
11289                            start: lsp::Position {
11290                                line: 1,
11291                                character: 2,
11292                            },
11293                            end: lsp::Position {
11294                                line: 1,
11295                                character: 3,
11296                            },
11297                        },
11298                        new_text: "unsafe".to_string(),
11299                    })),
11300                    insert_text_mode: Some(lsp::InsertTextMode::AS_IS),
11301                    ..Default::default()
11302                },
11303            ])))
11304        });
11305    cx.set_state("fn a() {}\n");
11306    cx.executor().run_until_parked();
11307    cx.update_editor(|editor, window, cx| {
11308        editor.show_completions(
11309            &ShowCompletions {
11310                trigger: Some("\n".into()),
11311            },
11312            window,
11313            cx,
11314        );
11315    });
11316    cx.executor().run_until_parked();
11317
11318    cx.update_editor(|editor, window, cx| {
11319        editor.confirm_completion(&Default::default(), window, cx)
11320    });
11321    cx.executor().run_until_parked();
11322    cx.assert_editor_state("fn a() {}\n  unsafeˇ");
11323}
11324
11325#[gpui::test]
11326async fn test_no_duplicated_completion_requests(cx: &mut TestAppContext) {
11327    init_test(cx, |_| {});
11328
11329    let mut cx = EditorLspTestContext::new_rust(
11330        lsp::ServerCapabilities {
11331            completion_provider: Some(lsp::CompletionOptions {
11332                trigger_characters: Some(vec![".".to_string()]),
11333                resolve_provider: Some(true),
11334                ..Default::default()
11335            }),
11336            ..Default::default()
11337        },
11338        cx,
11339    )
11340    .await;
11341
11342    cx.set_state("fn main() { let a = 2ˇ; }");
11343    cx.simulate_keystroke(".");
11344    let completion_item = lsp::CompletionItem {
11345        label: "Some".into(),
11346        kind: Some(lsp::CompletionItemKind::SNIPPET),
11347        detail: Some("Wrap the expression in an `Option::Some`".to_string()),
11348        documentation: Some(lsp::Documentation::MarkupContent(lsp::MarkupContent {
11349            kind: lsp::MarkupKind::Markdown,
11350            value: "```rust\nSome(2)\n```".to_string(),
11351        })),
11352        deprecated: Some(false),
11353        sort_text: Some("Some".to_string()),
11354        filter_text: Some("Some".to_string()),
11355        insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
11356        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
11357            range: lsp::Range {
11358                start: lsp::Position {
11359                    line: 0,
11360                    character: 22,
11361                },
11362                end: lsp::Position {
11363                    line: 0,
11364                    character: 22,
11365                },
11366            },
11367            new_text: "Some(2)".to_string(),
11368        })),
11369        additional_text_edits: Some(vec![lsp::TextEdit {
11370            range: lsp::Range {
11371                start: lsp::Position {
11372                    line: 0,
11373                    character: 20,
11374                },
11375                end: lsp::Position {
11376                    line: 0,
11377                    character: 22,
11378                },
11379            },
11380            new_text: "".to_string(),
11381        }]),
11382        ..Default::default()
11383    };
11384
11385    let closure_completion_item = completion_item.clone();
11386    let counter = Arc::new(AtomicUsize::new(0));
11387    let counter_clone = counter.clone();
11388    let mut request = cx.set_request_handler::<lsp::request::Completion, _, _>(move |_, _, _| {
11389        let task_completion_item = closure_completion_item.clone();
11390        counter_clone.fetch_add(1, atomic::Ordering::Release);
11391        async move {
11392            Ok(Some(lsp::CompletionResponse::Array(vec![
11393                task_completion_item,
11394            ])))
11395        }
11396    });
11397
11398    cx.condition(|editor, _| editor.context_menu_visible())
11399        .await;
11400    cx.assert_editor_state("fn main() { let a = 2.ˇ; }");
11401    assert!(request.next().await.is_some());
11402    assert_eq!(counter.load(atomic::Ordering::Acquire), 1);
11403
11404    cx.simulate_keystrokes("S o m");
11405    cx.condition(|editor, _| editor.context_menu_visible())
11406        .await;
11407    cx.assert_editor_state("fn main() { let a = 2.Somˇ; }");
11408    assert!(request.next().await.is_some());
11409    assert!(request.next().await.is_some());
11410    assert!(request.next().await.is_some());
11411    request.close();
11412    assert!(request.next().await.is_none());
11413    assert_eq!(
11414        counter.load(atomic::Ordering::Acquire),
11415        4,
11416        "With the completions menu open, only one LSP request should happen per input"
11417    );
11418}
11419
11420#[gpui::test]
11421async fn test_toggle_comment(cx: &mut TestAppContext) {
11422    init_test(cx, |_| {});
11423    let mut cx = EditorTestContext::new(cx).await;
11424    let language = Arc::new(Language::new(
11425        LanguageConfig {
11426            line_comments: vec!["// ".into(), "//! ".into(), "/// ".into()],
11427            ..Default::default()
11428        },
11429        Some(tree_sitter_rust::LANGUAGE.into()),
11430    ));
11431    cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
11432
11433    // If multiple selections intersect a line, the line is only toggled once.
11434    cx.set_state(indoc! {"
11435        fn a() {
11436            «//b();
11437            ˇ»// «c();
11438            //ˇ»  d();
11439        }
11440    "});
11441
11442    cx.update_editor(|e, window, cx| e.toggle_comments(&ToggleComments::default(), window, cx));
11443
11444    cx.assert_editor_state(indoc! {"
11445        fn a() {
11446            «b();
11447            c();
11448            ˇ» d();
11449        }
11450    "});
11451
11452    // The comment prefix is inserted at the same column for every line in a
11453    // selection.
11454    cx.update_editor(|e, window, cx| e.toggle_comments(&ToggleComments::default(), window, cx));
11455
11456    cx.assert_editor_state(indoc! {"
11457        fn a() {
11458            // «b();
11459            // c();
11460            ˇ»//  d();
11461        }
11462    "});
11463
11464    // If a selection ends at the beginning of a line, that line is not toggled.
11465    cx.set_selections_state(indoc! {"
11466        fn a() {
11467            // b();
11468            «// c();
11469        ˇ»    //  d();
11470        }
11471    "});
11472
11473    cx.update_editor(|e, window, cx| e.toggle_comments(&ToggleComments::default(), window, cx));
11474
11475    cx.assert_editor_state(indoc! {"
11476        fn a() {
11477            // b();
11478            «c();
11479        ˇ»    //  d();
11480        }
11481    "});
11482
11483    // If a selection span a single line and is empty, the line is toggled.
11484    cx.set_state(indoc! {"
11485        fn a() {
11486            a();
11487            b();
11488        ˇ
11489        }
11490    "});
11491
11492    cx.update_editor(|e, window, cx| e.toggle_comments(&ToggleComments::default(), window, cx));
11493
11494    cx.assert_editor_state(indoc! {"
11495        fn a() {
11496            a();
11497            b();
11498        //•ˇ
11499        }
11500    "});
11501
11502    // If a selection span multiple lines, empty lines are not toggled.
11503    cx.set_state(indoc! {"
11504        fn a() {
11505            «a();
11506
11507            c();ˇ»
11508        }
11509    "});
11510
11511    cx.update_editor(|e, window, cx| e.toggle_comments(&ToggleComments::default(), window, cx));
11512
11513    cx.assert_editor_state(indoc! {"
11514        fn a() {
11515            // «a();
11516
11517            // c();ˇ»
11518        }
11519    "});
11520
11521    // If a selection includes multiple comment prefixes, all lines are uncommented.
11522    cx.set_state(indoc! {"
11523        fn a() {
11524            «// a();
11525            /// b();
11526            //! c();ˇ»
11527        }
11528    "});
11529
11530    cx.update_editor(|e, window, cx| e.toggle_comments(&ToggleComments::default(), window, cx));
11531
11532    cx.assert_editor_state(indoc! {"
11533        fn a() {
11534            «a();
11535            b();
11536            c();ˇ»
11537        }
11538    "});
11539}
11540
11541#[gpui::test]
11542async fn test_toggle_comment_ignore_indent(cx: &mut TestAppContext) {
11543    init_test(cx, |_| {});
11544    let mut cx = EditorTestContext::new(cx).await;
11545    let language = Arc::new(Language::new(
11546        LanguageConfig {
11547            line_comments: vec!["// ".into(), "//! ".into(), "/// ".into()],
11548            ..Default::default()
11549        },
11550        Some(tree_sitter_rust::LANGUAGE.into()),
11551    ));
11552    cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
11553
11554    let toggle_comments = &ToggleComments {
11555        advance_downwards: false,
11556        ignore_indent: true,
11557    };
11558
11559    // If multiple selections intersect a line, the line is only toggled once.
11560    cx.set_state(indoc! {"
11561        fn a() {
11562        //    «b();
11563        //    c();
11564        //    ˇ» d();
11565        }
11566    "});
11567
11568    cx.update_editor(|e, window, cx| e.toggle_comments(toggle_comments, window, cx));
11569
11570    cx.assert_editor_state(indoc! {"
11571        fn a() {
11572            «b();
11573            c();
11574            ˇ» d();
11575        }
11576    "});
11577
11578    // The comment prefix is inserted at the beginning of each line
11579    cx.update_editor(|e, window, cx| e.toggle_comments(toggle_comments, window, cx));
11580
11581    cx.assert_editor_state(indoc! {"
11582        fn a() {
11583        //    «b();
11584        //    c();
11585        //    ˇ» d();
11586        }
11587    "});
11588
11589    // If a selection ends at the beginning of a line, that line is not toggled.
11590    cx.set_selections_state(indoc! {"
11591        fn a() {
11592        //    b();
11593        //    «c();
11594        ˇ»//     d();
11595        }
11596    "});
11597
11598    cx.update_editor(|e, window, cx| e.toggle_comments(toggle_comments, window, cx));
11599
11600    cx.assert_editor_state(indoc! {"
11601        fn a() {
11602        //    b();
11603            «c();
11604        ˇ»//     d();
11605        }
11606    "});
11607
11608    // If a selection span a single line and is empty, the line is toggled.
11609    cx.set_state(indoc! {"
11610        fn a() {
11611            a();
11612            b();
11613        ˇ
11614        }
11615    "});
11616
11617    cx.update_editor(|e, window, cx| e.toggle_comments(toggle_comments, window, cx));
11618
11619    cx.assert_editor_state(indoc! {"
11620        fn a() {
11621            a();
11622            b();
11623        //ˇ
11624        }
11625    "});
11626
11627    // If a selection span multiple lines, empty lines are not toggled.
11628    cx.set_state(indoc! {"
11629        fn a() {
11630            «a();
11631
11632            c();ˇ»
11633        }
11634    "});
11635
11636    cx.update_editor(|e, window, cx| e.toggle_comments(toggle_comments, window, cx));
11637
11638    cx.assert_editor_state(indoc! {"
11639        fn a() {
11640        //    «a();
11641
11642        //    c();ˇ»
11643        }
11644    "});
11645
11646    // If a selection includes multiple comment prefixes, all lines are uncommented.
11647    cx.set_state(indoc! {"
11648        fn a() {
11649        //    «a();
11650        ///    b();
11651        //!    c();ˇ»
11652        }
11653    "});
11654
11655    cx.update_editor(|e, window, cx| e.toggle_comments(toggle_comments, window, cx));
11656
11657    cx.assert_editor_state(indoc! {"
11658        fn a() {
11659            «a();
11660            b();
11661            c();ˇ»
11662        }
11663    "});
11664}
11665
11666#[gpui::test]
11667async fn test_advance_downward_on_toggle_comment(cx: &mut TestAppContext) {
11668    init_test(cx, |_| {});
11669
11670    let language = Arc::new(Language::new(
11671        LanguageConfig {
11672            line_comments: vec!["// ".into()],
11673            ..Default::default()
11674        },
11675        Some(tree_sitter_rust::LANGUAGE.into()),
11676    ));
11677
11678    let mut cx = EditorTestContext::new(cx).await;
11679
11680    cx.language_registry().add(language.clone());
11681    cx.update_buffer(|buffer, cx| {
11682        buffer.set_language(Some(language), cx);
11683    });
11684
11685    let toggle_comments = &ToggleComments {
11686        advance_downwards: true,
11687        ignore_indent: false,
11688    };
11689
11690    // Single cursor on one line -> advance
11691    // Cursor moves horizontally 3 characters as well on non-blank line
11692    cx.set_state(indoc!(
11693        "fn a() {
11694             ˇdog();
11695             cat();
11696        }"
11697    ));
11698    cx.update_editor(|editor, window, cx| {
11699        editor.toggle_comments(toggle_comments, window, cx);
11700    });
11701    cx.assert_editor_state(indoc!(
11702        "fn a() {
11703             // dog();
11704             catˇ();
11705        }"
11706    ));
11707
11708    // Single selection on one line -> don't advance
11709    cx.set_state(indoc!(
11710        "fn a() {
11711             «dog()ˇ»;
11712             cat();
11713        }"
11714    ));
11715    cx.update_editor(|editor, window, cx| {
11716        editor.toggle_comments(toggle_comments, window, cx);
11717    });
11718    cx.assert_editor_state(indoc!(
11719        "fn a() {
11720             // «dog()ˇ»;
11721             cat();
11722        }"
11723    ));
11724
11725    // Multiple cursors on one line -> advance
11726    cx.set_state(indoc!(
11727        "fn a() {
11728             ˇdˇog();
11729             cat();
11730        }"
11731    ));
11732    cx.update_editor(|editor, window, cx| {
11733        editor.toggle_comments(toggle_comments, window, cx);
11734    });
11735    cx.assert_editor_state(indoc!(
11736        "fn a() {
11737             // dog();
11738             catˇ(ˇ);
11739        }"
11740    ));
11741
11742    // Multiple cursors on one line, with selection -> don't advance
11743    cx.set_state(indoc!(
11744        "fn a() {
11745             ˇdˇog«()ˇ»;
11746             cat();
11747        }"
11748    ));
11749    cx.update_editor(|editor, window, cx| {
11750        editor.toggle_comments(toggle_comments, window, cx);
11751    });
11752    cx.assert_editor_state(indoc!(
11753        "fn a() {
11754             // ˇdˇog«()ˇ»;
11755             cat();
11756        }"
11757    ));
11758
11759    // Single cursor on one line -> advance
11760    // Cursor moves to column 0 on blank line
11761    cx.set_state(indoc!(
11762        "fn a() {
11763             ˇdog();
11764
11765             cat();
11766        }"
11767    ));
11768    cx.update_editor(|editor, window, cx| {
11769        editor.toggle_comments(toggle_comments, window, cx);
11770    });
11771    cx.assert_editor_state(indoc!(
11772        "fn a() {
11773             // dog();
11774        ˇ
11775             cat();
11776        }"
11777    ));
11778
11779    // Single cursor on one line -> advance
11780    // Cursor starts and ends at column 0
11781    cx.set_state(indoc!(
11782        "fn a() {
11783         ˇ    dog();
11784             cat();
11785        }"
11786    ));
11787    cx.update_editor(|editor, window, cx| {
11788        editor.toggle_comments(toggle_comments, window, cx);
11789    });
11790    cx.assert_editor_state(indoc!(
11791        "fn a() {
11792             // dog();
11793         ˇ    cat();
11794        }"
11795    ));
11796}
11797
11798#[gpui::test]
11799async fn test_toggle_block_comment(cx: &mut TestAppContext) {
11800    init_test(cx, |_| {});
11801
11802    let mut cx = EditorTestContext::new(cx).await;
11803
11804    let html_language = Arc::new(
11805        Language::new(
11806            LanguageConfig {
11807                name: "HTML".into(),
11808                block_comment: Some(("<!-- ".into(), " -->".into())),
11809                ..Default::default()
11810            },
11811            Some(tree_sitter_html::LANGUAGE.into()),
11812        )
11813        .with_injection_query(
11814            r#"
11815            (script_element
11816                (raw_text) @injection.content
11817                (#set! injection.language "javascript"))
11818            "#,
11819        )
11820        .unwrap(),
11821    );
11822
11823    let javascript_language = Arc::new(Language::new(
11824        LanguageConfig {
11825            name: "JavaScript".into(),
11826            line_comments: vec!["// ".into()],
11827            ..Default::default()
11828        },
11829        Some(tree_sitter_typescript::LANGUAGE_TSX.into()),
11830    ));
11831
11832    cx.language_registry().add(html_language.clone());
11833    cx.language_registry().add(javascript_language.clone());
11834    cx.update_buffer(|buffer, cx| {
11835        buffer.set_language(Some(html_language), cx);
11836    });
11837
11838    // Toggle comments for empty selections
11839    cx.set_state(
11840        &r#"
11841            <p>A</p>ˇ
11842            <p>B</p>ˇ
11843            <p>C</p>ˇ
11844        "#
11845        .unindent(),
11846    );
11847    cx.update_editor(|editor, window, cx| {
11848        editor.toggle_comments(&ToggleComments::default(), window, cx)
11849    });
11850    cx.assert_editor_state(
11851        &r#"
11852            <!-- <p>A</p>ˇ -->
11853            <!-- <p>B</p>ˇ -->
11854            <!-- <p>C</p>ˇ -->
11855        "#
11856        .unindent(),
11857    );
11858    cx.update_editor(|editor, window, cx| {
11859        editor.toggle_comments(&ToggleComments::default(), window, cx)
11860    });
11861    cx.assert_editor_state(
11862        &r#"
11863            <p>A</p>ˇ
11864            <p>B</p>ˇ
11865            <p>C</p>ˇ
11866        "#
11867        .unindent(),
11868    );
11869
11870    // Toggle comments for mixture of empty and non-empty selections, where
11871    // multiple selections occupy a given line.
11872    cx.set_state(
11873        &r#"
11874            <p>A«</p>
11875            <p>ˇ»B</p>ˇ
11876            <p>C«</p>
11877            <p>ˇ»D</p>ˇ
11878        "#
11879        .unindent(),
11880    );
11881
11882    cx.update_editor(|editor, window, cx| {
11883        editor.toggle_comments(&ToggleComments::default(), window, cx)
11884    });
11885    cx.assert_editor_state(
11886        &r#"
11887            <!-- <p>A«</p>
11888            <p>ˇ»B</p>ˇ -->
11889            <!-- <p>C«</p>
11890            <p>ˇ»D</p>ˇ -->
11891        "#
11892        .unindent(),
11893    );
11894    cx.update_editor(|editor, window, cx| {
11895        editor.toggle_comments(&ToggleComments::default(), window, cx)
11896    });
11897    cx.assert_editor_state(
11898        &r#"
11899            <p>A«</p>
11900            <p>ˇ»B</p>ˇ
11901            <p>C«</p>
11902            <p>ˇ»D</p>ˇ
11903        "#
11904        .unindent(),
11905    );
11906
11907    // Toggle comments when different languages are active for different
11908    // selections.
11909    cx.set_state(
11910        &r#"
11911            ˇ<script>
11912                ˇvar x = new Y();
11913            ˇ</script>
11914        "#
11915        .unindent(),
11916    );
11917    cx.executor().run_until_parked();
11918    cx.update_editor(|editor, window, cx| {
11919        editor.toggle_comments(&ToggleComments::default(), window, cx)
11920    });
11921    // TODO this is how it actually worked in Zed Stable, which is not very ergonomic.
11922    // Uncommenting and commenting from this position brings in even more wrong artifacts.
11923    cx.assert_editor_state(
11924        &r#"
11925            <!-- ˇ<script> -->
11926                // ˇvar x = new Y();
11927            <!-- ˇ</script> -->
11928        "#
11929        .unindent(),
11930    );
11931}
11932
11933#[gpui::test]
11934fn test_editing_disjoint_excerpts(cx: &mut TestAppContext) {
11935    init_test(cx, |_| {});
11936
11937    let buffer = cx.new(|cx| Buffer::local(sample_text(3, 4, 'a'), cx));
11938    let multibuffer = cx.new(|cx| {
11939        let mut multibuffer = MultiBuffer::new(ReadWrite);
11940        multibuffer.push_excerpts(
11941            buffer.clone(),
11942            [
11943                ExcerptRange::new(Point::new(0, 0)..Point::new(0, 4)),
11944                ExcerptRange::new(Point::new(1, 0)..Point::new(1, 4)),
11945            ],
11946            cx,
11947        );
11948        assert_eq!(multibuffer.read(cx).text(), "aaaa\nbbbb");
11949        multibuffer
11950    });
11951
11952    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(multibuffer, window, cx));
11953    editor.update_in(cx, |editor, window, cx| {
11954        assert_eq!(editor.text(cx), "aaaa\nbbbb");
11955        editor.change_selections(None, window, cx, |s| {
11956            s.select_ranges([
11957                Point::new(0, 0)..Point::new(0, 0),
11958                Point::new(1, 0)..Point::new(1, 0),
11959            ])
11960        });
11961
11962        editor.handle_input("X", window, cx);
11963        assert_eq!(editor.text(cx), "Xaaaa\nXbbbb");
11964        assert_eq!(
11965            editor.selections.ranges(cx),
11966            [
11967                Point::new(0, 1)..Point::new(0, 1),
11968                Point::new(1, 1)..Point::new(1, 1),
11969            ]
11970        );
11971
11972        // Ensure the cursor's head is respected when deleting across an excerpt boundary.
11973        editor.change_selections(None, window, cx, |s| {
11974            s.select_ranges([Point::new(0, 2)..Point::new(1, 2)])
11975        });
11976        editor.backspace(&Default::default(), window, cx);
11977        assert_eq!(editor.text(cx), "Xa\nbbb");
11978        assert_eq!(
11979            editor.selections.ranges(cx),
11980            [Point::new(1, 0)..Point::new(1, 0)]
11981        );
11982
11983        editor.change_selections(None, window, cx, |s| {
11984            s.select_ranges([Point::new(1, 1)..Point::new(0, 1)])
11985        });
11986        editor.backspace(&Default::default(), window, cx);
11987        assert_eq!(editor.text(cx), "X\nbb");
11988        assert_eq!(
11989            editor.selections.ranges(cx),
11990            [Point::new(0, 1)..Point::new(0, 1)]
11991        );
11992    });
11993}
11994
11995#[gpui::test]
11996fn test_editing_overlapping_excerpts(cx: &mut TestAppContext) {
11997    init_test(cx, |_| {});
11998
11999    let markers = vec![('[', ']').into(), ('(', ')').into()];
12000    let (initial_text, mut excerpt_ranges) = marked_text_ranges_by(
12001        indoc! {"
12002            [aaaa
12003            (bbbb]
12004            cccc)",
12005        },
12006        markers.clone(),
12007    );
12008    let excerpt_ranges = markers.into_iter().map(|marker| {
12009        let context = excerpt_ranges.remove(&marker).unwrap()[0].clone();
12010        ExcerptRange::new(context.clone())
12011    });
12012    let buffer = cx.new(|cx| Buffer::local(initial_text, cx));
12013    let multibuffer = cx.new(|cx| {
12014        let mut multibuffer = MultiBuffer::new(ReadWrite);
12015        multibuffer.push_excerpts(buffer, excerpt_ranges, cx);
12016        multibuffer
12017    });
12018
12019    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(multibuffer, window, cx));
12020    editor.update_in(cx, |editor, window, cx| {
12021        let (expected_text, selection_ranges) = marked_text_ranges(
12022            indoc! {"
12023                aaaa
12024                bˇbbb
12025                bˇbbˇb
12026                cccc"
12027            },
12028            true,
12029        );
12030        assert_eq!(editor.text(cx), expected_text);
12031        editor.change_selections(None, window, cx, |s| s.select_ranges(selection_ranges));
12032
12033        editor.handle_input("X", window, cx);
12034
12035        let (expected_text, expected_selections) = marked_text_ranges(
12036            indoc! {"
12037                aaaa
12038                bXˇbbXb
12039                bXˇbbXˇb
12040                cccc"
12041            },
12042            false,
12043        );
12044        assert_eq!(editor.text(cx), expected_text);
12045        assert_eq!(editor.selections.ranges(cx), expected_selections);
12046
12047        editor.newline(&Newline, window, cx);
12048        let (expected_text, expected_selections) = marked_text_ranges(
12049            indoc! {"
12050                aaaa
12051                bX
12052                ˇbbX
12053                b
12054                bX
12055                ˇbbX
12056                ˇb
12057                cccc"
12058            },
12059            false,
12060        );
12061        assert_eq!(editor.text(cx), expected_text);
12062        assert_eq!(editor.selections.ranges(cx), expected_selections);
12063    });
12064}
12065
12066#[gpui::test]
12067fn test_refresh_selections(cx: &mut TestAppContext) {
12068    init_test(cx, |_| {});
12069
12070    let buffer = cx.new(|cx| Buffer::local(sample_text(3, 4, 'a'), cx));
12071    let mut excerpt1_id = None;
12072    let multibuffer = cx.new(|cx| {
12073        let mut multibuffer = MultiBuffer::new(ReadWrite);
12074        excerpt1_id = multibuffer
12075            .push_excerpts(
12076                buffer.clone(),
12077                [
12078                    ExcerptRange::new(Point::new(0, 0)..Point::new(1, 4)),
12079                    ExcerptRange::new(Point::new(1, 0)..Point::new(2, 4)),
12080                ],
12081                cx,
12082            )
12083            .into_iter()
12084            .next();
12085        assert_eq!(multibuffer.read(cx).text(), "aaaa\nbbbb\nbbbb\ncccc");
12086        multibuffer
12087    });
12088
12089    let editor = cx.add_window(|window, cx| {
12090        let mut editor = build_editor(multibuffer.clone(), window, cx);
12091        let snapshot = editor.snapshot(window, cx);
12092        editor.change_selections(None, window, cx, |s| {
12093            s.select_ranges([Point::new(1, 3)..Point::new(1, 3)])
12094        });
12095        editor.begin_selection(
12096            Point::new(2, 1).to_display_point(&snapshot),
12097            true,
12098            1,
12099            window,
12100            cx,
12101        );
12102        assert_eq!(
12103            editor.selections.ranges(cx),
12104            [
12105                Point::new(1, 3)..Point::new(1, 3),
12106                Point::new(2, 1)..Point::new(2, 1),
12107            ]
12108        );
12109        editor
12110    });
12111
12112    // Refreshing selections is a no-op when excerpts haven't changed.
12113    _ = editor.update(cx, |editor, window, cx| {
12114        editor.change_selections(None, window, cx, |s| s.refresh());
12115        assert_eq!(
12116            editor.selections.ranges(cx),
12117            [
12118                Point::new(1, 3)..Point::new(1, 3),
12119                Point::new(2, 1)..Point::new(2, 1),
12120            ]
12121        );
12122    });
12123
12124    multibuffer.update(cx, |multibuffer, cx| {
12125        multibuffer.remove_excerpts([excerpt1_id.unwrap()], cx);
12126    });
12127    _ = editor.update(cx, |editor, window, cx| {
12128        // Removing an excerpt causes the first selection to become degenerate.
12129        assert_eq!(
12130            editor.selections.ranges(cx),
12131            [
12132                Point::new(0, 0)..Point::new(0, 0),
12133                Point::new(0, 1)..Point::new(0, 1)
12134            ]
12135        );
12136
12137        // Refreshing selections will relocate the first selection to the original buffer
12138        // location.
12139        editor.change_selections(None, window, cx, |s| s.refresh());
12140        assert_eq!(
12141            editor.selections.ranges(cx),
12142            [
12143                Point::new(0, 1)..Point::new(0, 1),
12144                Point::new(0, 3)..Point::new(0, 3)
12145            ]
12146        );
12147        assert!(editor.selections.pending_anchor().is_some());
12148    });
12149}
12150
12151#[gpui::test]
12152fn test_refresh_selections_while_selecting_with_mouse(cx: &mut TestAppContext) {
12153    init_test(cx, |_| {});
12154
12155    let buffer = cx.new(|cx| Buffer::local(sample_text(3, 4, 'a'), cx));
12156    let mut excerpt1_id = None;
12157    let multibuffer = cx.new(|cx| {
12158        let mut multibuffer = MultiBuffer::new(ReadWrite);
12159        excerpt1_id = multibuffer
12160            .push_excerpts(
12161                buffer.clone(),
12162                [
12163                    ExcerptRange::new(Point::new(0, 0)..Point::new(1, 4)),
12164                    ExcerptRange::new(Point::new(1, 0)..Point::new(2, 4)),
12165                ],
12166                cx,
12167            )
12168            .into_iter()
12169            .next();
12170        assert_eq!(multibuffer.read(cx).text(), "aaaa\nbbbb\nbbbb\ncccc");
12171        multibuffer
12172    });
12173
12174    let editor = cx.add_window(|window, cx| {
12175        let mut editor = build_editor(multibuffer.clone(), window, cx);
12176        let snapshot = editor.snapshot(window, cx);
12177        editor.begin_selection(
12178            Point::new(1, 3).to_display_point(&snapshot),
12179            false,
12180            1,
12181            window,
12182            cx,
12183        );
12184        assert_eq!(
12185            editor.selections.ranges(cx),
12186            [Point::new(1, 3)..Point::new(1, 3)]
12187        );
12188        editor
12189    });
12190
12191    multibuffer.update(cx, |multibuffer, cx| {
12192        multibuffer.remove_excerpts([excerpt1_id.unwrap()], cx);
12193    });
12194    _ = editor.update(cx, |editor, window, cx| {
12195        assert_eq!(
12196            editor.selections.ranges(cx),
12197            [Point::new(0, 0)..Point::new(0, 0)]
12198        );
12199
12200        // Ensure we don't panic when selections are refreshed and that the pending selection is finalized.
12201        editor.change_selections(None, window, cx, |s| s.refresh());
12202        assert_eq!(
12203            editor.selections.ranges(cx),
12204            [Point::new(0, 3)..Point::new(0, 3)]
12205        );
12206        assert!(editor.selections.pending_anchor().is_some());
12207    });
12208}
12209
12210#[gpui::test]
12211async fn test_extra_newline_insertion(cx: &mut TestAppContext) {
12212    init_test(cx, |_| {});
12213
12214    let language = Arc::new(
12215        Language::new(
12216            LanguageConfig {
12217                brackets: BracketPairConfig {
12218                    pairs: vec![
12219                        BracketPair {
12220                            start: "{".to_string(),
12221                            end: "}".to_string(),
12222                            close: true,
12223                            surround: true,
12224                            newline: true,
12225                        },
12226                        BracketPair {
12227                            start: "/* ".to_string(),
12228                            end: " */".to_string(),
12229                            close: true,
12230                            surround: true,
12231                            newline: true,
12232                        },
12233                    ],
12234                    ..Default::default()
12235                },
12236                ..Default::default()
12237            },
12238            Some(tree_sitter_rust::LANGUAGE.into()),
12239        )
12240        .with_indents_query("")
12241        .unwrap(),
12242    );
12243
12244    let text = concat!(
12245        "{   }\n",     //
12246        "  x\n",       //
12247        "  /*   */\n", //
12248        "x\n",         //
12249        "{{} }\n",     //
12250    );
12251
12252    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
12253    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
12254    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
12255    editor
12256        .condition::<crate::EditorEvent>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
12257        .await;
12258
12259    editor.update_in(cx, |editor, window, cx| {
12260        editor.change_selections(None, window, cx, |s| {
12261            s.select_display_ranges([
12262                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 3),
12263                DisplayPoint::new(DisplayRow(2), 5)..DisplayPoint::new(DisplayRow(2), 5),
12264                DisplayPoint::new(DisplayRow(4), 4)..DisplayPoint::new(DisplayRow(4), 4),
12265            ])
12266        });
12267        editor.newline(&Newline, window, cx);
12268
12269        assert_eq!(
12270            editor.buffer().read(cx).read(cx).text(),
12271            concat!(
12272                "{ \n",    // Suppress rustfmt
12273                "\n",      //
12274                "}\n",     //
12275                "  x\n",   //
12276                "  /* \n", //
12277                "  \n",    //
12278                "  */\n",  //
12279                "x\n",     //
12280                "{{} \n",  //
12281                "}\n",     //
12282            )
12283        );
12284    });
12285}
12286
12287#[gpui::test]
12288fn test_highlighted_ranges(cx: &mut TestAppContext) {
12289    init_test(cx, |_| {});
12290
12291    let editor = cx.add_window(|window, cx| {
12292        let buffer = MultiBuffer::build_simple(&sample_text(16, 8, 'a'), cx);
12293        build_editor(buffer.clone(), window, cx)
12294    });
12295
12296    _ = editor.update(cx, |editor, window, cx| {
12297        struct Type1;
12298        struct Type2;
12299
12300        let buffer = editor.buffer.read(cx).snapshot(cx);
12301
12302        let anchor_range =
12303            |range: Range<Point>| buffer.anchor_after(range.start)..buffer.anchor_after(range.end);
12304
12305        editor.highlight_background::<Type1>(
12306            &[
12307                anchor_range(Point::new(2, 1)..Point::new(2, 3)),
12308                anchor_range(Point::new(4, 2)..Point::new(4, 4)),
12309                anchor_range(Point::new(6, 3)..Point::new(6, 5)),
12310                anchor_range(Point::new(8, 4)..Point::new(8, 6)),
12311            ],
12312            |_| Hsla::red(),
12313            cx,
12314        );
12315        editor.highlight_background::<Type2>(
12316            &[
12317                anchor_range(Point::new(3, 2)..Point::new(3, 5)),
12318                anchor_range(Point::new(5, 3)..Point::new(5, 6)),
12319                anchor_range(Point::new(7, 4)..Point::new(7, 7)),
12320                anchor_range(Point::new(9, 5)..Point::new(9, 8)),
12321            ],
12322            |_| Hsla::green(),
12323            cx,
12324        );
12325
12326        let snapshot = editor.snapshot(window, cx);
12327        let mut highlighted_ranges = editor.background_highlights_in_range(
12328            anchor_range(Point::new(3, 4)..Point::new(7, 4)),
12329            &snapshot,
12330            cx.theme().colors(),
12331        );
12332        // Enforce a consistent ordering based on color without relying on the ordering of the
12333        // highlight's `TypeId` which is non-executor.
12334        highlighted_ranges.sort_unstable_by_key(|(_, color)| *color);
12335        assert_eq!(
12336            highlighted_ranges,
12337            &[
12338                (
12339                    DisplayPoint::new(DisplayRow(4), 2)..DisplayPoint::new(DisplayRow(4), 4),
12340                    Hsla::red(),
12341                ),
12342                (
12343                    DisplayPoint::new(DisplayRow(6), 3)..DisplayPoint::new(DisplayRow(6), 5),
12344                    Hsla::red(),
12345                ),
12346                (
12347                    DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 5),
12348                    Hsla::green(),
12349                ),
12350                (
12351                    DisplayPoint::new(DisplayRow(5), 3)..DisplayPoint::new(DisplayRow(5), 6),
12352                    Hsla::green(),
12353                ),
12354            ]
12355        );
12356        assert_eq!(
12357            editor.background_highlights_in_range(
12358                anchor_range(Point::new(5, 6)..Point::new(6, 4)),
12359                &snapshot,
12360                cx.theme().colors(),
12361            ),
12362            &[(
12363                DisplayPoint::new(DisplayRow(6), 3)..DisplayPoint::new(DisplayRow(6), 5),
12364                Hsla::red(),
12365            )]
12366        );
12367    });
12368}
12369
12370#[gpui::test]
12371async fn test_following(cx: &mut TestAppContext) {
12372    init_test(cx, |_| {});
12373
12374    let fs = FakeFs::new(cx.executor());
12375    let project = Project::test(fs, ["/file.rs".as_ref()], cx).await;
12376
12377    let buffer = project.update(cx, |project, cx| {
12378        let buffer = project.create_local_buffer(&sample_text(16, 8, 'a'), None, cx);
12379        cx.new(|cx| MultiBuffer::singleton(buffer, cx))
12380    });
12381    let leader = cx.add_window(|window, cx| build_editor(buffer.clone(), window, cx));
12382    let follower = cx.update(|cx| {
12383        cx.open_window(
12384            WindowOptions {
12385                window_bounds: Some(WindowBounds::Windowed(Bounds::from_corners(
12386                    gpui::Point::new(px(0.), px(0.)),
12387                    gpui::Point::new(px(10.), px(80.)),
12388                ))),
12389                ..Default::default()
12390            },
12391            |window, cx| cx.new(|cx| build_editor(buffer.clone(), window, cx)),
12392        )
12393        .unwrap()
12394    });
12395
12396    let is_still_following = Rc::new(RefCell::new(true));
12397    let follower_edit_event_count = Rc::new(RefCell::new(0));
12398    let pending_update = Rc::new(RefCell::new(None));
12399    let leader_entity = leader.root(cx).unwrap();
12400    let follower_entity = follower.root(cx).unwrap();
12401    _ = follower.update(cx, {
12402        let update = pending_update.clone();
12403        let is_still_following = is_still_following.clone();
12404        let follower_edit_event_count = follower_edit_event_count.clone();
12405        |_, window, cx| {
12406            cx.subscribe_in(
12407                &leader_entity,
12408                window,
12409                move |_, leader, event, window, cx| {
12410                    leader.read(cx).add_event_to_update_proto(
12411                        event,
12412                        &mut update.borrow_mut(),
12413                        window,
12414                        cx,
12415                    );
12416                },
12417            )
12418            .detach();
12419
12420            cx.subscribe_in(
12421                &follower_entity,
12422                window,
12423                move |_, _, event: &EditorEvent, _window, _cx| {
12424                    if matches!(Editor::to_follow_event(event), Some(FollowEvent::Unfollow)) {
12425                        *is_still_following.borrow_mut() = false;
12426                    }
12427
12428                    if let EditorEvent::BufferEdited = event {
12429                        *follower_edit_event_count.borrow_mut() += 1;
12430                    }
12431                },
12432            )
12433            .detach();
12434        }
12435    });
12436
12437    // Update the selections only
12438    _ = leader.update(cx, |leader, window, cx| {
12439        leader.change_selections(None, window, cx, |s| s.select_ranges([1..1]));
12440    });
12441    follower
12442        .update(cx, |follower, window, cx| {
12443            follower.apply_update_proto(
12444                &project,
12445                pending_update.borrow_mut().take().unwrap(),
12446                window,
12447                cx,
12448            )
12449        })
12450        .unwrap()
12451        .await
12452        .unwrap();
12453    _ = follower.update(cx, |follower, _, cx| {
12454        assert_eq!(follower.selections.ranges(cx), vec![1..1]);
12455    });
12456    assert!(*is_still_following.borrow());
12457    assert_eq!(*follower_edit_event_count.borrow(), 0);
12458
12459    // Update the scroll position only
12460    _ = leader.update(cx, |leader, window, cx| {
12461        leader.set_scroll_position(gpui::Point::new(1.5, 3.5), window, cx);
12462    });
12463    follower
12464        .update(cx, |follower, window, cx| {
12465            follower.apply_update_proto(
12466                &project,
12467                pending_update.borrow_mut().take().unwrap(),
12468                window,
12469                cx,
12470            )
12471        })
12472        .unwrap()
12473        .await
12474        .unwrap();
12475    assert_eq!(
12476        follower
12477            .update(cx, |follower, _, cx| follower.scroll_position(cx))
12478            .unwrap(),
12479        gpui::Point::new(1.5, 3.5)
12480    );
12481    assert!(*is_still_following.borrow());
12482    assert_eq!(*follower_edit_event_count.borrow(), 0);
12483
12484    // Update the selections and scroll position. The follower's scroll position is updated
12485    // via autoscroll, not via the leader's exact scroll position.
12486    _ = leader.update(cx, |leader, window, cx| {
12487        leader.change_selections(None, window, cx, |s| s.select_ranges([0..0]));
12488        leader.request_autoscroll(Autoscroll::newest(), cx);
12489        leader.set_scroll_position(gpui::Point::new(1.5, 3.5), window, cx);
12490    });
12491    follower
12492        .update(cx, |follower, window, cx| {
12493            follower.apply_update_proto(
12494                &project,
12495                pending_update.borrow_mut().take().unwrap(),
12496                window,
12497                cx,
12498            )
12499        })
12500        .unwrap()
12501        .await
12502        .unwrap();
12503    _ = follower.update(cx, |follower, _, cx| {
12504        assert_eq!(follower.scroll_position(cx), gpui::Point::new(1.5, 0.0));
12505        assert_eq!(follower.selections.ranges(cx), vec![0..0]);
12506    });
12507    assert!(*is_still_following.borrow());
12508
12509    // Creating a pending selection that precedes another selection
12510    _ = leader.update(cx, |leader, window, cx| {
12511        leader.change_selections(None, window, cx, |s| s.select_ranges([1..1]));
12512        leader.begin_selection(DisplayPoint::new(DisplayRow(0), 0), true, 1, window, cx);
12513    });
12514    follower
12515        .update(cx, |follower, window, cx| {
12516            follower.apply_update_proto(
12517                &project,
12518                pending_update.borrow_mut().take().unwrap(),
12519                window,
12520                cx,
12521            )
12522        })
12523        .unwrap()
12524        .await
12525        .unwrap();
12526    _ = follower.update(cx, |follower, _, cx| {
12527        assert_eq!(follower.selections.ranges(cx), vec![0..0, 1..1]);
12528    });
12529    assert!(*is_still_following.borrow());
12530
12531    // Extend the pending selection so that it surrounds another selection
12532    _ = leader.update(cx, |leader, window, cx| {
12533        leader.extend_selection(DisplayPoint::new(DisplayRow(0), 2), 1, window, cx);
12534    });
12535    follower
12536        .update(cx, |follower, window, cx| {
12537            follower.apply_update_proto(
12538                &project,
12539                pending_update.borrow_mut().take().unwrap(),
12540                window,
12541                cx,
12542            )
12543        })
12544        .unwrap()
12545        .await
12546        .unwrap();
12547    _ = follower.update(cx, |follower, _, cx| {
12548        assert_eq!(follower.selections.ranges(cx), vec![0..2]);
12549    });
12550
12551    // Scrolling locally breaks the follow
12552    _ = follower.update(cx, |follower, window, cx| {
12553        let top_anchor = follower.buffer().read(cx).read(cx).anchor_after(0);
12554        follower.set_scroll_anchor(
12555            ScrollAnchor {
12556                anchor: top_anchor,
12557                offset: gpui::Point::new(0.0, 0.5),
12558            },
12559            window,
12560            cx,
12561        );
12562    });
12563    assert!(!(*is_still_following.borrow()));
12564}
12565
12566#[gpui::test]
12567async fn test_following_with_multiple_excerpts(cx: &mut TestAppContext) {
12568    init_test(cx, |_| {});
12569
12570    let fs = FakeFs::new(cx.executor());
12571    let project = Project::test(fs, ["/file.rs".as_ref()], cx).await;
12572    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
12573    let pane = workspace
12574        .update(cx, |workspace, _, _| workspace.active_pane().clone())
12575        .unwrap();
12576
12577    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
12578
12579    let leader = pane.update_in(cx, |_, window, cx| {
12580        let multibuffer = cx.new(|_| MultiBuffer::new(ReadWrite));
12581        cx.new(|cx| build_editor(multibuffer.clone(), window, cx))
12582    });
12583
12584    // Start following the editor when it has no excerpts.
12585    let mut state_message =
12586        leader.update_in(cx, |leader, window, cx| leader.to_state_proto(window, cx));
12587    let workspace_entity = workspace.root(cx).unwrap();
12588    let follower_1 = cx
12589        .update_window(*workspace.deref(), |_, window, cx| {
12590            Editor::from_state_proto(
12591                workspace_entity,
12592                ViewId {
12593                    creator: Default::default(),
12594                    id: 0,
12595                },
12596                &mut state_message,
12597                window,
12598                cx,
12599            )
12600        })
12601        .unwrap()
12602        .unwrap()
12603        .await
12604        .unwrap();
12605
12606    let update_message = Rc::new(RefCell::new(None));
12607    follower_1.update_in(cx, {
12608        let update = update_message.clone();
12609        |_, window, cx| {
12610            cx.subscribe_in(&leader, window, move |_, leader, event, window, cx| {
12611                leader.read(cx).add_event_to_update_proto(
12612                    event,
12613                    &mut update.borrow_mut(),
12614                    window,
12615                    cx,
12616                );
12617            })
12618            .detach();
12619        }
12620    });
12621
12622    let (buffer_1, buffer_2) = project.update(cx, |project, cx| {
12623        (
12624            project.create_local_buffer("abc\ndef\nghi\njkl\n", None, cx),
12625            project.create_local_buffer("mno\npqr\nstu\nvwx\n", None, cx),
12626        )
12627    });
12628
12629    // Insert some excerpts.
12630    leader.update(cx, |leader, cx| {
12631        leader.buffer.update(cx, |multibuffer, cx| {
12632            multibuffer.set_excerpts_for_path(
12633                PathKey::namespaced(1, Arc::from(Path::new("b.txt"))),
12634                buffer_1.clone(),
12635                vec![
12636                    Point::row_range(0..3),
12637                    Point::row_range(1..6),
12638                    Point::row_range(12..15),
12639                ],
12640                0,
12641                cx,
12642            );
12643            multibuffer.set_excerpts_for_path(
12644                PathKey::namespaced(1, Arc::from(Path::new("a.txt"))),
12645                buffer_2.clone(),
12646                vec![Point::row_range(0..6), Point::row_range(8..12)],
12647                0,
12648                cx,
12649            );
12650        });
12651    });
12652
12653    // Apply the update of adding the excerpts.
12654    follower_1
12655        .update_in(cx, |follower, window, cx| {
12656            follower.apply_update_proto(
12657                &project,
12658                update_message.borrow().clone().unwrap(),
12659                window,
12660                cx,
12661            )
12662        })
12663        .await
12664        .unwrap();
12665    assert_eq!(
12666        follower_1.update(cx, |editor, cx| editor.text(cx)),
12667        leader.update(cx, |editor, cx| editor.text(cx))
12668    );
12669    update_message.borrow_mut().take();
12670
12671    // Start following separately after it already has excerpts.
12672    let mut state_message =
12673        leader.update_in(cx, |leader, window, cx| leader.to_state_proto(window, cx));
12674    let workspace_entity = workspace.root(cx).unwrap();
12675    let follower_2 = cx
12676        .update_window(*workspace.deref(), |_, window, cx| {
12677            Editor::from_state_proto(
12678                workspace_entity,
12679                ViewId {
12680                    creator: Default::default(),
12681                    id: 0,
12682                },
12683                &mut state_message,
12684                window,
12685                cx,
12686            )
12687        })
12688        .unwrap()
12689        .unwrap()
12690        .await
12691        .unwrap();
12692    assert_eq!(
12693        follower_2.update(cx, |editor, cx| editor.text(cx)),
12694        leader.update(cx, |editor, cx| editor.text(cx))
12695    );
12696
12697    // Remove some excerpts.
12698    leader.update(cx, |leader, cx| {
12699        leader.buffer.update(cx, |multibuffer, cx| {
12700            let excerpt_ids = multibuffer.excerpt_ids();
12701            multibuffer.remove_excerpts([excerpt_ids[1], excerpt_ids[2]], cx);
12702            multibuffer.remove_excerpts([excerpt_ids[0]], cx);
12703        });
12704    });
12705
12706    // Apply the update of removing the excerpts.
12707    follower_1
12708        .update_in(cx, |follower, window, cx| {
12709            follower.apply_update_proto(
12710                &project,
12711                update_message.borrow().clone().unwrap(),
12712                window,
12713                cx,
12714            )
12715        })
12716        .await
12717        .unwrap();
12718    follower_2
12719        .update_in(cx, |follower, window, cx| {
12720            follower.apply_update_proto(
12721                &project,
12722                update_message.borrow().clone().unwrap(),
12723                window,
12724                cx,
12725            )
12726        })
12727        .await
12728        .unwrap();
12729    update_message.borrow_mut().take();
12730    assert_eq!(
12731        follower_1.update(cx, |editor, cx| editor.text(cx)),
12732        leader.update(cx, |editor, cx| editor.text(cx))
12733    );
12734}
12735
12736#[gpui::test]
12737async fn go_to_prev_overlapping_diagnostic(executor: BackgroundExecutor, cx: &mut TestAppContext) {
12738    init_test(cx, |_| {});
12739
12740    let mut cx = EditorTestContext::new(cx).await;
12741    let lsp_store =
12742        cx.update_editor(|editor, _, cx| editor.project.as_ref().unwrap().read(cx).lsp_store());
12743
12744    cx.set_state(indoc! {"
12745        ˇfn func(abc def: i32) -> u32 {
12746        }
12747    "});
12748
12749    cx.update(|_, cx| {
12750        lsp_store.update(cx, |lsp_store, cx| {
12751            lsp_store
12752                .update_diagnostics(
12753                    LanguageServerId(0),
12754                    lsp::PublishDiagnosticsParams {
12755                        uri: lsp::Url::from_file_path(path!("/root/file")).unwrap(),
12756                        version: None,
12757                        diagnostics: vec![
12758                            lsp::Diagnostic {
12759                                range: lsp::Range::new(
12760                                    lsp::Position::new(0, 11),
12761                                    lsp::Position::new(0, 12),
12762                                ),
12763                                severity: Some(lsp::DiagnosticSeverity::ERROR),
12764                                ..Default::default()
12765                            },
12766                            lsp::Diagnostic {
12767                                range: lsp::Range::new(
12768                                    lsp::Position::new(0, 12),
12769                                    lsp::Position::new(0, 15),
12770                                ),
12771                                severity: Some(lsp::DiagnosticSeverity::ERROR),
12772                                ..Default::default()
12773                            },
12774                            lsp::Diagnostic {
12775                                range: lsp::Range::new(
12776                                    lsp::Position::new(0, 25),
12777                                    lsp::Position::new(0, 28),
12778                                ),
12779                                severity: Some(lsp::DiagnosticSeverity::ERROR),
12780                                ..Default::default()
12781                            },
12782                        ],
12783                    },
12784                    &[],
12785                    cx,
12786                )
12787                .unwrap()
12788        });
12789    });
12790
12791    executor.run_until_parked();
12792
12793    cx.update_editor(|editor, window, cx| {
12794        editor.go_to_prev_diagnostic(&GoToPreviousDiagnostic, window, cx);
12795    });
12796
12797    cx.assert_editor_state(indoc! {"
12798        fn func(abc def: i32) -> ˇu32 {
12799        }
12800    "});
12801
12802    cx.update_editor(|editor, window, cx| {
12803        editor.go_to_prev_diagnostic(&GoToPreviousDiagnostic, window, cx);
12804    });
12805
12806    cx.assert_editor_state(indoc! {"
12807        fn func(abc ˇdef: i32) -> u32 {
12808        }
12809    "});
12810
12811    cx.update_editor(|editor, window, cx| {
12812        editor.go_to_prev_diagnostic(&GoToPreviousDiagnostic, window, cx);
12813    });
12814
12815    cx.assert_editor_state(indoc! {"
12816        fn func(abcˇ def: i32) -> u32 {
12817        }
12818    "});
12819
12820    cx.update_editor(|editor, window, cx| {
12821        editor.go_to_prev_diagnostic(&GoToPreviousDiagnostic, window, cx);
12822    });
12823
12824    cx.assert_editor_state(indoc! {"
12825        fn func(abc def: i32) -> ˇu32 {
12826        }
12827    "});
12828}
12829
12830#[gpui::test]
12831async fn test_diagnostics_with_links(cx: &mut TestAppContext) {
12832    init_test(cx, |_| {});
12833
12834    let mut cx = EditorTestContext::new(cx).await;
12835
12836    cx.set_state(indoc! {"
12837        fn func(abˇc def: i32) -> u32 {
12838        }
12839    "});
12840    let lsp_store =
12841        cx.update_editor(|editor, _, cx| editor.project.as_ref().unwrap().read(cx).lsp_store());
12842
12843    cx.update(|_, cx| {
12844        lsp_store.update(cx, |lsp_store, cx| {
12845            lsp_store.update_diagnostics(
12846                LanguageServerId(0),
12847                lsp::PublishDiagnosticsParams {
12848                    uri: lsp::Url::from_file_path(path!("/root/file")).unwrap(),
12849                    version: None,
12850                    diagnostics: vec![lsp::Diagnostic {
12851                        range: lsp::Range::new(lsp::Position::new(0, 8), lsp::Position::new(0, 12)),
12852                        severity: Some(lsp::DiagnosticSeverity::ERROR),
12853                        message: "we've had problems with <https://link.one>, and <https://link.two> is broken".to_string(),
12854                        ..Default::default()
12855                    }],
12856                },
12857                &[],
12858                cx,
12859            )
12860        })
12861    }).unwrap();
12862    cx.run_until_parked();
12863    cx.update_editor(|editor, window, cx| {
12864        hover_popover::hover(editor, &Default::default(), window, cx)
12865    });
12866    cx.run_until_parked();
12867    cx.update_editor(|editor, _, _| assert!(editor.hover_state.diagnostic_popover.is_some()))
12868}
12869
12870#[gpui::test]
12871async fn test_go_to_hunk(executor: BackgroundExecutor, cx: &mut TestAppContext) {
12872    init_test(cx, |_| {});
12873
12874    let mut cx = EditorTestContext::new(cx).await;
12875
12876    let diff_base = r#"
12877        use some::mod;
12878
12879        const A: u32 = 42;
12880
12881        fn main() {
12882            println!("hello");
12883
12884            println!("world");
12885        }
12886        "#
12887    .unindent();
12888
12889    // Edits are modified, removed, modified, added
12890    cx.set_state(
12891        &r#"
12892        use some::modified;
12893
12894        ˇ
12895        fn main() {
12896            println!("hello there");
12897
12898            println!("around the");
12899            println!("world");
12900        }
12901        "#
12902        .unindent(),
12903    );
12904
12905    cx.set_head_text(&diff_base);
12906    executor.run_until_parked();
12907
12908    cx.update_editor(|editor, window, cx| {
12909        //Wrap around the bottom of the buffer
12910        for _ in 0..3 {
12911            editor.go_to_next_hunk(&GoToHunk, window, cx);
12912        }
12913    });
12914
12915    cx.assert_editor_state(
12916        &r#"
12917        ˇuse some::modified;
12918
12919
12920        fn main() {
12921            println!("hello there");
12922
12923            println!("around the");
12924            println!("world");
12925        }
12926        "#
12927        .unindent(),
12928    );
12929
12930    cx.update_editor(|editor, window, cx| {
12931        //Wrap around the top of the buffer
12932        for _ in 0..2 {
12933            editor.go_to_prev_hunk(&GoToPreviousHunk, window, cx);
12934        }
12935    });
12936
12937    cx.assert_editor_state(
12938        &r#"
12939        use some::modified;
12940
12941
12942        fn main() {
12943        ˇ    println!("hello there");
12944
12945            println!("around the");
12946            println!("world");
12947        }
12948        "#
12949        .unindent(),
12950    );
12951
12952    cx.update_editor(|editor, window, cx| {
12953        editor.go_to_prev_hunk(&GoToPreviousHunk, window, cx);
12954    });
12955
12956    cx.assert_editor_state(
12957        &r#"
12958        use some::modified;
12959
12960        ˇ
12961        fn main() {
12962            println!("hello there");
12963
12964            println!("around the");
12965            println!("world");
12966        }
12967        "#
12968        .unindent(),
12969    );
12970
12971    cx.update_editor(|editor, window, cx| {
12972        editor.go_to_prev_hunk(&GoToPreviousHunk, window, cx);
12973    });
12974
12975    cx.assert_editor_state(
12976        &r#"
12977        ˇuse some::modified;
12978
12979
12980        fn main() {
12981            println!("hello there");
12982
12983            println!("around the");
12984            println!("world");
12985        }
12986        "#
12987        .unindent(),
12988    );
12989
12990    cx.update_editor(|editor, window, cx| {
12991        for _ in 0..2 {
12992            editor.go_to_prev_hunk(&GoToPreviousHunk, window, cx);
12993        }
12994    });
12995
12996    cx.assert_editor_state(
12997        &r#"
12998        use some::modified;
12999
13000
13001        fn main() {
13002        ˇ    println!("hello there");
13003
13004            println!("around the");
13005            println!("world");
13006        }
13007        "#
13008        .unindent(),
13009    );
13010
13011    cx.update_editor(|editor, window, cx| {
13012        editor.fold(&Fold, window, cx);
13013    });
13014
13015    cx.update_editor(|editor, window, cx| {
13016        editor.go_to_next_hunk(&GoToHunk, window, cx);
13017    });
13018
13019    cx.assert_editor_state(
13020        &r#"
13021        ˇuse some::modified;
13022
13023
13024        fn main() {
13025            println!("hello there");
13026
13027            println!("around the");
13028            println!("world");
13029        }
13030        "#
13031        .unindent(),
13032    );
13033}
13034
13035#[test]
13036fn test_split_words() {
13037    fn split(text: &str) -> Vec<&str> {
13038        split_words(text).collect()
13039    }
13040
13041    assert_eq!(split("HelloWorld"), &["Hello", "World"]);
13042    assert_eq!(split("hello_world"), &["hello_", "world"]);
13043    assert_eq!(split("_hello_world_"), &["_", "hello_", "world_"]);
13044    assert_eq!(split("Hello_World"), &["Hello_", "World"]);
13045    assert_eq!(split("helloWOrld"), &["hello", "WOrld"]);
13046    assert_eq!(split("helloworld"), &["helloworld"]);
13047
13048    assert_eq!(split(":do_the_thing"), &[":", "do_", "the_", "thing"]);
13049}
13050
13051#[gpui::test]
13052async fn test_move_to_enclosing_bracket(cx: &mut TestAppContext) {
13053    init_test(cx, |_| {});
13054
13055    let mut cx = EditorLspTestContext::new_typescript(Default::default(), cx).await;
13056    let mut assert = |before, after| {
13057        let _state_context = cx.set_state(before);
13058        cx.run_until_parked();
13059        cx.update_editor(|editor, window, cx| {
13060            editor.move_to_enclosing_bracket(&MoveToEnclosingBracket, window, cx)
13061        });
13062        cx.run_until_parked();
13063        cx.assert_editor_state(after);
13064    };
13065
13066    // Outside bracket jumps to outside of matching bracket
13067    assert("console.logˇ(var);", "console.log(var)ˇ;");
13068    assert("console.log(var)ˇ;", "console.logˇ(var);");
13069
13070    // Inside bracket jumps to inside of matching bracket
13071    assert("console.log(ˇvar);", "console.log(varˇ);");
13072    assert("console.log(varˇ);", "console.log(ˇvar);");
13073
13074    // When outside a bracket and inside, favor jumping to the inside bracket
13075    assert(
13076        "console.log('foo', [1, 2, 3]ˇ);",
13077        "console.log(ˇ'foo', [1, 2, 3]);",
13078    );
13079    assert(
13080        "console.log(ˇ'foo', [1, 2, 3]);",
13081        "console.log('foo', [1, 2, 3]ˇ);",
13082    );
13083
13084    // Bias forward if two options are equally likely
13085    assert(
13086        "let result = curried_fun()ˇ();",
13087        "let result = curried_fun()()ˇ;",
13088    );
13089
13090    // If directly adjacent to a smaller pair but inside a larger (not adjacent), pick the smaller
13091    assert(
13092        indoc! {"
13093            function test() {
13094                console.log('test')ˇ
13095            }"},
13096        indoc! {"
13097            function test() {
13098                console.logˇ('test')
13099            }"},
13100    );
13101}
13102
13103#[gpui::test]
13104async fn test_on_type_formatting_not_triggered(cx: &mut TestAppContext) {
13105    init_test(cx, |_| {});
13106
13107    let fs = FakeFs::new(cx.executor());
13108    fs.insert_tree(
13109        path!("/a"),
13110        json!({
13111            "main.rs": "fn main() { let a = 5; }",
13112            "other.rs": "// Test file",
13113        }),
13114    )
13115    .await;
13116    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
13117
13118    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
13119    language_registry.add(Arc::new(Language::new(
13120        LanguageConfig {
13121            name: "Rust".into(),
13122            matcher: LanguageMatcher {
13123                path_suffixes: vec!["rs".to_string()],
13124                ..Default::default()
13125            },
13126            brackets: BracketPairConfig {
13127                pairs: vec![BracketPair {
13128                    start: "{".to_string(),
13129                    end: "}".to_string(),
13130                    close: true,
13131                    surround: true,
13132                    newline: true,
13133                }],
13134                disabled_scopes_by_bracket_ix: Vec::new(),
13135            },
13136            ..Default::default()
13137        },
13138        Some(tree_sitter_rust::LANGUAGE.into()),
13139    )));
13140    let mut fake_servers = language_registry.register_fake_lsp(
13141        "Rust",
13142        FakeLspAdapter {
13143            capabilities: lsp::ServerCapabilities {
13144                document_on_type_formatting_provider: Some(lsp::DocumentOnTypeFormattingOptions {
13145                    first_trigger_character: "{".to_string(),
13146                    more_trigger_character: None,
13147                }),
13148                ..Default::default()
13149            },
13150            ..Default::default()
13151        },
13152    );
13153
13154    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
13155
13156    let cx = &mut VisualTestContext::from_window(*workspace, cx);
13157
13158    let worktree_id = workspace
13159        .update(cx, |workspace, _, cx| {
13160            workspace.project().update(cx, |project, cx| {
13161                project.worktrees(cx).next().unwrap().read(cx).id()
13162            })
13163        })
13164        .unwrap();
13165
13166    let buffer = project
13167        .update(cx, |project, cx| {
13168            project.open_local_buffer(path!("/a/main.rs"), cx)
13169        })
13170        .await
13171        .unwrap();
13172    let editor_handle = workspace
13173        .update(cx, |workspace, window, cx| {
13174            workspace.open_path((worktree_id, "main.rs"), None, true, window, cx)
13175        })
13176        .unwrap()
13177        .await
13178        .unwrap()
13179        .downcast::<Editor>()
13180        .unwrap();
13181
13182    cx.executor().start_waiting();
13183    let fake_server = fake_servers.next().await.unwrap();
13184
13185    fake_server.set_request_handler::<lsp::request::OnTypeFormatting, _, _>(
13186        |params, _| async move {
13187            assert_eq!(
13188                params.text_document_position.text_document.uri,
13189                lsp::Url::from_file_path(path!("/a/main.rs")).unwrap(),
13190            );
13191            assert_eq!(
13192                params.text_document_position.position,
13193                lsp::Position::new(0, 21),
13194            );
13195
13196            Ok(Some(vec![lsp::TextEdit {
13197                new_text: "]".to_string(),
13198                range: lsp::Range::new(lsp::Position::new(0, 22), lsp::Position::new(0, 22)),
13199            }]))
13200        },
13201    );
13202
13203    editor_handle.update_in(cx, |editor, window, cx| {
13204        window.focus(&editor.focus_handle(cx));
13205        editor.change_selections(None, window, cx, |s| {
13206            s.select_ranges([Point::new(0, 21)..Point::new(0, 20)])
13207        });
13208        editor.handle_input("{", window, cx);
13209    });
13210
13211    cx.executor().run_until_parked();
13212
13213    buffer.update(cx, |buffer, _| {
13214        assert_eq!(
13215            buffer.text(),
13216            "fn main() { let a = {5}; }",
13217            "No extra braces from on type formatting should appear in the buffer"
13218        )
13219    });
13220}
13221
13222#[gpui::test]
13223async fn test_language_server_restart_due_to_settings_change(cx: &mut TestAppContext) {
13224    init_test(cx, |_| {});
13225
13226    let fs = FakeFs::new(cx.executor());
13227    fs.insert_tree(
13228        path!("/a"),
13229        json!({
13230            "main.rs": "fn main() { let a = 5; }",
13231            "other.rs": "// Test file",
13232        }),
13233    )
13234    .await;
13235
13236    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
13237
13238    let server_restarts = Arc::new(AtomicUsize::new(0));
13239    let closure_restarts = Arc::clone(&server_restarts);
13240    let language_server_name = "test language server";
13241    let language_name: LanguageName = "Rust".into();
13242
13243    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
13244    language_registry.add(Arc::new(Language::new(
13245        LanguageConfig {
13246            name: language_name.clone(),
13247            matcher: LanguageMatcher {
13248                path_suffixes: vec!["rs".to_string()],
13249                ..Default::default()
13250            },
13251            ..Default::default()
13252        },
13253        Some(tree_sitter_rust::LANGUAGE.into()),
13254    )));
13255    let mut fake_servers = language_registry.register_fake_lsp(
13256        "Rust",
13257        FakeLspAdapter {
13258            name: language_server_name,
13259            initialization_options: Some(json!({
13260                "testOptionValue": true
13261            })),
13262            initializer: Some(Box::new(move |fake_server| {
13263                let task_restarts = Arc::clone(&closure_restarts);
13264                fake_server.set_request_handler::<lsp::request::Shutdown, _, _>(move |_, _| {
13265                    task_restarts.fetch_add(1, atomic::Ordering::Release);
13266                    futures::future::ready(Ok(()))
13267                });
13268            })),
13269            ..Default::default()
13270        },
13271    );
13272
13273    let _window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
13274    let _buffer = project
13275        .update(cx, |project, cx| {
13276            project.open_local_buffer_with_lsp(path!("/a/main.rs"), cx)
13277        })
13278        .await
13279        .unwrap();
13280    let _fake_server = fake_servers.next().await.unwrap();
13281    update_test_language_settings(cx, |language_settings| {
13282        language_settings.languages.insert(
13283            language_name.clone(),
13284            LanguageSettingsContent {
13285                tab_size: NonZeroU32::new(8),
13286                ..Default::default()
13287            },
13288        );
13289    });
13290    cx.executor().run_until_parked();
13291    assert_eq!(
13292        server_restarts.load(atomic::Ordering::Acquire),
13293        0,
13294        "Should not restart LSP server on an unrelated change"
13295    );
13296
13297    update_test_project_settings(cx, |project_settings| {
13298        project_settings.lsp.insert(
13299            "Some other server name".into(),
13300            LspSettings {
13301                binary: None,
13302                settings: None,
13303                initialization_options: Some(json!({
13304                    "some other init value": false
13305                })),
13306                enable_lsp_tasks: false,
13307            },
13308        );
13309    });
13310    cx.executor().run_until_parked();
13311    assert_eq!(
13312        server_restarts.load(atomic::Ordering::Acquire),
13313        0,
13314        "Should not restart LSP server on an unrelated LSP settings change"
13315    );
13316
13317    update_test_project_settings(cx, |project_settings| {
13318        project_settings.lsp.insert(
13319            language_server_name.into(),
13320            LspSettings {
13321                binary: None,
13322                settings: None,
13323                initialization_options: Some(json!({
13324                    "anotherInitValue": false
13325                })),
13326                enable_lsp_tasks: false,
13327            },
13328        );
13329    });
13330    cx.executor().run_until_parked();
13331    assert_eq!(
13332        server_restarts.load(atomic::Ordering::Acquire),
13333        1,
13334        "Should restart LSP server on a related LSP settings change"
13335    );
13336
13337    update_test_project_settings(cx, |project_settings| {
13338        project_settings.lsp.insert(
13339            language_server_name.into(),
13340            LspSettings {
13341                binary: None,
13342                settings: None,
13343                initialization_options: Some(json!({
13344                    "anotherInitValue": false
13345                })),
13346                enable_lsp_tasks: false,
13347            },
13348        );
13349    });
13350    cx.executor().run_until_parked();
13351    assert_eq!(
13352        server_restarts.load(atomic::Ordering::Acquire),
13353        1,
13354        "Should not restart LSP server on a related LSP settings change that is the same"
13355    );
13356
13357    update_test_project_settings(cx, |project_settings| {
13358        project_settings.lsp.insert(
13359            language_server_name.into(),
13360            LspSettings {
13361                binary: None,
13362                settings: None,
13363                initialization_options: None,
13364                enable_lsp_tasks: false,
13365            },
13366        );
13367    });
13368    cx.executor().run_until_parked();
13369    assert_eq!(
13370        server_restarts.load(atomic::Ordering::Acquire),
13371        2,
13372        "Should restart LSP server on another related LSP settings change"
13373    );
13374}
13375
13376#[gpui::test]
13377async fn test_completions_with_additional_edits(cx: &mut TestAppContext) {
13378    init_test(cx, |_| {});
13379
13380    let mut cx = EditorLspTestContext::new_rust(
13381        lsp::ServerCapabilities {
13382            completion_provider: Some(lsp::CompletionOptions {
13383                trigger_characters: Some(vec![".".to_string()]),
13384                resolve_provider: Some(true),
13385                ..Default::default()
13386            }),
13387            ..Default::default()
13388        },
13389        cx,
13390    )
13391    .await;
13392
13393    cx.set_state("fn main() { let a = 2ˇ; }");
13394    cx.simulate_keystroke(".");
13395    let completion_item = lsp::CompletionItem {
13396        label: "some".into(),
13397        kind: Some(lsp::CompletionItemKind::SNIPPET),
13398        detail: Some("Wrap the expression in an `Option::Some`".to_string()),
13399        documentation: Some(lsp::Documentation::MarkupContent(lsp::MarkupContent {
13400            kind: lsp::MarkupKind::Markdown,
13401            value: "```rust\nSome(2)\n```".to_string(),
13402        })),
13403        deprecated: Some(false),
13404        sort_text: Some("fffffff2".to_string()),
13405        filter_text: Some("some".to_string()),
13406        insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
13407        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
13408            range: lsp::Range {
13409                start: lsp::Position {
13410                    line: 0,
13411                    character: 22,
13412                },
13413                end: lsp::Position {
13414                    line: 0,
13415                    character: 22,
13416                },
13417            },
13418            new_text: "Some(2)".to_string(),
13419        })),
13420        additional_text_edits: Some(vec![lsp::TextEdit {
13421            range: lsp::Range {
13422                start: lsp::Position {
13423                    line: 0,
13424                    character: 20,
13425                },
13426                end: lsp::Position {
13427                    line: 0,
13428                    character: 22,
13429                },
13430            },
13431            new_text: "".to_string(),
13432        }]),
13433        ..Default::default()
13434    };
13435
13436    let closure_completion_item = completion_item.clone();
13437    let mut request = cx.set_request_handler::<lsp::request::Completion, _, _>(move |_, _, _| {
13438        let task_completion_item = closure_completion_item.clone();
13439        async move {
13440            Ok(Some(lsp::CompletionResponse::Array(vec![
13441                task_completion_item,
13442            ])))
13443        }
13444    });
13445
13446    request.next().await;
13447
13448    cx.condition(|editor, _| editor.context_menu_visible())
13449        .await;
13450    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
13451        editor
13452            .confirm_completion(&ConfirmCompletion::default(), window, cx)
13453            .unwrap()
13454    });
13455    cx.assert_editor_state("fn main() { let a = 2.Some(2)ˇ; }");
13456
13457    cx.set_request_handler::<lsp::request::ResolveCompletionItem, _, _>(move |_, _, _| {
13458        let task_completion_item = completion_item.clone();
13459        async move { Ok(task_completion_item) }
13460    })
13461    .next()
13462    .await
13463    .unwrap();
13464    apply_additional_edits.await.unwrap();
13465    cx.assert_editor_state("fn main() { let a = Some(2)ˇ; }");
13466}
13467
13468#[gpui::test]
13469async fn test_completions_resolve_updates_labels_if_filter_text_matches(cx: &mut TestAppContext) {
13470    init_test(cx, |_| {});
13471
13472    let mut cx = EditorLspTestContext::new_rust(
13473        lsp::ServerCapabilities {
13474            completion_provider: Some(lsp::CompletionOptions {
13475                trigger_characters: Some(vec![".".to_string()]),
13476                resolve_provider: Some(true),
13477                ..Default::default()
13478            }),
13479            ..Default::default()
13480        },
13481        cx,
13482    )
13483    .await;
13484
13485    cx.set_state("fn main() { let a = 2ˇ; }");
13486    cx.simulate_keystroke(".");
13487
13488    let item1 = lsp::CompletionItem {
13489        label: "method id()".to_string(),
13490        filter_text: Some("id".to_string()),
13491        detail: None,
13492        documentation: None,
13493        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
13494            range: lsp::Range::new(lsp::Position::new(0, 22), lsp::Position::new(0, 22)),
13495            new_text: ".id".to_string(),
13496        })),
13497        ..lsp::CompletionItem::default()
13498    };
13499
13500    let item2 = lsp::CompletionItem {
13501        label: "other".to_string(),
13502        filter_text: Some("other".to_string()),
13503        detail: None,
13504        documentation: None,
13505        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
13506            range: lsp::Range::new(lsp::Position::new(0, 22), lsp::Position::new(0, 22)),
13507            new_text: ".other".to_string(),
13508        })),
13509        ..lsp::CompletionItem::default()
13510    };
13511
13512    let item1 = item1.clone();
13513    cx.set_request_handler::<lsp::request::Completion, _, _>({
13514        let item1 = item1.clone();
13515        move |_, _, _| {
13516            let item1 = item1.clone();
13517            let item2 = item2.clone();
13518            async move { Ok(Some(lsp::CompletionResponse::Array(vec![item1, item2]))) }
13519        }
13520    })
13521    .next()
13522    .await;
13523
13524    cx.condition(|editor, _| editor.context_menu_visible())
13525        .await;
13526    cx.update_editor(|editor, _, _| {
13527        let context_menu = editor.context_menu.borrow_mut();
13528        let context_menu = context_menu
13529            .as_ref()
13530            .expect("Should have the context menu deployed");
13531        match context_menu {
13532            CodeContextMenu::Completions(completions_menu) => {
13533                let completions = completions_menu.completions.borrow_mut();
13534                assert_eq!(
13535                    completions
13536                        .iter()
13537                        .map(|completion| &completion.label.text)
13538                        .collect::<Vec<_>>(),
13539                    vec!["method id()", "other"]
13540                )
13541            }
13542            CodeContextMenu::CodeActions(_) => panic!("Should show the completions menu"),
13543        }
13544    });
13545
13546    cx.set_request_handler::<lsp::request::ResolveCompletionItem, _, _>({
13547        let item1 = item1.clone();
13548        move |_, item_to_resolve, _| {
13549            let item1 = item1.clone();
13550            async move {
13551                if item1 == item_to_resolve {
13552                    Ok(lsp::CompletionItem {
13553                        label: "method id()".to_string(),
13554                        filter_text: Some("id".to_string()),
13555                        detail: Some("Now resolved!".to_string()),
13556                        documentation: Some(lsp::Documentation::String("Docs".to_string())),
13557                        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
13558                            range: lsp::Range::new(
13559                                lsp::Position::new(0, 22),
13560                                lsp::Position::new(0, 22),
13561                            ),
13562                            new_text: ".id".to_string(),
13563                        })),
13564                        ..lsp::CompletionItem::default()
13565                    })
13566                } else {
13567                    Ok(item_to_resolve)
13568                }
13569            }
13570        }
13571    })
13572    .next()
13573    .await
13574    .unwrap();
13575    cx.run_until_parked();
13576
13577    cx.update_editor(|editor, window, cx| {
13578        editor.context_menu_next(&Default::default(), window, cx);
13579    });
13580
13581    cx.update_editor(|editor, _, _| {
13582        let context_menu = editor.context_menu.borrow_mut();
13583        let context_menu = context_menu
13584            .as_ref()
13585            .expect("Should have the context menu deployed");
13586        match context_menu {
13587            CodeContextMenu::Completions(completions_menu) => {
13588                let completions = completions_menu.completions.borrow_mut();
13589                assert_eq!(
13590                    completions
13591                        .iter()
13592                        .map(|completion| &completion.label.text)
13593                        .collect::<Vec<_>>(),
13594                    vec!["method id() Now resolved!", "other"],
13595                    "Should update first completion label, but not second as the filter text did not match."
13596                );
13597            }
13598            CodeContextMenu::CodeActions(_) => panic!("Should show the completions menu"),
13599        }
13600    });
13601}
13602
13603#[gpui::test]
13604async fn test_completions_resolve_happens_once(cx: &mut TestAppContext) {
13605    init_test(cx, |_| {});
13606
13607    let mut cx = EditorLspTestContext::new_rust(
13608        lsp::ServerCapabilities {
13609            completion_provider: Some(lsp::CompletionOptions {
13610                trigger_characters: Some(vec![".".to_string()]),
13611                resolve_provider: Some(true),
13612                ..Default::default()
13613            }),
13614            ..Default::default()
13615        },
13616        cx,
13617    )
13618    .await;
13619
13620    cx.set_state("fn main() { let a = 2ˇ; }");
13621    cx.simulate_keystroke(".");
13622
13623    let unresolved_item_1 = lsp::CompletionItem {
13624        label: "id".to_string(),
13625        filter_text: Some("id".to_string()),
13626        detail: None,
13627        documentation: None,
13628        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
13629            range: lsp::Range::new(lsp::Position::new(0, 22), lsp::Position::new(0, 22)),
13630            new_text: ".id".to_string(),
13631        })),
13632        ..lsp::CompletionItem::default()
13633    };
13634    let resolved_item_1 = lsp::CompletionItem {
13635        additional_text_edits: Some(vec![lsp::TextEdit {
13636            range: lsp::Range::new(lsp::Position::new(0, 20), lsp::Position::new(0, 22)),
13637            new_text: "!!".to_string(),
13638        }]),
13639        ..unresolved_item_1.clone()
13640    };
13641    let unresolved_item_2 = lsp::CompletionItem {
13642        label: "other".to_string(),
13643        filter_text: Some("other".to_string()),
13644        detail: None,
13645        documentation: None,
13646        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
13647            range: lsp::Range::new(lsp::Position::new(0, 22), lsp::Position::new(0, 22)),
13648            new_text: ".other".to_string(),
13649        })),
13650        ..lsp::CompletionItem::default()
13651    };
13652    let resolved_item_2 = lsp::CompletionItem {
13653        additional_text_edits: Some(vec![lsp::TextEdit {
13654            range: lsp::Range::new(lsp::Position::new(0, 20), lsp::Position::new(0, 22)),
13655            new_text: "??".to_string(),
13656        }]),
13657        ..unresolved_item_2.clone()
13658    };
13659
13660    let resolve_requests_1 = Arc::new(AtomicUsize::new(0));
13661    let resolve_requests_2 = Arc::new(AtomicUsize::new(0));
13662    cx.lsp
13663        .server
13664        .on_request::<lsp::request::ResolveCompletionItem, _, _>({
13665            let unresolved_item_1 = unresolved_item_1.clone();
13666            let resolved_item_1 = resolved_item_1.clone();
13667            let unresolved_item_2 = unresolved_item_2.clone();
13668            let resolved_item_2 = resolved_item_2.clone();
13669            let resolve_requests_1 = resolve_requests_1.clone();
13670            let resolve_requests_2 = resolve_requests_2.clone();
13671            move |unresolved_request, _| {
13672                let unresolved_item_1 = unresolved_item_1.clone();
13673                let resolved_item_1 = resolved_item_1.clone();
13674                let unresolved_item_2 = unresolved_item_2.clone();
13675                let resolved_item_2 = resolved_item_2.clone();
13676                let resolve_requests_1 = resolve_requests_1.clone();
13677                let resolve_requests_2 = resolve_requests_2.clone();
13678                async move {
13679                    if unresolved_request == unresolved_item_1 {
13680                        resolve_requests_1.fetch_add(1, atomic::Ordering::Release);
13681                        Ok(resolved_item_1.clone())
13682                    } else if unresolved_request == unresolved_item_2 {
13683                        resolve_requests_2.fetch_add(1, atomic::Ordering::Release);
13684                        Ok(resolved_item_2.clone())
13685                    } else {
13686                        panic!("Unexpected completion item {unresolved_request:?}")
13687                    }
13688                }
13689            }
13690        })
13691        .detach();
13692
13693    cx.set_request_handler::<lsp::request::Completion, _, _>(move |_, _, _| {
13694        let unresolved_item_1 = unresolved_item_1.clone();
13695        let unresolved_item_2 = unresolved_item_2.clone();
13696        async move {
13697            Ok(Some(lsp::CompletionResponse::Array(vec![
13698                unresolved_item_1,
13699                unresolved_item_2,
13700            ])))
13701        }
13702    })
13703    .next()
13704    .await;
13705
13706    cx.condition(|editor, _| editor.context_menu_visible())
13707        .await;
13708    cx.update_editor(|editor, _, _| {
13709        let context_menu = editor.context_menu.borrow_mut();
13710        let context_menu = context_menu
13711            .as_ref()
13712            .expect("Should have the context menu deployed");
13713        match context_menu {
13714            CodeContextMenu::Completions(completions_menu) => {
13715                let completions = completions_menu.completions.borrow_mut();
13716                assert_eq!(
13717                    completions
13718                        .iter()
13719                        .map(|completion| &completion.label.text)
13720                        .collect::<Vec<_>>(),
13721                    vec!["id", "other"]
13722                )
13723            }
13724            CodeContextMenu::CodeActions(_) => panic!("Should show the completions menu"),
13725        }
13726    });
13727    cx.run_until_parked();
13728
13729    cx.update_editor(|editor, window, cx| {
13730        editor.context_menu_next(&ContextMenuNext, window, cx);
13731    });
13732    cx.run_until_parked();
13733    cx.update_editor(|editor, window, cx| {
13734        editor.context_menu_prev(&ContextMenuPrevious, window, cx);
13735    });
13736    cx.run_until_parked();
13737    cx.update_editor(|editor, window, cx| {
13738        editor.context_menu_next(&ContextMenuNext, window, cx);
13739    });
13740    cx.run_until_parked();
13741    cx.update_editor(|editor, window, cx| {
13742        editor
13743            .compose_completion(&ComposeCompletion::default(), window, cx)
13744            .expect("No task returned")
13745    })
13746    .await
13747    .expect("Completion failed");
13748    cx.run_until_parked();
13749
13750    cx.update_editor(|editor, _, cx| {
13751        assert_eq!(
13752            resolve_requests_1.load(atomic::Ordering::Acquire),
13753            1,
13754            "Should always resolve once despite multiple selections"
13755        );
13756        assert_eq!(
13757            resolve_requests_2.load(atomic::Ordering::Acquire),
13758            1,
13759            "Should always resolve once after multiple selections and applying the completion"
13760        );
13761        assert_eq!(
13762            editor.text(cx),
13763            "fn main() { let a = ??.other; }",
13764            "Should use resolved data when applying the completion"
13765        );
13766    });
13767}
13768
13769#[gpui::test]
13770async fn test_completions_default_resolve_data_handling(cx: &mut TestAppContext) {
13771    init_test(cx, |_| {});
13772
13773    let item_0 = lsp::CompletionItem {
13774        label: "abs".into(),
13775        insert_text: Some("abs".into()),
13776        data: Some(json!({ "very": "special"})),
13777        insert_text_mode: Some(lsp::InsertTextMode::ADJUST_INDENTATION),
13778        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13779            lsp::InsertReplaceEdit {
13780                new_text: "abs".to_string(),
13781                insert: lsp::Range::default(),
13782                replace: lsp::Range::default(),
13783            },
13784        )),
13785        ..lsp::CompletionItem::default()
13786    };
13787    let items = iter::once(item_0.clone())
13788        .chain((11..51).map(|i| lsp::CompletionItem {
13789            label: format!("item_{}", i),
13790            insert_text: Some(format!("item_{}", i)),
13791            insert_text_format: Some(lsp::InsertTextFormat::PLAIN_TEXT),
13792            ..lsp::CompletionItem::default()
13793        }))
13794        .collect::<Vec<_>>();
13795
13796    let default_commit_characters = vec!["?".to_string()];
13797    let default_data = json!({ "default": "data"});
13798    let default_insert_text_format = lsp::InsertTextFormat::SNIPPET;
13799    let default_insert_text_mode = lsp::InsertTextMode::AS_IS;
13800    let default_edit_range = lsp::Range {
13801        start: lsp::Position {
13802            line: 0,
13803            character: 5,
13804        },
13805        end: lsp::Position {
13806            line: 0,
13807            character: 5,
13808        },
13809    };
13810
13811    let mut cx = EditorLspTestContext::new_rust(
13812        lsp::ServerCapabilities {
13813            completion_provider: Some(lsp::CompletionOptions {
13814                trigger_characters: Some(vec![".".to_string()]),
13815                resolve_provider: Some(true),
13816                ..Default::default()
13817            }),
13818            ..Default::default()
13819        },
13820        cx,
13821    )
13822    .await;
13823
13824    cx.set_state("fn main() { let a = 2ˇ; }");
13825    cx.simulate_keystroke(".");
13826
13827    let completion_data = default_data.clone();
13828    let completion_characters = default_commit_characters.clone();
13829    let completion_items = items.clone();
13830    cx.set_request_handler::<lsp::request::Completion, _, _>(move |_, _, _| {
13831        let default_data = completion_data.clone();
13832        let default_commit_characters = completion_characters.clone();
13833        let items = completion_items.clone();
13834        async move {
13835            Ok(Some(lsp::CompletionResponse::List(lsp::CompletionList {
13836                items,
13837                item_defaults: Some(lsp::CompletionListItemDefaults {
13838                    data: Some(default_data.clone()),
13839                    commit_characters: Some(default_commit_characters.clone()),
13840                    edit_range: Some(lsp::CompletionListItemDefaultsEditRange::Range(
13841                        default_edit_range,
13842                    )),
13843                    insert_text_format: Some(default_insert_text_format),
13844                    insert_text_mode: Some(default_insert_text_mode),
13845                }),
13846                ..lsp::CompletionList::default()
13847            })))
13848        }
13849    })
13850    .next()
13851    .await;
13852
13853    let resolved_items = Arc::new(Mutex::new(Vec::new()));
13854    cx.lsp
13855        .server
13856        .on_request::<lsp::request::ResolveCompletionItem, _, _>({
13857            let closure_resolved_items = resolved_items.clone();
13858            move |item_to_resolve, _| {
13859                let closure_resolved_items = closure_resolved_items.clone();
13860                async move {
13861                    closure_resolved_items.lock().push(item_to_resolve.clone());
13862                    Ok(item_to_resolve)
13863                }
13864            }
13865        })
13866        .detach();
13867
13868    cx.condition(|editor, _| editor.context_menu_visible())
13869        .await;
13870    cx.run_until_parked();
13871    cx.update_editor(|editor, _, _| {
13872        let menu = editor.context_menu.borrow_mut();
13873        match menu.as_ref().expect("should have the completions menu") {
13874            CodeContextMenu::Completions(completions_menu) => {
13875                assert_eq!(
13876                    completions_menu
13877                        .entries
13878                        .borrow()
13879                        .iter()
13880                        .map(|mat| mat.string.clone())
13881                        .collect::<Vec<String>>(),
13882                    items
13883                        .iter()
13884                        .map(|completion| completion.label.clone())
13885                        .collect::<Vec<String>>()
13886                );
13887            }
13888            CodeContextMenu::CodeActions(_) => panic!("Expected to have the completions menu"),
13889        }
13890    });
13891    // Approximate initial displayed interval is 0..12. With extra item padding of 4 this is 0..16
13892    // with 4 from the end.
13893    assert_eq!(
13894        *resolved_items.lock(),
13895        [&items[0..16], &items[items.len() - 4..items.len()]]
13896            .concat()
13897            .iter()
13898            .cloned()
13899            .map(|mut item| {
13900                if item.data.is_none() {
13901                    item.data = Some(default_data.clone());
13902                }
13903                item
13904            })
13905            .collect::<Vec<lsp::CompletionItem>>(),
13906        "Items sent for resolve should be unchanged modulo resolve `data` filled with default if missing"
13907    );
13908    resolved_items.lock().clear();
13909
13910    cx.update_editor(|editor, window, cx| {
13911        editor.context_menu_prev(&ContextMenuPrevious, window, cx);
13912    });
13913    cx.run_until_parked();
13914    // Completions that have already been resolved are skipped.
13915    assert_eq!(
13916        *resolved_items.lock(),
13917        items[items.len() - 16..items.len() - 4]
13918            .iter()
13919            .cloned()
13920            .map(|mut item| {
13921                if item.data.is_none() {
13922                    item.data = Some(default_data.clone());
13923                }
13924                item
13925            })
13926            .collect::<Vec<lsp::CompletionItem>>()
13927    );
13928    resolved_items.lock().clear();
13929}
13930
13931#[gpui::test]
13932async fn test_completions_in_languages_with_extra_word_characters(cx: &mut TestAppContext) {
13933    init_test(cx, |_| {});
13934
13935    let mut cx = EditorLspTestContext::new(
13936        Language::new(
13937            LanguageConfig {
13938                matcher: LanguageMatcher {
13939                    path_suffixes: vec!["jsx".into()],
13940                    ..Default::default()
13941                },
13942                overrides: [(
13943                    "element".into(),
13944                    LanguageConfigOverride {
13945                        completion_query_characters: Override::Set(['-'].into_iter().collect()),
13946                        ..Default::default()
13947                    },
13948                )]
13949                .into_iter()
13950                .collect(),
13951                ..Default::default()
13952            },
13953            Some(tree_sitter_typescript::LANGUAGE_TSX.into()),
13954        )
13955        .with_override_query("(jsx_self_closing_element) @element")
13956        .unwrap(),
13957        lsp::ServerCapabilities {
13958            completion_provider: Some(lsp::CompletionOptions {
13959                trigger_characters: Some(vec![":".to_string()]),
13960                ..Default::default()
13961            }),
13962            ..Default::default()
13963        },
13964        cx,
13965    )
13966    .await;
13967
13968    cx.lsp
13969        .set_request_handler::<lsp::request::Completion, _, _>(move |_, _| async move {
13970            Ok(Some(lsp::CompletionResponse::Array(vec![
13971                lsp::CompletionItem {
13972                    label: "bg-blue".into(),
13973                    ..Default::default()
13974                },
13975                lsp::CompletionItem {
13976                    label: "bg-red".into(),
13977                    ..Default::default()
13978                },
13979                lsp::CompletionItem {
13980                    label: "bg-yellow".into(),
13981                    ..Default::default()
13982                },
13983            ])))
13984        });
13985
13986    cx.set_state(r#"<p class="bgˇ" />"#);
13987
13988    // Trigger completion when typing a dash, because the dash is an extra
13989    // word character in the 'element' scope, which contains the cursor.
13990    cx.simulate_keystroke("-");
13991    cx.executor().run_until_parked();
13992    cx.update_editor(|editor, _, _| {
13993        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
13994        {
13995            assert_eq!(
13996                completion_menu_entries(&menu),
13997                &["bg-blue", "bg-red", "bg-yellow"]
13998            );
13999        } else {
14000            panic!("expected completion menu to be open");
14001        }
14002    });
14003
14004    cx.simulate_keystroke("l");
14005    cx.executor().run_until_parked();
14006    cx.update_editor(|editor, _, _| {
14007        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
14008        {
14009            assert_eq!(completion_menu_entries(&menu), &["bg-blue", "bg-yellow"]);
14010        } else {
14011            panic!("expected completion menu to be open");
14012        }
14013    });
14014
14015    // When filtering completions, consider the character after the '-' to
14016    // be the start of a subword.
14017    cx.set_state(r#"<p class="yelˇ" />"#);
14018    cx.simulate_keystroke("l");
14019    cx.executor().run_until_parked();
14020    cx.update_editor(|editor, _, _| {
14021        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
14022        {
14023            assert_eq!(completion_menu_entries(&menu), &["bg-yellow"]);
14024        } else {
14025            panic!("expected completion menu to be open");
14026        }
14027    });
14028}
14029
14030fn completion_menu_entries(menu: &CompletionsMenu) -> Vec<String> {
14031    let entries = menu.entries.borrow();
14032    entries.iter().map(|mat| mat.string.clone()).collect()
14033}
14034
14035#[gpui::test]
14036async fn test_document_format_with_prettier(cx: &mut TestAppContext) {
14037    init_test(cx, |settings| {
14038        settings.defaults.formatter = Some(language_settings::SelectedFormatter::List(
14039            FormatterList(vec![Formatter::Prettier].into()),
14040        ))
14041    });
14042
14043    let fs = FakeFs::new(cx.executor());
14044    fs.insert_file(path!("/file.ts"), Default::default()).await;
14045
14046    let project = Project::test(fs, [path!("/file.ts").as_ref()], cx).await;
14047    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
14048
14049    language_registry.add(Arc::new(Language::new(
14050        LanguageConfig {
14051            name: "TypeScript".into(),
14052            matcher: LanguageMatcher {
14053                path_suffixes: vec!["ts".to_string()],
14054                ..Default::default()
14055            },
14056            ..Default::default()
14057        },
14058        Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
14059    )));
14060    update_test_language_settings(cx, |settings| {
14061        settings.defaults.prettier = Some(PrettierSettings {
14062            allowed: true,
14063            ..PrettierSettings::default()
14064        });
14065    });
14066
14067    let test_plugin = "test_plugin";
14068    let _ = language_registry.register_fake_lsp(
14069        "TypeScript",
14070        FakeLspAdapter {
14071            prettier_plugins: vec![test_plugin],
14072            ..Default::default()
14073        },
14074    );
14075
14076    let prettier_format_suffix = project::TEST_PRETTIER_FORMAT_SUFFIX;
14077    let buffer = project
14078        .update(cx, |project, cx| {
14079            project.open_local_buffer(path!("/file.ts"), cx)
14080        })
14081        .await
14082        .unwrap();
14083
14084    let buffer_text = "one\ntwo\nthree\n";
14085    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
14086    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
14087    editor.update_in(cx, |editor, window, cx| {
14088        editor.set_text(buffer_text, window, cx)
14089    });
14090
14091    editor
14092        .update_in(cx, |editor, window, cx| {
14093            editor.perform_format(
14094                project.clone(),
14095                FormatTrigger::Manual,
14096                FormatTarget::Buffers,
14097                window,
14098                cx,
14099            )
14100        })
14101        .unwrap()
14102        .await;
14103    assert_eq!(
14104        editor.update(cx, |editor, cx| editor.text(cx)),
14105        buffer_text.to_string() + prettier_format_suffix,
14106        "Test prettier formatting was not applied to the original buffer text",
14107    );
14108
14109    update_test_language_settings(cx, |settings| {
14110        settings.defaults.formatter = Some(language_settings::SelectedFormatter::Auto)
14111    });
14112    let format = editor.update_in(cx, |editor, window, cx| {
14113        editor.perform_format(
14114            project.clone(),
14115            FormatTrigger::Manual,
14116            FormatTarget::Buffers,
14117            window,
14118            cx,
14119        )
14120    });
14121    format.await.unwrap();
14122    assert_eq!(
14123        editor.update(cx, |editor, cx| editor.text(cx)),
14124        buffer_text.to_string() + prettier_format_suffix + "\n" + prettier_format_suffix,
14125        "Autoformatting (via test prettier) was not applied to the original buffer text",
14126    );
14127}
14128
14129#[gpui::test]
14130async fn test_addition_reverts(cx: &mut TestAppContext) {
14131    init_test(cx, |_| {});
14132    let mut cx = EditorLspTestContext::new_rust(lsp::ServerCapabilities::default(), cx).await;
14133    let base_text = indoc! {r#"
14134        struct Row;
14135        struct Row1;
14136        struct Row2;
14137
14138        struct Row4;
14139        struct Row5;
14140        struct Row6;
14141
14142        struct Row8;
14143        struct Row9;
14144        struct Row10;"#};
14145
14146    // When addition hunks are not adjacent to carets, no hunk revert is performed
14147    assert_hunk_revert(
14148        indoc! {r#"struct Row;
14149                   struct Row1;
14150                   struct Row1.1;
14151                   struct Row1.2;
14152                   struct Row2;ˇ
14153
14154                   struct Row4;
14155                   struct Row5;
14156                   struct Row6;
14157
14158                   struct Row8;
14159                   ˇstruct Row9;
14160                   struct Row9.1;
14161                   struct Row9.2;
14162                   struct Row9.3;
14163                   struct Row10;"#},
14164        vec![DiffHunkStatusKind::Added, DiffHunkStatusKind::Added],
14165        indoc! {r#"struct Row;
14166                   struct Row1;
14167                   struct Row1.1;
14168                   struct Row1.2;
14169                   struct Row2;ˇ
14170
14171                   struct Row4;
14172                   struct Row5;
14173                   struct Row6;
14174
14175                   struct Row8;
14176                   ˇstruct Row9;
14177                   struct Row9.1;
14178                   struct Row9.2;
14179                   struct Row9.3;
14180                   struct Row10;"#},
14181        base_text,
14182        &mut cx,
14183    );
14184    // Same for selections
14185    assert_hunk_revert(
14186        indoc! {r#"struct Row;
14187                   struct Row1;
14188                   struct Row2;
14189                   struct Row2.1;
14190                   struct Row2.2;
14191                   «ˇ
14192                   struct Row4;
14193                   struct» Row5;
14194                   «struct Row6;
14195                   ˇ»
14196                   struct Row9.1;
14197                   struct Row9.2;
14198                   struct Row9.3;
14199                   struct Row8;
14200                   struct Row9;
14201                   struct Row10;"#},
14202        vec![DiffHunkStatusKind::Added, DiffHunkStatusKind::Added],
14203        indoc! {r#"struct Row;
14204                   struct Row1;
14205                   struct Row2;
14206                   struct Row2.1;
14207                   struct Row2.2;
14208                   «ˇ
14209                   struct Row4;
14210                   struct» Row5;
14211                   «struct Row6;
14212                   ˇ»
14213                   struct Row9.1;
14214                   struct Row9.2;
14215                   struct Row9.3;
14216                   struct Row8;
14217                   struct Row9;
14218                   struct Row10;"#},
14219        base_text,
14220        &mut cx,
14221    );
14222
14223    // When carets and selections intersect the addition hunks, those are reverted.
14224    // Adjacent carets got merged.
14225    assert_hunk_revert(
14226        indoc! {r#"struct Row;
14227                   ˇ// something on the top
14228                   struct Row1;
14229                   struct Row2;
14230                   struct Roˇw3.1;
14231                   struct Row2.2;
14232                   struct Row2.3;ˇ
14233
14234                   struct Row4;
14235                   struct ˇRow5.1;
14236                   struct Row5.2;
14237                   struct «Rowˇ»5.3;
14238                   struct Row5;
14239                   struct Row6;
14240                   ˇ
14241                   struct Row9.1;
14242                   struct «Rowˇ»9.2;
14243                   struct «ˇRow»9.3;
14244                   struct Row8;
14245                   struct Row9;
14246                   «ˇ// something on bottom»
14247                   struct Row10;"#},
14248        vec![
14249            DiffHunkStatusKind::Added,
14250            DiffHunkStatusKind::Added,
14251            DiffHunkStatusKind::Added,
14252            DiffHunkStatusKind::Added,
14253            DiffHunkStatusKind::Added,
14254        ],
14255        indoc! {r#"struct Row;
14256                   ˇstruct Row1;
14257                   struct Row2;
14258                   ˇ
14259                   struct Row4;
14260                   ˇstruct Row5;
14261                   struct Row6;
14262                   ˇ
14263                   ˇstruct Row8;
14264                   struct Row9;
14265                   ˇstruct Row10;"#},
14266        base_text,
14267        &mut cx,
14268    );
14269}
14270
14271#[gpui::test]
14272async fn test_modification_reverts(cx: &mut TestAppContext) {
14273    init_test(cx, |_| {});
14274    let mut cx = EditorLspTestContext::new_rust(lsp::ServerCapabilities::default(), cx).await;
14275    let base_text = indoc! {r#"
14276        struct Row;
14277        struct Row1;
14278        struct Row2;
14279
14280        struct Row4;
14281        struct Row5;
14282        struct Row6;
14283
14284        struct Row8;
14285        struct Row9;
14286        struct Row10;"#};
14287
14288    // Modification hunks behave the same as the addition ones.
14289    assert_hunk_revert(
14290        indoc! {r#"struct Row;
14291                   struct Row1;
14292                   struct Row33;
14293                   ˇ
14294                   struct Row4;
14295                   struct Row5;
14296                   struct Row6;
14297                   ˇ
14298                   struct Row99;
14299                   struct Row9;
14300                   struct Row10;"#},
14301        vec![DiffHunkStatusKind::Modified, DiffHunkStatusKind::Modified],
14302        indoc! {r#"struct Row;
14303                   struct Row1;
14304                   struct Row33;
14305                   ˇ
14306                   struct Row4;
14307                   struct Row5;
14308                   struct Row6;
14309                   ˇ
14310                   struct Row99;
14311                   struct Row9;
14312                   struct Row10;"#},
14313        base_text,
14314        &mut cx,
14315    );
14316    assert_hunk_revert(
14317        indoc! {r#"struct Row;
14318                   struct Row1;
14319                   struct Row33;
14320                   «ˇ
14321                   struct Row4;
14322                   struct» Row5;
14323                   «struct Row6;
14324                   ˇ»
14325                   struct Row99;
14326                   struct Row9;
14327                   struct Row10;"#},
14328        vec![DiffHunkStatusKind::Modified, DiffHunkStatusKind::Modified],
14329        indoc! {r#"struct Row;
14330                   struct Row1;
14331                   struct Row33;
14332                   «ˇ
14333                   struct Row4;
14334                   struct» Row5;
14335                   «struct Row6;
14336                   ˇ»
14337                   struct Row99;
14338                   struct Row9;
14339                   struct Row10;"#},
14340        base_text,
14341        &mut cx,
14342    );
14343
14344    assert_hunk_revert(
14345        indoc! {r#"ˇstruct Row1.1;
14346                   struct Row1;
14347                   «ˇstr»uct Row22;
14348
14349                   struct ˇRow44;
14350                   struct Row5;
14351                   struct «Rˇ»ow66;ˇ
14352
14353                   «struˇ»ct Row88;
14354                   struct Row9;
14355                   struct Row1011;ˇ"#},
14356        vec![
14357            DiffHunkStatusKind::Modified,
14358            DiffHunkStatusKind::Modified,
14359            DiffHunkStatusKind::Modified,
14360            DiffHunkStatusKind::Modified,
14361            DiffHunkStatusKind::Modified,
14362            DiffHunkStatusKind::Modified,
14363        ],
14364        indoc! {r#"struct Row;
14365                   ˇstruct Row1;
14366                   struct Row2;
14367                   ˇ
14368                   struct Row4;
14369                   ˇstruct Row5;
14370                   struct Row6;
14371                   ˇ
14372                   struct Row8;
14373                   ˇstruct Row9;
14374                   struct Row10;ˇ"#},
14375        base_text,
14376        &mut cx,
14377    );
14378}
14379
14380#[gpui::test]
14381async fn test_deleting_over_diff_hunk(cx: &mut TestAppContext) {
14382    init_test(cx, |_| {});
14383    let mut cx = EditorLspTestContext::new_rust(lsp::ServerCapabilities::default(), cx).await;
14384    let base_text = indoc! {r#"
14385        one
14386
14387        two
14388        three
14389        "#};
14390
14391    cx.set_head_text(base_text);
14392    cx.set_state("\nˇ\n");
14393    cx.executor().run_until_parked();
14394    cx.update_editor(|editor, _window, cx| {
14395        editor.expand_selected_diff_hunks(cx);
14396    });
14397    cx.executor().run_until_parked();
14398    cx.update_editor(|editor, window, cx| {
14399        editor.backspace(&Default::default(), window, cx);
14400    });
14401    cx.run_until_parked();
14402    cx.assert_state_with_diff(
14403        indoc! {r#"
14404
14405        - two
14406        - threeˇ
14407        +
14408        "#}
14409        .to_string(),
14410    );
14411}
14412
14413#[gpui::test]
14414async fn test_deletion_reverts(cx: &mut TestAppContext) {
14415    init_test(cx, |_| {});
14416    let mut cx = EditorLspTestContext::new_rust(lsp::ServerCapabilities::default(), cx).await;
14417    let base_text = indoc! {r#"struct Row;
14418struct Row1;
14419struct Row2;
14420
14421struct Row4;
14422struct Row5;
14423struct Row6;
14424
14425struct Row8;
14426struct Row9;
14427struct Row10;"#};
14428
14429    // Deletion hunks trigger with carets on adjacent rows, so carets and selections have to stay farther to avoid the revert
14430    assert_hunk_revert(
14431        indoc! {r#"struct Row;
14432                   struct Row2;
14433
14434                   ˇstruct Row4;
14435                   struct Row5;
14436                   struct Row6;
14437                   ˇ
14438                   struct Row8;
14439                   struct Row10;"#},
14440        vec![DiffHunkStatusKind::Deleted, DiffHunkStatusKind::Deleted],
14441        indoc! {r#"struct Row;
14442                   struct Row2;
14443
14444                   ˇstruct Row4;
14445                   struct Row5;
14446                   struct Row6;
14447                   ˇ
14448                   struct Row8;
14449                   struct Row10;"#},
14450        base_text,
14451        &mut cx,
14452    );
14453    assert_hunk_revert(
14454        indoc! {r#"struct Row;
14455                   struct Row2;
14456
14457                   «ˇstruct Row4;
14458                   struct» Row5;
14459                   «struct Row6;
14460                   ˇ»
14461                   struct Row8;
14462                   struct Row10;"#},
14463        vec![DiffHunkStatusKind::Deleted, DiffHunkStatusKind::Deleted],
14464        indoc! {r#"struct Row;
14465                   struct Row2;
14466
14467                   «ˇstruct Row4;
14468                   struct» Row5;
14469                   «struct Row6;
14470                   ˇ»
14471                   struct Row8;
14472                   struct Row10;"#},
14473        base_text,
14474        &mut cx,
14475    );
14476
14477    // Deletion hunks are ephemeral, so it's impossible to place the caret into them — Zed triggers reverts for lines, adjacent to carets and selections.
14478    assert_hunk_revert(
14479        indoc! {r#"struct Row;
14480                   ˇstruct Row2;
14481
14482                   struct Row4;
14483                   struct Row5;
14484                   struct Row6;
14485
14486                   struct Row8;ˇ
14487                   struct Row10;"#},
14488        vec![DiffHunkStatusKind::Deleted, DiffHunkStatusKind::Deleted],
14489        indoc! {r#"struct Row;
14490                   struct Row1;
14491                   ˇstruct Row2;
14492
14493                   struct Row4;
14494                   struct Row5;
14495                   struct Row6;
14496
14497                   struct Row8;ˇ
14498                   struct Row9;
14499                   struct Row10;"#},
14500        base_text,
14501        &mut cx,
14502    );
14503    assert_hunk_revert(
14504        indoc! {r#"struct Row;
14505                   struct Row2«ˇ;
14506                   struct Row4;
14507                   struct» Row5;
14508                   «struct Row6;
14509
14510                   struct Row8;ˇ»
14511                   struct Row10;"#},
14512        vec![
14513            DiffHunkStatusKind::Deleted,
14514            DiffHunkStatusKind::Deleted,
14515            DiffHunkStatusKind::Deleted,
14516        ],
14517        indoc! {r#"struct Row;
14518                   struct Row1;
14519                   struct Row2«ˇ;
14520
14521                   struct Row4;
14522                   struct» Row5;
14523                   «struct Row6;
14524
14525                   struct Row8;ˇ»
14526                   struct Row9;
14527                   struct Row10;"#},
14528        base_text,
14529        &mut cx,
14530    );
14531}
14532
14533#[gpui::test]
14534async fn test_multibuffer_reverts(cx: &mut TestAppContext) {
14535    init_test(cx, |_| {});
14536
14537    let base_text_1 = "aaaa\nbbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj";
14538    let base_text_2 = "llll\nmmmm\nnnnn\noooo\npppp\nqqqq\nrrrr\nssss\ntttt\nuuuu";
14539    let base_text_3 =
14540        "vvvv\nwwww\nxxxx\nyyyy\nzzzz\n{{{{\n||||\n}}}}\n~~~~\n\u{7f}\u{7f}\u{7f}\u{7f}";
14541
14542    let text_1 = edit_first_char_of_every_line(base_text_1);
14543    let text_2 = edit_first_char_of_every_line(base_text_2);
14544    let text_3 = edit_first_char_of_every_line(base_text_3);
14545
14546    let buffer_1 = cx.new(|cx| Buffer::local(text_1.clone(), cx));
14547    let buffer_2 = cx.new(|cx| Buffer::local(text_2.clone(), cx));
14548    let buffer_3 = cx.new(|cx| Buffer::local(text_3.clone(), cx));
14549
14550    let multibuffer = cx.new(|cx| {
14551        let mut multibuffer = MultiBuffer::new(ReadWrite);
14552        multibuffer.push_excerpts(
14553            buffer_1.clone(),
14554            [
14555                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
14556                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
14557                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
14558            ],
14559            cx,
14560        );
14561        multibuffer.push_excerpts(
14562            buffer_2.clone(),
14563            [
14564                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
14565                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
14566                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
14567            ],
14568            cx,
14569        );
14570        multibuffer.push_excerpts(
14571            buffer_3.clone(),
14572            [
14573                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
14574                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
14575                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
14576            ],
14577            cx,
14578        );
14579        multibuffer
14580    });
14581
14582    let fs = FakeFs::new(cx.executor());
14583    let project = Project::test(fs, [path!("/").as_ref()], cx).await;
14584    let (editor, cx) = cx
14585        .add_window_view(|window, cx| build_editor_with_project(project, multibuffer, window, cx));
14586    editor.update_in(cx, |editor, _window, cx| {
14587        for (buffer, diff_base) in [
14588            (buffer_1.clone(), base_text_1),
14589            (buffer_2.clone(), base_text_2),
14590            (buffer_3.clone(), base_text_3),
14591        ] {
14592            let diff = cx.new(|cx| BufferDiff::new_with_base_text(&diff_base, &buffer, cx));
14593            editor
14594                .buffer
14595                .update(cx, |buffer, cx| buffer.add_diff(diff, cx));
14596        }
14597    });
14598    cx.executor().run_until_parked();
14599
14600    editor.update_in(cx, |editor, window, cx| {
14601        assert_eq!(editor.text(cx), "Xaaa\nXbbb\nXccc\n\nXfff\nXggg\n\nXjjj\nXlll\nXmmm\nXnnn\n\nXqqq\nXrrr\n\nXuuu\nXvvv\nXwww\nXxxx\n\nX{{{\nX|||\n\nX\u{7f}\u{7f}\u{7f}");
14602        editor.select_all(&SelectAll, window, cx);
14603        editor.git_restore(&Default::default(), window, cx);
14604    });
14605    cx.executor().run_until_parked();
14606
14607    // When all ranges are selected, all buffer hunks are reverted.
14608    editor.update(cx, |editor, cx| {
14609        assert_eq!(editor.text(cx), "aaaa\nbbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj\n\n\nllll\nmmmm\nnnnn\noooo\npppp\nqqqq\nrrrr\nssss\ntttt\nuuuu\n\n\nvvvv\nwwww\nxxxx\nyyyy\nzzzz\n{{{{\n||||\n}}}}\n~~~~\n\u{7f}\u{7f}\u{7f}\u{7f}\n\n");
14610    });
14611    buffer_1.update(cx, |buffer, _| {
14612        assert_eq!(buffer.text(), base_text_1);
14613    });
14614    buffer_2.update(cx, |buffer, _| {
14615        assert_eq!(buffer.text(), base_text_2);
14616    });
14617    buffer_3.update(cx, |buffer, _| {
14618        assert_eq!(buffer.text(), base_text_3);
14619    });
14620
14621    editor.update_in(cx, |editor, window, cx| {
14622        editor.undo(&Default::default(), window, cx);
14623    });
14624
14625    editor.update_in(cx, |editor, window, cx| {
14626        editor.change_selections(None, window, cx, |s| {
14627            s.select_ranges(Some(Point::new(0, 0)..Point::new(6, 0)));
14628        });
14629        editor.git_restore(&Default::default(), window, cx);
14630    });
14631
14632    // Now, when all ranges selected belong to buffer_1, the revert should succeed,
14633    // but not affect buffer_2 and its related excerpts.
14634    editor.update(cx, |editor, cx| {
14635        assert_eq!(
14636            editor.text(cx),
14637            "aaaa\nbbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj\n\n\nXlll\nXmmm\nXnnn\n\nXqqq\nXrrr\n\nXuuu\nXvvv\nXwww\nXxxx\n\nX{{{\nX|||\n\nX\u{7f}\u{7f}\u{7f}"
14638        );
14639    });
14640    buffer_1.update(cx, |buffer, _| {
14641        assert_eq!(buffer.text(), base_text_1);
14642    });
14643    buffer_2.update(cx, |buffer, _| {
14644        assert_eq!(
14645            buffer.text(),
14646            "Xlll\nXmmm\nXnnn\nXooo\nXppp\nXqqq\nXrrr\nXsss\nXttt\nXuuu"
14647        );
14648    });
14649    buffer_3.update(cx, |buffer, _| {
14650        assert_eq!(
14651            buffer.text(),
14652            "Xvvv\nXwww\nXxxx\nXyyy\nXzzz\nX{{{\nX|||\nX}}}\nX~~~\nX\u{7f}\u{7f}\u{7f}"
14653        );
14654    });
14655
14656    fn edit_first_char_of_every_line(text: &str) -> String {
14657        text.split('\n')
14658            .map(|line| format!("X{}", &line[1..]))
14659            .collect::<Vec<_>>()
14660            .join("\n")
14661    }
14662}
14663
14664#[gpui::test]
14665async fn test_mutlibuffer_in_navigation_history(cx: &mut TestAppContext) {
14666    init_test(cx, |_| {});
14667
14668    let cols = 4;
14669    let rows = 10;
14670    let sample_text_1 = sample_text(rows, cols, 'a');
14671    assert_eq!(
14672        sample_text_1,
14673        "aaaa\nbbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj"
14674    );
14675    let sample_text_2 = sample_text(rows, cols, 'l');
14676    assert_eq!(
14677        sample_text_2,
14678        "llll\nmmmm\nnnnn\noooo\npppp\nqqqq\nrrrr\nssss\ntttt\nuuuu"
14679    );
14680    let sample_text_3 = sample_text(rows, cols, 'v');
14681    assert_eq!(
14682        sample_text_3,
14683        "vvvv\nwwww\nxxxx\nyyyy\nzzzz\n{{{{\n||||\n}}}}\n~~~~\n\u{7f}\u{7f}\u{7f}\u{7f}"
14684    );
14685
14686    let buffer_1 = cx.new(|cx| Buffer::local(sample_text_1.clone(), cx));
14687    let buffer_2 = cx.new(|cx| Buffer::local(sample_text_2.clone(), cx));
14688    let buffer_3 = cx.new(|cx| Buffer::local(sample_text_3.clone(), cx));
14689
14690    let multi_buffer = cx.new(|cx| {
14691        let mut multibuffer = MultiBuffer::new(ReadWrite);
14692        multibuffer.push_excerpts(
14693            buffer_1.clone(),
14694            [
14695                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
14696                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
14697                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
14698            ],
14699            cx,
14700        );
14701        multibuffer.push_excerpts(
14702            buffer_2.clone(),
14703            [
14704                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
14705                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
14706                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
14707            ],
14708            cx,
14709        );
14710        multibuffer.push_excerpts(
14711            buffer_3.clone(),
14712            [
14713                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
14714                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
14715                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
14716            ],
14717            cx,
14718        );
14719        multibuffer
14720    });
14721
14722    let fs = FakeFs::new(cx.executor());
14723    fs.insert_tree(
14724        "/a",
14725        json!({
14726            "main.rs": sample_text_1,
14727            "other.rs": sample_text_2,
14728            "lib.rs": sample_text_3,
14729        }),
14730    )
14731    .await;
14732    let project = Project::test(fs, ["/a".as_ref()], cx).await;
14733    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
14734    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
14735    let multi_buffer_editor = cx.new_window_entity(|window, cx| {
14736        Editor::new(
14737            EditorMode::full(),
14738            multi_buffer,
14739            Some(project.clone()),
14740            window,
14741            cx,
14742        )
14743    });
14744    let multibuffer_item_id = workspace
14745        .update(cx, |workspace, window, cx| {
14746            assert!(
14747                workspace.active_item(cx).is_none(),
14748                "active item should be None before the first item is added"
14749            );
14750            workspace.add_item_to_active_pane(
14751                Box::new(multi_buffer_editor.clone()),
14752                None,
14753                true,
14754                window,
14755                cx,
14756            );
14757            let active_item = workspace
14758                .active_item(cx)
14759                .expect("should have an active item after adding the multi buffer");
14760            assert!(
14761                !active_item.is_singleton(cx),
14762                "A multi buffer was expected to active after adding"
14763            );
14764            active_item.item_id()
14765        })
14766        .unwrap();
14767    cx.executor().run_until_parked();
14768
14769    multi_buffer_editor.update_in(cx, |editor, window, cx| {
14770        editor.change_selections(Some(Autoscroll::Next), window, cx, |s| {
14771            s.select_ranges(Some(1..2))
14772        });
14773        editor.open_excerpts(&OpenExcerpts, window, cx);
14774    });
14775    cx.executor().run_until_parked();
14776    let first_item_id = workspace
14777        .update(cx, |workspace, window, cx| {
14778            let active_item = workspace
14779                .active_item(cx)
14780                .expect("should have an active item after navigating into the 1st buffer");
14781            let first_item_id = active_item.item_id();
14782            assert_ne!(
14783                first_item_id, multibuffer_item_id,
14784                "Should navigate into the 1st buffer and activate it"
14785            );
14786            assert!(
14787                active_item.is_singleton(cx),
14788                "New active item should be a singleton buffer"
14789            );
14790            assert_eq!(
14791                active_item
14792                    .act_as::<Editor>(cx)
14793                    .expect("should have navigated into an editor for the 1st buffer")
14794                    .read(cx)
14795                    .text(cx),
14796                sample_text_1
14797            );
14798
14799            workspace
14800                .go_back(workspace.active_pane().downgrade(), window, cx)
14801                .detach_and_log_err(cx);
14802
14803            first_item_id
14804        })
14805        .unwrap();
14806    cx.executor().run_until_parked();
14807    workspace
14808        .update(cx, |workspace, _, cx| {
14809            let active_item = workspace
14810                .active_item(cx)
14811                .expect("should have an active item after navigating back");
14812            assert_eq!(
14813                active_item.item_id(),
14814                multibuffer_item_id,
14815                "Should navigate back to the multi buffer"
14816            );
14817            assert!(!active_item.is_singleton(cx));
14818        })
14819        .unwrap();
14820
14821    multi_buffer_editor.update_in(cx, |editor, window, cx| {
14822        editor.change_selections(Some(Autoscroll::Next), window, cx, |s| {
14823            s.select_ranges(Some(39..40))
14824        });
14825        editor.open_excerpts(&OpenExcerpts, window, cx);
14826    });
14827    cx.executor().run_until_parked();
14828    let second_item_id = workspace
14829        .update(cx, |workspace, window, cx| {
14830            let active_item = workspace
14831                .active_item(cx)
14832                .expect("should have an active item after navigating into the 2nd buffer");
14833            let second_item_id = active_item.item_id();
14834            assert_ne!(
14835                second_item_id, multibuffer_item_id,
14836                "Should navigate away from the multibuffer"
14837            );
14838            assert_ne!(
14839                second_item_id, first_item_id,
14840                "Should navigate into the 2nd buffer and activate it"
14841            );
14842            assert!(
14843                active_item.is_singleton(cx),
14844                "New active item should be a singleton buffer"
14845            );
14846            assert_eq!(
14847                active_item
14848                    .act_as::<Editor>(cx)
14849                    .expect("should have navigated into an editor")
14850                    .read(cx)
14851                    .text(cx),
14852                sample_text_2
14853            );
14854
14855            workspace
14856                .go_back(workspace.active_pane().downgrade(), window, cx)
14857                .detach_and_log_err(cx);
14858
14859            second_item_id
14860        })
14861        .unwrap();
14862    cx.executor().run_until_parked();
14863    workspace
14864        .update(cx, |workspace, _, cx| {
14865            let active_item = workspace
14866                .active_item(cx)
14867                .expect("should have an active item after navigating back from the 2nd buffer");
14868            assert_eq!(
14869                active_item.item_id(),
14870                multibuffer_item_id,
14871                "Should navigate back from the 2nd buffer to the multi buffer"
14872            );
14873            assert!(!active_item.is_singleton(cx));
14874        })
14875        .unwrap();
14876
14877    multi_buffer_editor.update_in(cx, |editor, window, cx| {
14878        editor.change_selections(Some(Autoscroll::Next), window, cx, |s| {
14879            s.select_ranges(Some(70..70))
14880        });
14881        editor.open_excerpts(&OpenExcerpts, window, cx);
14882    });
14883    cx.executor().run_until_parked();
14884    workspace
14885        .update(cx, |workspace, window, cx| {
14886            let active_item = workspace
14887                .active_item(cx)
14888                .expect("should have an active item after navigating into the 3rd buffer");
14889            let third_item_id = active_item.item_id();
14890            assert_ne!(
14891                third_item_id, multibuffer_item_id,
14892                "Should navigate into the 3rd buffer and activate it"
14893            );
14894            assert_ne!(third_item_id, first_item_id);
14895            assert_ne!(third_item_id, second_item_id);
14896            assert!(
14897                active_item.is_singleton(cx),
14898                "New active item should be a singleton buffer"
14899            );
14900            assert_eq!(
14901                active_item
14902                    .act_as::<Editor>(cx)
14903                    .expect("should have navigated into an editor")
14904                    .read(cx)
14905                    .text(cx),
14906                sample_text_3
14907            );
14908
14909            workspace
14910                .go_back(workspace.active_pane().downgrade(), window, cx)
14911                .detach_and_log_err(cx);
14912        })
14913        .unwrap();
14914    cx.executor().run_until_parked();
14915    workspace
14916        .update(cx, |workspace, _, cx| {
14917            let active_item = workspace
14918                .active_item(cx)
14919                .expect("should have an active item after navigating back from the 3rd buffer");
14920            assert_eq!(
14921                active_item.item_id(),
14922                multibuffer_item_id,
14923                "Should navigate back from the 3rd buffer to the multi buffer"
14924            );
14925            assert!(!active_item.is_singleton(cx));
14926        })
14927        .unwrap();
14928}
14929
14930#[gpui::test]
14931async fn test_toggle_selected_diff_hunks(executor: BackgroundExecutor, cx: &mut TestAppContext) {
14932    init_test(cx, |_| {});
14933
14934    let mut cx = EditorTestContext::new(cx).await;
14935
14936    let diff_base = r#"
14937        use some::mod;
14938
14939        const A: u32 = 42;
14940
14941        fn main() {
14942            println!("hello");
14943
14944            println!("world");
14945        }
14946        "#
14947    .unindent();
14948
14949    cx.set_state(
14950        &r#"
14951        use some::modified;
14952
14953        ˇ
14954        fn main() {
14955            println!("hello there");
14956
14957            println!("around the");
14958            println!("world");
14959        }
14960        "#
14961        .unindent(),
14962    );
14963
14964    cx.set_head_text(&diff_base);
14965    executor.run_until_parked();
14966
14967    cx.update_editor(|editor, window, cx| {
14968        editor.go_to_next_hunk(&GoToHunk, window, cx);
14969        editor.toggle_selected_diff_hunks(&ToggleSelectedDiffHunks, window, cx);
14970    });
14971    executor.run_until_parked();
14972    cx.assert_state_with_diff(
14973        r#"
14974          use some::modified;
14975
14976
14977          fn main() {
14978        -     println!("hello");
14979        + ˇ    println!("hello there");
14980
14981              println!("around the");
14982              println!("world");
14983          }
14984        "#
14985        .unindent(),
14986    );
14987
14988    cx.update_editor(|editor, window, cx| {
14989        for _ in 0..2 {
14990            editor.go_to_next_hunk(&GoToHunk, window, cx);
14991            editor.toggle_selected_diff_hunks(&ToggleSelectedDiffHunks, window, cx);
14992        }
14993    });
14994    executor.run_until_parked();
14995    cx.assert_state_with_diff(
14996        r#"
14997        - use some::mod;
14998        + ˇuse some::modified;
14999
15000
15001          fn main() {
15002        -     println!("hello");
15003        +     println!("hello there");
15004
15005        +     println!("around the");
15006              println!("world");
15007          }
15008        "#
15009        .unindent(),
15010    );
15011
15012    cx.update_editor(|editor, window, cx| {
15013        editor.go_to_next_hunk(&GoToHunk, window, cx);
15014        editor.toggle_selected_diff_hunks(&ToggleSelectedDiffHunks, window, cx);
15015    });
15016    executor.run_until_parked();
15017    cx.assert_state_with_diff(
15018        r#"
15019        - use some::mod;
15020        + use some::modified;
15021
15022        - const A: u32 = 42;
15023          ˇ
15024          fn main() {
15025        -     println!("hello");
15026        +     println!("hello there");
15027
15028        +     println!("around the");
15029              println!("world");
15030          }
15031        "#
15032        .unindent(),
15033    );
15034
15035    cx.update_editor(|editor, window, cx| {
15036        editor.cancel(&Cancel, window, cx);
15037    });
15038
15039    cx.assert_state_with_diff(
15040        r#"
15041          use some::modified;
15042
15043          ˇ
15044          fn main() {
15045              println!("hello there");
15046
15047              println!("around the");
15048              println!("world");
15049          }
15050        "#
15051        .unindent(),
15052    );
15053}
15054
15055#[gpui::test]
15056async fn test_diff_base_change_with_expanded_diff_hunks(
15057    executor: BackgroundExecutor,
15058    cx: &mut TestAppContext,
15059) {
15060    init_test(cx, |_| {});
15061
15062    let mut cx = EditorTestContext::new(cx).await;
15063
15064    let diff_base = r#"
15065        use some::mod1;
15066        use some::mod2;
15067
15068        const A: u32 = 42;
15069        const B: u32 = 42;
15070        const C: u32 = 42;
15071
15072        fn main() {
15073            println!("hello");
15074
15075            println!("world");
15076        }
15077        "#
15078    .unindent();
15079
15080    cx.set_state(
15081        &r#"
15082        use some::mod2;
15083
15084        const A: u32 = 42;
15085        const C: u32 = 42;
15086
15087        fn main(ˇ) {
15088            //println!("hello");
15089
15090            println!("world");
15091            //
15092            //
15093        }
15094        "#
15095        .unindent(),
15096    );
15097
15098    cx.set_head_text(&diff_base);
15099    executor.run_until_parked();
15100
15101    cx.update_editor(|editor, window, cx| {
15102        editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
15103    });
15104    executor.run_until_parked();
15105    cx.assert_state_with_diff(
15106        r#"
15107        - use some::mod1;
15108          use some::mod2;
15109
15110          const A: u32 = 42;
15111        - const B: u32 = 42;
15112          const C: u32 = 42;
15113
15114          fn main(ˇ) {
15115        -     println!("hello");
15116        +     //println!("hello");
15117
15118              println!("world");
15119        +     //
15120        +     //
15121          }
15122        "#
15123        .unindent(),
15124    );
15125
15126    cx.set_head_text("new diff base!");
15127    executor.run_until_parked();
15128    cx.assert_state_with_diff(
15129        r#"
15130        - new diff base!
15131        + use some::mod2;
15132        +
15133        + const A: u32 = 42;
15134        + const C: u32 = 42;
15135        +
15136        + fn main(ˇ) {
15137        +     //println!("hello");
15138        +
15139        +     println!("world");
15140        +     //
15141        +     //
15142        + }
15143        "#
15144        .unindent(),
15145    );
15146}
15147
15148#[gpui::test]
15149async fn test_toggle_diff_expand_in_multi_buffer(cx: &mut TestAppContext) {
15150    init_test(cx, |_| {});
15151
15152    let file_1_old = "aaa\nbbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj";
15153    let file_1_new = "aaa\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj";
15154    let file_2_old = "lll\nmmm\nnnn\nooo\nppp\nqqq\nrrr\nsss\nttt\nuuu";
15155    let file_2_new = "lll\nmmm\nNNN\nooo\nppp\nqqq\nrrr\nsss\nttt\nuuu";
15156    let file_3_old = "111\n222\n333\n444\n555\n777\n888\n999\n000\n!!!";
15157    let file_3_new = "111\n222\n333\n444\n555\n666\n777\n888\n999\n000\n!!!";
15158
15159    let buffer_1 = cx.new(|cx| Buffer::local(file_1_new.to_string(), cx));
15160    let buffer_2 = cx.new(|cx| Buffer::local(file_2_new.to_string(), cx));
15161    let buffer_3 = cx.new(|cx| Buffer::local(file_3_new.to_string(), cx));
15162
15163    let multi_buffer = cx.new(|cx| {
15164        let mut multibuffer = MultiBuffer::new(ReadWrite);
15165        multibuffer.push_excerpts(
15166            buffer_1.clone(),
15167            [
15168                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
15169                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
15170                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 3)),
15171            ],
15172            cx,
15173        );
15174        multibuffer.push_excerpts(
15175            buffer_2.clone(),
15176            [
15177                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
15178                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
15179                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 3)),
15180            ],
15181            cx,
15182        );
15183        multibuffer.push_excerpts(
15184            buffer_3.clone(),
15185            [
15186                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
15187                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
15188                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 3)),
15189            ],
15190            cx,
15191        );
15192        multibuffer
15193    });
15194
15195    let editor =
15196        cx.add_window(|window, cx| Editor::new(EditorMode::full(), multi_buffer, None, window, cx));
15197    editor
15198        .update(cx, |editor, _window, cx| {
15199            for (buffer, diff_base) in [
15200                (buffer_1.clone(), file_1_old),
15201                (buffer_2.clone(), file_2_old),
15202                (buffer_3.clone(), file_3_old),
15203            ] {
15204                let diff = cx.new(|cx| BufferDiff::new_with_base_text(&diff_base, &buffer, cx));
15205                editor
15206                    .buffer
15207                    .update(cx, |buffer, cx| buffer.add_diff(diff, cx));
15208            }
15209        })
15210        .unwrap();
15211
15212    let mut cx = EditorTestContext::for_editor(editor, cx).await;
15213    cx.run_until_parked();
15214
15215    cx.assert_editor_state(
15216        &"
15217            ˇaaa
15218            ccc
15219            ddd
15220
15221            ggg
15222            hhh
15223
15224
15225            lll
15226            mmm
15227            NNN
15228
15229            qqq
15230            rrr
15231
15232            uuu
15233            111
15234            222
15235            333
15236
15237            666
15238            777
15239
15240            000
15241            !!!"
15242        .unindent(),
15243    );
15244
15245    cx.update_editor(|editor, window, cx| {
15246        editor.select_all(&SelectAll, window, cx);
15247        editor.toggle_selected_diff_hunks(&ToggleSelectedDiffHunks, window, cx);
15248    });
15249    cx.executor().run_until_parked();
15250
15251    cx.assert_state_with_diff(
15252        "
15253            «aaa
15254          - bbb
15255            ccc
15256            ddd
15257
15258            ggg
15259            hhh
15260
15261
15262            lll
15263            mmm
15264          - nnn
15265          + NNN
15266
15267            qqq
15268            rrr
15269
15270            uuu
15271            111
15272            222
15273            333
15274
15275          + 666
15276            777
15277
15278            000
15279            !!!ˇ»"
15280            .unindent(),
15281    );
15282}
15283
15284#[gpui::test]
15285async fn test_expand_diff_hunk_at_excerpt_boundary(cx: &mut TestAppContext) {
15286    init_test(cx, |_| {});
15287
15288    let base = "aaa\nbbb\nccc\nddd\neee\nfff\nggg\n";
15289    let text = "aaa\nBBB\nBB2\nccc\nDDD\nEEE\nfff\nggg\nhhh\niii\n";
15290
15291    let buffer = cx.new(|cx| Buffer::local(text.to_string(), cx));
15292    let multi_buffer = cx.new(|cx| {
15293        let mut multibuffer = MultiBuffer::new(ReadWrite);
15294        multibuffer.push_excerpts(
15295            buffer.clone(),
15296            [
15297                ExcerptRange::new(Point::new(0, 0)..Point::new(2, 0)),
15298                ExcerptRange::new(Point::new(4, 0)..Point::new(7, 0)),
15299                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 0)),
15300            ],
15301            cx,
15302        );
15303        multibuffer
15304    });
15305
15306    let editor =
15307        cx.add_window(|window, cx| Editor::new(EditorMode::full(), multi_buffer, None, window, cx));
15308    editor
15309        .update(cx, |editor, _window, cx| {
15310            let diff = cx.new(|cx| BufferDiff::new_with_base_text(base, &buffer, cx));
15311            editor
15312                .buffer
15313                .update(cx, |buffer, cx| buffer.add_diff(diff, cx))
15314        })
15315        .unwrap();
15316
15317    let mut cx = EditorTestContext::for_editor(editor, cx).await;
15318    cx.run_until_parked();
15319
15320    cx.update_editor(|editor, window, cx| {
15321        editor.expand_all_diff_hunks(&Default::default(), window, cx)
15322    });
15323    cx.executor().run_until_parked();
15324
15325    // When the start of a hunk coincides with the start of its excerpt,
15326    // the hunk is expanded. When the start of a a hunk is earlier than
15327    // the start of its excerpt, the hunk is not expanded.
15328    cx.assert_state_with_diff(
15329        "
15330            ˇaaa
15331          - bbb
15332          + BBB
15333
15334          - ddd
15335          - eee
15336          + DDD
15337          + EEE
15338            fff
15339
15340            iii
15341        "
15342        .unindent(),
15343    );
15344}
15345
15346#[gpui::test]
15347async fn test_edits_around_expanded_insertion_hunks(
15348    executor: BackgroundExecutor,
15349    cx: &mut TestAppContext,
15350) {
15351    init_test(cx, |_| {});
15352
15353    let mut cx = EditorTestContext::new(cx).await;
15354
15355    let diff_base = r#"
15356        use some::mod1;
15357        use some::mod2;
15358
15359        const A: u32 = 42;
15360
15361        fn main() {
15362            println!("hello");
15363
15364            println!("world");
15365        }
15366        "#
15367    .unindent();
15368    executor.run_until_parked();
15369    cx.set_state(
15370        &r#"
15371        use some::mod1;
15372        use some::mod2;
15373
15374        const A: u32 = 42;
15375        const B: u32 = 42;
15376        const C: u32 = 42;
15377        ˇ
15378
15379        fn main() {
15380            println!("hello");
15381
15382            println!("world");
15383        }
15384        "#
15385        .unindent(),
15386    );
15387
15388    cx.set_head_text(&diff_base);
15389    executor.run_until_parked();
15390
15391    cx.update_editor(|editor, window, cx| {
15392        editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
15393    });
15394    executor.run_until_parked();
15395
15396    cx.assert_state_with_diff(
15397        r#"
15398        use some::mod1;
15399        use some::mod2;
15400
15401        const A: u32 = 42;
15402      + const B: u32 = 42;
15403      + const C: u32 = 42;
15404      + ˇ
15405
15406        fn main() {
15407            println!("hello");
15408
15409            println!("world");
15410        }
15411      "#
15412        .unindent(),
15413    );
15414
15415    cx.update_editor(|editor, window, cx| editor.handle_input("const D: u32 = 42;\n", window, cx));
15416    executor.run_until_parked();
15417
15418    cx.assert_state_with_diff(
15419        r#"
15420        use some::mod1;
15421        use some::mod2;
15422
15423        const A: u32 = 42;
15424      + const B: u32 = 42;
15425      + const C: u32 = 42;
15426      + const D: u32 = 42;
15427      + ˇ
15428
15429        fn main() {
15430            println!("hello");
15431
15432            println!("world");
15433        }
15434      "#
15435        .unindent(),
15436    );
15437
15438    cx.update_editor(|editor, window, cx| editor.handle_input("const E: u32 = 42;\n", window, cx));
15439    executor.run_until_parked();
15440
15441    cx.assert_state_with_diff(
15442        r#"
15443        use some::mod1;
15444        use some::mod2;
15445
15446        const A: u32 = 42;
15447      + const B: u32 = 42;
15448      + const C: u32 = 42;
15449      + const D: u32 = 42;
15450      + const E: u32 = 42;
15451      + ˇ
15452
15453        fn main() {
15454            println!("hello");
15455
15456            println!("world");
15457        }
15458      "#
15459        .unindent(),
15460    );
15461
15462    cx.update_editor(|editor, window, cx| {
15463        editor.delete_line(&DeleteLine, window, cx);
15464    });
15465    executor.run_until_parked();
15466
15467    cx.assert_state_with_diff(
15468        r#"
15469        use some::mod1;
15470        use some::mod2;
15471
15472        const A: u32 = 42;
15473      + const B: u32 = 42;
15474      + const C: u32 = 42;
15475      + const D: u32 = 42;
15476      + const E: u32 = 42;
15477        ˇ
15478        fn main() {
15479            println!("hello");
15480
15481            println!("world");
15482        }
15483      "#
15484        .unindent(),
15485    );
15486
15487    cx.update_editor(|editor, window, cx| {
15488        editor.move_up(&MoveUp, window, cx);
15489        editor.delete_line(&DeleteLine, window, cx);
15490        editor.move_up(&MoveUp, window, cx);
15491        editor.delete_line(&DeleteLine, window, cx);
15492        editor.move_up(&MoveUp, window, cx);
15493        editor.delete_line(&DeleteLine, window, cx);
15494    });
15495    executor.run_until_parked();
15496    cx.assert_state_with_diff(
15497        r#"
15498        use some::mod1;
15499        use some::mod2;
15500
15501        const A: u32 = 42;
15502      + const B: u32 = 42;
15503        ˇ
15504        fn main() {
15505            println!("hello");
15506
15507            println!("world");
15508        }
15509      "#
15510        .unindent(),
15511    );
15512
15513    cx.update_editor(|editor, window, cx| {
15514        editor.select_up_by_lines(&SelectUpByLines { lines: 5 }, window, cx);
15515        editor.delete_line(&DeleteLine, window, cx);
15516    });
15517    executor.run_until_parked();
15518    cx.assert_state_with_diff(
15519        r#"
15520        ˇ
15521        fn main() {
15522            println!("hello");
15523
15524            println!("world");
15525        }
15526      "#
15527        .unindent(),
15528    );
15529}
15530
15531#[gpui::test]
15532async fn test_toggling_adjacent_diff_hunks(cx: &mut TestAppContext) {
15533    init_test(cx, |_| {});
15534
15535    let mut cx = EditorTestContext::new(cx).await;
15536    cx.set_head_text(indoc! { "
15537        one
15538        two
15539        three
15540        four
15541        five
15542        "
15543    });
15544    cx.set_state(indoc! { "
15545        one
15546        ˇthree
15547        five
15548    "});
15549    cx.run_until_parked();
15550    cx.update_editor(|editor, window, cx| {
15551        editor.toggle_selected_diff_hunks(&Default::default(), window, cx);
15552    });
15553    cx.assert_state_with_diff(
15554        indoc! { "
15555        one
15556      - two
15557        ˇthree
15558      - four
15559        five
15560    "}
15561        .to_string(),
15562    );
15563    cx.update_editor(|editor, window, cx| {
15564        editor.toggle_selected_diff_hunks(&Default::default(), window, cx);
15565    });
15566
15567    cx.assert_state_with_diff(
15568        indoc! { "
15569        one
15570        ˇthree
15571        five
15572    "}
15573        .to_string(),
15574    );
15575
15576    cx.set_state(indoc! { "
15577        one
15578        ˇTWO
15579        three
15580        four
15581        five
15582    "});
15583    cx.run_until_parked();
15584    cx.update_editor(|editor, window, cx| {
15585        editor.toggle_selected_diff_hunks(&Default::default(), window, cx);
15586    });
15587
15588    cx.assert_state_with_diff(
15589        indoc! { "
15590            one
15591          - two
15592          + ˇTWO
15593            three
15594            four
15595            five
15596        "}
15597        .to_string(),
15598    );
15599    cx.update_editor(|editor, window, cx| {
15600        editor.move_up(&Default::default(), window, cx);
15601        editor.toggle_selected_diff_hunks(&Default::default(), window, cx);
15602    });
15603    cx.assert_state_with_diff(
15604        indoc! { "
15605            one
15606            ˇTWO
15607            three
15608            four
15609            five
15610        "}
15611        .to_string(),
15612    );
15613}
15614
15615#[gpui::test]
15616async fn test_edits_around_expanded_deletion_hunks(
15617    executor: BackgroundExecutor,
15618    cx: &mut TestAppContext,
15619) {
15620    init_test(cx, |_| {});
15621
15622    let mut cx = EditorTestContext::new(cx).await;
15623
15624    let diff_base = r#"
15625        use some::mod1;
15626        use some::mod2;
15627
15628        const A: u32 = 42;
15629        const B: u32 = 42;
15630        const C: u32 = 42;
15631
15632
15633        fn main() {
15634            println!("hello");
15635
15636            println!("world");
15637        }
15638    "#
15639    .unindent();
15640    executor.run_until_parked();
15641    cx.set_state(
15642        &r#"
15643        use some::mod1;
15644        use some::mod2;
15645
15646        ˇconst B: u32 = 42;
15647        const C: u32 = 42;
15648
15649
15650        fn main() {
15651            println!("hello");
15652
15653            println!("world");
15654        }
15655        "#
15656        .unindent(),
15657    );
15658
15659    cx.set_head_text(&diff_base);
15660    executor.run_until_parked();
15661
15662    cx.update_editor(|editor, window, cx| {
15663        editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
15664    });
15665    executor.run_until_parked();
15666
15667    cx.assert_state_with_diff(
15668        r#"
15669        use some::mod1;
15670        use some::mod2;
15671
15672      - const A: u32 = 42;
15673        ˇconst B: u32 = 42;
15674        const C: u32 = 42;
15675
15676
15677        fn main() {
15678            println!("hello");
15679
15680            println!("world");
15681        }
15682      "#
15683        .unindent(),
15684    );
15685
15686    cx.update_editor(|editor, window, cx| {
15687        editor.delete_line(&DeleteLine, window, cx);
15688    });
15689    executor.run_until_parked();
15690    cx.assert_state_with_diff(
15691        r#"
15692        use some::mod1;
15693        use some::mod2;
15694
15695      - const A: u32 = 42;
15696      - const B: u32 = 42;
15697        ˇconst C: u32 = 42;
15698
15699
15700        fn main() {
15701            println!("hello");
15702
15703            println!("world");
15704        }
15705      "#
15706        .unindent(),
15707    );
15708
15709    cx.update_editor(|editor, window, cx| {
15710        editor.delete_line(&DeleteLine, window, cx);
15711    });
15712    executor.run_until_parked();
15713    cx.assert_state_with_diff(
15714        r#"
15715        use some::mod1;
15716        use some::mod2;
15717
15718      - const A: u32 = 42;
15719      - const B: u32 = 42;
15720      - const C: u32 = 42;
15721        ˇ
15722
15723        fn main() {
15724            println!("hello");
15725
15726            println!("world");
15727        }
15728      "#
15729        .unindent(),
15730    );
15731
15732    cx.update_editor(|editor, window, cx| {
15733        editor.handle_input("replacement", window, cx);
15734    });
15735    executor.run_until_parked();
15736    cx.assert_state_with_diff(
15737        r#"
15738        use some::mod1;
15739        use some::mod2;
15740
15741      - const A: u32 = 42;
15742      - const B: u32 = 42;
15743      - const C: u32 = 42;
15744      -
15745      + replacementˇ
15746
15747        fn main() {
15748            println!("hello");
15749
15750            println!("world");
15751        }
15752      "#
15753        .unindent(),
15754    );
15755}
15756
15757#[gpui::test]
15758async fn test_backspace_after_deletion_hunk(executor: BackgroundExecutor, cx: &mut TestAppContext) {
15759    init_test(cx, |_| {});
15760
15761    let mut cx = EditorTestContext::new(cx).await;
15762
15763    let base_text = r#"
15764        one
15765        two
15766        three
15767        four
15768        five
15769    "#
15770    .unindent();
15771    executor.run_until_parked();
15772    cx.set_state(
15773        &r#"
15774        one
15775        two
15776        fˇour
15777        five
15778        "#
15779        .unindent(),
15780    );
15781
15782    cx.set_head_text(&base_text);
15783    executor.run_until_parked();
15784
15785    cx.update_editor(|editor, window, cx| {
15786        editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
15787    });
15788    executor.run_until_parked();
15789
15790    cx.assert_state_with_diff(
15791        r#"
15792          one
15793          two
15794        - three
15795          fˇour
15796          five
15797        "#
15798        .unindent(),
15799    );
15800
15801    cx.update_editor(|editor, window, cx| {
15802        editor.backspace(&Backspace, window, cx);
15803        editor.backspace(&Backspace, window, cx);
15804    });
15805    executor.run_until_parked();
15806    cx.assert_state_with_diff(
15807        r#"
15808          one
15809          two
15810        - threeˇ
15811        - four
15812        + our
15813          five
15814        "#
15815        .unindent(),
15816    );
15817}
15818
15819#[gpui::test]
15820async fn test_edit_after_expanded_modification_hunk(
15821    executor: BackgroundExecutor,
15822    cx: &mut TestAppContext,
15823) {
15824    init_test(cx, |_| {});
15825
15826    let mut cx = EditorTestContext::new(cx).await;
15827
15828    let diff_base = r#"
15829        use some::mod1;
15830        use some::mod2;
15831
15832        const A: u32 = 42;
15833        const B: u32 = 42;
15834        const C: u32 = 42;
15835        const D: u32 = 42;
15836
15837
15838        fn main() {
15839            println!("hello");
15840
15841            println!("world");
15842        }"#
15843    .unindent();
15844
15845    cx.set_state(
15846        &r#"
15847        use some::mod1;
15848        use some::mod2;
15849
15850        const A: u32 = 42;
15851        const B: u32 = 42;
15852        const C: u32 = 43ˇ
15853        const D: u32 = 42;
15854
15855
15856        fn main() {
15857            println!("hello");
15858
15859            println!("world");
15860        }"#
15861        .unindent(),
15862    );
15863
15864    cx.set_head_text(&diff_base);
15865    executor.run_until_parked();
15866    cx.update_editor(|editor, window, cx| {
15867        editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
15868    });
15869    executor.run_until_parked();
15870
15871    cx.assert_state_with_diff(
15872        r#"
15873        use some::mod1;
15874        use some::mod2;
15875
15876        const A: u32 = 42;
15877        const B: u32 = 42;
15878      - const C: u32 = 42;
15879      + const C: u32 = 43ˇ
15880        const D: u32 = 42;
15881
15882
15883        fn main() {
15884            println!("hello");
15885
15886            println!("world");
15887        }"#
15888        .unindent(),
15889    );
15890
15891    cx.update_editor(|editor, window, cx| {
15892        editor.handle_input("\nnew_line\n", window, cx);
15893    });
15894    executor.run_until_parked();
15895
15896    cx.assert_state_with_diff(
15897        r#"
15898        use some::mod1;
15899        use some::mod2;
15900
15901        const A: u32 = 42;
15902        const B: u32 = 42;
15903      - const C: u32 = 42;
15904      + const C: u32 = 43
15905      + new_line
15906      + ˇ
15907        const D: u32 = 42;
15908
15909
15910        fn main() {
15911            println!("hello");
15912
15913            println!("world");
15914        }"#
15915        .unindent(),
15916    );
15917}
15918
15919#[gpui::test]
15920async fn test_stage_and_unstage_added_file_hunk(
15921    executor: BackgroundExecutor,
15922    cx: &mut TestAppContext,
15923) {
15924    init_test(cx, |_| {});
15925
15926    let mut cx = EditorTestContext::new(cx).await;
15927    cx.update_editor(|editor, _, cx| {
15928        editor.set_expand_all_diff_hunks(cx);
15929    });
15930
15931    let working_copy = r#"
15932            ˇfn main() {
15933                println!("hello, world!");
15934            }
15935        "#
15936    .unindent();
15937
15938    cx.set_state(&working_copy);
15939    executor.run_until_parked();
15940
15941    cx.assert_state_with_diff(
15942        r#"
15943            + ˇfn main() {
15944            +     println!("hello, world!");
15945            + }
15946        "#
15947        .unindent(),
15948    );
15949    cx.assert_index_text(None);
15950
15951    cx.update_editor(|editor, window, cx| {
15952        editor.toggle_staged_selected_diff_hunks(&Default::default(), window, cx);
15953    });
15954    executor.run_until_parked();
15955    cx.assert_index_text(Some(&working_copy.replace("ˇ", "")));
15956    cx.assert_state_with_diff(
15957        r#"
15958            + ˇfn main() {
15959            +     println!("hello, world!");
15960            + }
15961        "#
15962        .unindent(),
15963    );
15964
15965    cx.update_editor(|editor, window, cx| {
15966        editor.toggle_staged_selected_diff_hunks(&Default::default(), window, cx);
15967    });
15968    executor.run_until_parked();
15969    cx.assert_index_text(None);
15970}
15971
15972async fn setup_indent_guides_editor(
15973    text: &str,
15974    cx: &mut TestAppContext,
15975) -> (BufferId, EditorTestContext) {
15976    init_test(cx, |_| {});
15977
15978    let mut cx = EditorTestContext::new(cx).await;
15979
15980    let buffer_id = cx.update_editor(|editor, window, cx| {
15981        editor.set_text(text, window, cx);
15982        let buffer_ids = editor.buffer().read(cx).excerpt_buffer_ids();
15983
15984        buffer_ids[0]
15985    });
15986
15987    (buffer_id, cx)
15988}
15989
15990fn assert_indent_guides(
15991    range: Range<u32>,
15992    expected: Vec<IndentGuide>,
15993    active_indices: Option<Vec<usize>>,
15994    cx: &mut EditorTestContext,
15995) {
15996    let indent_guides = cx.update_editor(|editor, window, cx| {
15997        let snapshot = editor.snapshot(window, cx).display_snapshot;
15998        let mut indent_guides: Vec<_> = crate::indent_guides::indent_guides_in_range(
15999            editor,
16000            MultiBufferRow(range.start)..MultiBufferRow(range.end),
16001            true,
16002            &snapshot,
16003            cx,
16004        );
16005
16006        indent_guides.sort_by(|a, b| {
16007            a.depth.cmp(&b.depth).then(
16008                a.start_row
16009                    .cmp(&b.start_row)
16010                    .then(a.end_row.cmp(&b.end_row)),
16011            )
16012        });
16013        indent_guides
16014    });
16015
16016    if let Some(expected) = active_indices {
16017        let active_indices = cx.update_editor(|editor, window, cx| {
16018            let snapshot = editor.snapshot(window, cx).display_snapshot;
16019            editor.find_active_indent_guide_indices(&indent_guides, &snapshot, window, cx)
16020        });
16021
16022        assert_eq!(
16023            active_indices.unwrap().into_iter().collect::<Vec<_>>(),
16024            expected,
16025            "Active indent guide indices do not match"
16026        );
16027    }
16028
16029    assert_eq!(indent_guides, expected, "Indent guides do not match");
16030}
16031
16032fn indent_guide(buffer_id: BufferId, start_row: u32, end_row: u32, depth: u32) -> IndentGuide {
16033    IndentGuide {
16034        buffer_id,
16035        start_row: MultiBufferRow(start_row),
16036        end_row: MultiBufferRow(end_row),
16037        depth,
16038        tab_size: 4,
16039        settings: IndentGuideSettings {
16040            enabled: true,
16041            line_width: 1,
16042            active_line_width: 1,
16043            ..Default::default()
16044        },
16045    }
16046}
16047
16048#[gpui::test]
16049async fn test_indent_guide_single_line(cx: &mut TestAppContext) {
16050    let (buffer_id, mut cx) = setup_indent_guides_editor(
16051        &"
16052    fn main() {
16053        let a = 1;
16054    }"
16055        .unindent(),
16056        cx,
16057    )
16058    .await;
16059
16060    assert_indent_guides(0..3, vec![indent_guide(buffer_id, 1, 1, 0)], None, &mut cx);
16061}
16062
16063#[gpui::test]
16064async fn test_indent_guide_simple_block(cx: &mut TestAppContext) {
16065    let (buffer_id, mut cx) = setup_indent_guides_editor(
16066        &"
16067    fn main() {
16068        let a = 1;
16069        let b = 2;
16070    }"
16071        .unindent(),
16072        cx,
16073    )
16074    .await;
16075
16076    assert_indent_guides(0..4, vec![indent_guide(buffer_id, 1, 2, 0)], None, &mut cx);
16077}
16078
16079#[gpui::test]
16080async fn test_indent_guide_nested(cx: &mut TestAppContext) {
16081    let (buffer_id, mut cx) = setup_indent_guides_editor(
16082        &"
16083    fn main() {
16084        let a = 1;
16085        if a == 3 {
16086            let b = 2;
16087        } else {
16088            let c = 3;
16089        }
16090    }"
16091        .unindent(),
16092        cx,
16093    )
16094    .await;
16095
16096    assert_indent_guides(
16097        0..8,
16098        vec![
16099            indent_guide(buffer_id, 1, 6, 0),
16100            indent_guide(buffer_id, 3, 3, 1),
16101            indent_guide(buffer_id, 5, 5, 1),
16102        ],
16103        None,
16104        &mut cx,
16105    );
16106}
16107
16108#[gpui::test]
16109async fn test_indent_guide_tab(cx: &mut TestAppContext) {
16110    let (buffer_id, mut cx) = setup_indent_guides_editor(
16111        &"
16112    fn main() {
16113        let a = 1;
16114            let b = 2;
16115        let c = 3;
16116    }"
16117        .unindent(),
16118        cx,
16119    )
16120    .await;
16121
16122    assert_indent_guides(
16123        0..5,
16124        vec![
16125            indent_guide(buffer_id, 1, 3, 0),
16126            indent_guide(buffer_id, 2, 2, 1),
16127        ],
16128        None,
16129        &mut cx,
16130    );
16131}
16132
16133#[gpui::test]
16134async fn test_indent_guide_continues_on_empty_line(cx: &mut TestAppContext) {
16135    let (buffer_id, mut cx) = setup_indent_guides_editor(
16136        &"
16137        fn main() {
16138            let a = 1;
16139
16140            let c = 3;
16141        }"
16142        .unindent(),
16143        cx,
16144    )
16145    .await;
16146
16147    assert_indent_guides(0..5, vec![indent_guide(buffer_id, 1, 3, 0)], None, &mut cx);
16148}
16149
16150#[gpui::test]
16151async fn test_indent_guide_complex(cx: &mut TestAppContext) {
16152    let (buffer_id, mut cx) = setup_indent_guides_editor(
16153        &"
16154        fn main() {
16155            let a = 1;
16156
16157            let c = 3;
16158
16159            if a == 3 {
16160                let b = 2;
16161            } else {
16162                let c = 3;
16163            }
16164        }"
16165        .unindent(),
16166        cx,
16167    )
16168    .await;
16169
16170    assert_indent_guides(
16171        0..11,
16172        vec![
16173            indent_guide(buffer_id, 1, 9, 0),
16174            indent_guide(buffer_id, 6, 6, 1),
16175            indent_guide(buffer_id, 8, 8, 1),
16176        ],
16177        None,
16178        &mut cx,
16179    );
16180}
16181
16182#[gpui::test]
16183async fn test_indent_guide_starts_off_screen(cx: &mut TestAppContext) {
16184    let (buffer_id, mut cx) = setup_indent_guides_editor(
16185        &"
16186        fn main() {
16187            let a = 1;
16188
16189            let c = 3;
16190
16191            if a == 3 {
16192                let b = 2;
16193            } else {
16194                let c = 3;
16195            }
16196        }"
16197        .unindent(),
16198        cx,
16199    )
16200    .await;
16201
16202    assert_indent_guides(
16203        1..11,
16204        vec![
16205            indent_guide(buffer_id, 1, 9, 0),
16206            indent_guide(buffer_id, 6, 6, 1),
16207            indent_guide(buffer_id, 8, 8, 1),
16208        ],
16209        None,
16210        &mut cx,
16211    );
16212}
16213
16214#[gpui::test]
16215async fn test_indent_guide_ends_off_screen(cx: &mut TestAppContext) {
16216    let (buffer_id, mut cx) = setup_indent_guides_editor(
16217        &"
16218        fn main() {
16219            let a = 1;
16220
16221            let c = 3;
16222
16223            if a == 3 {
16224                let b = 2;
16225            } else {
16226                let c = 3;
16227            }
16228        }"
16229        .unindent(),
16230        cx,
16231    )
16232    .await;
16233
16234    assert_indent_guides(
16235        1..10,
16236        vec![
16237            indent_guide(buffer_id, 1, 9, 0),
16238            indent_guide(buffer_id, 6, 6, 1),
16239            indent_guide(buffer_id, 8, 8, 1),
16240        ],
16241        None,
16242        &mut cx,
16243    );
16244}
16245
16246#[gpui::test]
16247async fn test_indent_guide_without_brackets(cx: &mut TestAppContext) {
16248    let (buffer_id, mut cx) = setup_indent_guides_editor(
16249        &"
16250        block1
16251            block2
16252                block3
16253                    block4
16254            block2
16255        block1
16256        block1"
16257            .unindent(),
16258        cx,
16259    )
16260    .await;
16261
16262    assert_indent_guides(
16263        1..10,
16264        vec![
16265            indent_guide(buffer_id, 1, 4, 0),
16266            indent_guide(buffer_id, 2, 3, 1),
16267            indent_guide(buffer_id, 3, 3, 2),
16268        ],
16269        None,
16270        &mut cx,
16271    );
16272}
16273
16274#[gpui::test]
16275async fn test_indent_guide_ends_before_empty_line(cx: &mut TestAppContext) {
16276    let (buffer_id, mut cx) = setup_indent_guides_editor(
16277        &"
16278        block1
16279            block2
16280                block3
16281
16282        block1
16283        block1"
16284            .unindent(),
16285        cx,
16286    )
16287    .await;
16288
16289    assert_indent_guides(
16290        0..6,
16291        vec![
16292            indent_guide(buffer_id, 1, 2, 0),
16293            indent_guide(buffer_id, 2, 2, 1),
16294        ],
16295        None,
16296        &mut cx,
16297    );
16298}
16299
16300#[gpui::test]
16301async fn test_indent_guide_continuing_off_screen(cx: &mut TestAppContext) {
16302    let (buffer_id, mut cx) = setup_indent_guides_editor(
16303        &"
16304        block1
16305
16306
16307
16308            block2
16309        "
16310        .unindent(),
16311        cx,
16312    )
16313    .await;
16314
16315    assert_indent_guides(0..1, vec![indent_guide(buffer_id, 1, 1, 0)], None, &mut cx);
16316}
16317
16318#[gpui::test]
16319async fn test_indent_guide_tabs(cx: &mut TestAppContext) {
16320    let (buffer_id, mut cx) = setup_indent_guides_editor(
16321        &"
16322        def a:
16323        \tb = 3
16324        \tif True:
16325        \t\tc = 4
16326        \t\td = 5
16327        \tprint(b)
16328        "
16329        .unindent(),
16330        cx,
16331    )
16332    .await;
16333
16334    assert_indent_guides(
16335        0..6,
16336        vec![
16337            indent_guide(buffer_id, 1, 6, 0),
16338            indent_guide(buffer_id, 3, 4, 1),
16339        ],
16340        None,
16341        &mut cx,
16342    );
16343}
16344
16345#[gpui::test]
16346async fn test_active_indent_guide_single_line(cx: &mut TestAppContext) {
16347    let (buffer_id, mut cx) = setup_indent_guides_editor(
16348        &"
16349    fn main() {
16350        let a = 1;
16351    }"
16352        .unindent(),
16353        cx,
16354    )
16355    .await;
16356
16357    cx.update_editor(|editor, window, cx| {
16358        editor.change_selections(None, window, cx, |s| {
16359            s.select_ranges([Point::new(1, 0)..Point::new(1, 0)])
16360        });
16361    });
16362
16363    assert_indent_guides(
16364        0..3,
16365        vec![indent_guide(buffer_id, 1, 1, 0)],
16366        Some(vec![0]),
16367        &mut cx,
16368    );
16369}
16370
16371#[gpui::test]
16372async fn test_active_indent_guide_respect_indented_range(cx: &mut TestAppContext) {
16373    let (buffer_id, mut cx) = setup_indent_guides_editor(
16374        &"
16375    fn main() {
16376        if 1 == 2 {
16377            let a = 1;
16378        }
16379    }"
16380        .unindent(),
16381        cx,
16382    )
16383    .await;
16384
16385    cx.update_editor(|editor, window, cx| {
16386        editor.change_selections(None, window, cx, |s| {
16387            s.select_ranges([Point::new(1, 0)..Point::new(1, 0)])
16388        });
16389    });
16390
16391    assert_indent_guides(
16392        0..4,
16393        vec![
16394            indent_guide(buffer_id, 1, 3, 0),
16395            indent_guide(buffer_id, 2, 2, 1),
16396        ],
16397        Some(vec![1]),
16398        &mut cx,
16399    );
16400
16401    cx.update_editor(|editor, window, cx| {
16402        editor.change_selections(None, window, cx, |s| {
16403            s.select_ranges([Point::new(2, 0)..Point::new(2, 0)])
16404        });
16405    });
16406
16407    assert_indent_guides(
16408        0..4,
16409        vec![
16410            indent_guide(buffer_id, 1, 3, 0),
16411            indent_guide(buffer_id, 2, 2, 1),
16412        ],
16413        Some(vec![1]),
16414        &mut cx,
16415    );
16416
16417    cx.update_editor(|editor, window, cx| {
16418        editor.change_selections(None, window, cx, |s| {
16419            s.select_ranges([Point::new(3, 0)..Point::new(3, 0)])
16420        });
16421    });
16422
16423    assert_indent_guides(
16424        0..4,
16425        vec![
16426            indent_guide(buffer_id, 1, 3, 0),
16427            indent_guide(buffer_id, 2, 2, 1),
16428        ],
16429        Some(vec![0]),
16430        &mut cx,
16431    );
16432}
16433
16434#[gpui::test]
16435async fn test_active_indent_guide_empty_line(cx: &mut TestAppContext) {
16436    let (buffer_id, mut cx) = setup_indent_guides_editor(
16437        &"
16438    fn main() {
16439        let a = 1;
16440
16441        let b = 2;
16442    }"
16443        .unindent(),
16444        cx,
16445    )
16446    .await;
16447
16448    cx.update_editor(|editor, window, cx| {
16449        editor.change_selections(None, window, cx, |s| {
16450            s.select_ranges([Point::new(2, 0)..Point::new(2, 0)])
16451        });
16452    });
16453
16454    assert_indent_guides(
16455        0..5,
16456        vec![indent_guide(buffer_id, 1, 3, 0)],
16457        Some(vec![0]),
16458        &mut cx,
16459    );
16460}
16461
16462#[gpui::test]
16463async fn test_active_indent_guide_non_matching_indent(cx: &mut TestAppContext) {
16464    let (buffer_id, mut cx) = setup_indent_guides_editor(
16465        &"
16466    def m:
16467        a = 1
16468        pass"
16469            .unindent(),
16470        cx,
16471    )
16472    .await;
16473
16474    cx.update_editor(|editor, window, cx| {
16475        editor.change_selections(None, window, cx, |s| {
16476            s.select_ranges([Point::new(1, 0)..Point::new(1, 0)])
16477        });
16478    });
16479
16480    assert_indent_guides(
16481        0..3,
16482        vec![indent_guide(buffer_id, 1, 2, 0)],
16483        Some(vec![0]),
16484        &mut cx,
16485    );
16486}
16487
16488#[gpui::test]
16489async fn test_indent_guide_with_expanded_diff_hunks(cx: &mut TestAppContext) {
16490    init_test(cx, |_| {});
16491    let mut cx = EditorTestContext::new(cx).await;
16492    let text = indoc! {
16493        "
16494        impl A {
16495            fn b() {
16496                0;
16497                3;
16498                5;
16499                6;
16500                7;
16501            }
16502        }
16503        "
16504    };
16505    let base_text = indoc! {
16506        "
16507        impl A {
16508            fn b() {
16509                0;
16510                1;
16511                2;
16512                3;
16513                4;
16514            }
16515            fn c() {
16516                5;
16517                6;
16518                7;
16519            }
16520        }
16521        "
16522    };
16523
16524    cx.update_editor(|editor, window, cx| {
16525        editor.set_text(text, window, cx);
16526
16527        editor.buffer().update(cx, |multibuffer, cx| {
16528            let buffer = multibuffer.as_singleton().unwrap();
16529            let diff = cx.new(|cx| BufferDiff::new_with_base_text(base_text, &buffer, cx));
16530
16531            multibuffer.set_all_diff_hunks_expanded(cx);
16532            multibuffer.add_diff(diff, cx);
16533
16534            buffer.read(cx).remote_id()
16535        })
16536    });
16537    cx.run_until_parked();
16538
16539    cx.assert_state_with_diff(
16540        indoc! { "
16541          impl A {
16542              fn b() {
16543                  0;
16544        -         1;
16545        -         2;
16546                  3;
16547        -         4;
16548        -     }
16549        -     fn c() {
16550                  5;
16551                  6;
16552                  7;
16553              }
16554          }
16555          ˇ"
16556        }
16557        .to_string(),
16558    );
16559
16560    let mut actual_guides = cx.update_editor(|editor, window, cx| {
16561        editor
16562            .snapshot(window, cx)
16563            .buffer_snapshot
16564            .indent_guides_in_range(Anchor::min()..Anchor::max(), false, cx)
16565            .map(|guide| (guide.start_row..=guide.end_row, guide.depth))
16566            .collect::<Vec<_>>()
16567    });
16568    actual_guides.sort_by_key(|item| (*item.0.start(), item.1));
16569    assert_eq!(
16570        actual_guides,
16571        vec![
16572            (MultiBufferRow(1)..=MultiBufferRow(12), 0),
16573            (MultiBufferRow(2)..=MultiBufferRow(6), 1),
16574            (MultiBufferRow(9)..=MultiBufferRow(11), 1),
16575        ]
16576    );
16577}
16578
16579#[gpui::test]
16580async fn test_adjacent_diff_hunks(executor: BackgroundExecutor, cx: &mut TestAppContext) {
16581    init_test(cx, |_| {});
16582    let mut cx = EditorTestContext::new(cx).await;
16583
16584    let diff_base = r#"
16585        a
16586        b
16587        c
16588        "#
16589    .unindent();
16590
16591    cx.set_state(
16592        &r#"
16593        ˇA
16594        b
16595        C
16596        "#
16597        .unindent(),
16598    );
16599    cx.set_head_text(&diff_base);
16600    cx.update_editor(|editor, window, cx| {
16601        editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
16602    });
16603    executor.run_until_parked();
16604
16605    let both_hunks_expanded = r#"
16606        - a
16607        + ˇA
16608          b
16609        - c
16610        + C
16611        "#
16612    .unindent();
16613
16614    cx.assert_state_with_diff(both_hunks_expanded.clone());
16615
16616    let hunk_ranges = cx.update_editor(|editor, window, cx| {
16617        let snapshot = editor.snapshot(window, cx);
16618        let hunks = editor
16619            .diff_hunks_in_ranges(&[Anchor::min()..Anchor::max()], &snapshot.buffer_snapshot)
16620            .collect::<Vec<_>>();
16621        let excerpt_id = editor.buffer.read(cx).excerpt_ids()[0];
16622        let buffer_id = hunks[0].buffer_id;
16623        hunks
16624            .into_iter()
16625            .map(|hunk| Anchor::range_in_buffer(excerpt_id, buffer_id, hunk.buffer_range.clone()))
16626            .collect::<Vec<_>>()
16627    });
16628    assert_eq!(hunk_ranges.len(), 2);
16629
16630    cx.update_editor(|editor, _, cx| {
16631        editor.toggle_single_diff_hunk(hunk_ranges[0].clone(), cx);
16632    });
16633    executor.run_until_parked();
16634
16635    let second_hunk_expanded = r#"
16636          ˇA
16637          b
16638        - c
16639        + C
16640        "#
16641    .unindent();
16642
16643    cx.assert_state_with_diff(second_hunk_expanded);
16644
16645    cx.update_editor(|editor, _, cx| {
16646        editor.toggle_single_diff_hunk(hunk_ranges[0].clone(), cx);
16647    });
16648    executor.run_until_parked();
16649
16650    cx.assert_state_with_diff(both_hunks_expanded.clone());
16651
16652    cx.update_editor(|editor, _, cx| {
16653        editor.toggle_single_diff_hunk(hunk_ranges[1].clone(), cx);
16654    });
16655    executor.run_until_parked();
16656
16657    let first_hunk_expanded = r#"
16658        - a
16659        + ˇA
16660          b
16661          C
16662        "#
16663    .unindent();
16664
16665    cx.assert_state_with_diff(first_hunk_expanded);
16666
16667    cx.update_editor(|editor, _, cx| {
16668        editor.toggle_single_diff_hunk(hunk_ranges[1].clone(), cx);
16669    });
16670    executor.run_until_parked();
16671
16672    cx.assert_state_with_diff(both_hunks_expanded);
16673
16674    cx.set_state(
16675        &r#"
16676        ˇA
16677        b
16678        "#
16679        .unindent(),
16680    );
16681    cx.run_until_parked();
16682
16683    // TODO this cursor position seems bad
16684    cx.assert_state_with_diff(
16685        r#"
16686        - ˇa
16687        + A
16688          b
16689        "#
16690        .unindent(),
16691    );
16692
16693    cx.update_editor(|editor, window, cx| {
16694        editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
16695    });
16696
16697    cx.assert_state_with_diff(
16698        r#"
16699            - ˇa
16700            + A
16701              b
16702            - c
16703            "#
16704        .unindent(),
16705    );
16706
16707    let hunk_ranges = cx.update_editor(|editor, window, cx| {
16708        let snapshot = editor.snapshot(window, cx);
16709        let hunks = editor
16710            .diff_hunks_in_ranges(&[Anchor::min()..Anchor::max()], &snapshot.buffer_snapshot)
16711            .collect::<Vec<_>>();
16712        let excerpt_id = editor.buffer.read(cx).excerpt_ids()[0];
16713        let buffer_id = hunks[0].buffer_id;
16714        hunks
16715            .into_iter()
16716            .map(|hunk| Anchor::range_in_buffer(excerpt_id, buffer_id, hunk.buffer_range.clone()))
16717            .collect::<Vec<_>>()
16718    });
16719    assert_eq!(hunk_ranges.len(), 2);
16720
16721    cx.update_editor(|editor, _, cx| {
16722        editor.toggle_single_diff_hunk(hunk_ranges[1].clone(), cx);
16723    });
16724    executor.run_until_parked();
16725
16726    cx.assert_state_with_diff(
16727        r#"
16728        - ˇa
16729        + A
16730          b
16731        "#
16732        .unindent(),
16733    );
16734}
16735
16736#[gpui::test]
16737async fn test_toggle_deletion_hunk_at_start_of_file(
16738    executor: BackgroundExecutor,
16739    cx: &mut TestAppContext,
16740) {
16741    init_test(cx, |_| {});
16742    let mut cx = EditorTestContext::new(cx).await;
16743
16744    let diff_base = r#"
16745        a
16746        b
16747        c
16748        "#
16749    .unindent();
16750
16751    cx.set_state(
16752        &r#"
16753        ˇb
16754        c
16755        "#
16756        .unindent(),
16757    );
16758    cx.set_head_text(&diff_base);
16759    cx.update_editor(|editor, window, cx| {
16760        editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
16761    });
16762    executor.run_until_parked();
16763
16764    let hunk_expanded = r#"
16765        - a
16766          ˇb
16767          c
16768        "#
16769    .unindent();
16770
16771    cx.assert_state_with_diff(hunk_expanded.clone());
16772
16773    let hunk_ranges = cx.update_editor(|editor, window, cx| {
16774        let snapshot = editor.snapshot(window, cx);
16775        let hunks = editor
16776            .diff_hunks_in_ranges(&[Anchor::min()..Anchor::max()], &snapshot.buffer_snapshot)
16777            .collect::<Vec<_>>();
16778        let excerpt_id = editor.buffer.read(cx).excerpt_ids()[0];
16779        let buffer_id = hunks[0].buffer_id;
16780        hunks
16781            .into_iter()
16782            .map(|hunk| Anchor::range_in_buffer(excerpt_id, buffer_id, hunk.buffer_range.clone()))
16783            .collect::<Vec<_>>()
16784    });
16785    assert_eq!(hunk_ranges.len(), 1);
16786
16787    cx.update_editor(|editor, _, cx| {
16788        editor.toggle_single_diff_hunk(hunk_ranges[0].clone(), cx);
16789    });
16790    executor.run_until_parked();
16791
16792    let hunk_collapsed = r#"
16793          ˇb
16794          c
16795        "#
16796    .unindent();
16797
16798    cx.assert_state_with_diff(hunk_collapsed);
16799
16800    cx.update_editor(|editor, _, cx| {
16801        editor.toggle_single_diff_hunk(hunk_ranges[0].clone(), cx);
16802    });
16803    executor.run_until_parked();
16804
16805    cx.assert_state_with_diff(hunk_expanded.clone());
16806}
16807
16808#[gpui::test]
16809async fn test_display_diff_hunks(cx: &mut TestAppContext) {
16810    init_test(cx, |_| {});
16811
16812    let fs = FakeFs::new(cx.executor());
16813    fs.insert_tree(
16814        path!("/test"),
16815        json!({
16816            ".git": {},
16817            "file-1": "ONE\n",
16818            "file-2": "TWO\n",
16819            "file-3": "THREE\n",
16820        }),
16821    )
16822    .await;
16823
16824    fs.set_head_for_repo(
16825        path!("/test/.git").as_ref(),
16826        &[
16827            ("file-1".into(), "one\n".into()),
16828            ("file-2".into(), "two\n".into()),
16829            ("file-3".into(), "three\n".into()),
16830        ],
16831    );
16832
16833    let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
16834    let mut buffers = vec![];
16835    for i in 1..=3 {
16836        let buffer = project
16837            .update(cx, |project, cx| {
16838                let path = format!(path!("/test/file-{}"), i);
16839                project.open_local_buffer(path, cx)
16840            })
16841            .await
16842            .unwrap();
16843        buffers.push(buffer);
16844    }
16845
16846    let multibuffer = cx.new(|cx| {
16847        let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
16848        multibuffer.set_all_diff_hunks_expanded(cx);
16849        for buffer in &buffers {
16850            let snapshot = buffer.read(cx).snapshot();
16851            multibuffer.set_excerpts_for_path(
16852                PathKey::namespaced(0, buffer.read(cx).file().unwrap().path().clone()),
16853                buffer.clone(),
16854                vec![text::Anchor::MIN.to_point(&snapshot)..text::Anchor::MAX.to_point(&snapshot)],
16855                DEFAULT_MULTIBUFFER_CONTEXT,
16856                cx,
16857            );
16858        }
16859        multibuffer
16860    });
16861
16862    let editor = cx.add_window(|window, cx| {
16863        Editor::new(EditorMode::full(), multibuffer, Some(project), window, cx)
16864    });
16865    cx.run_until_parked();
16866
16867    let snapshot = editor
16868        .update(cx, |editor, window, cx| editor.snapshot(window, cx))
16869        .unwrap();
16870    let hunks = snapshot
16871        .display_diff_hunks_for_rows(DisplayRow(0)..DisplayRow(u32::MAX), &Default::default())
16872        .map(|hunk| match hunk {
16873            DisplayDiffHunk::Unfolded {
16874                display_row_range, ..
16875            } => display_row_range,
16876            DisplayDiffHunk::Folded { .. } => unreachable!(),
16877        })
16878        .collect::<Vec<_>>();
16879    assert_eq!(
16880        hunks,
16881        [
16882            DisplayRow(2)..DisplayRow(4),
16883            DisplayRow(7)..DisplayRow(9),
16884            DisplayRow(12)..DisplayRow(14),
16885        ]
16886    );
16887}
16888
16889#[gpui::test]
16890async fn test_partially_staged_hunk(cx: &mut TestAppContext) {
16891    init_test(cx, |_| {});
16892
16893    let mut cx = EditorTestContext::new(cx).await;
16894    cx.set_head_text(indoc! { "
16895        one
16896        two
16897        three
16898        four
16899        five
16900        "
16901    });
16902    cx.set_index_text(indoc! { "
16903        one
16904        two
16905        three
16906        four
16907        five
16908        "
16909    });
16910    cx.set_state(indoc! {"
16911        one
16912        TWO
16913        ˇTHREE
16914        FOUR
16915        five
16916    "});
16917    cx.run_until_parked();
16918    cx.update_editor(|editor, window, cx| {
16919        editor.toggle_staged_selected_diff_hunks(&Default::default(), window, cx);
16920    });
16921    cx.run_until_parked();
16922    cx.assert_index_text(Some(indoc! {"
16923        one
16924        TWO
16925        THREE
16926        FOUR
16927        five
16928    "}));
16929    cx.set_state(indoc! { "
16930        one
16931        TWO
16932        ˇTHREE-HUNDRED
16933        FOUR
16934        five
16935    "});
16936    cx.run_until_parked();
16937    cx.update_editor(|editor, window, cx| {
16938        let snapshot = editor.snapshot(window, cx);
16939        let hunks = editor
16940            .diff_hunks_in_ranges(&[Anchor::min()..Anchor::max()], &snapshot.buffer_snapshot)
16941            .collect::<Vec<_>>();
16942        assert_eq!(hunks.len(), 1);
16943        assert_eq!(
16944            hunks[0].status(),
16945            DiffHunkStatus {
16946                kind: DiffHunkStatusKind::Modified,
16947                secondary: DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk
16948            }
16949        );
16950
16951        editor.toggle_staged_selected_diff_hunks(&Default::default(), window, cx);
16952    });
16953    cx.run_until_parked();
16954    cx.assert_index_text(Some(indoc! {"
16955        one
16956        TWO
16957        THREE-HUNDRED
16958        FOUR
16959        five
16960    "}));
16961}
16962
16963#[gpui::test]
16964fn test_crease_insertion_and_rendering(cx: &mut TestAppContext) {
16965    init_test(cx, |_| {});
16966
16967    let editor = cx.add_window(|window, cx| {
16968        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\nddddddd\n", cx);
16969        build_editor(buffer, window, cx)
16970    });
16971
16972    let render_args = Arc::new(Mutex::new(None));
16973    let snapshot = editor
16974        .update(cx, |editor, window, cx| {
16975            let snapshot = editor.buffer().read(cx).snapshot(cx);
16976            let range =
16977                snapshot.anchor_before(Point::new(1, 0))..snapshot.anchor_after(Point::new(2, 6));
16978
16979            struct RenderArgs {
16980                row: MultiBufferRow,
16981                folded: bool,
16982                callback: Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>,
16983            }
16984
16985            let crease = Crease::inline(
16986                range,
16987                FoldPlaceholder::test(),
16988                {
16989                    let toggle_callback = render_args.clone();
16990                    move |row, folded, callback, _window, _cx| {
16991                        *toggle_callback.lock() = Some(RenderArgs {
16992                            row,
16993                            folded,
16994                            callback,
16995                        });
16996                        div()
16997                    }
16998                },
16999                |_row, _folded, _window, _cx| div(),
17000            );
17001
17002            editor.insert_creases(Some(crease), cx);
17003            let snapshot = editor.snapshot(window, cx);
17004            let _div = snapshot.render_crease_toggle(
17005                MultiBufferRow(1),
17006                false,
17007                cx.entity().clone(),
17008                window,
17009                cx,
17010            );
17011            snapshot
17012        })
17013        .unwrap();
17014
17015    let render_args = render_args.lock().take().unwrap();
17016    assert_eq!(render_args.row, MultiBufferRow(1));
17017    assert!(!render_args.folded);
17018    assert!(!snapshot.is_line_folded(MultiBufferRow(1)));
17019
17020    cx.update_window(*editor, |_, window, cx| {
17021        (render_args.callback)(true, window, cx)
17022    })
17023    .unwrap();
17024    let snapshot = editor
17025        .update(cx, |editor, window, cx| editor.snapshot(window, cx))
17026        .unwrap();
17027    assert!(snapshot.is_line_folded(MultiBufferRow(1)));
17028
17029    cx.update_window(*editor, |_, window, cx| {
17030        (render_args.callback)(false, window, cx)
17031    })
17032    .unwrap();
17033    let snapshot = editor
17034        .update(cx, |editor, window, cx| editor.snapshot(window, cx))
17035        .unwrap();
17036    assert!(!snapshot.is_line_folded(MultiBufferRow(1)));
17037}
17038
17039#[gpui::test]
17040async fn test_input_text(cx: &mut TestAppContext) {
17041    init_test(cx, |_| {});
17042    let mut cx = EditorTestContext::new(cx).await;
17043
17044    cx.set_state(
17045        &r#"ˇone
17046        two
17047
17048        three
17049        fourˇ
17050        five
17051
17052        siˇx"#
17053            .unindent(),
17054    );
17055
17056    cx.dispatch_action(HandleInput(String::new()));
17057    cx.assert_editor_state(
17058        &r#"ˇone
17059        two
17060
17061        three
17062        fourˇ
17063        five
17064
17065        siˇx"#
17066            .unindent(),
17067    );
17068
17069    cx.dispatch_action(HandleInput("AAAA".to_string()));
17070    cx.assert_editor_state(
17071        &r#"AAAAˇone
17072        two
17073
17074        three
17075        fourAAAAˇ
17076        five
17077
17078        siAAAAˇx"#
17079            .unindent(),
17080    );
17081}
17082
17083#[gpui::test]
17084async fn test_scroll_cursor_center_top_bottom(cx: &mut TestAppContext) {
17085    init_test(cx, |_| {});
17086
17087    let mut cx = EditorTestContext::new(cx).await;
17088    cx.set_state(
17089        r#"let foo = 1;
17090let foo = 2;
17091let foo = 3;
17092let fooˇ = 4;
17093let foo = 5;
17094let foo = 6;
17095let foo = 7;
17096let foo = 8;
17097let foo = 9;
17098let foo = 10;
17099let foo = 11;
17100let foo = 12;
17101let foo = 13;
17102let foo = 14;
17103let foo = 15;"#,
17104    );
17105
17106    cx.update_editor(|e, window, cx| {
17107        assert_eq!(
17108            e.next_scroll_position,
17109            NextScrollCursorCenterTopBottom::Center,
17110            "Default next scroll direction is center",
17111        );
17112
17113        e.scroll_cursor_center_top_bottom(&ScrollCursorCenterTopBottom, window, cx);
17114        assert_eq!(
17115            e.next_scroll_position,
17116            NextScrollCursorCenterTopBottom::Top,
17117            "After center, next scroll direction should be top",
17118        );
17119
17120        e.scroll_cursor_center_top_bottom(&ScrollCursorCenterTopBottom, window, cx);
17121        assert_eq!(
17122            e.next_scroll_position,
17123            NextScrollCursorCenterTopBottom::Bottom,
17124            "After top, next scroll direction should be bottom",
17125        );
17126
17127        e.scroll_cursor_center_top_bottom(&ScrollCursorCenterTopBottom, window, cx);
17128        assert_eq!(
17129            e.next_scroll_position,
17130            NextScrollCursorCenterTopBottom::Center,
17131            "After bottom, scrolling should start over",
17132        );
17133
17134        e.scroll_cursor_center_top_bottom(&ScrollCursorCenterTopBottom, window, cx);
17135        assert_eq!(
17136            e.next_scroll_position,
17137            NextScrollCursorCenterTopBottom::Top,
17138            "Scrolling continues if retriggered fast enough"
17139        );
17140    });
17141
17142    cx.executor()
17143        .advance_clock(SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT + Duration::from_millis(200));
17144    cx.executor().run_until_parked();
17145    cx.update_editor(|e, _, _| {
17146        assert_eq!(
17147            e.next_scroll_position,
17148            NextScrollCursorCenterTopBottom::Center,
17149            "If scrolling is not triggered fast enough, it should reset"
17150        );
17151    });
17152}
17153
17154#[gpui::test]
17155async fn test_goto_definition_with_find_all_references_fallback(cx: &mut TestAppContext) {
17156    init_test(cx, |_| {});
17157    let mut cx = EditorLspTestContext::new_rust(
17158        lsp::ServerCapabilities {
17159            definition_provider: Some(lsp::OneOf::Left(true)),
17160            references_provider: Some(lsp::OneOf::Left(true)),
17161            ..lsp::ServerCapabilities::default()
17162        },
17163        cx,
17164    )
17165    .await;
17166
17167    let set_up_lsp_handlers = |empty_go_to_definition: bool, cx: &mut EditorLspTestContext| {
17168        let go_to_definition = cx
17169            .lsp
17170            .set_request_handler::<lsp::request::GotoDefinition, _, _>(
17171                move |params, _| async move {
17172                    if empty_go_to_definition {
17173                        Ok(None)
17174                    } else {
17175                        Ok(Some(lsp::GotoDefinitionResponse::Scalar(lsp::Location {
17176                            uri: params.text_document_position_params.text_document.uri,
17177                            range: lsp::Range::new(
17178                                lsp::Position::new(4, 3),
17179                                lsp::Position::new(4, 6),
17180                            ),
17181                        })))
17182                    }
17183                },
17184            );
17185        let references = cx
17186            .lsp
17187            .set_request_handler::<lsp::request::References, _, _>(move |params, _| async move {
17188                Ok(Some(vec![lsp::Location {
17189                    uri: params.text_document_position.text_document.uri,
17190                    range: lsp::Range::new(lsp::Position::new(0, 8), lsp::Position::new(0, 11)),
17191                }]))
17192            });
17193        (go_to_definition, references)
17194    };
17195
17196    cx.set_state(
17197        &r#"fn one() {
17198            let mut a = ˇtwo();
17199        }
17200
17201        fn two() {}"#
17202            .unindent(),
17203    );
17204    set_up_lsp_handlers(false, &mut cx);
17205    let navigated = cx
17206        .update_editor(|editor, window, cx| editor.go_to_definition(&GoToDefinition, window, cx))
17207        .await
17208        .expect("Failed to navigate to definition");
17209    assert_eq!(
17210        navigated,
17211        Navigated::Yes,
17212        "Should have navigated to definition from the GetDefinition response"
17213    );
17214    cx.assert_editor_state(
17215        &r#"fn one() {
17216            let mut a = two();
17217        }
17218
17219        fn «twoˇ»() {}"#
17220            .unindent(),
17221    );
17222
17223    let editors = cx.update_workspace(|workspace, _, cx| {
17224        workspace.items_of_type::<Editor>(cx).collect::<Vec<_>>()
17225    });
17226    cx.update_editor(|_, _, test_editor_cx| {
17227        assert_eq!(
17228            editors.len(),
17229            1,
17230            "Initially, only one, test, editor should be open in the workspace"
17231        );
17232        assert_eq!(
17233            test_editor_cx.entity(),
17234            editors.last().expect("Asserted len is 1").clone()
17235        );
17236    });
17237
17238    set_up_lsp_handlers(true, &mut cx);
17239    let navigated = cx
17240        .update_editor(|editor, window, cx| editor.go_to_definition(&GoToDefinition, window, cx))
17241        .await
17242        .expect("Failed to navigate to lookup references");
17243    assert_eq!(
17244        navigated,
17245        Navigated::Yes,
17246        "Should have navigated to references as a fallback after empty GoToDefinition response"
17247    );
17248    // We should not change the selections in the existing file,
17249    // if opening another milti buffer with the references
17250    cx.assert_editor_state(
17251        &r#"fn one() {
17252            let mut a = two();
17253        }
17254
17255        fn «twoˇ»() {}"#
17256            .unindent(),
17257    );
17258    let editors = cx.update_workspace(|workspace, _, cx| {
17259        workspace.items_of_type::<Editor>(cx).collect::<Vec<_>>()
17260    });
17261    cx.update_editor(|_, _, test_editor_cx| {
17262        assert_eq!(
17263            editors.len(),
17264            2,
17265            "After falling back to references search, we open a new editor with the results"
17266        );
17267        let references_fallback_text = editors
17268            .into_iter()
17269            .find(|new_editor| *new_editor != test_editor_cx.entity())
17270            .expect("Should have one non-test editor now")
17271            .read(test_editor_cx)
17272            .text(test_editor_cx);
17273        assert_eq!(
17274            references_fallback_text, "fn one() {\n    let mut a = two();\n}",
17275            "Should use the range from the references response and not the GoToDefinition one"
17276        );
17277    });
17278}
17279
17280#[gpui::test]
17281async fn test_goto_definition_no_fallback(cx: &mut TestAppContext) {
17282    init_test(cx, |_| {});
17283    cx.update(|cx| {
17284        let mut editor_settings = EditorSettings::get_global(cx).clone();
17285        editor_settings.go_to_definition_fallback = GoToDefinitionFallback::None;
17286        EditorSettings::override_global(editor_settings, cx);
17287    });
17288    let mut cx = EditorLspTestContext::new_rust(
17289        lsp::ServerCapabilities {
17290            definition_provider: Some(lsp::OneOf::Left(true)),
17291            references_provider: Some(lsp::OneOf::Left(true)),
17292            ..lsp::ServerCapabilities::default()
17293        },
17294        cx,
17295    )
17296    .await;
17297    let original_state = r#"fn one() {
17298        let mut a = ˇtwo();
17299    }
17300
17301    fn two() {}"#
17302        .unindent();
17303    cx.set_state(&original_state);
17304
17305    let mut go_to_definition = cx
17306        .lsp
17307        .set_request_handler::<lsp::request::GotoDefinition, _, _>(
17308            move |_, _| async move { Ok(None) },
17309        );
17310    let _references = cx
17311        .lsp
17312        .set_request_handler::<lsp::request::References, _, _>(move |_, _| async move {
17313            panic!("Should not call for references with no go to definition fallback")
17314        });
17315
17316    let navigated = cx
17317        .update_editor(|editor, window, cx| editor.go_to_definition(&GoToDefinition, window, cx))
17318        .await
17319        .expect("Failed to navigate to lookup references");
17320    go_to_definition
17321        .next()
17322        .await
17323        .expect("Should have called the go_to_definition handler");
17324
17325    assert_eq!(
17326        navigated,
17327        Navigated::No,
17328        "Should have navigated to references as a fallback after empty GoToDefinition response"
17329    );
17330    cx.assert_editor_state(&original_state);
17331    let editors = cx.update_workspace(|workspace, _, cx| {
17332        workspace.items_of_type::<Editor>(cx).collect::<Vec<_>>()
17333    });
17334    cx.update_editor(|_, _, _| {
17335        assert_eq!(
17336            editors.len(),
17337            1,
17338            "After unsuccessful fallback, no other editor should have been opened"
17339        );
17340    });
17341}
17342
17343#[gpui::test]
17344async fn test_find_enclosing_node_with_task(cx: &mut TestAppContext) {
17345    init_test(cx, |_| {});
17346
17347    let language = Arc::new(Language::new(
17348        LanguageConfig::default(),
17349        Some(tree_sitter_rust::LANGUAGE.into()),
17350    ));
17351
17352    let text = r#"
17353        #[cfg(test)]
17354        mod tests() {
17355            #[test]
17356            fn runnable_1() {
17357                let a = 1;
17358            }
17359
17360            #[test]
17361            fn runnable_2() {
17362                let a = 1;
17363                let b = 2;
17364            }
17365        }
17366    "#
17367    .unindent();
17368
17369    let fs = FakeFs::new(cx.executor());
17370    fs.insert_file("/file.rs", Default::default()).await;
17371
17372    let project = Project::test(fs, ["/a".as_ref()], cx).await;
17373    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
17374    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
17375    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
17376    let multi_buffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
17377
17378    let editor = cx.new_window_entity(|window, cx| {
17379        Editor::new(
17380            EditorMode::full(),
17381            multi_buffer,
17382            Some(project.clone()),
17383            window,
17384            cx,
17385        )
17386    });
17387
17388    editor.update_in(cx, |editor, window, cx| {
17389        let snapshot = editor.buffer().read(cx).snapshot(cx);
17390        editor.tasks.insert(
17391            (buffer.read(cx).remote_id(), 3),
17392            RunnableTasks {
17393                templates: vec![],
17394                offset: snapshot.anchor_before(43),
17395                column: 0,
17396                extra_variables: HashMap::default(),
17397                context_range: BufferOffset(43)..BufferOffset(85),
17398            },
17399        );
17400        editor.tasks.insert(
17401            (buffer.read(cx).remote_id(), 8),
17402            RunnableTasks {
17403                templates: vec![],
17404                offset: snapshot.anchor_before(86),
17405                column: 0,
17406                extra_variables: HashMap::default(),
17407                context_range: BufferOffset(86)..BufferOffset(191),
17408            },
17409        );
17410
17411        // Test finding task when cursor is inside function body
17412        editor.change_selections(None, window, cx, |s| {
17413            s.select_ranges([Point::new(4, 5)..Point::new(4, 5)])
17414        });
17415        let (_, row, _) = editor.find_enclosing_node_task(cx).unwrap();
17416        assert_eq!(row, 3, "Should find task for cursor inside runnable_1");
17417
17418        // Test finding task when cursor is on function name
17419        editor.change_selections(None, window, cx, |s| {
17420            s.select_ranges([Point::new(8, 4)..Point::new(8, 4)])
17421        });
17422        let (_, row, _) = editor.find_enclosing_node_task(cx).unwrap();
17423        assert_eq!(row, 8, "Should find task when cursor is on function name");
17424    });
17425}
17426
17427#[gpui::test]
17428async fn test_folding_buffers(cx: &mut TestAppContext) {
17429    init_test(cx, |_| {});
17430
17431    let sample_text_1 = "aaaa\nbbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj".to_string();
17432    let sample_text_2 = "llll\nmmmm\nnnnn\noooo\npppp\nqqqq\nrrrr\nssss\ntttt\nuuuu".to_string();
17433    let sample_text_3 = "vvvv\nwwww\nxxxx\nyyyy\nzzzz\n1111\n2222\n3333\n4444\n5555".to_string();
17434
17435    let fs = FakeFs::new(cx.executor());
17436    fs.insert_tree(
17437        path!("/a"),
17438        json!({
17439            "first.rs": sample_text_1,
17440            "second.rs": sample_text_2,
17441            "third.rs": sample_text_3,
17442        }),
17443    )
17444    .await;
17445    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
17446    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
17447    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
17448    let worktree = project.update(cx, |project, cx| {
17449        let mut worktrees = project.worktrees(cx).collect::<Vec<_>>();
17450        assert_eq!(worktrees.len(), 1);
17451        worktrees.pop().unwrap()
17452    });
17453    let worktree_id = worktree.update(cx, |worktree, _| worktree.id());
17454
17455    let buffer_1 = project
17456        .update(cx, |project, cx| {
17457            project.open_buffer((worktree_id, "first.rs"), cx)
17458        })
17459        .await
17460        .unwrap();
17461    let buffer_2 = project
17462        .update(cx, |project, cx| {
17463            project.open_buffer((worktree_id, "second.rs"), cx)
17464        })
17465        .await
17466        .unwrap();
17467    let buffer_3 = project
17468        .update(cx, |project, cx| {
17469            project.open_buffer((worktree_id, "third.rs"), cx)
17470        })
17471        .await
17472        .unwrap();
17473
17474    let multi_buffer = cx.new(|cx| {
17475        let mut multi_buffer = MultiBuffer::new(ReadWrite);
17476        multi_buffer.push_excerpts(
17477            buffer_1.clone(),
17478            [
17479                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
17480                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
17481                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
17482            ],
17483            cx,
17484        );
17485        multi_buffer.push_excerpts(
17486            buffer_2.clone(),
17487            [
17488                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
17489                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
17490                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
17491            ],
17492            cx,
17493        );
17494        multi_buffer.push_excerpts(
17495            buffer_3.clone(),
17496            [
17497                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
17498                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
17499                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
17500            ],
17501            cx,
17502        );
17503        multi_buffer
17504    });
17505    let multi_buffer_editor = cx.new_window_entity(|window, cx| {
17506        Editor::new(
17507            EditorMode::full(),
17508            multi_buffer.clone(),
17509            Some(project.clone()),
17510            window,
17511            cx,
17512        )
17513    });
17514
17515    assert_eq!(
17516        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17517        "\n\naaaa\nbbbb\ncccc\n\n\nffff\ngggg\n\n\njjjj\n\n\nllll\nmmmm\nnnnn\n\n\nqqqq\nrrrr\n\n\nuuuu\n\n\nvvvv\nwwww\nxxxx\n\n\n1111\n2222\n\n\n5555",
17518    );
17519
17520    multi_buffer_editor.update(cx, |editor, cx| {
17521        editor.fold_buffer(buffer_1.read(cx).remote_id(), cx)
17522    });
17523    assert_eq!(
17524        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17525        "\n\n\n\nllll\nmmmm\nnnnn\n\n\nqqqq\nrrrr\n\n\nuuuu\n\n\nvvvv\nwwww\nxxxx\n\n\n1111\n2222\n\n\n5555",
17526        "After folding the first buffer, its text should not be displayed"
17527    );
17528
17529    multi_buffer_editor.update(cx, |editor, cx| {
17530        editor.fold_buffer(buffer_2.read(cx).remote_id(), cx)
17531    });
17532    assert_eq!(
17533        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17534        "\n\n\n\n\n\nvvvv\nwwww\nxxxx\n\n\n1111\n2222\n\n\n5555",
17535        "After folding the second buffer, its text should not be displayed"
17536    );
17537
17538    multi_buffer_editor.update(cx, |editor, cx| {
17539        editor.fold_buffer(buffer_3.read(cx).remote_id(), cx)
17540    });
17541    assert_eq!(
17542        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17543        "\n\n\n\n\n",
17544        "After folding the third buffer, its text should not be displayed"
17545    );
17546
17547    // Emulate selection inside the fold logic, that should work
17548    multi_buffer_editor.update_in(cx, |editor, window, cx| {
17549        editor
17550            .snapshot(window, cx)
17551            .next_line_boundary(Point::new(0, 4));
17552    });
17553
17554    multi_buffer_editor.update(cx, |editor, cx| {
17555        editor.unfold_buffer(buffer_2.read(cx).remote_id(), cx)
17556    });
17557    assert_eq!(
17558        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17559        "\n\n\n\nllll\nmmmm\nnnnn\n\n\nqqqq\nrrrr\n\n\nuuuu\n\n",
17560        "After unfolding the second buffer, its text should be displayed"
17561    );
17562
17563    // Typing inside of buffer 1 causes that buffer to be unfolded.
17564    multi_buffer_editor.update_in(cx, |editor, window, cx| {
17565        assert_eq!(
17566            multi_buffer
17567                .read(cx)
17568                .snapshot(cx)
17569                .text_for_range(Point::new(1, 0)..Point::new(1, 4))
17570                .collect::<String>(),
17571            "bbbb"
17572        );
17573        editor.change_selections(None, window, cx, |selections| {
17574            selections.select_ranges(vec![Point::new(1, 0)..Point::new(1, 0)]);
17575        });
17576        editor.handle_input("B", window, cx);
17577    });
17578
17579    assert_eq!(
17580        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17581        "\n\nB\n\n\n\n\n\n\nllll\nmmmm\nnnnn\n\n\nqqqq\nrrrr\n\n\nuuuu\n\n",
17582        "After unfolding the first buffer, its and 2nd buffer's text should be displayed"
17583    );
17584
17585    multi_buffer_editor.update(cx, |editor, cx| {
17586        editor.unfold_buffer(buffer_3.read(cx).remote_id(), cx)
17587    });
17588    assert_eq!(
17589        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17590        "\n\nB\n\n\n\n\n\n\nllll\nmmmm\nnnnn\n\n\nqqqq\nrrrr\n\n\nuuuu\n\n\nvvvv\nwwww\nxxxx\n\n\n1111\n2222\n\n\n5555",
17591        "After unfolding the all buffers, all original text should be displayed"
17592    );
17593}
17594
17595#[gpui::test]
17596async fn test_folding_buffers_with_one_excerpt(cx: &mut TestAppContext) {
17597    init_test(cx, |_| {});
17598
17599    let sample_text_1 = "1111\n2222\n3333".to_string();
17600    let sample_text_2 = "4444\n5555\n6666".to_string();
17601    let sample_text_3 = "7777\n8888\n9999".to_string();
17602
17603    let fs = FakeFs::new(cx.executor());
17604    fs.insert_tree(
17605        path!("/a"),
17606        json!({
17607            "first.rs": sample_text_1,
17608            "second.rs": sample_text_2,
17609            "third.rs": sample_text_3,
17610        }),
17611    )
17612    .await;
17613    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
17614    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
17615    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
17616    let worktree = project.update(cx, |project, cx| {
17617        let mut worktrees = project.worktrees(cx).collect::<Vec<_>>();
17618        assert_eq!(worktrees.len(), 1);
17619        worktrees.pop().unwrap()
17620    });
17621    let worktree_id = worktree.update(cx, |worktree, _| worktree.id());
17622
17623    let buffer_1 = project
17624        .update(cx, |project, cx| {
17625            project.open_buffer((worktree_id, "first.rs"), cx)
17626        })
17627        .await
17628        .unwrap();
17629    let buffer_2 = project
17630        .update(cx, |project, cx| {
17631            project.open_buffer((worktree_id, "second.rs"), cx)
17632        })
17633        .await
17634        .unwrap();
17635    let buffer_3 = project
17636        .update(cx, |project, cx| {
17637            project.open_buffer((worktree_id, "third.rs"), cx)
17638        })
17639        .await
17640        .unwrap();
17641
17642    let multi_buffer = cx.new(|cx| {
17643        let mut multi_buffer = MultiBuffer::new(ReadWrite);
17644        multi_buffer.push_excerpts(
17645            buffer_1.clone(),
17646            [ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0))],
17647            cx,
17648        );
17649        multi_buffer.push_excerpts(
17650            buffer_2.clone(),
17651            [ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0))],
17652            cx,
17653        );
17654        multi_buffer.push_excerpts(
17655            buffer_3.clone(),
17656            [ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0))],
17657            cx,
17658        );
17659        multi_buffer
17660    });
17661
17662    let multi_buffer_editor = cx.new_window_entity(|window, cx| {
17663        Editor::new(
17664            EditorMode::full(),
17665            multi_buffer,
17666            Some(project.clone()),
17667            window,
17668            cx,
17669        )
17670    });
17671
17672    let full_text = "\n\n1111\n2222\n3333\n\n\n4444\n5555\n6666\n\n\n7777\n8888\n9999";
17673    assert_eq!(
17674        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17675        full_text,
17676    );
17677
17678    multi_buffer_editor.update(cx, |editor, cx| {
17679        editor.fold_buffer(buffer_1.read(cx).remote_id(), cx)
17680    });
17681    assert_eq!(
17682        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17683        "\n\n\n\n4444\n5555\n6666\n\n\n7777\n8888\n9999",
17684        "After folding the first buffer, its text should not be displayed"
17685    );
17686
17687    multi_buffer_editor.update(cx, |editor, cx| {
17688        editor.fold_buffer(buffer_2.read(cx).remote_id(), cx)
17689    });
17690
17691    assert_eq!(
17692        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17693        "\n\n\n\n\n\n7777\n8888\n9999",
17694        "After folding the second buffer, its text should not be displayed"
17695    );
17696
17697    multi_buffer_editor.update(cx, |editor, cx| {
17698        editor.fold_buffer(buffer_3.read(cx).remote_id(), cx)
17699    });
17700    assert_eq!(
17701        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17702        "\n\n\n\n\n",
17703        "After folding the third buffer, its text should not be displayed"
17704    );
17705
17706    multi_buffer_editor.update(cx, |editor, cx| {
17707        editor.unfold_buffer(buffer_2.read(cx).remote_id(), cx)
17708    });
17709    assert_eq!(
17710        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17711        "\n\n\n\n4444\n5555\n6666\n\n",
17712        "After unfolding the second buffer, its text should be displayed"
17713    );
17714
17715    multi_buffer_editor.update(cx, |editor, cx| {
17716        editor.unfold_buffer(buffer_1.read(cx).remote_id(), cx)
17717    });
17718    assert_eq!(
17719        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17720        "\n\n1111\n2222\n3333\n\n\n4444\n5555\n6666\n\n",
17721        "After unfolding the first buffer, its text should be displayed"
17722    );
17723
17724    multi_buffer_editor.update(cx, |editor, cx| {
17725        editor.unfold_buffer(buffer_3.read(cx).remote_id(), cx)
17726    });
17727    assert_eq!(
17728        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17729        full_text,
17730        "After unfolding all buffers, all original text should be displayed"
17731    );
17732}
17733
17734#[gpui::test]
17735async fn test_folding_buffer_when_multibuffer_has_only_one_excerpt(cx: &mut TestAppContext) {
17736    init_test(cx, |_| {});
17737
17738    let sample_text = "aaaa\nbbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj".to_string();
17739
17740    let fs = FakeFs::new(cx.executor());
17741    fs.insert_tree(
17742        path!("/a"),
17743        json!({
17744            "main.rs": sample_text,
17745        }),
17746    )
17747    .await;
17748    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
17749    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
17750    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
17751    let worktree = project.update(cx, |project, cx| {
17752        let mut worktrees = project.worktrees(cx).collect::<Vec<_>>();
17753        assert_eq!(worktrees.len(), 1);
17754        worktrees.pop().unwrap()
17755    });
17756    let worktree_id = worktree.update(cx, |worktree, _| worktree.id());
17757
17758    let buffer_1 = project
17759        .update(cx, |project, cx| {
17760            project.open_buffer((worktree_id, "main.rs"), cx)
17761        })
17762        .await
17763        .unwrap();
17764
17765    let multi_buffer = cx.new(|cx| {
17766        let mut multi_buffer = MultiBuffer::new(ReadWrite);
17767        multi_buffer.push_excerpts(
17768            buffer_1.clone(),
17769            [ExcerptRange::new(
17770                Point::new(0, 0)
17771                    ..Point::new(
17772                        sample_text.chars().filter(|&c| c == '\n').count() as u32 + 1,
17773                        0,
17774                    ),
17775            )],
17776            cx,
17777        );
17778        multi_buffer
17779    });
17780    let multi_buffer_editor = cx.new_window_entity(|window, cx| {
17781        Editor::new(
17782            EditorMode::full(),
17783            multi_buffer,
17784            Some(project.clone()),
17785            window,
17786            cx,
17787        )
17788    });
17789
17790    let selection_range = Point::new(1, 0)..Point::new(2, 0);
17791    multi_buffer_editor.update_in(cx, |editor, window, cx| {
17792        enum TestHighlight {}
17793        let multi_buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
17794        let highlight_range = selection_range.clone().to_anchors(&multi_buffer_snapshot);
17795        editor.highlight_text::<TestHighlight>(
17796            vec![highlight_range.clone()],
17797            HighlightStyle::color(Hsla::green()),
17798            cx,
17799        );
17800        editor.change_selections(None, window, cx, |s| s.select_ranges(Some(highlight_range)));
17801    });
17802
17803    let full_text = format!("\n\n{sample_text}");
17804    assert_eq!(
17805        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17806        full_text,
17807    );
17808}
17809
17810#[gpui::test]
17811async fn test_multi_buffer_navigation_with_folded_buffers(cx: &mut TestAppContext) {
17812    init_test(cx, |_| {});
17813    cx.update(|cx| {
17814        let default_key_bindings = settings::KeymapFile::load_asset_allow_partial_failure(
17815            "keymaps/default-linux.json",
17816            cx,
17817        )
17818        .unwrap();
17819        cx.bind_keys(default_key_bindings);
17820    });
17821
17822    let (editor, cx) = cx.add_window_view(|window, cx| {
17823        let multi_buffer = MultiBuffer::build_multi(
17824            [
17825                ("a0\nb0\nc0\nd0\ne0\n", vec![Point::row_range(0..2)]),
17826                ("a1\nb1\nc1\nd1\ne1\n", vec![Point::row_range(0..2)]),
17827                ("a2\nb2\nc2\nd2\ne2\n", vec![Point::row_range(0..2)]),
17828                ("a3\nb3\nc3\nd3\ne3\n", vec![Point::row_range(0..2)]),
17829            ],
17830            cx,
17831        );
17832        let mut editor = Editor::new(EditorMode::full(), multi_buffer.clone(), None, window, cx);
17833
17834        let buffer_ids = multi_buffer.read(cx).excerpt_buffer_ids();
17835        // fold all but the second buffer, so that we test navigating between two
17836        // adjacent folded buffers, as well as folded buffers at the start and
17837        // end the multibuffer
17838        editor.fold_buffer(buffer_ids[0], cx);
17839        editor.fold_buffer(buffer_ids[2], cx);
17840        editor.fold_buffer(buffer_ids[3], cx);
17841
17842        editor
17843    });
17844    cx.simulate_resize(size(px(1000.), px(1000.)));
17845
17846    let mut cx = EditorTestContext::for_editor_in(editor.clone(), cx).await;
17847    cx.assert_excerpts_with_selections(indoc! {"
17848        [EXCERPT]
17849        ˇ[FOLDED]
17850        [EXCERPT]
17851        a1
17852        b1
17853        [EXCERPT]
17854        [FOLDED]
17855        [EXCERPT]
17856        [FOLDED]
17857        "
17858    });
17859    cx.simulate_keystroke("down");
17860    cx.assert_excerpts_with_selections(indoc! {"
17861        [EXCERPT]
17862        [FOLDED]
17863        [EXCERPT]
17864        ˇa1
17865        b1
17866        [EXCERPT]
17867        [FOLDED]
17868        [EXCERPT]
17869        [FOLDED]
17870        "
17871    });
17872    cx.simulate_keystroke("down");
17873    cx.assert_excerpts_with_selections(indoc! {"
17874        [EXCERPT]
17875        [FOLDED]
17876        [EXCERPT]
17877        a1
17878        ˇb1
17879        [EXCERPT]
17880        [FOLDED]
17881        [EXCERPT]
17882        [FOLDED]
17883        "
17884    });
17885    cx.simulate_keystroke("down");
17886    cx.assert_excerpts_with_selections(indoc! {"
17887        [EXCERPT]
17888        [FOLDED]
17889        [EXCERPT]
17890        a1
17891        b1
17892        ˇ[EXCERPT]
17893        [FOLDED]
17894        [EXCERPT]
17895        [FOLDED]
17896        "
17897    });
17898    cx.simulate_keystroke("down");
17899    cx.assert_excerpts_with_selections(indoc! {"
17900        [EXCERPT]
17901        [FOLDED]
17902        [EXCERPT]
17903        a1
17904        b1
17905        [EXCERPT]
17906        ˇ[FOLDED]
17907        [EXCERPT]
17908        [FOLDED]
17909        "
17910    });
17911    for _ in 0..5 {
17912        cx.simulate_keystroke("down");
17913        cx.assert_excerpts_with_selections(indoc! {"
17914            [EXCERPT]
17915            [FOLDED]
17916            [EXCERPT]
17917            a1
17918            b1
17919            [EXCERPT]
17920            [FOLDED]
17921            [EXCERPT]
17922            ˇ[FOLDED]
17923            "
17924        });
17925    }
17926
17927    cx.simulate_keystroke("up");
17928    cx.assert_excerpts_with_selections(indoc! {"
17929        [EXCERPT]
17930        [FOLDED]
17931        [EXCERPT]
17932        a1
17933        b1
17934        [EXCERPT]
17935        ˇ[FOLDED]
17936        [EXCERPT]
17937        [FOLDED]
17938        "
17939    });
17940    cx.simulate_keystroke("up");
17941    cx.assert_excerpts_with_selections(indoc! {"
17942        [EXCERPT]
17943        [FOLDED]
17944        [EXCERPT]
17945        a1
17946        b1
17947        ˇ[EXCERPT]
17948        [FOLDED]
17949        [EXCERPT]
17950        [FOLDED]
17951        "
17952    });
17953    cx.simulate_keystroke("up");
17954    cx.assert_excerpts_with_selections(indoc! {"
17955        [EXCERPT]
17956        [FOLDED]
17957        [EXCERPT]
17958        a1
17959        ˇb1
17960        [EXCERPT]
17961        [FOLDED]
17962        [EXCERPT]
17963        [FOLDED]
17964        "
17965    });
17966    cx.simulate_keystroke("up");
17967    cx.assert_excerpts_with_selections(indoc! {"
17968        [EXCERPT]
17969        [FOLDED]
17970        [EXCERPT]
17971        ˇa1
17972        b1
17973        [EXCERPT]
17974        [FOLDED]
17975        [EXCERPT]
17976        [FOLDED]
17977        "
17978    });
17979    for _ in 0..5 {
17980        cx.simulate_keystroke("up");
17981        cx.assert_excerpts_with_selections(indoc! {"
17982            [EXCERPT]
17983            ˇ[FOLDED]
17984            [EXCERPT]
17985            a1
17986            b1
17987            [EXCERPT]
17988            [FOLDED]
17989            [EXCERPT]
17990            [FOLDED]
17991            "
17992        });
17993    }
17994}
17995
17996#[gpui::test]
17997async fn test_inline_completion_text(cx: &mut TestAppContext) {
17998    init_test(cx, |_| {});
17999
18000    // Simple insertion
18001    assert_highlighted_edits(
18002        "Hello, world!",
18003        vec![(Point::new(0, 6)..Point::new(0, 6), " beautiful".into())],
18004        true,
18005        cx,
18006        |highlighted_edits, cx| {
18007            assert_eq!(highlighted_edits.text, "Hello, beautiful world!");
18008            assert_eq!(highlighted_edits.highlights.len(), 1);
18009            assert_eq!(highlighted_edits.highlights[0].0, 6..16);
18010            assert_eq!(
18011                highlighted_edits.highlights[0].1.background_color,
18012                Some(cx.theme().status().created_background)
18013            );
18014        },
18015    )
18016    .await;
18017
18018    // Replacement
18019    assert_highlighted_edits(
18020        "This is a test.",
18021        vec![(Point::new(0, 0)..Point::new(0, 4), "That".into())],
18022        false,
18023        cx,
18024        |highlighted_edits, cx| {
18025            assert_eq!(highlighted_edits.text, "That is a test.");
18026            assert_eq!(highlighted_edits.highlights.len(), 1);
18027            assert_eq!(highlighted_edits.highlights[0].0, 0..4);
18028            assert_eq!(
18029                highlighted_edits.highlights[0].1.background_color,
18030                Some(cx.theme().status().created_background)
18031            );
18032        },
18033    )
18034    .await;
18035
18036    // Multiple edits
18037    assert_highlighted_edits(
18038        "Hello, world!",
18039        vec![
18040            (Point::new(0, 0)..Point::new(0, 5), "Greetings".into()),
18041            (Point::new(0, 12)..Point::new(0, 12), " and universe".into()),
18042        ],
18043        false,
18044        cx,
18045        |highlighted_edits, cx| {
18046            assert_eq!(highlighted_edits.text, "Greetings, world and universe!");
18047            assert_eq!(highlighted_edits.highlights.len(), 2);
18048            assert_eq!(highlighted_edits.highlights[0].0, 0..9);
18049            assert_eq!(highlighted_edits.highlights[1].0, 16..29);
18050            assert_eq!(
18051                highlighted_edits.highlights[0].1.background_color,
18052                Some(cx.theme().status().created_background)
18053            );
18054            assert_eq!(
18055                highlighted_edits.highlights[1].1.background_color,
18056                Some(cx.theme().status().created_background)
18057            );
18058        },
18059    )
18060    .await;
18061
18062    // Multiple lines with edits
18063    assert_highlighted_edits(
18064        "First line\nSecond line\nThird line\nFourth line",
18065        vec![
18066            (Point::new(1, 7)..Point::new(1, 11), "modified".to_string()),
18067            (
18068                Point::new(2, 0)..Point::new(2, 10),
18069                "New third line".to_string(),
18070            ),
18071            (Point::new(3, 6)..Point::new(3, 6), " updated".to_string()),
18072        ],
18073        false,
18074        cx,
18075        |highlighted_edits, cx| {
18076            assert_eq!(
18077                highlighted_edits.text,
18078                "Second modified\nNew third line\nFourth updated line"
18079            );
18080            assert_eq!(highlighted_edits.highlights.len(), 3);
18081            assert_eq!(highlighted_edits.highlights[0].0, 7..15); // "modified"
18082            assert_eq!(highlighted_edits.highlights[1].0, 16..30); // "New third line"
18083            assert_eq!(highlighted_edits.highlights[2].0, 37..45); // " updated"
18084            for highlight in &highlighted_edits.highlights {
18085                assert_eq!(
18086                    highlight.1.background_color,
18087                    Some(cx.theme().status().created_background)
18088                );
18089            }
18090        },
18091    )
18092    .await;
18093}
18094
18095#[gpui::test]
18096async fn test_inline_completion_text_with_deletions(cx: &mut TestAppContext) {
18097    init_test(cx, |_| {});
18098
18099    // Deletion
18100    assert_highlighted_edits(
18101        "Hello, world!",
18102        vec![(Point::new(0, 5)..Point::new(0, 11), "".to_string())],
18103        true,
18104        cx,
18105        |highlighted_edits, cx| {
18106            assert_eq!(highlighted_edits.text, "Hello, world!");
18107            assert_eq!(highlighted_edits.highlights.len(), 1);
18108            assert_eq!(highlighted_edits.highlights[0].0, 5..11);
18109            assert_eq!(
18110                highlighted_edits.highlights[0].1.background_color,
18111                Some(cx.theme().status().deleted_background)
18112            );
18113        },
18114    )
18115    .await;
18116
18117    // Insertion
18118    assert_highlighted_edits(
18119        "Hello, world!",
18120        vec![(Point::new(0, 6)..Point::new(0, 6), " digital".to_string())],
18121        true,
18122        cx,
18123        |highlighted_edits, cx| {
18124            assert_eq!(highlighted_edits.highlights.len(), 1);
18125            assert_eq!(highlighted_edits.highlights[0].0, 6..14);
18126            assert_eq!(
18127                highlighted_edits.highlights[0].1.background_color,
18128                Some(cx.theme().status().created_background)
18129            );
18130        },
18131    )
18132    .await;
18133}
18134
18135async fn assert_highlighted_edits(
18136    text: &str,
18137    edits: Vec<(Range<Point>, String)>,
18138    include_deletions: bool,
18139    cx: &mut TestAppContext,
18140    assertion_fn: impl Fn(HighlightedText, &App),
18141) {
18142    let window = cx.add_window(|window, cx| {
18143        let buffer = MultiBuffer::build_simple(text, cx);
18144        Editor::new(EditorMode::full(), buffer, None, window, cx)
18145    });
18146    let cx = &mut VisualTestContext::from_window(*window, cx);
18147
18148    let (buffer, snapshot) = window
18149        .update(cx, |editor, _window, cx| {
18150            (
18151                editor.buffer().clone(),
18152                editor.buffer().read(cx).snapshot(cx),
18153            )
18154        })
18155        .unwrap();
18156
18157    let edits = edits
18158        .into_iter()
18159        .map(|(range, edit)| {
18160            (
18161                snapshot.anchor_after(range.start)..snapshot.anchor_before(range.end),
18162                edit,
18163            )
18164        })
18165        .collect::<Vec<_>>();
18166
18167    let text_anchor_edits = edits
18168        .clone()
18169        .into_iter()
18170        .map(|(range, edit)| (range.start.text_anchor..range.end.text_anchor, edit))
18171        .collect::<Vec<_>>();
18172
18173    let edit_preview = window
18174        .update(cx, |_, _window, cx| {
18175            buffer
18176                .read(cx)
18177                .as_singleton()
18178                .unwrap()
18179                .read(cx)
18180                .preview_edits(text_anchor_edits.into(), cx)
18181        })
18182        .unwrap()
18183        .await;
18184
18185    cx.update(|_window, cx| {
18186        let highlighted_edits = inline_completion_edit_text(
18187            &snapshot.as_singleton().unwrap().2,
18188            &edits,
18189            &edit_preview,
18190            include_deletions,
18191            cx,
18192        );
18193        assertion_fn(highlighted_edits, cx)
18194    });
18195}
18196
18197#[track_caller]
18198fn assert_breakpoint(
18199    breakpoints: &BTreeMap<Arc<Path>, Vec<SourceBreakpoint>>,
18200    path: &Arc<Path>,
18201    expected: Vec<(u32, Breakpoint)>,
18202) {
18203    if expected.len() == 0usize {
18204        assert!(!breakpoints.contains_key(path), "{}", path.display());
18205    } else {
18206        let mut breakpoint = breakpoints
18207            .get(path)
18208            .unwrap()
18209            .into_iter()
18210            .map(|breakpoint| {
18211                (
18212                    breakpoint.row,
18213                    Breakpoint {
18214                        message: breakpoint.message.clone(),
18215                        state: breakpoint.state,
18216                        condition: breakpoint.condition.clone(),
18217                        hit_condition: breakpoint.hit_condition.clone(),
18218                    },
18219                )
18220            })
18221            .collect::<Vec<_>>();
18222
18223        breakpoint.sort_by_key(|(cached_position, _)| *cached_position);
18224
18225        assert_eq!(expected, breakpoint);
18226    }
18227}
18228
18229fn add_log_breakpoint_at_cursor(
18230    editor: &mut Editor,
18231    log_message: &str,
18232    window: &mut Window,
18233    cx: &mut Context<Editor>,
18234) {
18235    let (anchor, bp) = editor
18236        .breakpoints_at_cursors(window, cx)
18237        .first()
18238        .and_then(|(anchor, bp)| {
18239            if let Some(bp) = bp {
18240                Some((*anchor, bp.clone()))
18241            } else {
18242                None
18243            }
18244        })
18245        .unwrap_or_else(|| {
18246            let cursor_position: Point = editor.selections.newest(cx).head();
18247
18248            let breakpoint_position = editor
18249                .snapshot(window, cx)
18250                .display_snapshot
18251                .buffer_snapshot
18252                .anchor_before(Point::new(cursor_position.row, 0));
18253
18254            (breakpoint_position, Breakpoint::new_log(&log_message))
18255        });
18256
18257    editor.edit_breakpoint_at_anchor(
18258        anchor,
18259        bp,
18260        BreakpointEditAction::EditLogMessage(log_message.into()),
18261        cx,
18262    );
18263}
18264
18265#[gpui::test]
18266async fn test_breakpoint_toggling(cx: &mut TestAppContext) {
18267    init_test(cx, |_| {});
18268
18269    let sample_text = "First line\nSecond line\nThird line\nFourth line".to_string();
18270    let fs = FakeFs::new(cx.executor());
18271    fs.insert_tree(
18272        path!("/a"),
18273        json!({
18274            "main.rs": sample_text,
18275        }),
18276    )
18277    .await;
18278    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
18279    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
18280    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
18281
18282    let fs = FakeFs::new(cx.executor());
18283    fs.insert_tree(
18284        path!("/a"),
18285        json!({
18286            "main.rs": sample_text,
18287        }),
18288    )
18289    .await;
18290    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
18291    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
18292    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
18293    let worktree_id = workspace
18294        .update(cx, |workspace, _window, cx| {
18295            workspace.project().update(cx, |project, cx| {
18296                project.worktrees(cx).next().unwrap().read(cx).id()
18297            })
18298        })
18299        .unwrap();
18300
18301    let buffer = project
18302        .update(cx, |project, cx| {
18303            project.open_buffer((worktree_id, "main.rs"), cx)
18304        })
18305        .await
18306        .unwrap();
18307
18308    let (editor, cx) = cx.add_window_view(|window, cx| {
18309        Editor::new(
18310            EditorMode::full(),
18311            MultiBuffer::build_from_buffer(buffer, cx),
18312            Some(project.clone()),
18313            window,
18314            cx,
18315        )
18316    });
18317
18318    let project_path = editor.update(cx, |editor, cx| editor.project_path(cx).unwrap());
18319    let abs_path = project.read_with(cx, |project, cx| {
18320        project
18321            .absolute_path(&project_path, cx)
18322            .map(|path_buf| Arc::from(path_buf.to_owned()))
18323            .unwrap()
18324    });
18325
18326    // assert we can add breakpoint on the first line
18327    editor.update_in(cx, |editor, window, cx| {
18328        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18329        editor.move_to_end(&MoveToEnd, window, cx);
18330        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18331    });
18332
18333    let breakpoints = editor.update(cx, |editor, cx| {
18334        editor
18335            .breakpoint_store()
18336            .as_ref()
18337            .unwrap()
18338            .read(cx)
18339            .all_breakpoints(cx)
18340            .clone()
18341    });
18342
18343    assert_eq!(1, breakpoints.len());
18344    assert_breakpoint(
18345        &breakpoints,
18346        &abs_path,
18347        vec![
18348            (0, Breakpoint::new_standard()),
18349            (3, Breakpoint::new_standard()),
18350        ],
18351    );
18352
18353    editor.update_in(cx, |editor, window, cx| {
18354        editor.move_to_beginning(&MoveToBeginning, window, cx);
18355        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18356    });
18357
18358    let breakpoints = editor.update(cx, |editor, cx| {
18359        editor
18360            .breakpoint_store()
18361            .as_ref()
18362            .unwrap()
18363            .read(cx)
18364            .all_breakpoints(cx)
18365            .clone()
18366    });
18367
18368    assert_eq!(1, breakpoints.len());
18369    assert_breakpoint(
18370        &breakpoints,
18371        &abs_path,
18372        vec![(3, Breakpoint::new_standard())],
18373    );
18374
18375    editor.update_in(cx, |editor, window, cx| {
18376        editor.move_to_end(&MoveToEnd, window, cx);
18377        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18378    });
18379
18380    let breakpoints = editor.update(cx, |editor, cx| {
18381        editor
18382            .breakpoint_store()
18383            .as_ref()
18384            .unwrap()
18385            .read(cx)
18386            .all_breakpoints(cx)
18387            .clone()
18388    });
18389
18390    assert_eq!(0, breakpoints.len());
18391    assert_breakpoint(&breakpoints, &abs_path, vec![]);
18392}
18393
18394#[gpui::test]
18395async fn test_log_breakpoint_editing(cx: &mut TestAppContext) {
18396    init_test(cx, |_| {});
18397
18398    let sample_text = "First line\nSecond line\nThird line\nFourth line".to_string();
18399
18400    let fs = FakeFs::new(cx.executor());
18401    fs.insert_tree(
18402        path!("/a"),
18403        json!({
18404            "main.rs": sample_text,
18405        }),
18406    )
18407    .await;
18408    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
18409    let (workspace, cx) =
18410        cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
18411
18412    let worktree_id = workspace.update(cx, |workspace, cx| {
18413        workspace.project().update(cx, |project, cx| {
18414            project.worktrees(cx).next().unwrap().read(cx).id()
18415        })
18416    });
18417
18418    let buffer = project
18419        .update(cx, |project, cx| {
18420            project.open_buffer((worktree_id, "main.rs"), cx)
18421        })
18422        .await
18423        .unwrap();
18424
18425    let (editor, cx) = cx.add_window_view(|window, cx| {
18426        Editor::new(
18427            EditorMode::full(),
18428            MultiBuffer::build_from_buffer(buffer, cx),
18429            Some(project.clone()),
18430            window,
18431            cx,
18432        )
18433    });
18434
18435    let project_path = editor.update(cx, |editor, cx| editor.project_path(cx).unwrap());
18436    let abs_path = project.read_with(cx, |project, cx| {
18437        project
18438            .absolute_path(&project_path, cx)
18439            .map(|path_buf| Arc::from(path_buf.to_owned()))
18440            .unwrap()
18441    });
18442
18443    editor.update_in(cx, |editor, window, cx| {
18444        add_log_breakpoint_at_cursor(editor, "hello world", window, cx);
18445    });
18446
18447    let breakpoints = editor.update(cx, |editor, cx| {
18448        editor
18449            .breakpoint_store()
18450            .as_ref()
18451            .unwrap()
18452            .read(cx)
18453            .all_breakpoints(cx)
18454            .clone()
18455    });
18456
18457    assert_breakpoint(
18458        &breakpoints,
18459        &abs_path,
18460        vec![(0, Breakpoint::new_log("hello world"))],
18461    );
18462
18463    // Removing a log message from a log breakpoint should remove it
18464    editor.update_in(cx, |editor, window, cx| {
18465        add_log_breakpoint_at_cursor(editor, "", window, cx);
18466    });
18467
18468    let breakpoints = editor.update(cx, |editor, cx| {
18469        editor
18470            .breakpoint_store()
18471            .as_ref()
18472            .unwrap()
18473            .read(cx)
18474            .all_breakpoints(cx)
18475            .clone()
18476    });
18477
18478    assert_breakpoint(&breakpoints, &abs_path, vec![]);
18479
18480    editor.update_in(cx, |editor, window, cx| {
18481        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18482        editor.move_to_end(&MoveToEnd, window, cx);
18483        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18484        // Not adding a log message to a standard breakpoint shouldn't remove it
18485        add_log_breakpoint_at_cursor(editor, "", window, cx);
18486    });
18487
18488    let breakpoints = editor.update(cx, |editor, cx| {
18489        editor
18490            .breakpoint_store()
18491            .as_ref()
18492            .unwrap()
18493            .read(cx)
18494            .all_breakpoints(cx)
18495            .clone()
18496    });
18497
18498    assert_breakpoint(
18499        &breakpoints,
18500        &abs_path,
18501        vec![
18502            (0, Breakpoint::new_standard()),
18503            (3, Breakpoint::new_standard()),
18504        ],
18505    );
18506
18507    editor.update_in(cx, |editor, window, cx| {
18508        add_log_breakpoint_at_cursor(editor, "hello world", window, cx);
18509    });
18510
18511    let breakpoints = editor.update(cx, |editor, cx| {
18512        editor
18513            .breakpoint_store()
18514            .as_ref()
18515            .unwrap()
18516            .read(cx)
18517            .all_breakpoints(cx)
18518            .clone()
18519    });
18520
18521    assert_breakpoint(
18522        &breakpoints,
18523        &abs_path,
18524        vec![
18525            (0, Breakpoint::new_standard()),
18526            (3, Breakpoint::new_log("hello world")),
18527        ],
18528    );
18529
18530    editor.update_in(cx, |editor, window, cx| {
18531        add_log_breakpoint_at_cursor(editor, "hello Earth!!", window, cx);
18532    });
18533
18534    let breakpoints = editor.update(cx, |editor, cx| {
18535        editor
18536            .breakpoint_store()
18537            .as_ref()
18538            .unwrap()
18539            .read(cx)
18540            .all_breakpoints(cx)
18541            .clone()
18542    });
18543
18544    assert_breakpoint(
18545        &breakpoints,
18546        &abs_path,
18547        vec![
18548            (0, Breakpoint::new_standard()),
18549            (3, Breakpoint::new_log("hello Earth!!")),
18550        ],
18551    );
18552}
18553
18554/// This also tests that Editor::breakpoint_at_cursor_head is working properly
18555/// we had some issues where we wouldn't find a breakpoint at Point {row: 0, col: 0}
18556/// or when breakpoints were placed out of order. This tests for a regression too
18557#[gpui::test]
18558async fn test_breakpoint_enabling_and_disabling(cx: &mut TestAppContext) {
18559    init_test(cx, |_| {});
18560
18561    let sample_text = "First line\nSecond line\nThird line\nFourth line".to_string();
18562    let fs = FakeFs::new(cx.executor());
18563    fs.insert_tree(
18564        path!("/a"),
18565        json!({
18566            "main.rs": sample_text,
18567        }),
18568    )
18569    .await;
18570    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
18571    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
18572    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
18573
18574    let fs = FakeFs::new(cx.executor());
18575    fs.insert_tree(
18576        path!("/a"),
18577        json!({
18578            "main.rs": sample_text,
18579        }),
18580    )
18581    .await;
18582    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
18583    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
18584    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
18585    let worktree_id = workspace
18586        .update(cx, |workspace, _window, cx| {
18587            workspace.project().update(cx, |project, cx| {
18588                project.worktrees(cx).next().unwrap().read(cx).id()
18589            })
18590        })
18591        .unwrap();
18592
18593    let buffer = project
18594        .update(cx, |project, cx| {
18595            project.open_buffer((worktree_id, "main.rs"), cx)
18596        })
18597        .await
18598        .unwrap();
18599
18600    let (editor, cx) = cx.add_window_view(|window, cx| {
18601        Editor::new(
18602            EditorMode::full(),
18603            MultiBuffer::build_from_buffer(buffer, cx),
18604            Some(project.clone()),
18605            window,
18606            cx,
18607        )
18608    });
18609
18610    let project_path = editor.update(cx, |editor, cx| editor.project_path(cx).unwrap());
18611    let abs_path = project.read_with(cx, |project, cx| {
18612        project
18613            .absolute_path(&project_path, cx)
18614            .map(|path_buf| Arc::from(path_buf.to_owned()))
18615            .unwrap()
18616    });
18617
18618    // assert we can add breakpoint on the first line
18619    editor.update_in(cx, |editor, window, cx| {
18620        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18621        editor.move_to_end(&MoveToEnd, window, cx);
18622        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18623        editor.move_up(&MoveUp, window, cx);
18624        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18625    });
18626
18627    let breakpoints = editor.update(cx, |editor, cx| {
18628        editor
18629            .breakpoint_store()
18630            .as_ref()
18631            .unwrap()
18632            .read(cx)
18633            .all_breakpoints(cx)
18634            .clone()
18635    });
18636
18637    assert_eq!(1, breakpoints.len());
18638    assert_breakpoint(
18639        &breakpoints,
18640        &abs_path,
18641        vec![
18642            (0, Breakpoint::new_standard()),
18643            (2, Breakpoint::new_standard()),
18644            (3, Breakpoint::new_standard()),
18645        ],
18646    );
18647
18648    editor.update_in(cx, |editor, window, cx| {
18649        editor.move_to_beginning(&MoveToBeginning, window, cx);
18650        editor.disable_breakpoint(&actions::DisableBreakpoint, window, cx);
18651        editor.move_to_end(&MoveToEnd, window, cx);
18652        editor.disable_breakpoint(&actions::DisableBreakpoint, window, cx);
18653        // Disabling a breakpoint that doesn't exist should do nothing
18654        editor.move_up(&MoveUp, window, cx);
18655        editor.move_up(&MoveUp, window, cx);
18656        editor.disable_breakpoint(&actions::DisableBreakpoint, window, cx);
18657    });
18658
18659    let breakpoints = editor.update(cx, |editor, cx| {
18660        editor
18661            .breakpoint_store()
18662            .as_ref()
18663            .unwrap()
18664            .read(cx)
18665            .all_breakpoints(cx)
18666            .clone()
18667    });
18668
18669    let disable_breakpoint = {
18670        let mut bp = Breakpoint::new_standard();
18671        bp.state = BreakpointState::Disabled;
18672        bp
18673    };
18674
18675    assert_eq!(1, breakpoints.len());
18676    assert_breakpoint(
18677        &breakpoints,
18678        &abs_path,
18679        vec![
18680            (0, disable_breakpoint.clone()),
18681            (2, Breakpoint::new_standard()),
18682            (3, disable_breakpoint.clone()),
18683        ],
18684    );
18685
18686    editor.update_in(cx, |editor, window, cx| {
18687        editor.move_to_beginning(&MoveToBeginning, window, cx);
18688        editor.enable_breakpoint(&actions::EnableBreakpoint, window, cx);
18689        editor.move_to_end(&MoveToEnd, window, cx);
18690        editor.enable_breakpoint(&actions::EnableBreakpoint, window, cx);
18691        editor.move_up(&MoveUp, window, cx);
18692        editor.disable_breakpoint(&actions::DisableBreakpoint, window, cx);
18693    });
18694
18695    let breakpoints = editor.update(cx, |editor, cx| {
18696        editor
18697            .breakpoint_store()
18698            .as_ref()
18699            .unwrap()
18700            .read(cx)
18701            .all_breakpoints(cx)
18702            .clone()
18703    });
18704
18705    assert_eq!(1, breakpoints.len());
18706    assert_breakpoint(
18707        &breakpoints,
18708        &abs_path,
18709        vec![
18710            (0, Breakpoint::new_standard()),
18711            (2, disable_breakpoint),
18712            (3, Breakpoint::new_standard()),
18713        ],
18714    );
18715}
18716
18717#[gpui::test]
18718async fn test_rename_with_duplicate_edits(cx: &mut TestAppContext) {
18719    init_test(cx, |_| {});
18720    let capabilities = lsp::ServerCapabilities {
18721        rename_provider: Some(lsp::OneOf::Right(lsp::RenameOptions {
18722            prepare_provider: Some(true),
18723            work_done_progress_options: Default::default(),
18724        })),
18725        ..Default::default()
18726    };
18727    let mut cx = EditorLspTestContext::new_rust(capabilities, cx).await;
18728
18729    cx.set_state(indoc! {"
18730        struct Fˇoo {}
18731    "});
18732
18733    cx.update_editor(|editor, _, cx| {
18734        let highlight_range = Point::new(0, 7)..Point::new(0, 10);
18735        let highlight_range = highlight_range.to_anchors(&editor.buffer().read(cx).snapshot(cx));
18736        editor.highlight_background::<DocumentHighlightRead>(
18737            &[highlight_range],
18738            |c| c.editor_document_highlight_read_background,
18739            cx,
18740        );
18741    });
18742
18743    let mut prepare_rename_handler = cx
18744        .set_request_handler::<lsp::request::PrepareRenameRequest, _, _>(
18745            move |_, _, _| async move {
18746                Ok(Some(lsp::PrepareRenameResponse::Range(lsp::Range {
18747                    start: lsp::Position {
18748                        line: 0,
18749                        character: 7,
18750                    },
18751                    end: lsp::Position {
18752                        line: 0,
18753                        character: 10,
18754                    },
18755                })))
18756            },
18757        );
18758    let prepare_rename_task = cx
18759        .update_editor(|e, window, cx| e.rename(&Rename, window, cx))
18760        .expect("Prepare rename was not started");
18761    prepare_rename_handler.next().await.unwrap();
18762    prepare_rename_task.await.expect("Prepare rename failed");
18763
18764    let mut rename_handler =
18765        cx.set_request_handler::<lsp::request::Rename, _, _>(move |url, _, _| async move {
18766            let edit = lsp::TextEdit {
18767                range: lsp::Range {
18768                    start: lsp::Position {
18769                        line: 0,
18770                        character: 7,
18771                    },
18772                    end: lsp::Position {
18773                        line: 0,
18774                        character: 10,
18775                    },
18776                },
18777                new_text: "FooRenamed".to_string(),
18778            };
18779            Ok(Some(lsp::WorkspaceEdit::new(
18780                // Specify the same edit twice
18781                std::collections::HashMap::from_iter(Some((url, vec![edit.clone(), edit]))),
18782            )))
18783        });
18784    let rename_task = cx
18785        .update_editor(|e, window, cx| e.confirm_rename(&ConfirmRename, window, cx))
18786        .expect("Confirm rename was not started");
18787    rename_handler.next().await.unwrap();
18788    rename_task.await.expect("Confirm rename failed");
18789    cx.run_until_parked();
18790
18791    // Despite two edits, only one is actually applied as those are identical
18792    cx.assert_editor_state(indoc! {"
18793        struct FooRenamedˇ {}
18794    "});
18795}
18796
18797#[gpui::test]
18798async fn test_rename_without_prepare(cx: &mut TestAppContext) {
18799    init_test(cx, |_| {});
18800    // These capabilities indicate that the server does not support prepare rename.
18801    let capabilities = lsp::ServerCapabilities {
18802        rename_provider: Some(lsp::OneOf::Left(true)),
18803        ..Default::default()
18804    };
18805    let mut cx = EditorLspTestContext::new_rust(capabilities, cx).await;
18806
18807    cx.set_state(indoc! {"
18808        struct Fˇoo {}
18809    "});
18810
18811    cx.update_editor(|editor, _window, cx| {
18812        let highlight_range = Point::new(0, 7)..Point::new(0, 10);
18813        let highlight_range = highlight_range.to_anchors(&editor.buffer().read(cx).snapshot(cx));
18814        editor.highlight_background::<DocumentHighlightRead>(
18815            &[highlight_range],
18816            |c| c.editor_document_highlight_read_background,
18817            cx,
18818        );
18819    });
18820
18821    cx.update_editor(|e, window, cx| e.rename(&Rename, window, cx))
18822        .expect("Prepare rename was not started")
18823        .await
18824        .expect("Prepare rename failed");
18825
18826    let mut rename_handler =
18827        cx.set_request_handler::<lsp::request::Rename, _, _>(move |url, _, _| async move {
18828            let edit = lsp::TextEdit {
18829                range: lsp::Range {
18830                    start: lsp::Position {
18831                        line: 0,
18832                        character: 7,
18833                    },
18834                    end: lsp::Position {
18835                        line: 0,
18836                        character: 10,
18837                    },
18838                },
18839                new_text: "FooRenamed".to_string(),
18840            };
18841            Ok(Some(lsp::WorkspaceEdit::new(
18842                std::collections::HashMap::from_iter(Some((url, vec![edit]))),
18843            )))
18844        });
18845    let rename_task = cx
18846        .update_editor(|e, window, cx| e.confirm_rename(&ConfirmRename, window, cx))
18847        .expect("Confirm rename was not started");
18848    rename_handler.next().await.unwrap();
18849    rename_task.await.expect("Confirm rename failed");
18850    cx.run_until_parked();
18851
18852    // Correct range is renamed, as `surrounding_word` is used to find it.
18853    cx.assert_editor_state(indoc! {"
18854        struct FooRenamedˇ {}
18855    "});
18856}
18857
18858#[gpui::test]
18859async fn test_tree_sitter_brackets_newline_insertion(cx: &mut TestAppContext) {
18860    init_test(cx, |_| {});
18861    let mut cx = EditorTestContext::new(cx).await;
18862
18863    let language = Arc::new(
18864        Language::new(
18865            LanguageConfig::default(),
18866            Some(tree_sitter_html::LANGUAGE.into()),
18867        )
18868        .with_brackets_query(
18869            r#"
18870            ("<" @open "/>" @close)
18871            ("</" @open ">" @close)
18872            ("<" @open ">" @close)
18873            ("\"" @open "\"" @close)
18874            ((element (start_tag) @open (end_tag) @close) (#set! newline.only))
18875        "#,
18876        )
18877        .unwrap(),
18878    );
18879    cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
18880
18881    cx.set_state(indoc! {"
18882        <span>ˇ</span>
18883    "});
18884    cx.update_editor(|e, window, cx| e.newline(&Newline, window, cx));
18885    cx.assert_editor_state(indoc! {"
18886        <span>
18887        ˇ
18888        </span>
18889    "});
18890
18891    cx.set_state(indoc! {"
18892        <span><span></span>ˇ</span>
18893    "});
18894    cx.update_editor(|e, window, cx| e.newline(&Newline, window, cx));
18895    cx.assert_editor_state(indoc! {"
18896        <span><span></span>
18897        ˇ</span>
18898    "});
18899
18900    cx.set_state(indoc! {"
18901        <span>ˇ
18902        </span>
18903    "});
18904    cx.update_editor(|e, window, cx| e.newline(&Newline, window, cx));
18905    cx.assert_editor_state(indoc! {"
18906        <span>
18907        ˇ
18908        </span>
18909    "});
18910}
18911
18912#[gpui::test(iterations = 10)]
18913async fn test_apply_code_lens_actions_with_commands(cx: &mut gpui::TestAppContext) {
18914    init_test(cx, |_| {});
18915
18916    let fs = FakeFs::new(cx.executor());
18917    fs.insert_tree(
18918        path!("/dir"),
18919        json!({
18920            "a.ts": "a",
18921        }),
18922    )
18923    .await;
18924
18925    let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
18926    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
18927    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
18928
18929    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
18930    language_registry.add(Arc::new(Language::new(
18931        LanguageConfig {
18932            name: "TypeScript".into(),
18933            matcher: LanguageMatcher {
18934                path_suffixes: vec!["ts".to_string()],
18935                ..Default::default()
18936            },
18937            ..Default::default()
18938        },
18939        Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
18940    )));
18941    let mut fake_language_servers = language_registry.register_fake_lsp(
18942        "TypeScript",
18943        FakeLspAdapter {
18944            capabilities: lsp::ServerCapabilities {
18945                code_lens_provider: Some(lsp::CodeLensOptions {
18946                    resolve_provider: Some(true),
18947                }),
18948                execute_command_provider: Some(lsp::ExecuteCommandOptions {
18949                    commands: vec!["_the/command".to_string()],
18950                    ..lsp::ExecuteCommandOptions::default()
18951                }),
18952                ..lsp::ServerCapabilities::default()
18953            },
18954            ..FakeLspAdapter::default()
18955        },
18956    );
18957
18958    let (buffer, _handle) = project
18959        .update(cx, |p, cx| {
18960            p.open_local_buffer_with_lsp(path!("/dir/a.ts"), cx)
18961        })
18962        .await
18963        .unwrap();
18964    cx.executor().run_until_parked();
18965
18966    let fake_server = fake_language_servers.next().await.unwrap();
18967
18968    let buffer_snapshot = buffer.update(cx, |buffer, _| buffer.snapshot());
18969    let anchor = buffer_snapshot.anchor_at(0, text::Bias::Left);
18970    drop(buffer_snapshot);
18971    let actions = cx
18972        .update_window(*workspace, |_, window, cx| {
18973            project.code_actions(&buffer, anchor..anchor, window, cx)
18974        })
18975        .unwrap();
18976
18977    fake_server
18978        .set_request_handler::<lsp::request::CodeLensRequest, _, _>(|_, _| async move {
18979            Ok(Some(vec![
18980                lsp::CodeLens {
18981                    range: lsp::Range::default(),
18982                    command: Some(lsp::Command {
18983                        title: "Code lens command".to_owned(),
18984                        command: "_the/command".to_owned(),
18985                        arguments: None,
18986                    }),
18987                    data: None,
18988                },
18989                lsp::CodeLens {
18990                    range: lsp::Range::default(),
18991                    command: Some(lsp::Command {
18992                        title: "Command not in capabilities".to_owned(),
18993                        command: "not in capabilities".to_owned(),
18994                        arguments: None,
18995                    }),
18996                    data: None,
18997                },
18998                lsp::CodeLens {
18999                    range: lsp::Range {
19000                        start: lsp::Position {
19001                            line: 1,
19002                            character: 1,
19003                        },
19004                        end: lsp::Position {
19005                            line: 1,
19006                            character: 1,
19007                        },
19008                    },
19009                    command: Some(lsp::Command {
19010                        title: "Command not in range".to_owned(),
19011                        command: "_the/command".to_owned(),
19012                        arguments: None,
19013                    }),
19014                    data: None,
19015                },
19016            ]))
19017        })
19018        .next()
19019        .await;
19020
19021    let actions = actions.await.unwrap();
19022    assert_eq!(
19023        actions.len(),
19024        1,
19025        "Should have only one valid action for the 0..0 range"
19026    );
19027    let action = actions[0].clone();
19028    let apply = project.update(cx, |project, cx| {
19029        project.apply_code_action(buffer.clone(), action, true, cx)
19030    });
19031
19032    // Resolving the code action does not populate its edits. In absence of
19033    // edits, we must execute the given command.
19034    fake_server.set_request_handler::<lsp::request::CodeLensResolve, _, _>(
19035        |mut lens, _| async move {
19036            let lens_command = lens.command.as_mut().expect("should have a command");
19037            assert_eq!(lens_command.title, "Code lens command");
19038            lens_command.arguments = Some(vec![json!("the-argument")]);
19039            Ok(lens)
19040        },
19041    );
19042
19043    // While executing the command, the language server sends the editor
19044    // a `workspaceEdit` request.
19045    fake_server
19046        .set_request_handler::<lsp::request::ExecuteCommand, _, _>({
19047            let fake = fake_server.clone();
19048            move |params, _| {
19049                assert_eq!(params.command, "_the/command");
19050                let fake = fake.clone();
19051                async move {
19052                    fake.server
19053                        .request::<lsp::request::ApplyWorkspaceEdit>(
19054                            lsp::ApplyWorkspaceEditParams {
19055                                label: None,
19056                                edit: lsp::WorkspaceEdit {
19057                                    changes: Some(
19058                                        [(
19059                                            lsp::Url::from_file_path(path!("/dir/a.ts")).unwrap(),
19060                                            vec![lsp::TextEdit {
19061                                                range: lsp::Range::new(
19062                                                    lsp::Position::new(0, 0),
19063                                                    lsp::Position::new(0, 0),
19064                                                ),
19065                                                new_text: "X".into(),
19066                                            }],
19067                                        )]
19068                                        .into_iter()
19069                                        .collect(),
19070                                    ),
19071                                    ..Default::default()
19072                                },
19073                            },
19074                        )
19075                        .await
19076                        .unwrap();
19077                    Ok(Some(json!(null)))
19078                }
19079            }
19080        })
19081        .next()
19082        .await;
19083
19084    // Applying the code lens command returns a project transaction containing the edits
19085    // sent by the language server in its `workspaceEdit` request.
19086    let transaction = apply.await.unwrap();
19087    assert!(transaction.0.contains_key(&buffer));
19088    buffer.update(cx, |buffer, cx| {
19089        assert_eq!(buffer.text(), "Xa");
19090        buffer.undo(cx);
19091        assert_eq!(buffer.text(), "a");
19092    });
19093}
19094
19095#[gpui::test]
19096async fn test_editor_restore_data_different_in_panes(cx: &mut TestAppContext) {
19097    init_test(cx, |_| {});
19098
19099    let fs = FakeFs::new(cx.executor());
19100    let main_text = r#"fn main() {
19101println!("1");
19102println!("2");
19103println!("3");
19104println!("4");
19105println!("5");
19106}"#;
19107    let lib_text = "mod foo {}";
19108    fs.insert_tree(
19109        path!("/a"),
19110        json!({
19111            "lib.rs": lib_text,
19112            "main.rs": main_text,
19113        }),
19114    )
19115    .await;
19116
19117    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
19118    let (workspace, cx) =
19119        cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
19120    let worktree_id = workspace.update(cx, |workspace, cx| {
19121        workspace.project().update(cx, |project, cx| {
19122            project.worktrees(cx).next().unwrap().read(cx).id()
19123        })
19124    });
19125
19126    let expected_ranges = vec![
19127        Point::new(0, 0)..Point::new(0, 0),
19128        Point::new(1, 0)..Point::new(1, 1),
19129        Point::new(2, 0)..Point::new(2, 2),
19130        Point::new(3, 0)..Point::new(3, 3),
19131    ];
19132
19133    let pane_1 = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
19134    let editor_1 = workspace
19135        .update_in(cx, |workspace, window, cx| {
19136            workspace.open_path(
19137                (worktree_id, "main.rs"),
19138                Some(pane_1.downgrade()),
19139                true,
19140                window,
19141                cx,
19142            )
19143        })
19144        .unwrap()
19145        .await
19146        .downcast::<Editor>()
19147        .unwrap();
19148    pane_1.update(cx, |pane, cx| {
19149        let open_editor = pane.active_item().unwrap().downcast::<Editor>().unwrap();
19150        open_editor.update(cx, |editor, cx| {
19151            assert_eq!(
19152                editor.display_text(cx),
19153                main_text,
19154                "Original main.rs text on initial open",
19155            );
19156            assert_eq!(
19157                editor
19158                    .selections
19159                    .all::<Point>(cx)
19160                    .into_iter()
19161                    .map(|s| s.range())
19162                    .collect::<Vec<_>>(),
19163                vec![Point::zero()..Point::zero()],
19164                "Default selections on initial open",
19165            );
19166        })
19167    });
19168    editor_1.update_in(cx, |editor, window, cx| {
19169        editor.change_selections(None, window, cx, |s| {
19170            s.select_ranges(expected_ranges.clone());
19171        });
19172    });
19173
19174    let pane_2 = workspace.update_in(cx, |workspace, window, cx| {
19175        workspace.split_pane(pane_1.clone(), SplitDirection::Right, window, cx)
19176    });
19177    let editor_2 = workspace
19178        .update_in(cx, |workspace, window, cx| {
19179            workspace.open_path(
19180                (worktree_id, "main.rs"),
19181                Some(pane_2.downgrade()),
19182                true,
19183                window,
19184                cx,
19185            )
19186        })
19187        .unwrap()
19188        .await
19189        .downcast::<Editor>()
19190        .unwrap();
19191    pane_2.update(cx, |pane, cx| {
19192        let open_editor = pane.active_item().unwrap().downcast::<Editor>().unwrap();
19193        open_editor.update(cx, |editor, cx| {
19194            assert_eq!(
19195                editor.display_text(cx),
19196                main_text,
19197                "Original main.rs text on initial open in another panel",
19198            );
19199            assert_eq!(
19200                editor
19201                    .selections
19202                    .all::<Point>(cx)
19203                    .into_iter()
19204                    .map(|s| s.range())
19205                    .collect::<Vec<_>>(),
19206                vec![Point::zero()..Point::zero()],
19207                "Default selections on initial open in another panel",
19208            );
19209        })
19210    });
19211
19212    editor_2.update_in(cx, |editor, window, cx| {
19213        editor.fold_ranges(expected_ranges.clone(), false, window, cx);
19214    });
19215
19216    let _other_editor_1 = workspace
19217        .update_in(cx, |workspace, window, cx| {
19218            workspace.open_path(
19219                (worktree_id, "lib.rs"),
19220                Some(pane_1.downgrade()),
19221                true,
19222                window,
19223                cx,
19224            )
19225        })
19226        .unwrap()
19227        .await
19228        .downcast::<Editor>()
19229        .unwrap();
19230    pane_1
19231        .update_in(cx, |pane, window, cx| {
19232            pane.close_inactive_items(&CloseInactiveItems::default(), window, cx)
19233                .unwrap()
19234        })
19235        .await
19236        .unwrap();
19237    drop(editor_1);
19238    pane_1.update(cx, |pane, cx| {
19239        pane.active_item()
19240            .unwrap()
19241            .downcast::<Editor>()
19242            .unwrap()
19243            .update(cx, |editor, cx| {
19244                assert_eq!(
19245                    editor.display_text(cx),
19246                    lib_text,
19247                    "Other file should be open and active",
19248                );
19249            });
19250        assert_eq!(pane.items().count(), 1, "No other editors should be open");
19251    });
19252
19253    let _other_editor_2 = workspace
19254        .update_in(cx, |workspace, window, cx| {
19255            workspace.open_path(
19256                (worktree_id, "lib.rs"),
19257                Some(pane_2.downgrade()),
19258                true,
19259                window,
19260                cx,
19261            )
19262        })
19263        .unwrap()
19264        .await
19265        .downcast::<Editor>()
19266        .unwrap();
19267    pane_2
19268        .update_in(cx, |pane, window, cx| {
19269            pane.close_inactive_items(&CloseInactiveItems::default(), window, cx)
19270                .unwrap()
19271        })
19272        .await
19273        .unwrap();
19274    drop(editor_2);
19275    pane_2.update(cx, |pane, cx| {
19276        let open_editor = pane.active_item().unwrap().downcast::<Editor>().unwrap();
19277        open_editor.update(cx, |editor, cx| {
19278            assert_eq!(
19279                editor.display_text(cx),
19280                lib_text,
19281                "Other file should be open and active in another panel too",
19282            );
19283        });
19284        assert_eq!(
19285            pane.items().count(),
19286            1,
19287            "No other editors should be open in another pane",
19288        );
19289    });
19290
19291    let _editor_1_reopened = workspace
19292        .update_in(cx, |workspace, window, cx| {
19293            workspace.open_path(
19294                (worktree_id, "main.rs"),
19295                Some(pane_1.downgrade()),
19296                true,
19297                window,
19298                cx,
19299            )
19300        })
19301        .unwrap()
19302        .await
19303        .downcast::<Editor>()
19304        .unwrap();
19305    let _editor_2_reopened = workspace
19306        .update_in(cx, |workspace, window, cx| {
19307            workspace.open_path(
19308                (worktree_id, "main.rs"),
19309                Some(pane_2.downgrade()),
19310                true,
19311                window,
19312                cx,
19313            )
19314        })
19315        .unwrap()
19316        .await
19317        .downcast::<Editor>()
19318        .unwrap();
19319    pane_1.update(cx, |pane, cx| {
19320        let open_editor = pane.active_item().unwrap().downcast::<Editor>().unwrap();
19321        open_editor.update(cx, |editor, cx| {
19322            assert_eq!(
19323                editor.display_text(cx),
19324                main_text,
19325                "Previous editor in the 1st panel had no extra text manipulations and should get none on reopen",
19326            );
19327            assert_eq!(
19328                editor
19329                    .selections
19330                    .all::<Point>(cx)
19331                    .into_iter()
19332                    .map(|s| s.range())
19333                    .collect::<Vec<_>>(),
19334                expected_ranges,
19335                "Previous editor in the 1st panel had selections and should get them restored on reopen",
19336            );
19337        })
19338    });
19339    pane_2.update(cx, |pane, cx| {
19340        let open_editor = pane.active_item().unwrap().downcast::<Editor>().unwrap();
19341        open_editor.update(cx, |editor, cx| {
19342            assert_eq!(
19343                editor.display_text(cx),
19344                r#"fn main() {
19345⋯rintln!("1");
19346⋯intln!("2");
19347⋯ntln!("3");
19348println!("4");
19349println!("5");
19350}"#,
19351                "Previous editor in the 2nd pane had folds and should restore those on reopen in the same pane",
19352            );
19353            assert_eq!(
19354                editor
19355                    .selections
19356                    .all::<Point>(cx)
19357                    .into_iter()
19358                    .map(|s| s.range())
19359                    .collect::<Vec<_>>(),
19360                vec![Point::zero()..Point::zero()],
19361                "Previous editor in the 2nd pane had no selections changed hence should restore none",
19362            );
19363        })
19364    });
19365}
19366
19367#[gpui::test]
19368async fn test_editor_does_not_restore_data_when_turned_off(cx: &mut TestAppContext) {
19369    init_test(cx, |_| {});
19370
19371    let fs = FakeFs::new(cx.executor());
19372    let main_text = r#"fn main() {
19373println!("1");
19374println!("2");
19375println!("3");
19376println!("4");
19377println!("5");
19378}"#;
19379    let lib_text = "mod foo {}";
19380    fs.insert_tree(
19381        path!("/a"),
19382        json!({
19383            "lib.rs": lib_text,
19384            "main.rs": main_text,
19385        }),
19386    )
19387    .await;
19388
19389    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
19390    let (workspace, cx) =
19391        cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
19392    let worktree_id = workspace.update(cx, |workspace, cx| {
19393        workspace.project().update(cx, |project, cx| {
19394            project.worktrees(cx).next().unwrap().read(cx).id()
19395        })
19396    });
19397
19398    let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
19399    let editor = workspace
19400        .update_in(cx, |workspace, window, cx| {
19401            workspace.open_path(
19402                (worktree_id, "main.rs"),
19403                Some(pane.downgrade()),
19404                true,
19405                window,
19406                cx,
19407            )
19408        })
19409        .unwrap()
19410        .await
19411        .downcast::<Editor>()
19412        .unwrap();
19413    pane.update(cx, |pane, cx| {
19414        let open_editor = pane.active_item().unwrap().downcast::<Editor>().unwrap();
19415        open_editor.update(cx, |editor, cx| {
19416            assert_eq!(
19417                editor.display_text(cx),
19418                main_text,
19419                "Original main.rs text on initial open",
19420            );
19421        })
19422    });
19423    editor.update_in(cx, |editor, window, cx| {
19424        editor.fold_ranges(vec![Point::new(0, 0)..Point::new(0, 0)], false, window, cx);
19425    });
19426
19427    cx.update_global(|store: &mut SettingsStore, cx| {
19428        store.update_user_settings::<WorkspaceSettings>(cx, |s| {
19429            s.restore_on_file_reopen = Some(false);
19430        });
19431    });
19432    editor.update_in(cx, |editor, window, cx| {
19433        editor.fold_ranges(
19434            vec![
19435                Point::new(1, 0)..Point::new(1, 1),
19436                Point::new(2, 0)..Point::new(2, 2),
19437                Point::new(3, 0)..Point::new(3, 3),
19438            ],
19439            false,
19440            window,
19441            cx,
19442        );
19443    });
19444    pane.update_in(cx, |pane, window, cx| {
19445        pane.close_all_items(&CloseAllItems::default(), window, cx)
19446            .unwrap()
19447    })
19448    .await
19449    .unwrap();
19450    pane.update(cx, |pane, _| {
19451        assert!(pane.active_item().is_none());
19452    });
19453    cx.update_global(|store: &mut SettingsStore, cx| {
19454        store.update_user_settings::<WorkspaceSettings>(cx, |s| {
19455            s.restore_on_file_reopen = Some(true);
19456        });
19457    });
19458
19459    let _editor_reopened = workspace
19460        .update_in(cx, |workspace, window, cx| {
19461            workspace.open_path(
19462                (worktree_id, "main.rs"),
19463                Some(pane.downgrade()),
19464                true,
19465                window,
19466                cx,
19467            )
19468        })
19469        .unwrap()
19470        .await
19471        .downcast::<Editor>()
19472        .unwrap();
19473    pane.update(cx, |pane, cx| {
19474        let open_editor = pane.active_item().unwrap().downcast::<Editor>().unwrap();
19475        open_editor.update(cx, |editor, cx| {
19476            assert_eq!(
19477                editor.display_text(cx),
19478                main_text,
19479                "No folds: even after enabling the restoration, previous editor's data should not be saved to be used for the restoration"
19480            );
19481        })
19482    });
19483}
19484
19485#[gpui::test]
19486async fn test_hide_mouse_context_menu_on_modal_opened(cx: &mut TestAppContext) {
19487    struct EmptyModalView {
19488        focus_handle: gpui::FocusHandle,
19489    }
19490    impl EventEmitter<DismissEvent> for EmptyModalView {}
19491    impl Render for EmptyModalView {
19492        fn render(&mut self, _: &mut Window, _: &mut Context<'_, Self>) -> impl IntoElement {
19493            div()
19494        }
19495    }
19496    impl Focusable for EmptyModalView {
19497        fn focus_handle(&self, _cx: &App) -> gpui::FocusHandle {
19498            self.focus_handle.clone()
19499        }
19500    }
19501    impl workspace::ModalView for EmptyModalView {}
19502    fn new_empty_modal_view(cx: &App) -> EmptyModalView {
19503        EmptyModalView {
19504            focus_handle: cx.focus_handle(),
19505        }
19506    }
19507
19508    init_test(cx, |_| {});
19509
19510    let fs = FakeFs::new(cx.executor());
19511    let project = Project::test(fs, [], cx).await;
19512    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
19513    let buffer = cx.update(|cx| MultiBuffer::build_simple("hello world!", cx));
19514    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
19515    let editor = cx.new_window_entity(|window, cx| {
19516        Editor::new(
19517            EditorMode::full(),
19518            buffer,
19519            Some(project.clone()),
19520            window,
19521            cx,
19522        )
19523    });
19524    workspace
19525        .update(cx, |workspace, window, cx| {
19526            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
19527        })
19528        .unwrap();
19529    editor.update_in(cx, |editor, window, cx| {
19530        editor.open_context_menu(&OpenContextMenu, window, cx);
19531        assert!(editor.mouse_context_menu.is_some());
19532    });
19533    workspace
19534        .update(cx, |workspace, window, cx| {
19535            workspace.toggle_modal(window, cx, |_, cx| new_empty_modal_view(cx));
19536        })
19537        .unwrap();
19538    cx.read(|cx| {
19539        assert!(editor.read(cx).mouse_context_menu.is_none());
19540    });
19541}
19542
19543fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
19544    let point = DisplayPoint::new(DisplayRow(row as u32), column as u32);
19545    point..point
19546}
19547
19548fn assert_selection_ranges(marked_text: &str, editor: &mut Editor, cx: &mut Context<Editor>) {
19549    let (text, ranges) = marked_text_ranges(marked_text, true);
19550    assert_eq!(editor.text(cx), text);
19551    assert_eq!(
19552        editor.selections.ranges(cx),
19553        ranges,
19554        "Assert selections are {}",
19555        marked_text
19556    );
19557}
19558
19559pub fn handle_signature_help_request(
19560    cx: &mut EditorLspTestContext,
19561    mocked_response: lsp::SignatureHelp,
19562) -> impl Future<Output = ()> + use<> {
19563    let mut request =
19564        cx.set_request_handler::<lsp::request::SignatureHelpRequest, _, _>(move |_, _, _| {
19565            let mocked_response = mocked_response.clone();
19566            async move { Ok(Some(mocked_response)) }
19567        });
19568
19569    async move {
19570        request.next().await;
19571    }
19572}
19573
19574/// Handle completion request passing a marked string specifying where the completion
19575/// should be triggered from using '|' character, what range should be replaced, and what completions
19576/// should be returned using '<' and '>' to delimit the range.
19577///
19578/// Also see `handle_completion_request_with_insert_and_replace`.
19579#[track_caller]
19580pub fn handle_completion_request(
19581    cx: &mut EditorLspTestContext,
19582    marked_string: &str,
19583    completions: Vec<&'static str>,
19584    counter: Arc<AtomicUsize>,
19585) -> impl Future<Output = ()> {
19586    let complete_from_marker: TextRangeMarker = '|'.into();
19587    let replace_range_marker: TextRangeMarker = ('<', '>').into();
19588    let (_, mut marked_ranges) = marked_text_ranges_by(
19589        marked_string,
19590        vec![complete_from_marker.clone(), replace_range_marker.clone()],
19591    );
19592
19593    let complete_from_position =
19594        cx.to_lsp(marked_ranges.remove(&complete_from_marker).unwrap()[0].start);
19595    let replace_range =
19596        cx.to_lsp_range(marked_ranges.remove(&replace_range_marker).unwrap()[0].clone());
19597
19598    let mut request =
19599        cx.set_request_handler::<lsp::request::Completion, _, _>(move |url, params, _| {
19600            let completions = completions.clone();
19601            counter.fetch_add(1, atomic::Ordering::Release);
19602            async move {
19603                assert_eq!(params.text_document_position.text_document.uri, url.clone());
19604                assert_eq!(
19605                    params.text_document_position.position,
19606                    complete_from_position
19607                );
19608                Ok(Some(lsp::CompletionResponse::Array(
19609                    completions
19610                        .iter()
19611                        .map(|completion_text| lsp::CompletionItem {
19612                            label: completion_text.to_string(),
19613                            text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
19614                                range: replace_range,
19615                                new_text: completion_text.to_string(),
19616                            })),
19617                            ..Default::default()
19618                        })
19619                        .collect(),
19620                )))
19621            }
19622        });
19623
19624    async move {
19625        request.next().await;
19626    }
19627}
19628
19629/// Similar to `handle_completion_request`, but a [`CompletionTextEdit::InsertAndReplace`] will be
19630/// given instead, which also contains an `insert` range.
19631///
19632/// This function uses the cursor position to mimic what Rust-Analyzer provides as the `insert` range,
19633/// that is, `replace_range.start..cursor_pos`.
19634pub fn handle_completion_request_with_insert_and_replace(
19635    cx: &mut EditorLspTestContext,
19636    marked_string: &str,
19637    completions: Vec<&'static str>,
19638    counter: Arc<AtomicUsize>,
19639) -> impl Future<Output = ()> {
19640    let complete_from_marker: TextRangeMarker = '|'.into();
19641    let replace_range_marker: TextRangeMarker = ('<', '>').into();
19642    let (_, mut marked_ranges) = marked_text_ranges_by(
19643        marked_string,
19644        vec![complete_from_marker.clone(), replace_range_marker.clone()],
19645    );
19646
19647    let complete_from_position =
19648        cx.to_lsp(marked_ranges.remove(&complete_from_marker).unwrap()[0].start);
19649    let replace_range =
19650        cx.to_lsp_range(marked_ranges.remove(&replace_range_marker).unwrap()[0].clone());
19651
19652    let mut request =
19653        cx.set_request_handler::<lsp::request::Completion, _, _>(move |url, params, _| {
19654            let completions = completions.clone();
19655            counter.fetch_add(1, atomic::Ordering::Release);
19656            async move {
19657                assert_eq!(params.text_document_position.text_document.uri, url.clone());
19658                assert_eq!(
19659                    params.text_document_position.position, complete_from_position,
19660                    "marker `|` position doesn't match",
19661                );
19662                Ok(Some(lsp::CompletionResponse::Array(
19663                    completions
19664                        .iter()
19665                        .map(|completion_text| lsp::CompletionItem {
19666                            label: completion_text.to_string(),
19667                            text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19668                                lsp::InsertReplaceEdit {
19669                                    insert: lsp::Range {
19670                                        start: replace_range.start,
19671                                        end: complete_from_position,
19672                                    },
19673                                    replace: replace_range,
19674                                    new_text: completion_text.to_string(),
19675                                },
19676                            )),
19677                            ..Default::default()
19678                        })
19679                        .collect(),
19680                )))
19681            }
19682        });
19683
19684    async move {
19685        request.next().await;
19686    }
19687}
19688
19689fn handle_resolve_completion_request(
19690    cx: &mut EditorLspTestContext,
19691    edits: Option<Vec<(&'static str, &'static str)>>,
19692) -> impl Future<Output = ()> {
19693    let edits = edits.map(|edits| {
19694        edits
19695            .iter()
19696            .map(|(marked_string, new_text)| {
19697                let (_, marked_ranges) = marked_text_ranges(marked_string, false);
19698                let replace_range = cx.to_lsp_range(marked_ranges[0].clone());
19699                lsp::TextEdit::new(replace_range, new_text.to_string())
19700            })
19701            .collect::<Vec<_>>()
19702    });
19703
19704    let mut request =
19705        cx.set_request_handler::<lsp::request::ResolveCompletionItem, _, _>(move |_, _, _| {
19706            let edits = edits.clone();
19707            async move {
19708                Ok(lsp::CompletionItem {
19709                    additional_text_edits: edits,
19710                    ..Default::default()
19711                })
19712            }
19713        });
19714
19715    async move {
19716        request.next().await;
19717    }
19718}
19719
19720pub(crate) fn update_test_language_settings(
19721    cx: &mut TestAppContext,
19722    f: impl Fn(&mut AllLanguageSettingsContent),
19723) {
19724    cx.update(|cx| {
19725        SettingsStore::update_global(cx, |store, cx| {
19726            store.update_user_settings::<AllLanguageSettings>(cx, f);
19727        });
19728    });
19729}
19730
19731pub(crate) fn update_test_project_settings(
19732    cx: &mut TestAppContext,
19733    f: impl Fn(&mut ProjectSettings),
19734) {
19735    cx.update(|cx| {
19736        SettingsStore::update_global(cx, |store, cx| {
19737            store.update_user_settings::<ProjectSettings>(cx, f);
19738        });
19739    });
19740}
19741
19742pub(crate) fn init_test(cx: &mut TestAppContext, f: fn(&mut AllLanguageSettingsContent)) {
19743    cx.update(|cx| {
19744        assets::Assets.load_test_fonts(cx);
19745        let store = SettingsStore::test(cx);
19746        cx.set_global(store);
19747        theme::init(theme::LoadThemes::JustBase, cx);
19748        release_channel::init(SemanticVersion::default(), cx);
19749        client::init_settings(cx);
19750        language::init(cx);
19751        Project::init_settings(cx);
19752        workspace::init_settings(cx);
19753        crate::init(cx);
19754    });
19755
19756    update_test_language_settings(cx, f);
19757}
19758
19759#[track_caller]
19760fn assert_hunk_revert(
19761    not_reverted_text_with_selections: &str,
19762    expected_hunk_statuses_before: Vec<DiffHunkStatusKind>,
19763    expected_reverted_text_with_selections: &str,
19764    base_text: &str,
19765    cx: &mut EditorLspTestContext,
19766) {
19767    cx.set_state(not_reverted_text_with_selections);
19768    cx.set_head_text(base_text);
19769    cx.executor().run_until_parked();
19770
19771    let actual_hunk_statuses_before = cx.update_editor(|editor, window, cx| {
19772        let snapshot = editor.snapshot(window, cx);
19773        let reverted_hunk_statuses = snapshot
19774            .buffer_snapshot
19775            .diff_hunks_in_range(0..snapshot.buffer_snapshot.len())
19776            .map(|hunk| hunk.status().kind)
19777            .collect::<Vec<_>>();
19778
19779        editor.git_restore(&Default::default(), window, cx);
19780        reverted_hunk_statuses
19781    });
19782    cx.executor().run_until_parked();
19783    cx.assert_editor_state(expected_reverted_text_with_selections);
19784    assert_eq!(actual_hunk_statuses_before, expected_hunk_statuses_before);
19785}