@@ -1,92 +1,80 @@
-use gpui::TestAppContext;
-use language::language_settings::{AllLanguageSettings, AllLanguageSettingsContent};
-use settings::SettingsStore;
-
-// use super::*;
-// use crate::{
-// scroll::scroll_amount::ScrollAmount,
-// test::{
-// assert_text_with_selections, build_editor, editor_lsp_test_context::EditorLspTestContext,
-// editor_test_context::EditorTestContext, select_ranges,
-// },
-// JoinLines,
-// };
-// use drag_and_drop::DragAndDrop;
-// use futures::StreamExt;
-// use gpui::{
-// executor::Deterministic,
-// geometry::{rect::RectF, vector::vec2f},
-// platform::{WindowBounds, WindowOptions},
-// serde_json::{self, json},
-// TestAppContext,
-// };
-// use indoc::indoc;
-// use language::{
-// language_settings::{AllLanguageSettings, AllLanguageSettingsContent, LanguageSettingsContent},
-// BracketPairConfig, FakeLspAdapter, LanguageConfig, LanguageConfigOverride, LanguageRegistry,
-// Override, Point,
-// };
-// use parking_lot::Mutex;
-// use project::project_settings::{LspSettings, ProjectSettings};
-// use project::FakeFs;
-// use std::sync::atomic;
-// use std::sync::atomic::AtomicUsize;
-// use std::{cell::RefCell, future::Future, rc::Rc, time::Instant};
-// use unindent::Unindent;
-// use util::{
-// assert_set_eq,
-// test::{marked_text_ranges, marked_text_ranges_by, sample_text, TextRangeMarker},
-// };
-// use workspace::{
-// item::{FollowableItem, Item, ItemHandle},
-// NavigationEntry, ViewId,
-// };
-
+use super::*;
+use crate::{
+ scroll::scroll_amount::ScrollAmount,
+ test::{
+ assert_text_with_selections, build_editor, editor_lsp_test_context::EditorLspTestContext,
+ editor_test_context::EditorTestContext, select_ranges,
+ },
+ JoinLines,
+};
+
+use futures::StreamExt;
+use gpui::{
+ div,
+ serde_json::{self, json},
+ Div, TestAppContext, VisualTestContext, WindowBounds, WindowOptions,
+};
+use indoc::indoc;
+use language::{
+ language_settings::{AllLanguageSettings, AllLanguageSettingsContent, LanguageSettingsContent},
+ BracketPairConfig, FakeLspAdapter, LanguageConfig, LanguageConfigOverride, LanguageRegistry,
+ Override, Point,
+};
+use parking_lot::Mutex;
+use project::project_settings::{LspSettings, ProjectSettings};
+use project::FakeFs;
+use std::sync::atomic;
+use std::sync::atomic::AtomicUsize;
+use std::{cell::RefCell, future::Future, rc::Rc, time::Instant};
+use unindent::Unindent;
+use util::{
+ assert_set_eq,
+ test::{marked_text_ranges, marked_text_ranges_by, sample_text, TextRangeMarker},
+};
+use workspace::{
+ item::{FollowEvent, FollowableEvents, FollowableItem, Item, ItemHandle},
+ NavigationEntry, ViewId,
+};
+
+// todo(finish edit tests)
// #[gpui::test]
// fn test_edit_events(cx: &mut TestAppContext) {
// init_test(cx, |_| {});
-// let buffer = cx.add_model(|cx| {
-// let mut buffer = language::Buffer::new(0, cx.model_id() as u64, "123456");
+// let buffer = cx.build_model(|cx| {
+// let mut buffer = language::Buffer::new(0, cx.entity_id().as_u64(), "123456");
// buffer.set_group_interval(Duration::from_secs(1));
// buffer
// });
// let events = Rc::new(RefCell::new(Vec::new()));
-// let editor1 = cx
-// .add_window({
-// let events = events.clone();
-// |cx| {
-// cx.subscribe(&cx.handle(), move |_, _, event, _| {
-// if matches!(
-// event,
-// Event::Edited | Event::BufferEdited | Event::DirtyChanged
-// ) {
-// events.borrow_mut().push(("editor1", event.clone()));
-// }
-// })
-// .detach();
-// Editor::for_buffer(buffer.clone(), None, cx)
-// }
-// })
-// .root(cx);
-// let editor2 = cx
-// .add_window({
-// let events = events.clone();
-// |cx| {
-// cx.subscribe(&cx.handle(), move |_, _, event, _| {
-// if matches!(
-// event,
-// Event::Edited | Event::BufferEdited | Event::DirtyChanged
-// ) {
-// events.borrow_mut().push(("editor2", event.clone()));
-// }
-// })
-// .detach();
-// Editor::for_buffer(buffer.clone(), None, cx)
-// }
-// })
-// .root(cx);
+// let editor1 = cx.add_window({
+// let events = events.clone();
+// |cx| {
+// let view = cx.view().clone();
+// cx.subscribe(&view, move |_, _, event, _| {
+// if matches!(event, Event::Edited | Event::BufferEdited) {
+// events.borrow_mut().push(("editor1", event.clone()));
+// }
+// })
+// .detach();
+// Editor::for_buffer(buffer.clone(), None, cx)
+// }
+// });
+
+// let editor2 = cx.add_window({
+// let events = events.clone();
+// |cx| {
+// cx.subscribe(&cx.view().clone(), move |_, _, event, _| {
+// if matches!(event, Event::Edited | Event::BufferEdited) {
+// events.borrow_mut().push(("editor2", event.clone()));
+// }
+// })
+// .detach();
+// Editor::for_buffer(buffer.clone(), None, cx)
+// }
+// });
+
// assert_eq!(mem::take(&mut *events.borrow_mut()), []);
// // Mutating editor 1 will emit an `Edited` event only for that editor.
@@ -97,8 +85,6 @@ use settings::SettingsStore;
// ("editor1", Event::Edited),
// ("editor1", Event::BufferEdited),
// ("editor2", Event::BufferEdited),
-// ("editor1", Event::DirtyChanged),
-// ("editor2", Event::DirtyChanged)
// ]
// );
@@ -121,8 +107,6 @@ use settings::SettingsStore;
// ("editor1", Event::Edited),
// ("editor1", Event::BufferEdited),
// ("editor2", Event::BufferEdited),
-// ("editor1", Event::DirtyChanged),
-// ("editor2", Event::DirtyChanged),
// ]
// );
@@ -134,8 +118,6 @@ use settings::SettingsStore;
// ("editor1", Event::Edited),
// ("editor1", Event::BufferEdited),
// ("editor2", Event::BufferEdited),
-// ("editor1", Event::DirtyChanged),
-// ("editor2", Event::DirtyChanged),
// ]
// );
@@ -147,8 +129,6 @@ use settings::SettingsStore;
// ("editor2", Event::Edited),
// ("editor1", Event::BufferEdited),
// ("editor2", Event::BufferEdited),
-// ("editor1", Event::DirtyChanged),
-// ("editor2", Event::DirtyChanged),
// ]
// );
@@ -160,8 +140,6 @@ use settings::SettingsStore;
// ("editor2", Event::Edited),
// ("editor1", Event::BufferEdited),
// ("editor2", Event::BufferEdited),
-// ("editor1", Event::DirtyChanged),
-// ("editor2", Event::DirtyChanged),
// ]
// );
@@ -174,6095 +152,6198 @@ use settings::SettingsStore;
// assert_eq!(mem::take(&mut *events.borrow_mut()), []);
// }
-// #[gpui::test]
-// fn test_undo_redo_with_selection_restoration(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
-
-// let mut now = Instant::now();
-// let buffer = cx.add_model(|cx| language::Buffer::new(0, cx.model_id() as u64, "123456"));
-// let group_interval = buffer.read_with(cx, |buffer, _| buffer.transaction_group_interval());
-// let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
-// let editor = cx
-// .add_window(|cx| build_editor(buffer.clone(), cx))
-// .root(cx);
-
-// editor.update(cx, |editor, cx| {
-// editor.start_transaction_at(now, cx);
-// editor.change_selections(None, cx, |s| s.select_ranges([2..4]));
-
-// editor.insert("cd", cx);
-// editor.end_transaction_at(now, cx);
-// assert_eq!(editor.text(cx), "12cd56");
-// assert_eq!(editor.selections.ranges(cx), vec![4..4]);
-
-// editor.start_transaction_at(now, cx);
-// editor.change_selections(None, cx, |s| s.select_ranges([4..5]));
-// editor.insert("e", cx);
-// editor.end_transaction_at(now, cx);
-// assert_eq!(editor.text(cx), "12cde6");
-// assert_eq!(editor.selections.ranges(cx), vec![5..5]);
-
-// now += group_interval + Duration::from_millis(1);
-// editor.change_selections(None, cx, |s| s.select_ranges([2..2]));
-
-// // Simulate an edit in another editor
-// buffer.update(cx, |buffer, cx| {
-// buffer.start_transaction_at(now, cx);
-// buffer.edit([(0..1, "a")], None, cx);
-// buffer.edit([(1..1, "b")], None, cx);
-// buffer.end_transaction_at(now, cx);
-// });
+#[gpui::test]
+fn test_undo_redo_with_selection_restoration(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+
+ let mut now = Instant::now();
+ let buffer = cx.build_model(|cx| language::Buffer::new(0, cx.entity_id().as_u64(), "123456"));
+ let group_interval = buffer.update(cx, |buffer, _| buffer.transaction_group_interval());
+ let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
+ let editor = cx.add_window(|cx| build_editor(buffer.clone(), cx));
+
+ editor.update(cx, |editor, cx| {
+ editor.start_transaction_at(now, cx);
+ editor.change_selections(None, cx, |s| s.select_ranges([2..4]));
+
+ editor.insert("cd", cx);
+ editor.end_transaction_at(now, cx);
+ assert_eq!(editor.text(cx), "12cd56");
+ assert_eq!(editor.selections.ranges(cx), vec![4..4]);
+
+ editor.start_transaction_at(now, cx);
+ editor.change_selections(None, cx, |s| s.select_ranges([4..5]));
+ editor.insert("e", cx);
+ editor.end_transaction_at(now, cx);
+ assert_eq!(editor.text(cx), "12cde6");
+ assert_eq!(editor.selections.ranges(cx), vec![5..5]);
+
+ now += group_interval + Duration::from_millis(1);
+ editor.change_selections(None, cx, |s| s.select_ranges([2..2]));
+
+ // Simulate an edit in another editor
+ buffer.update(cx, |buffer, cx| {
+ buffer.start_transaction_at(now, cx);
+ buffer.edit([(0..1, "a")], None, cx);
+ buffer.edit([(1..1, "b")], None, cx);
+ buffer.end_transaction_at(now, cx);
+ });
-// assert_eq!(editor.text(cx), "ab2cde6");
-// assert_eq!(editor.selections.ranges(cx), vec![3..3]);
+ assert_eq!(editor.text(cx), "ab2cde6");
+ assert_eq!(editor.selections.ranges(cx), vec![3..3]);
+
+ // Last transaction happened past the group interval in a different editor.
+ // Undo it individually and don't restore selections.
+ editor.undo(&Undo, cx);
+ assert_eq!(editor.text(cx), "12cde6");
+ assert_eq!(editor.selections.ranges(cx), vec![2..2]);
+
+ // First two transactions happened within the group interval in this editor.
+ // Undo them together and restore selections.
+ editor.undo(&Undo, cx);
+ editor.undo(&Undo, cx); // Undo stack is empty here, so this is a no-op.
+ assert_eq!(editor.text(cx), "123456");
+ assert_eq!(editor.selections.ranges(cx), vec![0..0]);
+
+ // Redo the first two transactions together.
+ editor.redo(&Redo, cx);
+ assert_eq!(editor.text(cx), "12cde6");
+ assert_eq!(editor.selections.ranges(cx), vec![5..5]);
+
+ // Redo the last transaction on its own.
+ editor.redo(&Redo, cx);
+ assert_eq!(editor.text(cx), "ab2cde6");
+ assert_eq!(editor.selections.ranges(cx), vec![6..6]);
+
+ // Test empty transactions.
+ editor.start_transaction_at(now, cx);
+ editor.end_transaction_at(now, cx);
+ editor.undo(&Undo, cx);
+ assert_eq!(editor.text(cx), "12cde6");
+ });
+}
-// // Last transaction happened past the group interval in a different editor.
-// // Undo it individually and don't restore selections.
-// editor.undo(&Undo, cx);
-// assert_eq!(editor.text(cx), "12cde6");
-// assert_eq!(editor.selections.ranges(cx), vec![2..2]);
+#[gpui::test]
+fn test_ime_composition(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
-// // First two transactions happened within the group interval in this editor.
-// // Undo them together and restore selections.
-// editor.undo(&Undo, cx);
-// editor.undo(&Undo, cx); // Undo stack is empty here, so this is a no-op.
-// assert_eq!(editor.text(cx), "123456");
-// assert_eq!(editor.selections.ranges(cx), vec![0..0]);
-
-// // Redo the first two transactions together.
-// editor.redo(&Redo, cx);
-// assert_eq!(editor.text(cx), "12cde6");
-// assert_eq!(editor.selections.ranges(cx), vec![5..5]);
-
-// // Redo the last transaction on its own.
-// editor.redo(&Redo, cx);
-// assert_eq!(editor.text(cx), "ab2cde6");
-// assert_eq!(editor.selections.ranges(cx), vec![6..6]);
-
-// // Test empty transactions.
-// editor.start_transaction_at(now, cx);
-// editor.end_transaction_at(now, cx);
-// editor.undo(&Undo, cx);
-// assert_eq!(editor.text(cx), "12cde6");
-// });
-// }
+ let buffer = cx.build_model(|cx| {
+ let mut buffer = language::Buffer::new(0, cx.entity_id().as_u64(), "abcde");
+ // Ensure automatic grouping doesn't occur.
+ buffer.set_group_interval(Duration::ZERO);
+ buffer
+ });
-// #[gpui::test]
-// fn test_ime_composition(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
+ let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
+ cx.add_window(|cx| {
+ let mut editor = build_editor(buffer.clone(), cx);
+
+ // Start a new IME composition.
+ editor.replace_and_mark_text_in_range(Some(0..1), "à", None, cx);
+ editor.replace_and_mark_text_in_range(Some(0..1), "á", None, cx);
+ editor.replace_and_mark_text_in_range(Some(0..1), "ä", None, cx);
+ assert_eq!(editor.text(cx), "äbcde");
+ assert_eq!(
+ editor.marked_text_ranges(cx),
+ Some(vec![OffsetUtf16(0)..OffsetUtf16(1)])
+ );
+
+ // Finalize IME composition.
+ editor.replace_text_in_range(None, "ā", cx);
+ assert_eq!(editor.text(cx), "ābcde");
+ assert_eq!(editor.marked_text_ranges(cx), None);
+
+ // IME composition edits are grouped and are undone/redone at once.
+ editor.undo(&Default::default(), cx);
+ assert_eq!(editor.text(cx), "abcde");
+ assert_eq!(editor.marked_text_ranges(cx), None);
+ editor.redo(&Default::default(), cx);
+ assert_eq!(editor.text(cx), "ābcde");
+ assert_eq!(editor.marked_text_ranges(cx), None);
+
+ // Start a new IME composition.
+ editor.replace_and_mark_text_in_range(Some(0..1), "à", None, cx);
+ assert_eq!(
+ editor.marked_text_ranges(cx),
+ Some(vec![OffsetUtf16(0)..OffsetUtf16(1)])
+ );
+
+ // Undoing during an IME composition cancels it.
+ editor.undo(&Default::default(), cx);
+ assert_eq!(editor.text(cx), "ābcde");
+ assert_eq!(editor.marked_text_ranges(cx), None);
+
+ // Start a new IME composition with an invalid marked range, ensuring it gets clipped.
+ editor.replace_and_mark_text_in_range(Some(4..999), "è", None, cx);
+ assert_eq!(editor.text(cx), "ābcdè");
+ assert_eq!(
+ editor.marked_text_ranges(cx),
+ Some(vec![OffsetUtf16(4)..OffsetUtf16(5)])
+ );
+
+ // Finalize IME composition with an invalid replacement range, ensuring it gets clipped.
+ editor.replace_text_in_range(Some(4..999), "ę", cx);
+ assert_eq!(editor.text(cx), "ābcdę");
+ assert_eq!(editor.marked_text_ranges(cx), None);
+
+ // Start a new IME composition with multiple cursors.
+ editor.change_selections(None, cx, |s| {
+ s.select_ranges([
+ OffsetUtf16(1)..OffsetUtf16(1),
+ OffsetUtf16(3)..OffsetUtf16(3),
+ OffsetUtf16(5)..OffsetUtf16(5),
+ ])
+ });
+ editor.replace_and_mark_text_in_range(Some(4..5), "XYZ", None, cx);
+ assert_eq!(editor.text(cx), "XYZbXYZdXYZ");
+ assert_eq!(
+ editor.marked_text_ranges(cx),
+ Some(vec![
+ OffsetUtf16(0)..OffsetUtf16(3),
+ OffsetUtf16(4)..OffsetUtf16(7),
+ OffsetUtf16(8)..OffsetUtf16(11)
+ ])
+ );
+
+ // Ensure the newly-marked range gets treated as relative to the previously-marked ranges.
+ editor.replace_and_mark_text_in_range(Some(1..2), "1", None, cx);
+ assert_eq!(editor.text(cx), "X1ZbX1ZdX1Z");
+ assert_eq!(
+ editor.marked_text_ranges(cx),
+ Some(vec![
+ OffsetUtf16(1)..OffsetUtf16(2),
+ OffsetUtf16(5)..OffsetUtf16(6),
+ OffsetUtf16(9)..OffsetUtf16(10)
+ ])
+ );
+
+ // Finalize IME composition with multiple cursors.
+ editor.replace_text_in_range(Some(9..10), "2", cx);
+ assert_eq!(editor.text(cx), "X2ZbX2ZdX2Z");
+ assert_eq!(editor.marked_text_ranges(cx), None);
+
+ editor
+ });
+}
-// let buffer = cx.add_model(|cx| {
-// let mut buffer = language::Buffer::new(0, cx.model_id() as u64, "abcde");
-// // Ensure automatic grouping doesn't occur.
-// buffer.set_group_interval(Duration::ZERO);
-// buffer
-// });
+#[gpui::test]
+fn test_selection_with_mouse(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
-// let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
-// cx.add_window(|cx| {
-// let mut editor = build_editor(buffer.clone(), cx);
+ let editor = cx.add_window(|cx| {
+ let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\nddddddd\n", cx);
+ build_editor(buffer, cx)
+ });
-// // Start a new IME composition.
-// editor.replace_and_mark_text_in_range(Some(0..1), "à", None, cx);
-// editor.replace_and_mark_text_in_range(Some(0..1), "á", None, cx);
-// editor.replace_and_mark_text_in_range(Some(0..1), "ä", None, cx);
-// assert_eq!(editor.text(cx), "äbcde");
-// assert_eq!(
-// editor.marked_text_ranges(cx),
-// Some(vec![OffsetUtf16(0)..OffsetUtf16(1)])
-// );
+ editor.update(cx, |view, cx| {
+ view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
+ });
+ assert_eq!(
+ editor
+ .update(cx, |view, cx| view.selections.display_ranges(cx))
+ .unwrap(),
+ [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
+ );
+
+ editor.update(cx, |view, cx| {
+ view.update_selection(DisplayPoint::new(3, 3), 0, gpui::Point::<f32>::zero(), cx);
+ });
-// // Finalize IME composition.
-// editor.replace_text_in_range(None, "ā", cx);
-// assert_eq!(editor.text(cx), "ābcde");
-// assert_eq!(editor.marked_text_ranges(cx), None);
+ assert_eq!(
+ editor
+ .update(cx, |view, cx| view.selections.display_ranges(cx))
+ .unwrap(),
+ [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
+ );
-// // IME composition edits are grouped and are undone/redone at once.
-// editor.undo(&Default::default(), cx);
-// assert_eq!(editor.text(cx), "abcde");
-// assert_eq!(editor.marked_text_ranges(cx), None);
-// editor.redo(&Default::default(), cx);
-// assert_eq!(editor.text(cx), "ābcde");
-// assert_eq!(editor.marked_text_ranges(cx), None);
-
-// // Start a new IME composition.
-// editor.replace_and_mark_text_in_range(Some(0..1), "à", None, cx);
-// assert_eq!(
-// editor.marked_text_ranges(cx),
-// Some(vec![OffsetUtf16(0)..OffsetUtf16(1)])
-// );
+ editor.update(cx, |view, cx| {
+ view.update_selection(DisplayPoint::new(1, 1), 0, gpui::Point::<f32>::zero(), cx);
+ });
-// // Undoing during an IME composition cancels it.
-// editor.undo(&Default::default(), cx);
-// assert_eq!(editor.text(cx), "ābcde");
-// assert_eq!(editor.marked_text_ranges(cx), None);
+ assert_eq!(
+ editor
+ .update(cx, |view, cx| view.selections.display_ranges(cx))
+ .unwrap(),
+ [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
+ );
-// // Start a new IME composition with an invalid marked range, ensuring it gets clipped.
-// editor.replace_and_mark_text_in_range(Some(4..999), "è", None, cx);
-// assert_eq!(editor.text(cx), "ābcdè");
-// assert_eq!(
-// editor.marked_text_ranges(cx),
-// Some(vec![OffsetUtf16(4)..OffsetUtf16(5)])
-// );
+ editor.update(cx, |view, cx| {
+ view.end_selection(cx);
+ view.update_selection(DisplayPoint::new(3, 3), 0, gpui::Point::<f32>::zero(), cx);
+ });
-// // Finalize IME composition with an invalid replacement range, ensuring it gets clipped.
-// editor.replace_text_in_range(Some(4..999), "ę", cx);
-// assert_eq!(editor.text(cx), "ābcdę");
-// assert_eq!(editor.marked_text_ranges(cx), None);
+ assert_eq!(
+ editor
+ .update(cx, |view, cx| view.selections.display_ranges(cx))
+ .unwrap(),
+ [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
+ );
-// // Start a new IME composition with multiple cursors.
-// editor.change_selections(None, cx, |s| {
-// s.select_ranges([
-// OffsetUtf16(1)..OffsetUtf16(1),
-// OffsetUtf16(3)..OffsetUtf16(3),
-// OffsetUtf16(5)..OffsetUtf16(5),
-// ])
-// });
-// editor.replace_and_mark_text_in_range(Some(4..5), "XYZ", None, cx);
-// assert_eq!(editor.text(cx), "XYZbXYZdXYZ");
-// assert_eq!(
-// editor.marked_text_ranges(cx),
-// Some(vec![
-// OffsetUtf16(0)..OffsetUtf16(3),
-// OffsetUtf16(4)..OffsetUtf16(7),
-// OffsetUtf16(8)..OffsetUtf16(11)
-// ])
-// );
+ editor.update(cx, |view, cx| {
+ view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
+ view.update_selection(DisplayPoint::new(0, 0), 0, gpui::Point::<f32>::zero(), cx);
+ });
-// // Ensure the newly-marked range gets treated as relative to the previously-marked ranges.
-// editor.replace_and_mark_text_in_range(Some(1..2), "1", None, cx);
-// assert_eq!(editor.text(cx), "X1ZbX1ZdX1Z");
-// assert_eq!(
-// editor.marked_text_ranges(cx),
-// Some(vec![
-// OffsetUtf16(1)..OffsetUtf16(2),
-// OffsetUtf16(5)..OffsetUtf16(6),
-// OffsetUtf16(9)..OffsetUtf16(10)
-// ])
-// );
+ assert_eq!(
+ editor
+ .update(cx, |view, cx| view.selections.display_ranges(cx))
+ .unwrap(),
+ [
+ DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
+ DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
+ ]
+ );
+
+ editor.update(cx, |view, cx| {
+ view.end_selection(cx);
+ });
-// // Finalize IME composition with multiple cursors.
-// editor.replace_text_in_range(Some(9..10), "2", cx);
-// assert_eq!(editor.text(cx), "X2ZbX2ZdX2Z");
-// assert_eq!(editor.marked_text_ranges(cx), None);
+ assert_eq!(
+ editor
+ .update(cx, |view, cx| view.selections.display_ranges(cx))
+ .unwrap(),
+ [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
+ );
+}
-// editor
-// });
-// }
+#[gpui::test]
+fn test_canceling_pending_selection(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
-// #[gpui::test]
-// fn test_selection_with_mouse(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
+ let view = cx.add_window(|cx| {
+ let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
+ build_editor(buffer, cx)
+ });
-// let editor = cx
-// .add_window(|cx| {
-// let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\nddddddd\n", cx);
-// build_editor(buffer, cx)
-// })
-// .root(cx);
-// editor.update(cx, |view, cx| {
-// view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
-// });
-// assert_eq!(
-// editor.update(cx, |view, cx| view.selections.display_ranges(cx)),
-// [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
-// );
+ view.update(cx, |view, cx| {
+ view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
+ );
+ });
-// editor.update(cx, |view, cx| {
-// view.update_selection(DisplayPoint::new(3, 3), 0, Point<Pixels>::zero(), cx);
-// });
+ view.update(cx, |view, cx| {
+ view.update_selection(DisplayPoint::new(3, 3), 0, gpui::Point::<f32>::zero(), cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
+ );
+ });
-// assert_eq!(
-// editor.update(cx, |view, cx| view.selections.display_ranges(cx)),
-// [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
-// );
+ view.update(cx, |view, cx| {
+ view.cancel(&Cancel, cx);
+ view.update_selection(DisplayPoint::new(1, 1), 0, gpui::Point::<f32>::zero(), cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
+ );
+ });
+}
-// editor.update(cx, |view, cx| {
-// view.update_selection(DisplayPoint::new(1, 1), 0, Point<Pixels>::zero(), cx);
-// });
+#[gpui::test]
+fn test_clone(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+
+ let (text, selection_ranges) = marked_text_ranges(
+ indoc! {"
+ one
+ two
+ threeˇ
+ four
+ fiveˇ
+ "},
+ true,
+ );
+
+ let editor = cx.add_window(|cx| {
+ let buffer = MultiBuffer::build_simple(&text, cx);
+ build_editor(buffer, cx)
+ });
-// assert_eq!(
-// editor.update(cx, |view, cx| view.selections.display_ranges(cx)),
-// [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
-// );
+ editor.update(cx, |editor, cx| {
+ editor.change_selections(None, cx, |s| s.select_ranges(selection_ranges.clone()));
+ editor.fold_ranges(
+ [
+ Point::new(1, 0)..Point::new(2, 0),
+ Point::new(3, 0)..Point::new(4, 0),
+ ],
+ true,
+ cx,
+ );
+ });
-// editor.update(cx, |view, cx| {
-// view.end_selection(cx);
-// view.update_selection(DisplayPoint::new(3, 3), 0, Point<Pixels>::zero(), cx);
-// });
+ let cloned_editor = editor
+ .update(cx, |editor, cx| {
+ cx.open_window(Default::default(), |cx| {
+ cx.build_view(|cx| editor.clone(cx))
+ })
+ })
+ .unwrap();
+
+ let snapshot = editor.update(cx, |e, cx| e.snapshot(cx)).unwrap();
+ let cloned_snapshot = cloned_editor.update(cx, |e, cx| e.snapshot(cx)).unwrap();
+
+ assert_eq!(
+ cloned_editor
+ .update(cx, |e, cx| e.display_text(cx))
+ .unwrap(),
+ editor.update(cx, |e, cx| e.display_text(cx)).unwrap()
+ );
+ assert_eq!(
+ cloned_snapshot
+ .folds_in_range(0..text.len())
+ .collect::<Vec<_>>(),
+ snapshot.folds_in_range(0..text.len()).collect::<Vec<_>>(),
+ );
+ assert_set_eq!(
+ cloned_editor
+ .update(cx, |editor, cx| editor.selections.ranges::<Point>(cx))
+ .unwrap(),
+ editor
+ .update(cx, |editor, cx| editor.selections.ranges(cx))
+ .unwrap()
+ );
+ assert_set_eq!(
+ cloned_editor
+ .update(cx, |e, cx| e.selections.display_ranges(cx))
+ .unwrap(),
+ editor
+ .update(cx, |e, cx| e.selections.display_ranges(cx))
+ .unwrap()
+ );
+}
-// assert_eq!(
-// editor.update(cx, |view, cx| view.selections.display_ranges(cx)),
-// [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
-// );
+//todo!(editor navigate)
+// #[gpui::test]
+// async fn test_navigation_history(cx: &mut TestAppContext) {
+// init_test(cx, |_| {});
-// editor.update(cx, |view, cx| {
-// view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
-// view.update_selection(DisplayPoint::new(0, 0), 0, Point<Pixels>::zero(), cx);
-// });
+// use workspace::item::Item;
-// assert_eq!(
-// editor.update(cx, |view, cx| view.selections.display_ranges(cx)),
-// [
-// DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
-// DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
-// ]
-// );
+// let fs = FakeFs::new(cx.executor());
+// let project = Project::test(fs, [], cx).await;
+// let workspace = cx.add_window(|cx| Workspace::test_new(project, cx));
+// let pane = workspace
+// .update(cx, |workspace, _| workspace.active_pane().clone())
+// .unwrap();
-// editor.update(cx, |view, cx| {
-// view.end_selection(cx);
-// });
+// workspace.update(cx, |v, cx| {
+// cx.build_view(|cx| {
+// let buffer = MultiBuffer::build_simple(&sample_text(300, 5, 'a'), cx);
+// let mut editor = build_editor(buffer.clone(), cx);
+// let handle = cx.view();
+// editor.set_nav_history(Some(pane.read(cx).nav_history_for_item(&handle)));
-// assert_eq!(
-// editor.update(cx, |view, cx| view.selections.display_ranges(cx)),
-// [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
-// );
-// }
+// fn pop_history(editor: &mut Editor, cx: &mut WindowContext) -> Option<NavigationEntry> {
+// editor.nav_history.as_mut().unwrap().pop_backward(cx)
+// }
-// #[gpui::test]
-// fn test_canceling_pending_selection(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
+// // Move the cursor a small distance.
+// // Nothing is added to the navigation history.
+// editor.change_selections(None, cx, |s| {
+// s.select_display_ranges([DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)])
+// });
+// editor.change_selections(None, cx, |s| {
+// s.select_display_ranges([DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)])
+// });
+// assert!(pop_history(&mut editor, cx).is_none());
-// let view = cx
-// .add_window(|cx| {
-// let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
-// build_editor(buffer, cx)
-// })
-// .root(cx);
+// // Move the cursor a large distance.
+// // The history can jump back to the previous position.
+// editor.change_selections(None, cx, |s| {
+// s.select_display_ranges([DisplayPoint::new(13, 0)..DisplayPoint::new(13, 3)])
+// });
+// let nav_entry = pop_history(&mut editor, cx).unwrap();
+// editor.navigate(nav_entry.data.unwrap(), cx);
+// assert_eq!(nav_entry.item.id(), cx.entity_id());
+// assert_eq!(
+// editor.selections.display_ranges(cx),
+// &[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)]
+// );
+// assert!(pop_history(&mut editor, cx).is_none());
-// view.update(cx, |view, cx| {
-// view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
-// );
-// });
+// // Move the cursor a small distance via the mouse.
+// // Nothing is added to the navigation history.
+// editor.begin_selection(DisplayPoint::new(5, 0), false, 1, cx);
+// editor.end_selection(cx);
+// assert_eq!(
+// editor.selections.display_ranges(cx),
+// &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
+// );
+// assert!(pop_history(&mut editor, cx).is_none());
-// view.update(cx, |view, cx| {
-// view.update_selection(DisplayPoint::new(3, 3), 0, Point<Pixels>::zero(), cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
-// );
-// });
+// // Move the cursor a large distance via the mouse.
+// // The history can jump back to the previous position.
+// editor.begin_selection(DisplayPoint::new(15, 0), false, 1, cx);
+// editor.end_selection(cx);
+// assert_eq!(
+// editor.selections.display_ranges(cx),
+// &[DisplayPoint::new(15, 0)..DisplayPoint::new(15, 0)]
+// );
+// let nav_entry = pop_history(&mut editor, cx).unwrap();
+// editor.navigate(nav_entry.data.unwrap(), cx);
+// assert_eq!(nav_entry.item.id(), cx.entity_id());
+// assert_eq!(
+// editor.selections.display_ranges(cx),
+// &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
+// );
+// assert!(pop_history(&mut editor, cx).is_none());
+
+// // Set scroll position to check later
+// editor.set_scroll_position(gpui::Point::<f32>::new(5.5, 5.5), cx);
+// let original_scroll_position = editor.scroll_manager.anchor();
+
+// // Jump to the end of the document and adjust scroll
+// editor.move_to_end(&MoveToEnd, cx);
+// editor.set_scroll_position(gpui::Point::<f32>::new(-2.5, -0.5), cx);
+// assert_ne!(editor.scroll_manager.anchor(), original_scroll_position);
+
+// let nav_entry = pop_history(&mut editor, cx).unwrap();
+// editor.navigate(nav_entry.data.unwrap(), cx);
+// assert_eq!(editor.scroll_manager.anchor(), original_scroll_position);
+
+// // Ensure we don't panic when navigation data contains invalid anchors *and* points.
+// let mut invalid_anchor = editor.scroll_manager.anchor().anchor;
+// invalid_anchor.text_anchor.buffer_id = Some(999);
+// let invalid_point = Point::new(9999, 0);
+// editor.navigate(
+// Box::new(NavigationData {
+// cursor_anchor: invalid_anchor,
+// cursor_position: invalid_point,
+// scroll_anchor: ScrollAnchor {
+// anchor: invalid_anchor,
+// offset: Default::default(),
+// },
+// scroll_top_row: invalid_point.row,
+// }),
+// cx,
+// );
+// assert_eq!(
+// editor.selections.display_ranges(cx),
+// &[editor.max_point(cx)..editor.max_point(cx)]
+// );
+// assert_eq!(
+// editor.scroll_position(cx),
+// gpui::Point::new(0., editor.max_point(cx).row() as f32)
+// );
-// view.update(cx, |view, cx| {
-// view.cancel(&Cancel, cx);
-// view.update_selection(DisplayPoint::new(1, 1), 0, Point<Pixels>::zero(), cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
-// );
+// editor
+// })
// });
// }
-// #[gpui::test]
-// fn test_clone(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
+#[gpui::test]
+fn test_cancel(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
-// let (text, selection_ranges) = marked_text_ranges(
-// indoc! {"
-// one
-// two
-// threeˇ
-// four
-// fiveˇ
-// "},
-// true,
-// );
+ let view = cx.add_window(|cx| {
+ let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
+ build_editor(buffer, cx)
+ });
-// let editor = cx
-// .add_window(|cx| {
-// let buffer = MultiBuffer::build_simple(&text, cx);
-// build_editor(buffer, cx)
-// })
-// .root(cx);
+ view.update(cx, |view, cx| {
+ view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
+ view.update_selection(DisplayPoint::new(1, 1), 0, gpui::Point::<f32>::zero(), cx);
+ view.end_selection(cx);
+
+ view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
+ view.update_selection(DisplayPoint::new(0, 3), 0, gpui::Point::<f32>::zero(), cx);
+ view.end_selection(cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ [
+ DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
+ DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
+ ]
+ );
+ });
-// editor.update(cx, |editor, cx| {
-// editor.change_selections(None, cx, |s| s.select_ranges(selection_ranges.clone()));
-// editor.fold_ranges(
-// [
-// Point::new(1, 0)..Point::new(2, 0),
-// Point::new(3, 0)..Point::new(4, 0),
-// ],
-// true,
-// cx,
-// );
-// });
+ view.update(cx, |view, cx| {
+ view.cancel(&Cancel, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
+ );
+ });
-// let cloned_editor = editor
-// .update(cx, |editor, cx| {
-// cx.add_window(Default::default(), |cx| editor.clone(cx))
-// })
-// .root(cx);
+ view.update(cx, |view, cx| {
+ view.cancel(&Cancel, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
+ );
+ });
+}
-// let snapshot = editor.update(cx, |e, cx| e.snapshot(cx));
-// let cloned_snapshot = cloned_editor.update(cx, |e, cx| e.snapshot(cx));
+#[gpui::test]
+fn test_fold_action(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+
+ let view = cx.add_window(|cx| {
+ let buffer = MultiBuffer::build_simple(
+ &"
+ impl Foo {
+ // Hello!
+
+ fn a() {
+ 1
+ }
+
+ fn b() {
+ 2
+ }
+
+ fn c() {
+ 3
+ }
+ }
+ "
+ .unindent(),
+ cx,
+ );
+ build_editor(buffer.clone(), cx)
+ });
-// assert_eq!(
-// cloned_editor.update(cx, |e, cx| e.display_text(cx)),
-// editor.update(cx, |e, cx| e.display_text(cx))
-// );
-// assert_eq!(
-// cloned_snapshot
-// .folds_in_range(0..text.len())
-// .collect::<Vec<_>>(),
-// snapshot.folds_in_range(0..text.len()).collect::<Vec<_>>(),
-// );
-// assert_set_eq!(
-// cloned_editor.read_with(cx, |editor, cx| editor.selections.ranges::<Point>(cx)),
-// editor.read_with(cx, |editor, cx| editor.selections.ranges(cx))
-// );
-// assert_set_eq!(
-// cloned_editor.update(cx, |e, cx| e.selections.display_ranges(cx)),
-// editor.update(cx, |e, cx| e.selections.display_ranges(cx))
-// );
-// }
+ view.update(cx, |view, cx| {
+ view.change_selections(None, cx, |s| {
+ s.select_display_ranges([DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)]);
+ });
+ view.fold(&Fold, cx);
+ assert_eq!(
+ view.display_text(cx),
+ "
+ impl Foo {
+ // Hello!
+
+ fn a() {
+ 1
+ }
+
+ fn b() {⋯
+ }
+
+ fn c() {⋯
+ }
+ }
+ "
+ .unindent(),
+ );
+
+ view.fold(&Fold, cx);
+ assert_eq!(
+ view.display_text(cx),
+ "
+ impl Foo {⋯
+ }
+ "
+ .unindent(),
+ );
+
+ view.unfold_lines(&UnfoldLines, cx);
+ assert_eq!(
+ view.display_text(cx),
+ "
+ impl Foo {
+ // Hello!
+
+ fn a() {
+ 1
+ }
+
+ fn b() {⋯
+ }
+
+ fn c() {⋯
+ }
+ }
+ "
+ .unindent(),
+ );
+
+ view.unfold_lines(&UnfoldLines, cx);
+ assert_eq!(view.display_text(cx), view.buffer.read(cx).read(cx).text());
+ });
+}
-// #[gpui::test]
-// async fn test_navigation_history(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
+#[gpui::test]
+fn test_move_cursor(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+
+ let buffer = cx.update(|cx| MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx));
+ let view = cx.add_window(|cx| build_editor(buffer.clone(), cx));
+
+ buffer.update(cx, |buffer, cx| {
+ buffer.edit(
+ vec![
+ (Point::new(1, 0)..Point::new(1, 0), "\t"),
+ (Point::new(1, 1)..Point::new(1, 1), "\t"),
+ ],
+ None,
+ cx,
+ );
+ });
+ view.update(cx, |view, cx| {
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
+ );
+
+ view.move_down(&MoveDown, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
+ );
+
+ view.move_right(&MoveRight, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
+ );
+
+ view.move_left(&MoveLeft, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
+ );
+
+ view.move_up(&MoveUp, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
+ );
+
+ view.move_to_end(&MoveToEnd, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
+ );
+
+ view.move_to_beginning(&MoveToBeginning, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
+ );
+
+ view.change_selections(None, cx, |s| {
+ s.select_display_ranges([DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)]);
+ });
+ view.select_to_beginning(&SelectToBeginning, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
+ );
+
+ view.select_to_end(&SelectToEnd, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
+ );
+ });
+}
-// cx.set_global(DragAndDrop::<Workspace>::default());
-// use workspace::item::Item;
+#[gpui::test]
+fn test_move_cursor_multibyte(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
-// let fs = FakeFs::new(cx.background());
-// let project = Project::test(fs, [], cx).await;
-// let window = cx.add_window(|cx| Workspace::test_new(project, cx));
-// let workspace = window.root(cx);
-// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
-// window.add_view(cx, |cx| {
-// let buffer = MultiBuffer::build_simple(&sample_text(300, 5, 'a'), cx);
-// let mut editor = build_editor(buffer.clone(), cx);
-// let handle = cx.handle();
-// editor.set_nav_history(Some(pane.read(cx).nav_history_for_item(&handle)));
+ let view = cx.add_window(|cx| {
+ let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcde\nαβγδε", cx);
+ build_editor(buffer.clone(), cx)
+ });
-// fn pop_history(editor: &mut Editor, cx: &mut WindowContext) -> Option<NavigationEntry> {
-// editor.nav_history.as_mut().unwrap().pop_backward(cx)
-// }
+ assert_eq!('ⓐ'.len_utf8(), 3);
+ assert_eq!('α'.len_utf8(), 2);
+
+ view.update(cx, |view, cx| {
+ view.fold_ranges(
+ vec![
+ Point::new(0, 6)..Point::new(0, 12),
+ Point::new(1, 2)..Point::new(1, 4),
+ Point::new(2, 4)..Point::new(2, 8),
+ ],
+ true,
+ cx,
+ );
+ assert_eq!(view.display_text(cx), "ⓐⓑ⋯ⓔ\nab⋯e\nαβ⋯ε");
+
+ view.move_right(&MoveRight, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[empty_range(0, "ⓐ".len())]
+ );
+ view.move_right(&MoveRight, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[empty_range(0, "ⓐⓑ".len())]
+ );
+ view.move_right(&MoveRight, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[empty_range(0, "ⓐⓑ⋯".len())]
+ );
+
+ view.move_down(&MoveDown, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[empty_range(1, "ab⋯e".len())]
+ );
+ view.move_left(&MoveLeft, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[empty_range(1, "ab⋯".len())]
+ );
+ view.move_left(&MoveLeft, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[empty_range(1, "ab".len())]
+ );
+ view.move_left(&MoveLeft, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[empty_range(1, "a".len())]
+ );
+
+ view.move_down(&MoveDown, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[empty_range(2, "α".len())]
+ );
+ view.move_right(&MoveRight, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[empty_range(2, "αβ".len())]
+ );
+ view.move_right(&MoveRight, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[empty_range(2, "αβ⋯".len())]
+ );
+ view.move_right(&MoveRight, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[empty_range(2, "αβ⋯ε".len())]
+ );
+
+ view.move_up(&MoveUp, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[empty_range(1, "ab⋯e".len())]
+ );
+ view.move_down(&MoveDown, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[empty_range(2, "αβ⋯ε".len())]
+ );
+ view.move_up(&MoveUp, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[empty_range(1, "ab⋯e".len())]
+ );
+
+ view.move_up(&MoveUp, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[empty_range(0, "ⓐⓑ".len())]
+ );
+ view.move_left(&MoveLeft, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[empty_range(0, "ⓐ".len())]
+ );
+ view.move_left(&MoveLeft, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[empty_range(0, "".len())]
+ );
+ });
+}
-// // Move the cursor a small distance.
-// // Nothing is added to the navigation history.
-// editor.change_selections(None, cx, |s| {
-// s.select_display_ranges([DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)])
-// });
-// editor.change_selections(None, cx, |s| {
-// s.select_display_ranges([DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)])
-// });
-// assert!(pop_history(&mut editor, cx).is_none());
+//todo!(finish editor tests)
+// #[gpui::test]
+// fn test_move_cursor_different_line_lengths(cx: &mut TestAppContext) {
+// init_test(cx, |_| {});
-// // Move the cursor a large distance.
-// // The history can jump back to the previous position.
-// editor.change_selections(None, cx, |s| {
-// s.select_display_ranges([DisplayPoint::new(13, 0)..DisplayPoint::new(13, 3)])
+// let view = cx.add_window(|cx| {
+// let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
+// build_editor(buffer.clone(), cx)
+// });
+// view.update(cx, |view, cx| {
+// view.change_selections(None, cx, |s| {
+// s.select_display_ranges([empty_range(0, "ⓐⓑⓒⓓⓔ".len())]);
// });
-// let nav_entry = pop_history(&mut editor, cx).unwrap();
-// editor.navigate(nav_entry.data.unwrap(), cx);
-// assert_eq!(nav_entry.item.id(), cx.view_id());
+// view.move_down(&MoveDown, cx);
// assert_eq!(
-// editor.selections.display_ranges(cx),
-// &[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)]
+// view.selections.display_ranges(cx),
+// &[empty_range(1, "abcd".len())]
// );
-// assert!(pop_history(&mut editor, cx).is_none());
-// // Move the cursor a small distance via the mouse.
-// // Nothing is added to the navigation history.
-// editor.begin_selection(DisplayPoint::new(5, 0), false, 1, cx);
-// editor.end_selection(cx);
+// view.move_down(&MoveDown, cx);
// assert_eq!(
-// editor.selections.display_ranges(cx),
-// &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
+// view.selections.display_ranges(cx),
+// &[empty_range(2, "αβγ".len())]
// );
-// assert!(pop_history(&mut editor, cx).is_none());
-// // Move the cursor a large distance via the mouse.
-// // The history can jump back to the previous position.
-// editor.begin_selection(DisplayPoint::new(15, 0), false, 1, cx);
-// editor.end_selection(cx);
-// assert_eq!(
-// editor.selections.display_ranges(cx),
-// &[DisplayPoint::new(15, 0)..DisplayPoint::new(15, 0)]
-// );
-// let nav_entry = pop_history(&mut editor, cx).unwrap();
-// editor.navigate(nav_entry.data.unwrap(), cx);
-// assert_eq!(nav_entry.item.id(), cx.view_id());
-// assert_eq!(
-// editor.selections.display_ranges(cx),
-// &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
-// );
-// assert!(pop_history(&mut editor, cx).is_none());
-
-// // Set scroll position to check later
-// editor.set_scroll_position(Point<Pixels>::new(5.5, 5.5), cx);
-// let original_scroll_position = editor.scroll_manager.anchor();
-
-// // Jump to the end of the document and adjust scroll
-// editor.move_to_end(&MoveToEnd, cx);
-// editor.set_scroll_position(Point<Pixels>::new(-2.5, -0.5), cx);
-// assert_ne!(editor.scroll_manager.anchor(), original_scroll_position);
-
-// let nav_entry = pop_history(&mut editor, cx).unwrap();
-// editor.navigate(nav_entry.data.unwrap(), cx);
-// assert_eq!(editor.scroll_manager.anchor(), original_scroll_position);
-
-// // Ensure we don't panic when navigation data contains invalid anchors *and* points.
-// let mut invalid_anchor = editor.scroll_manager.anchor().anchor;
-// invalid_anchor.text_anchor.buffer_id = Some(999);
-// let invalid_point = Point::new(9999, 0);
-// editor.navigate(
-// Box::new(NavigationData {
-// cursor_anchor: invalid_anchor,
-// cursor_position: invalid_point,
-// scroll_anchor: ScrollAnchor {
-// anchor: invalid_anchor,
-// offset: Default::default(),
-// },
-// scroll_top_row: invalid_point.row,
-// }),
-// cx,
-// );
-// assert_eq!(
-// editor.selections.display_ranges(cx),
-// &[editor.max_point(cx)..editor.max_point(cx)]
-// );
+// view.move_down(&MoveDown, cx);
// assert_eq!(
-// editor.scroll_position(cx),
-// vec2f(0., editor.max_point(cx).row() as f32)
+// view.selections.display_ranges(cx),
+// &[empty_range(3, "abcd".len())]
// );
-// editor
-// });
-// }
-
-// #[gpui::test]
-// fn test_cancel(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
-
-// let view = cx
-// .add_window(|cx| {
-// let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
-// build_editor(buffer, cx)
-// })
-// .root(cx);
-
-// view.update(cx, |view, cx| {
-// view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
-// view.update_selection(DisplayPoint::new(1, 1), 0, Point<Pixels>::zero(), cx);
-// view.end_selection(cx);
-
-// view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
-// view.update_selection(DisplayPoint::new(0, 3), 0, Point<Pixels>::zero(), cx);
-// view.end_selection(cx);
+// view.move_down(&MoveDown, cx);
// assert_eq!(
// view.selections.display_ranges(cx),
-// [
-// DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
-// DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
-// ]
+// &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
// );
-// });
-// view.update(cx, |view, cx| {
-// view.cancel(&Cancel, cx);
+// view.move_up(&MoveUp, cx);
// assert_eq!(
// view.selections.display_ranges(cx),
-// [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
+// &[empty_range(3, "abcd".len())]
// );
-// });
-// view.update(cx, |view, cx| {
-// view.cancel(&Cancel, cx);
+// view.move_up(&MoveUp, cx);
// assert_eq!(
// view.selections.display_ranges(cx),
-// [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
+// &[empty_range(2, "αβγ".len())]
// );
// });
// }
-// #[gpui::test]
-// fn test_fold_action(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
+#[gpui::test]
+fn test_beginning_end_of_line(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
-// let view = cx
-// .add_window(|cx| {
-// let buffer = MultiBuffer::build_simple(
-// &"
-// impl Foo {
-// // Hello!
-
-// fn a() {
-// 1
-// }
+ let view = cx.add_window(|cx| {
+ let buffer = MultiBuffer::build_simple("abc\n def", cx);
+ build_editor(buffer, cx)
+ });
+ view.update(cx, |view, cx| {
+ view.change_selections(None, cx, |s| {
+ s.select_display_ranges([
+ DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
+ DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
+ ]);
+ });
+ });
-// fn b() {
-// 2
-// }
+ view.update(cx, |view, cx| {
+ view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[
+ DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
+ DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
+ ]
+ );
+ });
-// fn c() {
-// 3
-// }
-// }
-// "
-// .unindent(),
-// cx,
-// );
-// build_editor(buffer.clone(), cx)
-// })
-// .root(cx);
+ view.update(cx, |view, cx| {
+ view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[
+ DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
+ DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
+ ]
+ );
+ });
-// view.update(cx, |view, cx| {
-// view.change_selections(None, cx, |s| {
-// s.select_display_ranges([DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)]);
-// });
-// view.fold(&Fold, cx);
-// assert_eq!(
-// view.display_text(cx),
-// "
-// impl Foo {
-// // Hello!
+ view.update(cx, |view, cx| {
+ view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[
+ DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
+ DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
+ ]
+ );
+ });
-// fn a() {
-// 1
-// }
+ view.update(cx, |view, cx| {
+ view.move_to_end_of_line(&MoveToEndOfLine, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[
+ DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
+ DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
+ ]
+ );
+ });
-// fn b() {⋯
-// }
+ // Moving to the end of line again is a no-op.
+ view.update(cx, |view, cx| {
+ view.move_to_end_of_line(&MoveToEndOfLine, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[
+ DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
+ DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
+ ]
+ );
+ });
-// fn c() {⋯
-// }
-// }
-// "
-// .unindent(),
-// );
+ view.update(cx, |view, cx| {
+ view.move_left(&MoveLeft, cx);
+ view.select_to_beginning_of_line(
+ &SelectToBeginningOfLine {
+ stop_at_soft_wraps: true,
+ },
+ cx,
+ );
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[
+ DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
+ DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
+ ]
+ );
+ });
-// view.fold(&Fold, cx);
-// assert_eq!(
-// view.display_text(cx),
-// "
-// impl Foo {⋯
-// }
-// "
-// .unindent(),
-// );
+ view.update(cx, |view, cx| {
+ view.select_to_beginning_of_line(
+ &SelectToBeginningOfLine {
+ stop_at_soft_wraps: true,
+ },
+ cx,
+ );
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[
+ DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
+ DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
+ ]
+ );
+ });
-// view.unfold_lines(&UnfoldLines, cx);
-// assert_eq!(
-// view.display_text(cx),
-// "
-// impl Foo {
-// // Hello!
+ view.update(cx, |view, cx| {
+ view.select_to_beginning_of_line(
+ &SelectToBeginningOfLine {
+ stop_at_soft_wraps: true,
+ },
+ cx,
+ );
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[
+ DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
+ DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
+ ]
+ );
+ });
-// fn a() {
-// 1
-// }
+ view.update(cx, |view, cx| {
+ view.select_to_end_of_line(
+ &SelectToEndOfLine {
+ stop_at_soft_wraps: true,
+ },
+ cx,
+ );
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[
+ DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
+ DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
+ ]
+ );
+ });
-// fn b() {⋯
-// }
+ view.update(cx, |view, cx| {
+ view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
+ assert_eq!(view.display_text(cx), "ab\n de");
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[
+ DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
+ DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
+ ]
+ );
+ });
-// fn c() {⋯
-// }
-// }
-// "
-// .unindent(),
-// );
+ view.update(cx, |view, cx| {
+ view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
+ assert_eq!(view.display_text(cx), "\n");
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[
+ DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
+ DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
+ ]
+ );
+ });
+}
-// view.unfold_lines(&UnfoldLines, cx);
-// assert_eq!(view.display_text(cx), view.buffer.read(cx).read(cx).text());
-// });
-// }
+#[gpui::test]
+fn test_prev_next_word_boundary(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+
+ let view = cx.add_window(|cx| {
+ let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n {baz.qux()}", cx);
+ build_editor(buffer, cx)
+ });
+ view.update(cx, |view, cx| {
+ view.change_selections(None, cx, |s| {
+ s.select_display_ranges([
+ DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
+ DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
+ ])
+ });
+
+ view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
+ assert_selection_ranges("use std::ˇstr::{foo, bar}\n\n {ˇbaz.qux()}", view, cx);
+
+ view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
+ assert_selection_ranges("use stdˇ::str::{foo, bar}\n\n ˇ{baz.qux()}", view, cx);
+
+ view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
+ assert_selection_ranges("use ˇstd::str::{foo, bar}\n\nˇ {baz.qux()}", view, cx);
+
+ view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
+ assert_selection_ranges("ˇuse std::str::{foo, bar}\nˇ\n {baz.qux()}", view, cx);
+
+ view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
+ assert_selection_ranges("ˇuse std::str::{foo, barˇ}\n\n {baz.qux()}", view, cx);
+
+ view.move_to_next_word_end(&MoveToNextWordEnd, cx);
+ assert_selection_ranges("useˇ std::str::{foo, bar}ˇ\n\n {baz.qux()}", view, cx);
+ view.move_to_next_word_end(&MoveToNextWordEnd, cx);
+ assert_selection_ranges("use stdˇ::str::{foo, bar}\nˇ\n {baz.qux()}", view, cx);
+
+ view.move_to_next_word_end(&MoveToNextWordEnd, cx);
+ assert_selection_ranges("use std::ˇstr::{foo, bar}\n\n {ˇbaz.qux()}", view, cx);
+
+ view.move_right(&MoveRight, cx);
+ view.select_to_previous_word_start(&SelectToPreviousWordStart, cx);
+ assert_selection_ranges("use std::«ˇs»tr::{foo, bar}\n\n {«ˇb»az.qux()}", view, cx);
+
+ view.select_to_previous_word_start(&SelectToPreviousWordStart, cx);
+ assert_selection_ranges("use std«ˇ::s»tr::{foo, bar}\n\n «ˇ{b»az.qux()}", view, cx);
+
+ view.select_to_next_word_end(&SelectToNextWordEnd, cx);
+ assert_selection_ranges("use std::«ˇs»tr::{foo, bar}\n\n {«ˇb»az.qux()}", view, cx);
+ });
+}
+
+//todo!(finish editor tests)
// #[gpui::test]
-// fn test_move_cursor(cx: &mut TestAppContext) {
+// fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut TestAppContext) {
// init_test(cx, |_| {});
-// let buffer = cx.update(|cx| MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx));
-// let view = cx
-// .add_window(|cx| build_editor(buffer.clone(), cx))
-// .root(cx);
-
-// buffer.update(cx, |buffer, cx| {
-// buffer.edit(
-// vec![
-// (Point::new(1, 0)..Point::new(1, 0), "\t"),
-// (Point::new(1, 1)..Point::new(1, 1), "\t"),
-// ],
-// None,
-// cx,
-// );
+// let view = cx.add_window(|cx| {
+// let buffer = MultiBuffer::build_simple("use one::{\n two::three::four::five\n};", cx);
+// build_editor(buffer, cx)
// });
-// view.update(cx, |view, cx| {
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
-// );
-// view.move_down(&MoveDown, cx);
+// view.update(cx, |view, cx| {
+// view.set_wrap_width(Some(140.0.into()), cx);
// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
+// view.display_text(cx),
+// "use one::{\n two::three::\n four::five\n};"
// );
-// view.move_right(&MoveRight, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
-// );
+// view.change_selections(None, cx, |s| {
+// s.select_display_ranges([DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)]);
+// });
-// view.move_left(&MoveLeft, cx);
+// view.move_to_next_word_end(&MoveToNextWordEnd, cx);
// assert_eq!(
// view.selections.display_ranges(cx),
-// &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
+// &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
// );
-// view.move_up(&MoveUp, cx);
+// view.move_to_next_word_end(&MoveToNextWordEnd, cx);
// assert_eq!(
// view.selections.display_ranges(cx),
-// &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
+// &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
// );
-// view.move_to_end(&MoveToEnd, cx);
+// view.move_to_next_word_end(&MoveToNextWordEnd, cx);
// assert_eq!(
// view.selections.display_ranges(cx),
-// &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
+// &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
// );
-// view.move_to_beginning(&MoveToBeginning, cx);
+// view.move_to_next_word_end(&MoveToNextWordEnd, cx);
// assert_eq!(
// view.selections.display_ranges(cx),
-// &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
+// &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
// );
-// view.change_selections(None, cx, |s| {
-// s.select_display_ranges([DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)]);
-// });
-// view.select_to_beginning(&SelectToBeginning, cx);
+// view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
// assert_eq!(
// view.selections.display_ranges(cx),
-// &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
+// &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
// );
-// view.select_to_end(&SelectToEnd, cx);
+// view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
// assert_eq!(
// view.selections.display_ranges(cx),
-// &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
+// &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
// );
// });
// }
+//todo!(simulate_resize)
// #[gpui::test]
-// fn test_move_cursor_multibyte(cx: &mut TestAppContext) {
+// async fn test_move_start_of_paragraph_end_of_paragraph(cx: &mut gpui::TestAppContext) {
// init_test(cx, |_| {});
+// let mut cx = EditorTestContext::new(cx).await;
-// let view = cx
-// .add_window(|cx| {
-// let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcde\nαβγδε", cx);
-// build_editor(buffer.clone(), cx)
-// })
-// .root(cx);
+// let line_height = cx.editor(|editor, cx| editor.style(cx).text.line_height(cx.font_cache()));
+// let window = cx.window;
+// window.simulate_resize(gpui::Point::new(100., 4. * line_height), &mut cx);
-// assert_eq!('ⓐ'.len_utf8(), 3);
-// assert_eq!('α'.len_utf8(), 2);
+// cx.set_state(
+// &r#"ˇone
+// two
-// view.update(cx, |view, cx| {
-// view.fold_ranges(
-// vec![
-// Point::new(0, 6)..Point::new(0, 12),
-// Point::new(1, 2)..Point::new(1, 4),
-// Point::new(2, 4)..Point::new(2, 8),
-// ],
-// true,
-// cx,
-// );
-// assert_eq!(view.display_text(cx), "ⓐⓑ⋯ⓔ\nab⋯e\nαβ⋯ε");
+// three
+// fourˇ
+// five
-// view.move_right(&MoveRight, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[empty_range(0, "ⓐ".len())]
-// );
-// view.move_right(&MoveRight, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[empty_range(0, "ⓐⓑ".len())]
-// );
-// view.move_right(&MoveRight, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[empty_range(0, "ⓐⓑ⋯".len())]
-// );
+// six"#
+// .unindent(),
+// );
-// view.move_down(&MoveDown, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[empty_range(1, "ab⋯e".len())]
-// );
-// view.move_left(&MoveLeft, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[empty_range(1, "ab⋯".len())]
-// );
-// view.move_left(&MoveLeft, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[empty_range(1, "ab".len())]
-// );
-// view.move_left(&MoveLeft, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[empty_range(1, "a".len())]
-// );
+// cx.update_editor(|editor, cx| editor.move_to_end_of_paragraph(&MoveToEndOfParagraph, cx));
+// cx.assert_editor_state(
+// &r#"one
+// two
+// ˇ
+// three
+// four
+// five
+// ˇ
+// six"#
+// .unindent(),
+// );
-// view.move_down(&MoveDown, cx);
+// cx.update_editor(|editor, cx| editor.move_to_end_of_paragraph(&MoveToEndOfParagraph, cx));
+// cx.assert_editor_state(
+// &r#"one
+// two
+
+// three
+// four
+// five
+// ˇ
+// sixˇ"#
+// .unindent(),
+// );
+
+// cx.update_editor(|editor, cx| editor.move_to_end_of_paragraph(&MoveToEndOfParagraph, cx));
+// cx.assert_editor_state(
+// &r#"one
+// two
+
+// three
+// four
+// five
+
+// sixˇ"#
+// .unindent(),
+// );
+
+// cx.update_editor(|editor, cx| editor.move_to_start_of_paragraph(&MoveToStartOfParagraph, cx));
+// cx.assert_editor_state(
+// &r#"one
+// two
+
+// three
+// four
+// five
+// ˇ
+// six"#
+// .unindent(),
+// );
+
+// cx.update_editor(|editor, cx| editor.move_to_start_of_paragraph(&MoveToStartOfParagraph, cx));
+// cx.assert_editor_state(
+// &r#"one
+// two
+// ˇ
+// three
+// four
+// five
+
+// six"#
+// .unindent(),
+// );
+
+// cx.update_editor(|editor, cx| editor.move_to_start_of_paragraph(&MoveToStartOfParagraph, cx));
+// cx.assert_editor_state(
+// &r#"ˇone
+// two
+
+// three
+// four
+// five
+
+// six"#
+// .unindent(),
+// );
+// }
+
+// #[gpui::test]
+// async fn test_scroll_page_up_page_down(cx: &mut gpui::TestAppContext) {
+// init_test(cx, |_| {});
+// let mut cx = EditorTestContext::new(cx).await;
+// let line_height = cx.editor(|editor, cx| editor.style(cx).text.line_height(cx.font_cache()));
+// let window = cx.window;
+// window.simulate_resize(Point::new(1000., 4. * line_height + 0.5), &mut cx);
+
+// cx.set_state(
+// &r#"ˇone
+// two
+// three
+// four
+// five
+// six
+// seven
+// eight
+// nine
+// ten
+// "#,
+// );
+
+// cx.update_editor(|editor, cx| {
// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[empty_range(2, "α".len())]
+// editor.snapshot(cx).scroll_position(),
+// gpui::Point::new(0., 0.)
// );
-// view.move_right(&MoveRight, cx);
+// editor.scroll_screen(&ScrollAmount::Page(1.), cx);
// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[empty_range(2, "αβ".len())]
+// editor.snapshot(cx).scroll_position(),
+// gpui::Point::new(0., 3.)
// );
-// view.move_right(&MoveRight, cx);
+// editor.scroll_screen(&ScrollAmount::Page(1.), cx);
// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[empty_range(2, "αβ⋯".len())]
+// editor.snapshot(cx).scroll_position(),
+// gpui::Point::new(0., 6.)
// );
-// view.move_right(&MoveRight, cx);
+// editor.scroll_screen(&ScrollAmount::Page(-1.), cx);
// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[empty_range(2, "αβ⋯ε".len())]
+// editor.snapshot(cx).scroll_position(),
+// gpui::Point::new(0., 3.)
// );
-// view.move_up(&MoveUp, cx);
+// editor.scroll_screen(&ScrollAmount::Page(-0.5), cx);
// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[empty_range(1, "ab⋯e".len())]
+// editor.snapshot(cx).scroll_position(),
+// gpui::Point::new(0., 1.)
// );
-// view.move_down(&MoveDown, cx);
+// editor.scroll_screen(&ScrollAmount::Page(0.5), cx);
// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[empty_range(2, "αβ⋯ε".len())]
-// );
-// view.move_up(&MoveUp, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[empty_range(1, "ab⋯e".len())]
-// );
-
-// view.move_up(&MoveUp, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[empty_range(0, "ⓐⓑ".len())]
-// );
-// view.move_left(&MoveLeft, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[empty_range(0, "ⓐ".len())]
-// );
-// view.move_left(&MoveLeft, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[empty_range(0, "".len())]
-// );
-// });
-// }
-
-// #[gpui::test]
-// fn test_move_cursor_different_line_lengths(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
-
-// let view = cx
-// .add_window(|cx| {
-// let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
-// build_editor(buffer.clone(), cx)
-// })
-// .root(cx);
-// view.update(cx, |view, cx| {
-// view.change_selections(None, cx, |s| {
-// s.select_display_ranges([empty_range(0, "ⓐⓑⓒⓓⓔ".len())]);
-// });
-// view.move_down(&MoveDown, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[empty_range(1, "abcd".len())]
-// );
-
-// view.move_down(&MoveDown, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[empty_range(2, "αβγ".len())]
-// );
-
-// view.move_down(&MoveDown, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[empty_range(3, "abcd".len())]
-// );
-
-// view.move_down(&MoveDown, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
-// );
-
-// view.move_up(&MoveUp, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[empty_range(3, "abcd".len())]
-// );
-
-// view.move_up(&MoveUp, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[empty_range(2, "αβγ".len())]
+// editor.snapshot(cx).scroll_position(),
+// gpui::Point::new(0., 3.)
// );
// });
// }
// #[gpui::test]
-// fn test_beginning_end_of_line(cx: &mut TestAppContext) {
+// async fn test_autoscroll(cx: &mut gpui::TestAppContext) {
// init_test(cx, |_| {});
+// let mut cx = EditorTestContext::new(cx).await;
-// let view = cx
-// .add_window(|cx| {
-// let buffer = MultiBuffer::build_simple("abc\n def", cx);
-// build_editor(buffer, cx)
-// })
-// .root(cx);
-// view.update(cx, |view, cx| {
-// view.change_selections(None, cx, |s| {
-// s.select_display_ranges([
-// DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
-// DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
-// ]);
-// });
-// });
-
-// view.update(cx, |view, cx| {
-// view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[
-// DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
-// DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
-// ]
-// );
-// });
-
-// view.update(cx, |view, cx| {
-// view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[
-// DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
-// DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
-// ]
-// );
-// });
-
-// view.update(cx, |view, cx| {
-// view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[
-// DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
-// DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
-// ]
-// );
+// let line_height = cx.update_editor(|editor, cx| {
+// editor.set_vertical_scroll_margin(2, cx);
+// editor.style(cx).text.line_height(cx.font_cache())
// });
-// view.update(cx, |view, cx| {
-// view.move_to_end_of_line(&MoveToEndOfLine, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[
-// DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
-// DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
-// ]
-// );
-// });
+// let window = cx.window;
+// window.simulate_resize(gpui::Point::new(1000., 6.0 * line_height), &mut cx);
-// // Moving to the end of line again is a no-op.
-// view.update(cx, |view, cx| {
-// view.move_to_end_of_line(&MoveToEndOfLine, cx);
+// cx.set_state(
+// &r#"ˇone
+// two
+// three
+// four
+// five
+// six
+// seven
+// eight
+// nine
+// ten
+// "#,
+// );
+// cx.update_editor(|editor, cx| {
// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[
-// DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
-// DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
-// ]
+// editor.snapshot(cx).scroll_position(),
+// gpui::Point::new(0., 0.0)
// );
// });
-// view.update(cx, |view, cx| {
-// view.move_left(&MoveLeft, cx);
-// view.select_to_beginning_of_line(
-// &SelectToBeginningOfLine {
-// stop_at_soft_wraps: true,
-// },
-// cx,
-// );
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[
-// DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
-// DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
-// ]
-// );
+// // Add a cursor below the visible area. Since both cursors cannot fit
+// // on screen, the editor autoscrolls to reveal the newest cursor, and
+// // allows the vertical scroll margin below that cursor.
+// cx.update_editor(|editor, cx| {
+// editor.change_selections(Some(Autoscroll::fit()), cx, |selections| {
+// selections.select_ranges([
+// Point::new(0, 0)..Point::new(0, 0),
+// Point::new(6, 0)..Point::new(6, 0),
+// ]);
+// })
// });
-
-// view.update(cx, |view, cx| {
-// view.select_to_beginning_of_line(
-// &SelectToBeginningOfLine {
-// stop_at_soft_wraps: true,
-// },
-// cx,
-// );
+// cx.update_editor(|editor, cx| {
// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[
-// DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
-// DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
-// ]
+// editor.snapshot(cx).scroll_position(),
+// gpui::Point::new(0., 3.0)
// );
// });
-// view.update(cx, |view, cx| {
-// view.select_to_beginning_of_line(
-// &SelectToBeginningOfLine {
-// stop_at_soft_wraps: true,
-// },
-// cx,
-// );
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[
-// DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
-// DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
-// ]
-// );
+// // Move down. The editor cursor scrolls down to track the newest cursor.
+// cx.update_editor(|editor, cx| {
+// editor.move_down(&Default::default(), cx);
// });
-
-// view.update(cx, |view, cx| {
-// view.select_to_end_of_line(
-// &SelectToEndOfLine {
-// stop_at_soft_wraps: true,
-// },
-// cx,
-// );
+// cx.update_editor(|editor, cx| {
// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[
-// DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
-// DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
-// ]
+// editor.snapshot(cx).scroll_position(),
+// gpui::Point::new(0., 4.0)
// );
// });
-// view.update(cx, |view, cx| {
-// view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
-// assert_eq!(view.display_text(cx), "ab\n de");
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[
-// DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
-// DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
-// ]
-// );
+// // Add a cursor above the visible area. Since both cursors fit on screen,
+// // the editor scrolls to show both.
+// cx.update_editor(|editor, cx| {
+// editor.change_selections(Some(Autoscroll::fit()), cx, |selections| {
+// selections.select_ranges([
+// Point::new(1, 0)..Point::new(1, 0),
+// Point::new(6, 0)..Point::new(6, 0),
+// ]);
+// })
// });
-
-// view.update(cx, |view, cx| {
-// view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
-// assert_eq!(view.display_text(cx), "\n");
+// cx.update_editor(|editor, cx| {
// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[
-// DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
-// DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
-// ]
+// editor.snapshot(cx).scroll_position(),
+// gpui::Point::new(0., 1.0)
// );
// });
// }
// #[gpui::test]
-// fn test_prev_next_word_boundary(cx: &mut TestAppContext) {
+// async fn test_move_page_up_page_down(cx: &mut gpui::TestAppContext) {
// init_test(cx, |_| {});
+// let mut cx = EditorTestContext::new(cx).await;
-// let view = cx
-// .add_window(|cx| {
-// let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n {baz.qux()}", cx);
-// build_editor(buffer, cx)
-// })
-// .root(cx);
-// view.update(cx, |view, cx| {
-// view.change_selections(None, cx, |s| {
-// s.select_display_ranges([
-// DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
-// DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
-// ])
-// });
-
-// view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
-// assert_selection_ranges("use std::ˇstr::{foo, bar}\n\n {ˇbaz.qux()}", view, cx);
-
-// view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
-// assert_selection_ranges("use stdˇ::str::{foo, bar}\n\n ˇ{baz.qux()}", view, cx);
-
-// view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
-// assert_selection_ranges("use ˇstd::str::{foo, bar}\n\nˇ {baz.qux()}", view, cx);
+// let line_height = cx.editor(|editor, cx| editor.style(cx).text.line_height(cx.font_cache()));
+// let window = cx.window;
+// window.simulate_resize(gpui::Point::new(100., 4. * line_height), &mut cx);
-// view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
-// assert_selection_ranges("ˇuse std::str::{foo, bar}\nˇ\n {baz.qux()}", view, cx);
+// cx.set_state(
+// &r#"
+// ˇone
+// two
+// threeˇ
+// four
+// five
+// six
+// seven
+// eight
+// nine
+// ten
+// "#
+// .unindent(),
+// );
-// view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
-// assert_selection_ranges("ˇuse std::str::{foo, barˇ}\n\n {baz.qux()}", view, cx);
+// cx.update_editor(|editor, cx| editor.move_page_down(&MovePageDown::default(), cx));
+// cx.assert_editor_state(
+// &r#"
+// one
+// two
+// three
+// ˇfour
+// five
+// sixˇ
+// seven
+// eight
+// nine
+// ten
+// "#
+// .unindent(),
+// );
-// view.move_to_next_word_end(&MoveToNextWordEnd, cx);
-// assert_selection_ranges("useˇ std::str::{foo, bar}ˇ\n\n {baz.qux()}", view, cx);
+// cx.update_editor(|editor, cx| editor.move_page_down(&MovePageDown::default(), cx));
+// cx.assert_editor_state(
+// &r#"
+// one
+// two
+// three
+// four
+// five
+// six
+// ˇseven
+// eight
+// nineˇ
+// ten
+// "#
+// .unindent(),
+// );
-// view.move_to_next_word_end(&MoveToNextWordEnd, cx);
-// assert_selection_ranges("use stdˇ::str::{foo, bar}\nˇ\n {baz.qux()}", view, cx);
-
-// view.move_to_next_word_end(&MoveToNextWordEnd, cx);
-// assert_selection_ranges("use std::ˇstr::{foo, bar}\n\n {ˇbaz.qux()}", view, cx);
-
-// view.move_right(&MoveRight, cx);
-// view.select_to_previous_word_start(&SelectToPreviousWordStart, cx);
-// assert_selection_ranges("use std::«ˇs»tr::{foo, bar}\n\n {«ˇb»az.qux()}", view, cx);
+// cx.update_editor(|editor, cx| editor.move_page_up(&MovePageUp::default(), cx));
+// cx.assert_editor_state(
+// &r#"
+// one
+// two
+// three
+// ˇfour
+// five
+// sixˇ
+// seven
+// eight
+// nine
+// ten
+// "#
+// .unindent(),
+// );
-// view.select_to_previous_word_start(&SelectToPreviousWordStart, cx);
-// assert_selection_ranges("use std«ˇ::s»tr::{foo, bar}\n\n «ˇ{b»az.qux()}", view, cx);
+// cx.update_editor(|editor, cx| editor.move_page_up(&MovePageUp::default(), cx));
+// cx.assert_editor_state(
+// &r#"
+// ˇone
+// two
+// threeˇ
+// four
+// five
+// six
+// seven
+// eight
+// nine
+// ten
+// "#
+// .unindent(),
+// );
-// view.select_to_next_word_end(&SelectToNextWordEnd, cx);
-// assert_selection_ranges("use std::«ˇs»tr::{foo, bar}\n\n {«ˇb»az.qux()}", view, cx);
+// // Test select collapsing
+// cx.update_editor(|editor, cx| {
+// editor.move_page_down(&MovePageDown::default(), cx);
+// editor.move_page_down(&MovePageDown::default(), cx);
+// editor.move_page_down(&MovePageDown::default(), cx);
// });
+// cx.assert_editor_state(
+// &r#"
+// one
+// two
+// three
+// four
+// five
+// six
+// seven
+// eight
+// nine
+// ˇten
+// ˇ"#
+// .unindent(),
+// );
// }
-// #[gpui::test]
-// fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
+#[gpui::test]
+async fn test_delete_to_beginning_of_line(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |_| {});
+ let mut cx = EditorTestContext::new(cx).await;
+ cx.set_state("one «two threeˇ» four");
+ cx.update_editor(|editor, cx| {
+ editor.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
+ assert_eq!(editor.text(cx), " four");
+ });
+}
-// let view = cx
-// .add_window(|cx| {
-// let buffer =
-// MultiBuffer::build_simple("use one::{\n two::three::four::five\n};", cx);
-// build_editor(buffer, cx)
-// })
-// .root(cx);
+#[gpui::test]
+fn test_delete_to_word_boundary(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
-// view.update(cx, |view, cx| {
-// view.set_wrap_width(Some(140.), cx);
-// assert_eq!(
-// view.display_text(cx),
-// "use one::{\n two::three::\n four::five\n};"
-// );
+ let view = cx.add_window(|cx| {
+ let buffer = MultiBuffer::build_simple("one two three four", cx);
+ build_editor(buffer.clone(), cx)
+ });
-// view.change_selections(None, cx, |s| {
-// s.select_display_ranges([DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)]);
-// });
+ view.update(cx, |view, cx| {
+ view.change_selections(None, cx, |s| {
+ s.select_display_ranges([
+ // an empty selection - the preceding word fragment is deleted
+ DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
+ // characters selected - they are deleted
+ DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
+ ])
+ });
+ view.delete_to_previous_word_start(&DeleteToPreviousWordStart, cx);
+ assert_eq!(view.buffer.read(cx).read(cx).text(), "e two te four");
+ });
-// view.move_to_next_word_end(&MoveToNextWordEnd, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
-// );
+ view.update(cx, |view, cx| {
+ view.change_selections(None, cx, |s| {
+ s.select_display_ranges([
+ // an empty selection - the following word fragment is deleted
+ DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
+ // characters selected - they are deleted
+ DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
+ ])
+ });
+ view.delete_to_next_word_end(&DeleteToNextWordEnd, cx);
+ assert_eq!(view.buffer.read(cx).read(cx).text(), "e t te our");
+ });
+}
-// view.move_to_next_word_end(&MoveToNextWordEnd, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
-// );
+#[gpui::test]
+fn test_newline(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
-// view.move_to_next_word_end(&MoveToNextWordEnd, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
-// );
+ let view = cx.add_window(|cx| {
+ let buffer = MultiBuffer::build_simple("aaaa\n bbbb\n", cx);
+ build_editor(buffer.clone(), cx)
+ });
-// view.move_to_next_word_end(&MoveToNextWordEnd, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
-// );
+ view.update(cx, |view, cx| {
+ view.change_selections(None, cx, |s| {
+ s.select_display_ranges([
+ DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
+ DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
+ DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
+ ])
+ });
-// view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
-// );
+ view.newline(&Newline, cx);
+ assert_eq!(view.text(cx), "aa\naa\n \n bb\n bb\n");
+ });
+}
-// view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
-// );
-// });
-// }
+#[gpui::test]
+fn test_newline_with_old_selections(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+
+ let editor = cx.add_window(|cx| {
+ let buffer = MultiBuffer::build_simple(
+ "
+ a
+ b(
+ X
+ )
+ c(
+ X
+ )
+ "
+ .unindent()
+ .as_str(),
+ cx,
+ );
+ let mut editor = build_editor(buffer.clone(), cx);
+ editor.change_selections(None, cx, |s| {
+ s.select_ranges([
+ Point::new(2, 4)..Point::new(2, 5),
+ Point::new(5, 4)..Point::new(5, 5),
+ ])
+ });
+ editor
+ });
-// #[gpui::test]
-// async fn test_move_start_of_paragraph_end_of_paragraph(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |_| {});
-// let mut cx = EditorTestContext::new(cx).await;
+ editor.update(cx, |editor, cx| {
+ // Edit the buffer directly, deleting ranges surrounding the editor's selections
+ editor.buffer.update(cx, |buffer, cx| {
+ buffer.edit(
+ [
+ (Point::new(1, 2)..Point::new(3, 0), ""),
+ (Point::new(4, 2)..Point::new(6, 0), ""),
+ ],
+ None,
+ cx,
+ );
+ assert_eq!(
+ buffer.read(cx).text(),
+ "
+ a
+ b()
+ c()
+ "
+ .unindent()
+ );
+ });
+ assert_eq!(
+ editor.selections.ranges(cx),
+ &[
+ Point::new(1, 2)..Point::new(1, 2),
+ Point::new(2, 2)..Point::new(2, 2),
+ ],
+ );
+
+ editor.newline(&Newline, cx);
+ assert_eq!(
+ editor.text(cx),
+ "
+ a
+ b(
+ )
+ c(
+ )
+ "
+ .unindent()
+ );
+
+ // The selections are moved after the inserted newlines
+ assert_eq!(
+ editor.selections.ranges(cx),
+ &[
+ Point::new(2, 0)..Point::new(2, 0),
+ Point::new(4, 0)..Point::new(4, 0),
+ ],
+ );
+ });
+}
-// let line_height = cx.editor(|editor, cx| editor.style(cx).text.line_height(cx.font_cache()));
-// let window = cx.window;
-// window.simulate_resize(vec2f(100., 4. * line_height), &mut cx);
+#[gpui::test]
+async fn test_newline_above(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |settings| {
+ settings.defaults.tab_size = NonZeroU32::new(4)
+ });
-// cx.set_state(
-// &r#"ˇone
-// two
+ let language = Arc::new(
+ Language::new(
+ LanguageConfig::default(),
+ Some(tree_sitter_rust::language()),
+ )
+ .with_indents_query(r#"(_ "(" ")" @end) @indent"#)
+ .unwrap(),
+ );
+
+ let mut cx = EditorTestContext::new(cx).await;
+ cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
+ cx.set_state(indoc! {"
+ const a: ˇA = (
+ (ˇ
+ «const_functionˇ»(ˇ),
+ so«mˇ»et«hˇ»ing_ˇelse,ˇ
+ )ˇ
+ ˇ);ˇ
+ "});
+
+ cx.update_editor(|e, cx| e.newline_above(&NewlineAbove, cx));
+ cx.assert_editor_state(indoc! {"
+ ˇ
+ const a: A = (
+ ˇ
+ (
+ ˇ
+ ˇ
+ const_function(),
+ ˇ
+ ˇ
+ ˇ
+ ˇ
+ something_else,
+ ˇ
+ )
+ ˇ
+ ˇ
+ );
+ "});
+}
-// three
-// fourˇ
-// five
+#[gpui::test]
+async fn test_newline_below(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |settings| {
+ settings.defaults.tab_size = NonZeroU32::new(4)
+ });
-// six"#
-// .unindent(),
-// );
+ let language = Arc::new(
+ Language::new(
+ LanguageConfig::default(),
+ Some(tree_sitter_rust::language()),
+ )
+ .with_indents_query(r#"(_ "(" ")" @end) @indent"#)
+ .unwrap(),
+ );
+
+ let mut cx = EditorTestContext::new(cx).await;
+ cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
+ cx.set_state(indoc! {"
+ const a: ˇA = (
+ (ˇ
+ «const_functionˇ»(ˇ),
+ so«mˇ»et«hˇ»ing_ˇelse,ˇ
+ )ˇ
+ ˇ);ˇ
+ "});
+
+ cx.update_editor(|e, cx| e.newline_below(&NewlineBelow, cx));
+ cx.assert_editor_state(indoc! {"
+ const a: A = (
+ ˇ
+ (
+ ˇ
+ const_function(),
+ ˇ
+ ˇ
+ something_else,
+ ˇ
+ ˇ
+ ˇ
+ ˇ
+ )
+ ˇ
+ );
+ ˇ
+ ˇ
+ "});
+}
-// cx.update_editor(|editor, cx| editor.move_to_end_of_paragraph(&MoveToEndOfParagraph, cx));
-// cx.assert_editor_state(
-// &r#"one
-// two
-// ˇ
-// three
-// four
-// five
-// ˇ
-// six"#
-// .unindent(),
-// );
+#[gpui::test]
+async fn test_newline_comments(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |settings| {
+ settings.defaults.tab_size = NonZeroU32::new(4)
+ });
-// cx.update_editor(|editor, cx| editor.move_to_end_of_paragraph(&MoveToEndOfParagraph, cx));
-// cx.assert_editor_state(
-// &r#"one
-// two
+ let language = Arc::new(Language::new(
+ LanguageConfig {
+ line_comment: Some("//".into()),
+ ..LanguageConfig::default()
+ },
+ None,
+ ));
+ {
+ let mut cx = EditorTestContext::new(cx).await;
+ cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
+ cx.set_state(indoc! {"
+ // Fooˇ
+ "});
+
+ cx.update_editor(|e, cx| e.newline(&Newline, cx));
+ cx.assert_editor_state(indoc! {"
+ // Foo
+ //ˇ
+ "});
+ // Ensure that if cursor is before the comment start, we do not actually insert a comment prefix.
+ cx.set_state(indoc! {"
+ ˇ// Foo
+ "});
+ cx.update_editor(|e, cx| e.newline(&Newline, cx));
+ cx.assert_editor_state(indoc! {"
+
+ ˇ// Foo
+ "});
+ }
+ // Ensure that comment continuations can be disabled.
+ update_test_language_settings(cx, |settings| {
+ settings.defaults.extend_comment_on_newline = Some(false);
+ });
+ let mut cx = EditorTestContext::new(cx).await;
+ cx.set_state(indoc! {"
+ // Fooˇ
+ "});
+ cx.update_editor(|e, cx| e.newline(&Newline, cx));
+ cx.assert_editor_state(indoc! {"
+ // Foo
+ ˇ
+ "});
+}
-// three
-// four
-// five
-// ˇ
-// sixˇ"#
-// .unindent(),
-// );
+#[gpui::test]
+fn test_insert_with_old_selections(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
-// cx.update_editor(|editor, cx| editor.move_to_end_of_paragraph(&MoveToEndOfParagraph, cx));
-// cx.assert_editor_state(
-// &r#"one
-// two
+ let editor = cx.add_window(|cx| {
+ let buffer = MultiBuffer::build_simple("a( X ), b( Y ), c( Z )", cx);
+ let mut editor = build_editor(buffer.clone(), cx);
+ editor.change_selections(None, cx, |s| s.select_ranges([3..4, 11..12, 19..20]));
+ editor
+ });
-// three
-// four
-// five
+ editor.update(cx, |editor, cx| {
+ // Edit the buffer directly, deleting ranges surrounding the editor's selections
+ editor.buffer.update(cx, |buffer, cx| {
+ buffer.edit([(2..5, ""), (10..13, ""), (18..21, "")], None, cx);
+ assert_eq!(buffer.read(cx).text(), "a(), b(), c()".unindent());
+ });
+ assert_eq!(editor.selections.ranges(cx), &[2..2, 7..7, 12..12],);
-// sixˇ"#
-// .unindent(),
-// );
+ editor.insert("Z", cx);
+ assert_eq!(editor.text(cx), "a(Z), b(Z), c(Z)");
-// cx.update_editor(|editor, cx| editor.move_to_start_of_paragraph(&MoveToStartOfParagraph, cx));
-// cx.assert_editor_state(
-// &r#"one
-// two
+ // The selections are moved after the inserted characters
+ assert_eq!(editor.selections.ranges(cx), &[3..3, 9..9, 15..15],);
+ });
+}
-// three
-// four
-// five
-// ˇ
-// six"#
-// .unindent(),
-// );
+#[gpui::test]
+async fn test_tab(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |settings| {
+ settings.defaults.tab_size = NonZeroU32::new(3)
+ });
-// cx.update_editor(|editor, cx| editor.move_to_start_of_paragraph(&MoveToStartOfParagraph, cx));
-// cx.assert_editor_state(
-// &r#"one
-// two
-// ˇ
-// three
-// four
-// five
+ let mut cx = EditorTestContext::new(cx).await;
+ cx.set_state(indoc! {"
+ ˇabˇc
+ ˇ🏀ˇ🏀ˇefg
+ dˇ
+ "});
+ cx.update_editor(|e, cx| e.tab(&Tab, cx));
+ cx.assert_editor_state(indoc! {"
+ ˇab ˇc
+ ˇ🏀 ˇ🏀 ˇefg
+ d ˇ
+ "});
+
+ cx.set_state(indoc! {"
+ a
+ «🏀ˇ»🏀«🏀ˇ»🏀«🏀ˇ»
+ "});
+ cx.update_editor(|e, cx| e.tab(&Tab, cx));
+ cx.assert_editor_state(indoc! {"
+ a
+ «🏀ˇ»🏀«🏀ˇ»🏀«🏀ˇ»
+ "});
+}
-// six"#
-// .unindent(),
-// );
+#[gpui::test]
+async fn test_tab_in_leading_whitespace_auto_indents_lines(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |_| {});
+
+ let mut cx = EditorTestContext::new(cx).await;
+ let language = Arc::new(
+ Language::new(
+ LanguageConfig::default(),
+ Some(tree_sitter_rust::language()),
+ )
+ .with_indents_query(r#"(_ "(" ")" @end) @indent"#)
+ .unwrap(),
+ );
+ cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
+
+ // cursors that are already at the suggested indent level insert
+ // a soft tab. cursors that are to the left of the suggested indent
+ // auto-indent their line.
+ cx.set_state(indoc! {"
+ ˇ
+ const a: B = (
+ c(
+ d(
+ ˇ
+ )
+ ˇ
+ ˇ )
+ );
+ "});
+ cx.update_editor(|e, cx| e.tab(&Tab, cx));
+ cx.assert_editor_state(indoc! {"
+ ˇ
+ const a: B = (
+ c(
+ d(
+ ˇ
+ )
+ ˇ
+ ˇ)
+ );
+ "});
+
+ // handle auto-indent when there are multiple cursors on the same line
+ cx.set_state(indoc! {"
+ const a: B = (
+ c(
+ ˇ ˇ
+ ˇ )
+ );
+ "});
+ cx.update_editor(|e, cx| e.tab(&Tab, cx));
+ cx.assert_editor_state(indoc! {"
+ const a: B = (
+ c(
+ ˇ
+ ˇ)
+ );
+ "});
+}
-// cx.update_editor(|editor, cx| editor.move_to_start_of_paragraph(&MoveToStartOfParagraph, cx));
-// cx.assert_editor_state(
-// &r#"ˇone
-// two
+#[gpui::test]
+async fn test_tab_with_mixed_whitespace(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |settings| {
+ settings.defaults.tab_size = NonZeroU32::new(4)
+ });
-// three
-// four
-// five
+ let language = Arc::new(
+ Language::new(
+ LanguageConfig::default(),
+ Some(tree_sitter_rust::language()),
+ )
+ .with_indents_query(r#"(_ "{" "}" @end) @indent"#)
+ .unwrap(),
+ );
+
+ let mut cx = EditorTestContext::new(cx).await;
+ cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
+ cx.set_state(indoc! {"
+ fn a() {
+ if b {
+ \t ˇc
+ }
+ }
+ "});
+
+ cx.update_editor(|e, cx| e.tab(&Tab, cx));
+ cx.assert_editor_state(indoc! {"
+ fn a() {
+ if b {
+ ˇc
+ }
+ }
+ "});
+}
-// six"#
-// .unindent(),
-// );
-// }
+#[gpui::test]
+async fn test_indent_outdent(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |settings| {
+ settings.defaults.tab_size = NonZeroU32::new(4);
+ });
-// #[gpui::test]
-// async fn test_scroll_page_up_page_down(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |_| {});
-// let mut cx = EditorTestContext::new(cx).await;
-// let line_height = cx.editor(|editor, cx| editor.style(cx).text.line_height(cx.font_cache()));
-// let window = cx.window;
-// window.simulate_resize(vec2f(1000., 4. * line_height + 0.5), &mut cx);
+ let mut cx = EditorTestContext::new(cx).await;
+
+ cx.set_state(indoc! {"
+ «oneˇ» «twoˇ»
+ three
+ four
+ "});
+ cx.update_editor(|e, cx| e.tab(&Tab, cx));
+ cx.assert_editor_state(indoc! {"
+ «oneˇ» «twoˇ»
+ three
+ four
+ "});
+
+ cx.update_editor(|e, cx| e.tab_prev(&TabPrev, cx));
+ cx.assert_editor_state(indoc! {"
+ «oneˇ» «twoˇ»
+ three
+ four
+ "});
+
+ // select across line ending
+ cx.set_state(indoc! {"
+ one two
+ t«hree
+ ˇ» four
+ "});
+ cx.update_editor(|e, cx| e.tab(&Tab, cx));
+ cx.assert_editor_state(indoc! {"
+ one two
+ t«hree
+ ˇ» four
+ "});
+
+ cx.update_editor(|e, cx| e.tab_prev(&TabPrev, cx));
+ cx.assert_editor_state(indoc! {"
+ one two
+ t«hree
+ ˇ» four
+ "});
+
+ // Ensure that indenting/outdenting works when the cursor is at column 0.
+ cx.set_state(indoc! {"
+ one two
+ ˇthree
+ four
+ "});
+ cx.update_editor(|e, cx| e.tab(&Tab, cx));
+ cx.assert_editor_state(indoc! {"
+ one two
+ ˇthree
+ four
+ "});
+
+ cx.set_state(indoc! {"
+ one two
+ ˇ three
+ four
+ "});
+ cx.update_editor(|e, cx| e.tab_prev(&TabPrev, cx));
+ cx.assert_editor_state(indoc! {"
+ one two
+ ˇthree
+ four
+ "});
+}
-// cx.set_state(
-// &r#"ˇone
-// two
-// three
-// four
-// five
-// six
-// seven
-// eight
-// nine
-// ten
-// "#,
-// );
+#[gpui::test]
+async fn test_indent_outdent_with_hard_tabs(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |settings| {
+ settings.defaults.hard_tabs = Some(true);
+ });
-// cx.update_editor(|editor, cx| {
-// assert_eq!(editor.snapshot(cx).scroll_position(), vec2f(0., 0.));
-// editor.scroll_screen(&ScrollAmount::Page(1.), cx);
-// assert_eq!(editor.snapshot(cx).scroll_position(), vec2f(0., 3.));
-// editor.scroll_screen(&ScrollAmount::Page(1.), cx);
-// assert_eq!(editor.snapshot(cx).scroll_position(), vec2f(0., 6.));
-// editor.scroll_screen(&ScrollAmount::Page(-1.), cx);
-// assert_eq!(editor.snapshot(cx).scroll_position(), vec2f(0., 3.));
+ let mut cx = EditorTestContext::new(cx).await;
+
+ // select two ranges on one line
+ cx.set_state(indoc! {"
+ «oneˇ» «twoˇ»
+ three
+ four
+ "});
+ cx.update_editor(|e, cx| e.tab(&Tab, cx));
+ cx.assert_editor_state(indoc! {"
+ \t«oneˇ» «twoˇ»
+ three
+ four
+ "});
+ cx.update_editor(|e, cx| e.tab(&Tab, cx));
+ cx.assert_editor_state(indoc! {"
+ \t\t«oneˇ» «twoˇ»
+ three
+ four
+ "});
+ cx.update_editor(|e, cx| e.tab_prev(&TabPrev, cx));
+ cx.assert_editor_state(indoc! {"
+ \t«oneˇ» «twoˇ»
+ three
+ four
+ "});
+ cx.update_editor(|e, cx| e.tab_prev(&TabPrev, cx));
+ cx.assert_editor_state(indoc! {"
+ «oneˇ» «twoˇ»
+ three
+ four
+ "});
+
+ // select across a line ending
+ cx.set_state(indoc! {"
+ one two
+ t«hree
+ ˇ»four
+ "});
+ cx.update_editor(|e, cx| e.tab(&Tab, cx));
+ cx.assert_editor_state(indoc! {"
+ one two
+ \tt«hree
+ ˇ»four
+ "});
+ cx.update_editor(|e, cx| e.tab(&Tab, cx));
+ cx.assert_editor_state(indoc! {"
+ one two
+ \t\tt«hree
+ ˇ»four
+ "});
+ cx.update_editor(|e, cx| e.tab_prev(&TabPrev, cx));
+ cx.assert_editor_state(indoc! {"
+ one two
+ \tt«hree
+ ˇ»four
+ "});
+ cx.update_editor(|e, cx| e.tab_prev(&TabPrev, cx));
+ cx.assert_editor_state(indoc! {"
+ one two
+ t«hree
+ ˇ»four
+ "});
+
+ // Ensure that indenting/outdenting works when the cursor is at column 0.
+ cx.set_state(indoc! {"
+ one two
+ ˇthree
+ four
+ "});
+ cx.update_editor(|e, cx| e.tab_prev(&TabPrev, cx));
+ cx.assert_editor_state(indoc! {"
+ one two
+ ˇthree
+ four
+ "});
+ cx.update_editor(|e, cx| e.tab(&Tab, cx));
+ cx.assert_editor_state(indoc! {"
+ one two
+ \tˇthree
+ four
+ "});
+ cx.update_editor(|e, cx| e.tab_prev(&TabPrev, cx));
+ cx.assert_editor_state(indoc! {"
+ one two
+ ˇthree
+ four
+ "});
+}
-// editor.scroll_screen(&ScrollAmount::Page(-0.5), cx);
-// assert_eq!(editor.snapshot(cx).scroll_position(), vec2f(0., 1.));
-// editor.scroll_screen(&ScrollAmount::Page(0.5), cx);
-// assert_eq!(editor.snapshot(cx).scroll_position(), vec2f(0., 3.));
-// });
-// }
+#[gpui::test]
+fn test_indent_outdent_with_excerpts(cx: &mut TestAppContext) {
+ init_test(cx, |settings| {
+ settings.languages.extend([
+ (
+ "TOML".into(),
+ LanguageSettingsContent {
+ tab_size: NonZeroU32::new(2),
+ ..Default::default()
+ },
+ ),
+ (
+ "Rust".into(),
+ LanguageSettingsContent {
+ tab_size: NonZeroU32::new(4),
+ ..Default::default()
+ },
+ ),
+ ]);
+ });
-// #[gpui::test]
-// async fn test_autoscroll(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |_| {});
-// let mut cx = EditorTestContext::new(cx).await;
+ let toml_language = Arc::new(Language::new(
+ LanguageConfig {
+ name: "TOML".into(),
+ ..Default::default()
+ },
+ None,
+ ));
+ let rust_language = Arc::new(Language::new(
+ LanguageConfig {
+ name: "Rust".into(),
+ ..Default::default()
+ },
+ None,
+ ));
+
+ let toml_buffer = cx.build_model(|cx| {
+ Buffer::new(0, cx.entity_id().as_u64(), "a = 1\nb = 2\n").with_language(toml_language, cx)
+ });
+ let rust_buffer = cx.build_model(|cx| {
+ Buffer::new(0, cx.entity_id().as_u64(), "const c: usize = 3;\n")
+ .with_language(rust_language, cx)
+ });
+ let multibuffer = cx.build_model(|cx| {
+ let mut multibuffer = MultiBuffer::new(0);
+ multibuffer.push_excerpts(
+ toml_buffer.clone(),
+ [ExcerptRange {
+ context: Point::new(0, 0)..Point::new(2, 0),
+ primary: None,
+ }],
+ cx,
+ );
+ multibuffer.push_excerpts(
+ rust_buffer.clone(),
+ [ExcerptRange {
+ context: Point::new(0, 0)..Point::new(1, 0),
+ primary: None,
+ }],
+ cx,
+ );
+ multibuffer
+ });
-// let line_height = cx.update_editor(|editor, cx| {
-// editor.set_vertical_scroll_margin(2, cx);
-// editor.style(cx).text.line_height(cx.font_cache())
-// });
-
-// let window = cx.window;
-// window.simulate_resize(vec2f(1000., 6.0 * line_height), &mut cx);
-
-// cx.set_state(
-// &r#"ˇone
-// two
-// three
-// four
-// five
-// six
-// seven
-// eight
-// nine
-// ten
-// "#,
-// );
-// cx.update_editor(|editor, cx| {
-// assert_eq!(editor.snapshot(cx).scroll_position(), vec2f(0., 0.0));
-// });
-
-// // Add a cursor below the visible area. Since both cursors cannot fit
-// // on screen, the editor autoscrolls to reveal the newest cursor, and
-// // allows the vertical scroll margin below that cursor.
-// cx.update_editor(|editor, cx| {
-// editor.change_selections(Some(Autoscroll::fit()), cx, |selections| {
-// selections.select_ranges([
-// Point::new(0, 0)..Point::new(0, 0),
-// Point::new(6, 0)..Point::new(6, 0),
-// ]);
-// })
-// });
-// cx.update_editor(|editor, cx| {
-// assert_eq!(editor.snapshot(cx).scroll_position(), vec2f(0., 3.0));
-// });
-
-// // Move down. The editor cursor scrolls down to track the newest cursor.
-// cx.update_editor(|editor, cx| {
-// editor.move_down(&Default::default(), cx);
-// });
-// cx.update_editor(|editor, cx| {
-// assert_eq!(editor.snapshot(cx).scroll_position(), vec2f(0., 4.0));
-// });
-
-// // Add a cursor above the visible area. Since both cursors fit on screen,
-// // the editor scrolls to show both.
-// cx.update_editor(|editor, cx| {
-// editor.change_selections(Some(Autoscroll::fit()), cx, |selections| {
-// selections.select_ranges([
-// Point::new(1, 0)..Point::new(1, 0),
-// Point::new(6, 0)..Point::new(6, 0),
-// ]);
-// })
-// });
-// cx.update_editor(|editor, cx| {
-// assert_eq!(editor.snapshot(cx).scroll_position(), vec2f(0., 1.0));
-// });
-// }
-
-// #[gpui::test]
-// async fn test_move_page_up_page_down(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |_| {});
-// let mut cx = EditorTestContext::new(cx).await;
-
-// let line_height = cx.editor(|editor, cx| editor.style(cx).text.line_height(cx.font_cache()));
-// let window = cx.window;
-// window.simulate_resize(vec2f(100., 4. * line_height), &mut cx);
-
-// cx.set_state(
-// &r#"
-// ˇone
-// two
-// threeˇ
-// four
-// five
-// six
-// seven
-// eight
-// nine
-// ten
-// "#
-// .unindent(),
-// );
-
-// cx.update_editor(|editor, cx| editor.move_page_down(&MovePageDown::default(), cx));
-// cx.assert_editor_state(
-// &r#"
-// one
-// two
-// three
-// ˇfour
-// five
-// sixˇ
-// seven
-// eight
-// nine
-// ten
-// "#
-// .unindent(),
-// );
-
-// cx.update_editor(|editor, cx| editor.move_page_down(&MovePageDown::default(), cx));
-// cx.assert_editor_state(
-// &r#"
-// one
-// two
-// three
-// four
-// five
-// six
-// ˇseven
-// eight
-// nineˇ
-// ten
-// "#
-// .unindent(),
-// );
-
-// cx.update_editor(|editor, cx| editor.move_page_up(&MovePageUp::default(), cx));
-// cx.assert_editor_state(
-// &r#"
-// one
-// two
-// three
-// ˇfour
-// five
-// sixˇ
-// seven
-// eight
-// nine
-// ten
-// "#
-// .unindent(),
-// );
-
-// cx.update_editor(|editor, cx| editor.move_page_up(&MovePageUp::default(), cx));
-// cx.assert_editor_state(
-// &r#"
-// ˇone
-// two
-// threeˇ
-// four
-// five
-// six
-// seven
-// eight
-// nine
-// ten
-// "#
-// .unindent(),
-// );
-
-// // Test select collapsing
-// cx.update_editor(|editor, cx| {
-// editor.move_page_down(&MovePageDown::default(), cx);
-// editor.move_page_down(&MovePageDown::default(), cx);
-// editor.move_page_down(&MovePageDown::default(), cx);
-// });
-// cx.assert_editor_state(
-// &r#"
-// one
-// two
-// three
-// four
-// five
-// six
-// seven
-// eight
-// nine
-// ˇten
-// ˇ"#
-// .unindent(),
-// );
-// }
-
-// #[gpui::test]
-// async fn test_delete_to_beginning_of_line(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |_| {});
-// let mut cx = EditorTestContext::new(cx).await;
-// cx.set_state("one «two threeˇ» four");
-// cx.update_editor(|editor, cx| {
-// editor.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
-// assert_eq!(editor.text(cx), " four");
-// });
-// }
-
-// #[gpui::test]
-// fn test_delete_to_word_boundary(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
-
-// let view = cx
-// .add_window(|cx| {
-// let buffer = MultiBuffer::build_simple("one two three four", cx);
-// build_editor(buffer.clone(), cx)
-// })
-// .root(cx);
-
-// view.update(cx, |view, cx| {
-// view.change_selections(None, cx, |s| {
-// s.select_display_ranges([
-// // an empty selection - the preceding word fragment is deleted
-// DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
-// // characters selected - they are deleted
-// DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
-// ])
-// });
-// view.delete_to_previous_word_start(&DeleteToPreviousWordStart, cx);
-// assert_eq!(view.buffer.read(cx).read(cx).text(), "e two te four");
-// });
-
-// view.update(cx, |view, cx| {
-// view.change_selections(None, cx, |s| {
-// s.select_display_ranges([
-// // an empty selection - the following word fragment is deleted
-// DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
-// // characters selected - they are deleted
-// DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
-// ])
-// });
-// view.delete_to_next_word_end(&DeleteToNextWordEnd, cx);
-// assert_eq!(view.buffer.read(cx).read(cx).text(), "e t te our");
-// });
-// }
-
-// #[gpui::test]
-// fn test_newline(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
-
-// let view = cx
-// .add_window(|cx| {
-// let buffer = MultiBuffer::build_simple("aaaa\n bbbb\n", cx);
-// build_editor(buffer.clone(), cx)
-// })
-// .root(cx);
-
-// view.update(cx, |view, cx| {
-// view.change_selections(None, cx, |s| {
-// s.select_display_ranges([
-// DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
-// DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
-// DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
-// ])
-// });
-
-// view.newline(&Newline, cx);
-// assert_eq!(view.text(cx), "aa\naa\n \n bb\n bb\n");
-// });
-// }
-
-// #[gpui::test]
-// fn test_newline_with_old_selections(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
-
-// let editor = cx
-// .add_window(|cx| {
-// let buffer = MultiBuffer::build_simple(
-// "
-// a
-// b(
-// X
-// )
-// c(
-// X
-// )
-// "
-// .unindent()
-// .as_str(),
-// cx,
-// );
-// let mut editor = build_editor(buffer.clone(), cx);
-// editor.change_selections(None, cx, |s| {
-// s.select_ranges([
-// Point::new(2, 4)..Point::new(2, 5),
-// Point::new(5, 4)..Point::new(5, 5),
-// ])
-// });
-// editor
-// })
-// .root(cx);
-
-// editor.update(cx, |editor, cx| {
-// // Edit the buffer directly, deleting ranges surrounding the editor's selections
-// editor.buffer.update(cx, |buffer, cx| {
-// buffer.edit(
-// [
-// (Point::new(1, 2)..Point::new(3, 0), ""),
-// (Point::new(4, 2)..Point::new(6, 0), ""),
-// ],
-// None,
-// cx,
-// );
-// assert_eq!(
-// buffer.read(cx).text(),
-// "
-// a
-// b()
-// c()
-// "
-// .unindent()
-// );
-// });
-// assert_eq!(
-// editor.selections.ranges(cx),
-// &[
-// Point::new(1, 2)..Point::new(1, 2),
-// Point::new(2, 2)..Point::new(2, 2),
-// ],
-// );
-
-// editor.newline(&Newline, cx);
-// assert_eq!(
-// editor.text(cx),
-// "
-// a
-// b(
-// )
-// c(
-// )
-// "
-// .unindent()
-// );
-
-// // The selections are moved after the inserted newlines
-// assert_eq!(
-// editor.selections.ranges(cx),
-// &[
-// Point::new(2, 0)..Point::new(2, 0),
-// Point::new(4, 0)..Point::new(4, 0),
-// ],
-// );
-// });
-// }
-
-// #[gpui::test]
-// async fn test_newline_above(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |settings| {
-// settings.defaults.tab_size = NonZeroU32::new(4)
-// });
-
-// let language = Arc::new(
-// Language::new(
-// LanguageConfig::default(),
-// Some(tree_sitter_rust::language()),
-// )
-// .with_indents_query(r#"(_ "(" ")" @end) @indent"#)
-// .unwrap(),
-// );
-
-// let mut cx = EditorTestContext::new(cx).await;
-// cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
-// cx.set_state(indoc! {"
-// const a: ˇA = (
-// (ˇ
-// «const_functionˇ»(ˇ),
-// so«mˇ»et«hˇ»ing_ˇelse,ˇ
-// )ˇ
-// ˇ);ˇ
-// "});
-
-// cx.update_editor(|e, cx| e.newline_above(&NewlineAbove, cx));
-// cx.assert_editor_state(indoc! {"
-// ˇ
-// const a: A = (
-// ˇ
-// (
-// ˇ
-// ˇ
-// const_function(),
-// ˇ
-// ˇ
-// ˇ
-// ˇ
-// something_else,
-// ˇ
-// )
-// ˇ
-// ˇ
-// );
-// "});
-// }
-
-// #[gpui::test]
-// async fn test_newline_below(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |settings| {
-// settings.defaults.tab_size = NonZeroU32::new(4)
-// });
-
-// let language = Arc::new(
-// Language::new(
-// LanguageConfig::default(),
-// Some(tree_sitter_rust::language()),
-// )
-// .with_indents_query(r#"(_ "(" ")" @end) @indent"#)
-// .unwrap(),
-// );
-
-// let mut cx = EditorTestContext::new(cx).await;
-// cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
-// cx.set_state(indoc! {"
-// const a: ˇA = (
-// (ˇ
-// «const_functionˇ»(ˇ),
-// so«mˇ»et«hˇ»ing_ˇelse,ˇ
-// )ˇ
-// ˇ);ˇ
-// "});
-
-// cx.update_editor(|e, cx| e.newline_below(&NewlineBelow, cx));
-// cx.assert_editor_state(indoc! {"
-// const a: A = (
-// ˇ
-// (
-// ˇ
-// const_function(),
-// ˇ
-// ˇ
-// something_else,
-// ˇ
-// ˇ
-// ˇ
-// ˇ
-// )
-// ˇ
-// );
-// ˇ
-// ˇ
-// "});
-// }
-
-// #[gpui::test]
-// async fn test_newline_comments(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |settings| {
-// settings.defaults.tab_size = NonZeroU32::new(4)
-// });
-
-// let language = Arc::new(Language::new(
-// LanguageConfig {
-// line_comment: Some("//".into()),
-// ..LanguageConfig::default()
-// },
-// None,
-// ));
-// {
-// let mut cx = EditorTestContext::new(cx).await;
-// cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
-// cx.set_state(indoc! {"
-// // Fooˇ
-// "});
-
-// cx.update_editor(|e, cx| e.newline(&Newline, cx));
-// cx.assert_editor_state(indoc! {"
-// // Foo
-// //ˇ
-// "});
-// // Ensure that if cursor is before the comment start, we do not actually insert a comment prefix.
-// cx.set_state(indoc! {"
-// ˇ// Foo
-// "});
-// cx.update_editor(|e, cx| e.newline(&Newline, cx));
-// cx.assert_editor_state(indoc! {"
-
-// ˇ// Foo
-// "});
-// }
-// // Ensure that comment continuations can be disabled.
-// update_test_language_settings(cx, |settings| {
-// settings.defaults.extend_comment_on_newline = Some(false);
-// });
-// let mut cx = EditorTestContext::new(cx).await;
-// cx.set_state(indoc! {"
-// // Fooˇ
-// "});
-// cx.update_editor(|e, cx| e.newline(&Newline, cx));
-// cx.assert_editor_state(indoc! {"
-// // Foo
-// ˇ
-// "});
-// }
-
-// #[gpui::test]
-// fn test_insert_with_old_selections(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
-
-// let editor = cx
-// .add_window(|cx| {
-// let buffer = MultiBuffer::build_simple("a( X ), b( Y ), c( Z )", cx);
-// let mut editor = build_editor(buffer.clone(), cx);
-// editor.change_selections(None, cx, |s| s.select_ranges([3..4, 11..12, 19..20]));
-// editor
-// })
-// .root(cx);
-
-// editor.update(cx, |editor, cx| {
-// // Edit the buffer directly, deleting ranges surrounding the editor's selections
-// editor.buffer.update(cx, |buffer, cx| {
-// buffer.edit([(2..5, ""), (10..13, ""), (18..21, "")], None, cx);
-// assert_eq!(buffer.read(cx).text(), "a(), b(), c()".unindent());
-// });
-// assert_eq!(editor.selections.ranges(cx), &[2..2, 7..7, 12..12],);
-
-// editor.insert("Z", cx);
-// assert_eq!(editor.text(cx), "a(Z), b(Z), c(Z)");
-
-// // The selections are moved after the inserted characters
-// assert_eq!(editor.selections.ranges(cx), &[3..3, 9..9, 15..15],);
-// });
-// }
-
-// #[gpui::test]
-// async fn test_tab(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |settings| {
-// settings.defaults.tab_size = NonZeroU32::new(3)
-// });
-
-// let mut cx = EditorTestContext::new(cx).await;
-// cx.set_state(indoc! {"
-// ˇabˇc
-// ˇ🏀ˇ🏀ˇefg
-// dˇ
-// "});
-// cx.update_editor(|e, cx| e.tab(&Tab, cx));
-// cx.assert_editor_state(indoc! {"
-// ˇab ˇc
-// ˇ🏀 ˇ🏀 ˇefg
-// d ˇ
-// "});
-
-// cx.set_state(indoc! {"
-// a
-// «🏀ˇ»🏀«🏀ˇ»🏀«🏀ˇ»
-// "});
-// cx.update_editor(|e, cx| e.tab(&Tab, cx));
-// cx.assert_editor_state(indoc! {"
-// a
-// «🏀ˇ»🏀«🏀ˇ»🏀«🏀ˇ»
-// "});
-// }
-
-// #[gpui::test]
-// async fn test_tab_in_leading_whitespace_auto_indents_lines(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |_| {});
-
-// let mut cx = EditorTestContext::new(cx).await;
-// let language = Arc::new(
-// Language::new(
-// LanguageConfig::default(),
-// Some(tree_sitter_rust::language()),
-// )
-// .with_indents_query(r#"(_ "(" ")" @end) @indent"#)
-// .unwrap(),
-// );
-// cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
-
-// // cursors that are already at the suggested indent level insert
-// // a soft tab. cursors that are to the left of the suggested indent
-// // auto-indent their line.
-// cx.set_state(indoc! {"
-// ˇ
-// const a: B = (
-// c(
-// d(
-// ˇ
-// )
-// ˇ
-// ˇ )
-// );
-// "});
-// cx.update_editor(|e, cx| e.tab(&Tab, cx));
-// cx.assert_editor_state(indoc! {"
-// ˇ
-// const a: B = (
-// c(
-// d(
-// ˇ
-// )
-// ˇ
-// ˇ)
-// );
-// "});
-
-// // handle auto-indent when there are multiple cursors on the same line
-// cx.set_state(indoc! {"
-// const a: B = (
-// c(
-// ˇ ˇ
-// ˇ )
-// );
-// "});
-// cx.update_editor(|e, cx| e.tab(&Tab, cx));
-// cx.assert_editor_state(indoc! {"
-// const a: B = (
-// c(
-// ˇ
-// ˇ)
-// );
-// "});
-// }
-
-// #[gpui::test]
-// async fn test_tab_with_mixed_whitespace(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |settings| {
-// settings.defaults.tab_size = NonZeroU32::new(4)
-// });
-
-// let language = Arc::new(
-// Language::new(
-// LanguageConfig::default(),
-// Some(tree_sitter_rust::language()),
-// )
-// .with_indents_query(r#"(_ "{" "}" @end) @indent"#)
-// .unwrap(),
-// );
-
-// let mut cx = EditorTestContext::new(cx).await;
-// cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
-// cx.set_state(indoc! {"
-// fn a() {
-// if b {
-// \t ˇc
-// }
-// }
-// "});
-
-// cx.update_editor(|e, cx| e.tab(&Tab, cx));
-// cx.assert_editor_state(indoc! {"
-// fn a() {
-// if b {
-// ˇc
-// }
-// }
-// "});
-// }
-
-// #[gpui::test]
-// async fn test_indent_outdent(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |settings| {
-// settings.defaults.tab_size = NonZeroU32::new(4);
-// });
-
-// let mut cx = EditorTestContext::new(cx).await;
-
-// cx.set_state(indoc! {"
-// «oneˇ» «twoˇ»
-// three
-// four
-// "});
-// cx.update_editor(|e, cx| e.tab(&Tab, cx));
-// cx.assert_editor_state(indoc! {"
-// «oneˇ» «twoˇ»
-// three
-// four
-// "});
-
-// cx.update_editor(|e, cx| e.tab_prev(&TabPrev, cx));
-// cx.assert_editor_state(indoc! {"
-// «oneˇ» «twoˇ»
-// three
-// four
-// "});
-
-// // select across line ending
-// cx.set_state(indoc! {"
-// one two
-// t«hree
-// ˇ» four
-// "});
-// cx.update_editor(|e, cx| e.tab(&Tab, cx));
-// cx.assert_editor_state(indoc! {"
-// one two
-// t«hree
-// ˇ» four
-// "});
-
-// cx.update_editor(|e, cx| e.tab_prev(&TabPrev, cx));
-// cx.assert_editor_state(indoc! {"
-// one two
-// t«hree
-// ˇ» four
-// "});
-
-// // Ensure that indenting/outdenting works when the cursor is at column 0.
-// cx.set_state(indoc! {"
-// one two
-// ˇthree
-// four
-// "});
-// cx.update_editor(|e, cx| e.tab(&Tab, cx));
-// cx.assert_editor_state(indoc! {"
-// one two
-// ˇthree
-// four
-// "});
-
-// cx.set_state(indoc! {"
-// one two
-// ˇ three
-// four
-// "});
-// cx.update_editor(|e, cx| e.tab_prev(&TabPrev, cx));
-// cx.assert_editor_state(indoc! {"
-// one two
-// ˇthree
-// four
-// "});
-// }
-
-// #[gpui::test]
-// async fn test_indent_outdent_with_hard_tabs(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |settings| {
-// settings.defaults.hard_tabs = Some(true);
-// });
-
-// let mut cx = EditorTestContext::new(cx).await;
-
-// // select two ranges on one line
-// cx.set_state(indoc! {"
-// «oneˇ» «twoˇ»
-// three
-// four
-// "});
-// cx.update_editor(|e, cx| e.tab(&Tab, cx));
-// cx.assert_editor_state(indoc! {"
-// \t«oneˇ» «twoˇ»
-// three
-// four
-// "});
-// cx.update_editor(|e, cx| e.tab(&Tab, cx));
-// cx.assert_editor_state(indoc! {"
-// \t\t«oneˇ» «twoˇ»
-// three
-// four
-// "});
-// cx.update_editor(|e, cx| e.tab_prev(&TabPrev, cx));
-// cx.assert_editor_state(indoc! {"
-// \t«oneˇ» «twoˇ»
-// three
-// four
-// "});
-// cx.update_editor(|e, cx| e.tab_prev(&TabPrev, cx));
-// cx.assert_editor_state(indoc! {"
-// «oneˇ» «twoˇ»
-// three
-// four
-// "});
-
-// // select across a line ending
-// cx.set_state(indoc! {"
-// one two
-// t«hree
-// ˇ»four
-// "});
-// cx.update_editor(|e, cx| e.tab(&Tab, cx));
-// cx.assert_editor_state(indoc! {"
-// one two
-// \tt«hree
-// ˇ»four
-// "});
-// cx.update_editor(|e, cx| e.tab(&Tab, cx));
-// cx.assert_editor_state(indoc! {"
-// one two
-// \t\tt«hree
-// ˇ»four
-// "});
-// cx.update_editor(|e, cx| e.tab_prev(&TabPrev, cx));
-// cx.assert_editor_state(indoc! {"
-// one two
-// \tt«hree
-// ˇ»four
-// "});
-// cx.update_editor(|e, cx| e.tab_prev(&TabPrev, cx));
-// cx.assert_editor_state(indoc! {"
-// one two
-// t«hree
-// ˇ»four
-// "});
-
-// // Ensure that indenting/outdenting works when the cursor is at column 0.
-// cx.set_state(indoc! {"
-// one two
-// ˇthree
-// four
-// "});
-// cx.update_editor(|e, cx| e.tab_prev(&TabPrev, cx));
-// cx.assert_editor_state(indoc! {"
-// one two
-// ˇthree
-// four
-// "});
-// cx.update_editor(|e, cx| e.tab(&Tab, cx));
-// cx.assert_editor_state(indoc! {"
-// one two
-// \tˇthree
-// four
-// "});
-// cx.update_editor(|e, cx| e.tab_prev(&TabPrev, cx));
-// cx.assert_editor_state(indoc! {"
-// one two
-// ˇthree
-// four
-// "});
-// }
-
-// #[gpui::test]
-// fn test_indent_outdent_with_excerpts(cx: &mut TestAppContext) {
-// init_test(cx, |settings| {
-// settings.languages.extend([
-// (
-// "TOML".into(),
-// LanguageSettingsContent {
-// tab_size: NonZeroU32::new(2),
-// ..Default::default()
-// },
-// ),
-// (
-// "Rust".into(),
-// LanguageSettingsContent {
-// tab_size: NonZeroU32::new(4),
-// ..Default::default()
-// },
-// ),
-// ]);
-// });
-
-// let toml_language = Arc::new(Language::new(
-// LanguageConfig {
-// name: "TOML".into(),
-// ..Default::default()
-// },
-// None,
-// ));
-// let rust_language = Arc::new(Language::new(
-// LanguageConfig {
-// name: "Rust".into(),
-// ..Default::default()
-// },
-// None,
-// ));
-
-// let toml_buffer = cx.add_model(|cx| {
-// Buffer::new(0, cx.model_id() as u64, "a = 1\nb = 2\n").with_language(toml_language, cx)
-// });
-// let rust_buffer = cx.add_model(|cx| {
-// Buffer::new(0, cx.model_id() as u64, "const c: usize = 3;\n")
-// .with_language(rust_language, cx)
-// });
-// let multibuffer = cx.add_model(|cx| {
-// let mut multibuffer = MultiBuffer::new(0);
-// multibuffer.push_excerpts(
-// toml_buffer.clone(),
-// [ExcerptRange {
-// context: Point::new(0, 0)..Point::new(2, 0),
-// primary: None,
-// }],
-// cx,
-// );
-// multibuffer.push_excerpts(
-// rust_buffer.clone(),
-// [ExcerptRange {
-// context: Point::new(0, 0)..Point::new(1, 0),
-// primary: None,
-// }],
-// cx,
-// );
-// multibuffer
-// });
-
-// cx.add_window(|cx| {
-// let mut editor = build_editor(multibuffer, cx);
-
-// assert_eq!(
-// editor.text(cx),
-// indoc! {"
-// a = 1
-// b = 2
-
-// const c: usize = 3;
-// "}
-// );
-
-// select_ranges(
-// &mut editor,
-// indoc! {"
-// «aˇ» = 1
-// b = 2
-
-// «const c:ˇ» usize = 3;
-// "},
-// cx,
-// );
-
-// editor.tab(&Tab, cx);
-// assert_text_with_selections(
-// &mut editor,
-// indoc! {"
-// «aˇ» = 1
-// b = 2
-
-// «const c:ˇ» usize = 3;
-// "},
-// cx,
-// );
-// editor.tab_prev(&TabPrev, cx);
-// assert_text_with_selections(
-// &mut editor,
-// indoc! {"
-// «aˇ» = 1
-// b = 2
-
-// «const c:ˇ» usize = 3;
-// "},
-// cx,
-// );
-
-// editor
-// });
-// }
-
-// #[gpui::test]
-// async fn test_backspace(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |_| {});
-
-// let mut cx = EditorTestContext::new(cx).await;
-
-// // Basic backspace
-// cx.set_state(indoc! {"
-// onˇe two three
-// fou«rˇ» five six
-// seven «ˇeight nine
-// »ten
-// "});
-// cx.update_editor(|e, cx| e.backspace(&Backspace, cx));
-// cx.assert_editor_state(indoc! {"
-// oˇe two three
-// fouˇ five six
-// seven ˇten
-// "});
-
-// // Test backspace inside and around indents
-// cx.set_state(indoc! {"
-// zero
-// ˇone
-// ˇtwo
-// ˇ ˇ ˇ three
-// ˇ ˇ four
-// "});
-// cx.update_editor(|e, cx| e.backspace(&Backspace, cx));
-// cx.assert_editor_state(indoc! {"
-// zero
-// ˇone
-// ˇtwo
-// ˇ threeˇ four
-// "});
-
-// // Test backspace with line_mode set to true
-// cx.update_editor(|e, _| e.selections.line_mode = true);
-// cx.set_state(indoc! {"
-// The ˇquick ˇbrown
-// fox jumps over
-// the lazy dog
-// ˇThe qu«ick bˇ»rown"});
-// cx.update_editor(|e, cx| e.backspace(&Backspace, cx));
-// cx.assert_editor_state(indoc! {"
-// ˇfox jumps over
-// the lazy dogˇ"});
-// }
-
-// #[gpui::test]
-// async fn test_delete(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |_| {});
-
-// let mut cx = EditorTestContext::new(cx).await;
-// cx.set_state(indoc! {"
-// onˇe two three
-// fou«rˇ» five six
-// seven «ˇeight nine
-// »ten
-// "});
-// cx.update_editor(|e, cx| e.delete(&Delete, cx));
-// cx.assert_editor_state(indoc! {"
-// onˇ two three
-// fouˇ five six
-// seven ˇten
-// "});
-
-// // Test backspace with line_mode set to true
-// cx.update_editor(|e, _| e.selections.line_mode = true);
-// cx.set_state(indoc! {"
-// The ˇquick ˇbrown
-// fox «ˇjum»ps over
-// the lazy dog
-// ˇThe qu«ick bˇ»rown"});
-// cx.update_editor(|e, cx| e.backspace(&Backspace, cx));
-// cx.assert_editor_state("ˇthe lazy dogˇ");
-// }
-
-// #[gpui::test]
-// fn test_delete_line(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
-
-// let view = cx
-// .add_window(|cx| {
-// let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
-// build_editor(buffer, cx)
-// })
-// .root(cx);
-// view.update(cx, |view, cx| {
-// view.change_selections(None, cx, |s| {
-// s.select_display_ranges([
-// DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
-// DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
-// DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
-// ])
-// });
-// view.delete_line(&DeleteLine, cx);
-// assert_eq!(view.display_text(cx), "ghi");
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![
-// DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
-// DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
-// ]
-// );
-// });
-
-// let view = cx
-// .add_window(|cx| {
-// let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
-// build_editor(buffer, cx)
-// })
-// .root(cx);
-// view.update(cx, |view, cx| {
-// view.change_selections(None, cx, |s| {
-// s.select_display_ranges([DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)])
-// });
-// view.delete_line(&DeleteLine, cx);
-// assert_eq!(view.display_text(cx), "ghi\n");
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
-// );
-// });
-// }
-
-// #[gpui::test]
-// fn test_join_lines_with_single_selection(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
-
-// cx.add_window(|cx| {
-// let buffer = MultiBuffer::build_simple("aaa\nbbb\nccc\nddd\n\n", cx);
-// let mut editor = build_editor(buffer.clone(), cx);
-// let buffer = buffer.read(cx).as_singleton().unwrap();
-
-// assert_eq!(
-// editor.selections.ranges::<Point>(cx),
-// &[Point::new(0, 0)..Point::new(0, 0)]
-// );
-
-// // When on single line, replace newline at end by space
-// editor.join_lines(&JoinLines, cx);
-// assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd\n\n");
-// assert_eq!(
-// editor.selections.ranges::<Point>(cx),
-// &[Point::new(0, 3)..Point::new(0, 3)]
-// );
-
-// // When multiple lines are selected, remove newlines that are spanned by the selection
-// editor.change_selections(None, cx, |s| {
-// s.select_ranges([Point::new(0, 5)..Point::new(2, 2)])
-// });
-// editor.join_lines(&JoinLines, cx);
-// assert_eq!(buffer.read(cx).text(), "aaa bbb ccc ddd\n\n");
-// assert_eq!(
-// editor.selections.ranges::<Point>(cx),
-// &[Point::new(0, 11)..Point::new(0, 11)]
-// );
-
-// // Undo should be transactional
-// editor.undo(&Undo, cx);
-// assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd\n\n");
-// assert_eq!(
-// editor.selections.ranges::<Point>(cx),
-// &[Point::new(0, 5)..Point::new(2, 2)]
-// );
-
-// // When joining an empty line don't insert a space
-// editor.change_selections(None, cx, |s| {
-// s.select_ranges([Point::new(2, 1)..Point::new(2, 2)])
-// });
-// editor.join_lines(&JoinLines, cx);
-// assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd\n");
-// assert_eq!(
-// editor.selections.ranges::<Point>(cx),
-// [Point::new(2, 3)..Point::new(2, 3)]
-// );
-
-// // We can remove trailing newlines
-// editor.join_lines(&JoinLines, cx);
-// assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd");
-// assert_eq!(
-// editor.selections.ranges::<Point>(cx),
-// [Point::new(2, 3)..Point::new(2, 3)]
-// );
-
-// // We don't blow up on the last line
-// editor.join_lines(&JoinLines, cx);
-// assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd");
-// assert_eq!(
-// editor.selections.ranges::<Point>(cx),
-// [Point::new(2, 3)..Point::new(2, 3)]
-// );
-
-// // reset to test indentation
-// editor.buffer.update(cx, |buffer, cx| {
-// buffer.edit(
-// [
-// (Point::new(1, 0)..Point::new(1, 2), " "),
-// (Point::new(2, 0)..Point::new(2, 3), " \n\td"),
-// ],
-// None,
-// cx,
-// )
-// });
-
-// // We remove any leading spaces
-// assert_eq!(buffer.read(cx).text(), "aaa bbb\n c\n \n\td");
-// editor.change_selections(None, cx, |s| {
-// s.select_ranges([Point::new(0, 1)..Point::new(0, 1)])
-// });
-// editor.join_lines(&JoinLines, cx);
-// assert_eq!(buffer.read(cx).text(), "aaa bbb c\n \n\td");
-
-// // We don't insert a space for a line containing only spaces
-// editor.join_lines(&JoinLines, cx);
-// assert_eq!(buffer.read(cx).text(), "aaa bbb c\n\td");
-
-// // We ignore any leading tabs
-// editor.join_lines(&JoinLines, cx);
-// assert_eq!(buffer.read(cx).text(), "aaa bbb c d");
-
-// editor
-// });
-// }
-
-// #[gpui::test]
-// fn test_join_lines_with_multi_selection(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
-
-// cx.add_window(|cx| {
-// let buffer = MultiBuffer::build_simple("aaa\nbbb\nccc\nddd\n\n", cx);
-// let mut editor = build_editor(buffer.clone(), cx);
-// let buffer = buffer.read(cx).as_singleton().unwrap();
-
-// editor.change_selections(None, cx, |s| {
-// s.select_ranges([
-// Point::new(0, 2)..Point::new(1, 1),
-// Point::new(1, 2)..Point::new(1, 2),
-// Point::new(3, 1)..Point::new(3, 2),
-// ])
-// });
-
-// editor.join_lines(&JoinLines, cx);
-// assert_eq!(buffer.read(cx).text(), "aaa bbb ccc\nddd\n");
-
-// assert_eq!(
-// editor.selections.ranges::<Point>(cx),
-// [
-// Point::new(0, 7)..Point::new(0, 7),
-// Point::new(1, 3)..Point::new(1, 3)
-// ]
-// );
-// editor
-// });
-// }
-
-// #[gpui::test]
-// async fn test_manipulate_lines_with_single_selection(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
-
-// let mut cx = EditorTestContext::new(cx).await;
-
-// // Test sort_lines_case_insensitive()
-// cx.set_state(indoc! {"
-// «z
-// y
-// x
-// Z
-// Y
-// Xˇ»
-// "});
-// cx.update_editor(|e, cx| e.sort_lines_case_insensitive(&SortLinesCaseInsensitive, cx));
-// cx.assert_editor_state(indoc! {"
-// «x
-// X
-// y
-// Y
-// z
-// Zˇ»
-// "});
-
-// // Test reverse_lines()
-// cx.set_state(indoc! {"
-// «5
-// 4
-// 3
-// 2
-// 1ˇ»
-// "});
-// cx.update_editor(|e, cx| e.reverse_lines(&ReverseLines, cx));
-// cx.assert_editor_state(indoc! {"
-// «1
-// 2
-// 3
-// 4
-// 5ˇ»
-// "});
-
-// // Skip testing shuffle_line()
-
-// // From here on out, test more complex cases of manipulate_lines() with a single driver method: sort_lines_case_sensitive()
-// // Since all methods calling manipulate_lines() are doing the exact same general thing (reordering lines)
-
-// // Don't manipulate when cursor is on single line, but expand the selection
-// cx.set_state(indoc! {"
-// ddˇdd
-// ccc
-// bb
-// a
-// "});
-// cx.update_editor(|e, cx| e.sort_lines_case_sensitive(&SortLinesCaseSensitive, cx));
-// cx.assert_editor_state(indoc! {"
-// «ddddˇ»
-// ccc
-// bb
-// a
-// "});
-
-// // Basic manipulate case
-// // Start selection moves to column 0
-// // End of selection shrinks to fit shorter line
-// cx.set_state(indoc! {"
-// dd«d
-// ccc
-// bb
-// aaaaaˇ»
-// "});
-// cx.update_editor(|e, cx| e.sort_lines_case_sensitive(&SortLinesCaseSensitive, cx));
-// cx.assert_editor_state(indoc! {"
-// «aaaaa
-// bb
-// ccc
-// dddˇ»
-// "});
-
-// // Manipulate case with newlines
-// cx.set_state(indoc! {"
-// dd«d
-// ccc
-
-// bb
-// aaaaa
-
-// ˇ»
-// "});
-// cx.update_editor(|e, cx| e.sort_lines_case_sensitive(&SortLinesCaseSensitive, cx));
-// cx.assert_editor_state(indoc! {"
-// «
-
-// aaaaa
-// bb
-// ccc
-// dddˇ»
-
-// "});
-// }
-
-// #[gpui::test]
-// async fn test_manipulate_lines_with_multi_selection(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
-
-// let mut cx = EditorTestContext::new(cx).await;
-
-// // Manipulate with multiple selections on a single line
-// cx.set_state(indoc! {"
-// dd«dd
-// cˇ»c«c
-// bb
-// aaaˇ»aa
-// "});
-// cx.update_editor(|e, cx| e.sort_lines_case_sensitive(&SortLinesCaseSensitive, cx));
-// cx.assert_editor_state(indoc! {"
-// «aaaaa
-// bb
-// ccc
-// ddddˇ»
-// "});
-
-// // Manipulate with multiple disjoin selections
-// cx.set_state(indoc! {"
-// 5«
-// 4
-// 3
-// 2
-// 1ˇ»
-
-// dd«dd
-// ccc
-// bb
-// aaaˇ»aa
-// "});
-// cx.update_editor(|e, cx| e.sort_lines_case_sensitive(&SortLinesCaseSensitive, cx));
-// cx.assert_editor_state(indoc! {"
-// «1
-// 2
-// 3
-// 4
-// 5ˇ»
-
-// «aaaaa
-// bb
-// ccc
-// ddddˇ»
-// "});
-// }
-
-// #[gpui::test]
-// async fn test_manipulate_text(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
-
-// let mut cx = EditorTestContext::new(cx).await;
-
-// // Test convert_to_upper_case()
-// cx.set_state(indoc! {"
-// «hello worldˇ»
-// "});
-// cx.update_editor(|e, cx| e.convert_to_upper_case(&ConvertToUpperCase, cx));
-// cx.assert_editor_state(indoc! {"
-// «HELLO WORLDˇ»
-// "});
-
-// // Test convert_to_lower_case()
-// cx.set_state(indoc! {"
-// «HELLO WORLDˇ»
-// "});
-// cx.update_editor(|e, cx| e.convert_to_lower_case(&ConvertToLowerCase, cx));
-// cx.assert_editor_state(indoc! {"
-// «hello worldˇ»
-// "});
-
-// // Test multiple line, single selection case
-// // Test code hack that covers the fact that to_case crate doesn't support '\n' as a word boundary
-// cx.set_state(indoc! {"
-// «The quick brown
-// fox jumps over
-// the lazy dogˇ»
-// "});
-// cx.update_editor(|e, cx| e.convert_to_title_case(&ConvertToTitleCase, cx));
-// cx.assert_editor_state(indoc! {"
-// «The Quick Brown
-// Fox Jumps Over
-// The Lazy Dogˇ»
-// "});
-
-// // Test multiple line, single selection case
-// // Test code hack that covers the fact that to_case crate doesn't support '\n' as a word boundary
-// cx.set_state(indoc! {"
-// «The quick brown
-// fox jumps over
-// the lazy dogˇ»
-// "});
-// cx.update_editor(|e, cx| e.convert_to_upper_camel_case(&ConvertToUpperCamelCase, cx));
-// cx.assert_editor_state(indoc! {"
-// «TheQuickBrown
-// FoxJumpsOver
-// TheLazyDogˇ»
-// "});
-
-// // From here on out, test more complex cases of manipulate_text()
-
-// // Test no selection case - should affect words cursors are in
-// // Cursor at beginning, middle, and end of word
-// cx.set_state(indoc! {"
-// ˇhello big beauˇtiful worldˇ
-// "});
-// cx.update_editor(|e, cx| e.convert_to_upper_case(&ConvertToUpperCase, cx));
-// cx.assert_editor_state(indoc! {"
-// «HELLOˇ» big «BEAUTIFULˇ» «WORLDˇ»
-// "});
-
-// // Test multiple selections on a single line and across multiple lines
-// cx.set_state(indoc! {"
-// «Theˇ» quick «brown
-// foxˇ» jumps «overˇ»
-// the «lazyˇ» dog
-// "});
-// cx.update_editor(|e, cx| e.convert_to_upper_case(&ConvertToUpperCase, cx));
-// cx.assert_editor_state(indoc! {"
-// «THEˇ» quick «BROWN
-// FOXˇ» jumps «OVERˇ»
-// the «LAZYˇ» dog
-// "});
-
-// // Test case where text length grows
-// cx.set_state(indoc! {"
-// «tschüߡ»
-// "});
-// cx.update_editor(|e, cx| e.convert_to_upper_case(&ConvertToUpperCase, cx));
-// cx.assert_editor_state(indoc! {"
-// «TSCHÜSSˇ»
-// "});
-
-// // Test to make sure we don't crash when text shrinks
-// cx.set_state(indoc! {"
-// aaa_bbbˇ
-// "});
-// cx.update_editor(|e, cx| e.convert_to_lower_camel_case(&ConvertToLowerCamelCase, cx));
-// cx.assert_editor_state(indoc! {"
-// «aaaBbbˇ»
-// "});
-
-// // Test to make sure we all aware of the fact that each word can grow and shrink
-// // Final selections should be aware of this fact
-// cx.set_state(indoc! {"
-// aaa_bˇbb bbˇb_ccc ˇccc_ddd
-// "});
-// cx.update_editor(|e, cx| e.convert_to_lower_camel_case(&ConvertToLowerCamelCase, cx));
-// cx.assert_editor_state(indoc! {"
-// «aaaBbbˇ» «bbbCccˇ» «cccDddˇ»
-// "});
-// }
-
-// #[gpui::test]
-// fn test_duplicate_line(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
-
-// let view = cx
-// .add_window(|cx| {
-// let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
-// build_editor(buffer, cx)
-// })
-// .root(cx);
-// view.update(cx, |view, cx| {
-// view.change_selections(None, cx, |s| {
-// s.select_display_ranges([
-// DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
-// DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
-// DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
-// DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
-// ])
-// });
-// view.duplicate_line(&DuplicateLine, cx);
-// assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![
-// DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
-// DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
-// DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
-// DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
-// ]
-// );
-// });
-
-// let view = cx
-// .add_window(|cx| {
-// let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
-// build_editor(buffer, cx)
-// })
-// .root(cx);
-// view.update(cx, |view, cx| {
-// view.change_selections(None, cx, |s| {
-// s.select_display_ranges([
-// DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
-// DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
-// ])
-// });
-// view.duplicate_line(&DuplicateLine, cx);
-// assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![
-// DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
-// DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
-// ]
-// );
-// });
-// }
-
-// #[gpui::test]
-// fn test_move_line_up_down(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
-
-// let view = cx
-// .add_window(|cx| {
-// let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
-// build_editor(buffer, cx)
-// })
-// .root(cx);
-// view.update(cx, |view, cx| {
-// view.fold_ranges(
-// vec![
-// Point::new(0, 2)..Point::new(1, 2),
-// Point::new(2, 3)..Point::new(4, 1),
-// Point::new(7, 0)..Point::new(8, 4),
-// ],
-// true,
-// cx,
-// );
-// view.change_selections(None, cx, |s| {
-// s.select_display_ranges([
-// DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
-// DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
-// DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
-// DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
-// ])
-// });
-// assert_eq!(
-// view.display_text(cx),
-// "aa⋯bbb\nccc⋯eeee\nfffff\nggggg\n⋯i\njjjjj"
-// );
-
-// view.move_line_up(&MoveLineUp, cx);
-// assert_eq!(
-// view.display_text(cx),
-// "aa⋯bbb\nccc⋯eeee\nggggg\n⋯i\njjjjj\nfffff"
-// );
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![
-// DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
-// DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
-// DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
-// DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
-// ]
-// );
-// });
-
-// view.update(cx, |view, cx| {
-// view.move_line_down(&MoveLineDown, cx);
-// assert_eq!(
-// view.display_text(cx),
-// "ccc⋯eeee\naa⋯bbb\nfffff\nggggg\n⋯i\njjjjj"
-// );
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![
-// DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
-// DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
-// DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
-// DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
-// ]
-// );
-// });
-
-// view.update(cx, |view, cx| {
-// view.move_line_down(&MoveLineDown, cx);
-// assert_eq!(
-// view.display_text(cx),
-// "ccc⋯eeee\nfffff\naa⋯bbb\nggggg\n⋯i\njjjjj"
-// );
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![
-// DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
-// DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
-// DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
-// DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
-// ]
-// );
-// });
-
-// view.update(cx, |view, cx| {
-// view.move_line_up(&MoveLineUp, cx);
-// assert_eq!(
-// view.display_text(cx),
-// "ccc⋯eeee\naa⋯bbb\nggggg\n⋯i\njjjjj\nfffff"
-// );
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![
-// DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
-// DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
-// DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
-// DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
-// ]
-// );
-// });
-// }
-
-// #[gpui::test]
-// fn test_move_line_up_down_with_blocks(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
-
-// let editor = cx
-// .add_window(|cx| {
-// let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
-// build_editor(buffer, cx)
-// })
-// .root(cx);
-// editor.update(cx, |editor, cx| {
-// let snapshot = editor.buffer.read(cx).snapshot(cx);
-// editor.insert_blocks(
-// [BlockProperties {
-// style: BlockStyle::Fixed,
-// position: snapshot.anchor_after(Point::new(2, 0)),
-// disposition: BlockDisposition::Below,
-// height: 1,
-// render: Arc::new(|_| Empty::new().into_any()),
-// }],
-// Some(Autoscroll::fit()),
-// cx,
-// );
-// editor.change_selections(None, cx, |s| {
-// s.select_ranges([Point::new(2, 0)..Point::new(2, 0)])
-// });
-// editor.move_line_down(&MoveLineDown, cx);
-// });
-// }
-
-// #[gpui::test]
-// fn test_transpose(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
-
-// _ = cx.add_window(|cx| {
-// let mut editor = build_editor(MultiBuffer::build_simple("abc", cx), cx);
-
-// editor.change_selections(None, cx, |s| s.select_ranges([1..1]));
-// editor.transpose(&Default::default(), cx);
-// assert_eq!(editor.text(cx), "bac");
-// assert_eq!(editor.selections.ranges(cx), [2..2]);
-
-// editor.transpose(&Default::default(), cx);
-// assert_eq!(editor.text(cx), "bca");
-// assert_eq!(editor.selections.ranges(cx), [3..3]);
-
-// editor.transpose(&Default::default(), cx);
-// assert_eq!(editor.text(cx), "bac");
-// assert_eq!(editor.selections.ranges(cx), [3..3]);
-
-// editor
-// });
-
-// _ = cx.add_window(|cx| {
-// let mut editor = build_editor(MultiBuffer::build_simple("abc\nde", cx), cx);
-
-// editor.change_selections(None, cx, |s| s.select_ranges([3..3]));
-// editor.transpose(&Default::default(), cx);
-// assert_eq!(editor.text(cx), "acb\nde");
-// assert_eq!(editor.selections.ranges(cx), [3..3]);
-
-// editor.change_selections(None, cx, |s| s.select_ranges([4..4]));
-// editor.transpose(&Default::default(), cx);
-// assert_eq!(editor.text(cx), "acbd\ne");
-// assert_eq!(editor.selections.ranges(cx), [5..5]);
-
-// editor.transpose(&Default::default(), cx);
-// assert_eq!(editor.text(cx), "acbde\n");
-// assert_eq!(editor.selections.ranges(cx), [6..6]);
-
-// editor.transpose(&Default::default(), cx);
-// assert_eq!(editor.text(cx), "acbd\ne");
-// assert_eq!(editor.selections.ranges(cx), [6..6]);
-
-// editor
-// });
-
-// _ = cx.add_window(|cx| {
-// let mut editor = build_editor(MultiBuffer::build_simple("abc\nde", cx), cx);
-
-// editor.change_selections(None, cx, |s| s.select_ranges([1..1, 2..2, 4..4]));
-// editor.transpose(&Default::default(), cx);
-// assert_eq!(editor.text(cx), "bacd\ne");
-// assert_eq!(editor.selections.ranges(cx), [2..2, 3..3, 5..5]);
-
-// editor.transpose(&Default::default(), cx);
-// assert_eq!(editor.text(cx), "bcade\n");
-// assert_eq!(editor.selections.ranges(cx), [3..3, 4..4, 6..6]);
-
-// editor.transpose(&Default::default(), cx);
-// assert_eq!(editor.text(cx), "bcda\ne");
-// assert_eq!(editor.selections.ranges(cx), [4..4, 6..6]);
-
-// editor.transpose(&Default::default(), cx);
-// assert_eq!(editor.text(cx), "bcade\n");
-// assert_eq!(editor.selections.ranges(cx), [4..4, 6..6]);
-
-// editor.transpose(&Default::default(), cx);
-// assert_eq!(editor.text(cx), "bcaed\n");
-// assert_eq!(editor.selections.ranges(cx), [5..5, 6..6]);
-
-// editor
-// });
-
-// _ = cx.add_window(|cx| {
-// let mut editor = build_editor(MultiBuffer::build_simple("🍐🏀✋", cx), cx);
-
-// editor.change_selections(None, cx, |s| s.select_ranges([4..4]));
-// editor.transpose(&Default::default(), cx);
-// assert_eq!(editor.text(cx), "🏀🍐✋");
-// assert_eq!(editor.selections.ranges(cx), [8..8]);
-
-// editor.transpose(&Default::default(), cx);
-// assert_eq!(editor.text(cx), "🏀✋🍐");
-// assert_eq!(editor.selections.ranges(cx), [11..11]);
-
-// editor.transpose(&Default::default(), cx);
-// assert_eq!(editor.text(cx), "🏀🍐✋");
-// assert_eq!(editor.selections.ranges(cx), [11..11]);
-
-// editor
-// });
-// }
-
-// #[gpui::test]
-// async fn test_clipboard(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |_| {});
-
-// let mut cx = EditorTestContext::new(cx).await;
-
-// cx.set_state("«one✅ ˇ»two «three ˇ»four «five ˇ»six ");
-// cx.update_editor(|e, cx| e.cut(&Cut, cx));
-// cx.assert_editor_state("ˇtwo ˇfour ˇsix ");
-
-// // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
-// cx.set_state("two ˇfour ˇsix ˇ");
-// cx.update_editor(|e, cx| e.paste(&Paste, cx));
-// cx.assert_editor_state("two one✅ ˇfour three ˇsix five ˇ");
-
-// // Paste again but with only two cursors. Since the number of cursors doesn't
-// // match the number of slices in the clipboard, the entire clipboard text
-// // is pasted at each cursor.
-// cx.set_state("ˇtwo one✅ four three six five ˇ");
-// cx.update_editor(|e, cx| {
-// e.handle_input("( ", cx);
-// e.paste(&Paste, cx);
-// e.handle_input(") ", cx);
-// });
-// cx.assert_editor_state(
-// &([
-// "( one✅ ",
-// "three ",
-// "five ) ˇtwo one✅ four three six five ( one✅ ",
-// "three ",
-// "five ) ˇ",
-// ]
-// .join("\n")),
-// );
-
-// // Cut with three selections, one of which is full-line.
-// cx.set_state(indoc! {"
-// 1«2ˇ»3
-// 4ˇ567
-// «8ˇ»9"});
-// cx.update_editor(|e, cx| e.cut(&Cut, cx));
-// cx.assert_editor_state(indoc! {"
-// 1ˇ3
-// ˇ9"});
-
-// // Paste with three selections, noticing how the copied selection that was full-line
-// // gets inserted before the second cursor.
-// cx.set_state(indoc! {"
-// 1ˇ3
-// 9ˇ
-// «oˇ»ne"});
-// cx.update_editor(|e, cx| e.paste(&Paste, cx));
-// cx.assert_editor_state(indoc! {"
-// 12ˇ3
-// 4567
-// 9ˇ
-// 8ˇne"});
-
-// // Copy with a single cursor only, which writes the whole line into the clipboard.
-// cx.set_state(indoc! {"
-// The quick brown
-// fox juˇmps over
-// the lazy dog"});
-// cx.update_editor(|e, cx| e.copy(&Copy, cx));
-// cx.cx.assert_clipboard_content(Some("fox jumps over\n"));
-
-// // Paste with three selections, noticing how the copied full-line selection is inserted
-// // before the empty selections but replaces the selection that is non-empty.
-// cx.set_state(indoc! {"
-// Tˇhe quick brown
-// «foˇ»x jumps over
-// tˇhe lazy dog"});
-// cx.update_editor(|e, cx| e.paste(&Paste, cx));
-// cx.assert_editor_state(indoc! {"
-// fox jumps over
-// Tˇhe quick brown
-// fox jumps over
-// ˇx jumps over
-// fox jumps over
-// tˇhe lazy dog"});
-// }
-
-// #[gpui::test]
-// async fn test_paste_multiline(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |_| {});
-
-// let mut cx = EditorTestContext::new(cx).await;
-// let language = Arc::new(Language::new(
-// LanguageConfig::default(),
-// Some(tree_sitter_rust::language()),
-// ));
-// cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
-
-// // Cut an indented block, without the leading whitespace.
-// cx.set_state(indoc! {"
-// const a: B = (
-// c(),
-// «d(
-// e,
-// f
-// )ˇ»
-// );
-// "});
-// cx.update_editor(|e, cx| e.cut(&Cut, cx));
-// cx.assert_editor_state(indoc! {"
-// const a: B = (
-// c(),
-// ˇ
-// );
-// "});
-
-// // Paste it at the same position.
-// cx.update_editor(|e, cx| e.paste(&Paste, cx));
-// cx.assert_editor_state(indoc! {"
-// const a: B = (
-// c(),
-// d(
-// e,
-// f
-// )ˇ
-// );
-// "});
-
-// // Paste it at a line with a lower indent level.
-// cx.set_state(indoc! {"
-// ˇ
-// const a: B = (
-// c(),
-// );
-// "});
-// cx.update_editor(|e, cx| e.paste(&Paste, cx));
-// cx.assert_editor_state(indoc! {"
-// d(
-// e,
-// f
-// )ˇ
-// const a: B = (
-// c(),
-// );
-// "});
-
-// // Cut an indented block, with the leading whitespace.
-// cx.set_state(indoc! {"
-// const a: B = (
-// c(),
-// « d(
-// e,
-// f
-// )
-// ˇ»);
-// "});
-// cx.update_editor(|e, cx| e.cut(&Cut, cx));
-// cx.assert_editor_state(indoc! {"
-// const a: B = (
-// c(),
-// ˇ);
-// "});
-
-// // Paste it at the same position.
-// cx.update_editor(|e, cx| e.paste(&Paste, cx));
-// cx.assert_editor_state(indoc! {"
-// const a: B = (
-// c(),
-// d(
-// e,
-// f
-// )
-// ˇ);
-// "});
-
-// // Paste it at a line with a higher indent level.
-// cx.set_state(indoc! {"
-// const a: B = (
-// c(),
-// d(
-// e,
-// fˇ
-// )
-// );
-// "});
-// cx.update_editor(|e, cx| e.paste(&Paste, cx));
-// cx.assert_editor_state(indoc! {"
-// const a: B = (
-// c(),
-// d(
-// e,
-// f d(
-// e,
-// f
-// )
-// ˇ
-// )
-// );
-// "});
-// }
-
-// #[gpui::test]
-// fn test_select_all(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
-
-// let view = cx
-// .add_window(|cx| {
-// let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
-// build_editor(buffer, cx)
-// })
-// .root(cx);
-// view.update(cx, |view, cx| {
-// view.select_all(&SelectAll, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
-// );
-// });
-// }
-
-// #[gpui::test]
-// fn test_select_line(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
-
-// let view = cx
-// .add_window(|cx| {
-// let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
-// build_editor(buffer, cx)
-// })
-// .root(cx);
-// view.update(cx, |view, cx| {
-// view.change_selections(None, cx, |s| {
-// s.select_display_ranges([
-// DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
-// DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
-// DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
-// DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
-// ])
-// });
-// view.select_line(&SelectLine, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![
-// DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
-// DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
-// ]
-// );
-// });
-
-// view.update(cx, |view, cx| {
-// view.select_line(&SelectLine, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![
-// DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
-// DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
-// ]
-// );
-// });
+ cx.add_window(|cx| {
+ let mut editor = build_editor(multibuffer, cx);
+
+ assert_eq!(
+ editor.text(cx),
+ indoc! {"
+ a = 1
+ b = 2
+
+ const c: usize = 3;
+ "}
+ );
+
+ select_ranges(
+ &mut editor,
+ indoc! {"
+ «aˇ» = 1
+ b = 2
+
+ «const c:ˇ» usize = 3;
+ "},
+ cx,
+ );
+
+ editor.tab(&Tab, cx);
+ assert_text_with_selections(
+ &mut editor,
+ indoc! {"
+ «aˇ» = 1
+ b = 2
+
+ «const c:ˇ» usize = 3;
+ "},
+ cx,
+ );
+ editor.tab_prev(&TabPrev, cx);
+ assert_text_with_selections(
+ &mut editor,
+ indoc! {"
+ «aˇ» = 1
+ b = 2
+
+ «const c:ˇ» usize = 3;
+ "},
+ cx,
+ );
+
+ editor
+ });
+}
-// view.update(cx, |view, cx| {
-// view.select_line(&SelectLine, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
-// );
-// });
-// }
+#[gpui::test]
+async fn test_backspace(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |_| {});
+
+ let mut cx = EditorTestContext::new(cx).await;
+
+ // Basic backspace
+ cx.set_state(indoc! {"
+ onˇe two three
+ fou«rˇ» five six
+ seven «ˇeight nine
+ »ten
+ "});
+ cx.update_editor(|e, cx| e.backspace(&Backspace, cx));
+ cx.assert_editor_state(indoc! {"
+ oˇe two three
+ fouˇ five six
+ seven ˇten
+ "});
+
+ // Test backspace inside and around indents
+ cx.set_state(indoc! {"
+ zero
+ ˇone
+ ˇtwo
+ ˇ ˇ ˇ three
+ ˇ ˇ four
+ "});
+ cx.update_editor(|e, cx| e.backspace(&Backspace, cx));
+ cx.assert_editor_state(indoc! {"
+ zero
+ ˇone
+ ˇtwo
+ ˇ threeˇ four
+ "});
+
+ // Test backspace with line_mode set to true
+ cx.update_editor(|e, _| e.selections.line_mode = true);
+ cx.set_state(indoc! {"
+ The ˇquick ˇbrown
+ fox jumps over
+ the lazy dog
+ ˇThe qu«ick bˇ»rown"});
+ cx.update_editor(|e, cx| e.backspace(&Backspace, cx));
+ cx.assert_editor_state(indoc! {"
+ ˇfox jumps over
+ the lazy dogˇ"});
+}
-// #[gpui::test]
-// fn test_split_selection_into_lines(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
+#[gpui::test]
+async fn test_delete(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |_| {});
+
+ let mut cx = EditorTestContext::new(cx).await;
+ cx.set_state(indoc! {"
+ onˇe two three
+ fou«rˇ» five six
+ seven «ˇeight nine
+ »ten
+ "});
+ cx.update_editor(|e, cx| e.delete(&Delete, cx));
+ cx.assert_editor_state(indoc! {"
+ onˇ two three
+ fouˇ five six
+ seven ˇten
+ "});
+
+ // Test backspace with line_mode set to true
+ cx.update_editor(|e, _| e.selections.line_mode = true);
+ cx.set_state(indoc! {"
+ The ˇquick ˇbrown
+ fox «ˇjum»ps over
+ the lazy dog
+ ˇThe qu«ick bˇ»rown"});
+ cx.update_editor(|e, cx| e.backspace(&Backspace, cx));
+ cx.assert_editor_state("ˇthe lazy dogˇ");
+}
-// let view = cx
-// .add_window(|cx| {
-// let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
-// build_editor(buffer, cx)
-// })
-// .root(cx);
-// view.update(cx, |view, cx| {
-// view.fold_ranges(
-// vec![
-// Point::new(0, 2)..Point::new(1, 2),
-// Point::new(2, 3)..Point::new(4, 1),
-// Point::new(7, 0)..Point::new(8, 4),
-// ],
-// true,
-// cx,
-// );
-// view.change_selections(None, cx, |s| {
-// s.select_display_ranges([
-// DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
-// DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
-// DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
-// DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
-// ])
-// });
-// assert_eq!(view.display_text(cx), "aa⋯bbb\nccc⋯eeee\nfffff\nggggg\n⋯i");
-// });
+#[gpui::test]
+fn test_delete_line(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
-// view.update(cx, |view, cx| {
-// view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
-// assert_eq!(
-// view.display_text(cx),
-// "aaaaa\nbbbbb\nccc⋯eeee\nfffff\nggggg\n⋯i"
-// );
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// [
-// DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
-// DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
-// DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
-// DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
-// ]
-// );
-// });
+ let view = cx.add_window(|cx| {
+ let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
+ build_editor(buffer, cx)
+ });
+ view.update(cx, |view, cx| {
+ view.change_selections(None, cx, |s| {
+ s.select_display_ranges([
+ DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
+ DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
+ DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
+ ])
+ });
+ view.delete_line(&DeleteLine, cx);
+ assert_eq!(view.display_text(cx), "ghi");
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ vec![
+ DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
+ DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
+ ]
+ );
+ });
-// view.update(cx, |view, cx| {
-// view.change_selections(None, cx, |s| {
-// s.select_display_ranges([DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)])
-// });
-// view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
-// assert_eq!(
-// view.display_text(cx),
-// "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
-// );
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// [
-// DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
-// DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
-// DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
-// DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
-// DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
-// DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
-// DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
-// DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
-// ]
-// );
-// });
-// }
+ let view = cx.add_window(|cx| {
+ let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
+ build_editor(buffer, cx)
+ });
+ view.update(cx, |view, cx| {
+ view.change_selections(None, cx, |s| {
+ s.select_display_ranges([DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)])
+ });
+ view.delete_line(&DeleteLine, cx);
+ assert_eq!(view.display_text(cx), "ghi\n");
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
+ );
+ });
+}
+//todo!(select_anchor_ranges)
// #[gpui::test]
-// fn test_add_selection_above_below(cx: &mut TestAppContext) {
+// fn test_join_lines_with_single_selection(cx: &mut TestAppContext) {
// init_test(cx, |_| {});
-// let view = cx
-// .add_window(|cx| {
-// let buffer = MultiBuffer::build_simple("abc\ndefghi\n\njk\nlmno\n", cx);
-// build_editor(buffer, cx)
-// })
-// .root(cx);
-
-// view.update(cx, |view, cx| {
-// view.change_selections(None, cx, |s| {
-// s.select_display_ranges([DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)])
-// });
-// });
-// view.update(cx, |view, cx| {
-// view.add_selection_above(&AddSelectionAbove, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![
-// DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
-// DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
-// ]
-// );
-// });
-
-// view.update(cx, |view, cx| {
-// view.add_selection_above(&AddSelectionAbove, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![
-// DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
-// DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
-// ]
-// );
-// });
-
-// view.update(cx, |view, cx| {
-// view.add_selection_below(&AddSelectionBelow, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
-// );
-
-// view.undo_selection(&UndoSelection, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![
-// DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
-// DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
-// ]
-// );
-
-// view.redo_selection(&RedoSelection, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
-// );
-// });
-
-// view.update(cx, |view, cx| {
-// view.add_selection_below(&AddSelectionBelow, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![
-// DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
-// DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
-// ]
-// );
-// });
-
-// view.update(cx, |view, cx| {
-// view.add_selection_below(&AddSelectionBelow, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![
-// DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
-// DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
-// ]
-// );
-// });
-
-// view.update(cx, |view, cx| {
-// view.change_selections(None, cx, |s| {
-// s.select_display_ranges([DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)])
-// });
-// });
-// view.update(cx, |view, cx| {
-// view.add_selection_below(&AddSelectionBelow, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![
-// DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
-// DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
-// ]
-// );
-// });
-
-// view.update(cx, |view, cx| {
-// view.add_selection_below(&AddSelectionBelow, cx);
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![
-// DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
-// DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
-// ]
-// );
-// });
+// cx.add_window(|cx| {
+// let buffer = MultiBuffer::build_simple("aaa\nbbb\nccc\nddd\n\n", cx);
+// let mut editor = build_editor(buffer.clone(), cx);
+// let buffer = buffer.read(cx).as_singleton().unwrap();
-// view.update(cx, |view, cx| {
-// view.add_selection_above(&AddSelectionAbove, cx);
// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
+// editor.selections.ranges::<Point>(cx),
+// &[Point::new(0, 0)..Point::new(0, 0)]
// );
-// });
-// view.update(cx, |view, cx| {
-// view.add_selection_above(&AddSelectionAbove, cx);
+// // When on single line, replace newline at end by space
+// editor.join_lines(&JoinLines, cx);
+// assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd\n\n");
// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
+// editor.selections.ranges::<Point>(cx),
+// &[Point::new(0, 3)..Point::new(0, 3)]
// );
-// });
-// view.update(cx, |view, cx| {
-// view.change_selections(None, cx, |s| {
-// s.select_display_ranges([DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)])
+// // When multiple lines are selected, remove newlines that are spanned by the selection
+// editor.change_selections(None, cx, |s| {
+// s.select_ranges([Point::new(0, 5)..Point::new(2, 2)])
// });
-// view.add_selection_below(&AddSelectionBelow, cx);
+// editor.join_lines(&JoinLines, cx);
+// assert_eq!(buffer.read(cx).text(), "aaa bbb ccc ddd\n\n");
// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![
-// DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
-// DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
-// DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
-// ]
+// editor.selections.ranges::<Point>(cx),
+// &[Point::new(0, 11)..Point::new(0, 11)]
// );
-// });
-// view.update(cx, |view, cx| {
-// view.add_selection_below(&AddSelectionBelow, cx);
+// // Undo should be transactional
+// editor.undo(&Undo, cx);
+// assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd\n\n");
// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![
-// DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
-// DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
-// DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
-// DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
-// ]
+// editor.selections.ranges::<Point>(cx),
+// &[Point::new(0, 5)..Point::new(2, 2)]
// );
-// });
-// view.update(cx, |view, cx| {
-// view.add_selection_above(&AddSelectionAbove, cx);
+// // When joining an empty line don't insert a space
+// editor.change_selections(None, cx, |s| {
+// s.select_ranges([Point::new(2, 1)..Point::new(2, 2)])
+// });
+// editor.join_lines(&JoinLines, cx);
+// assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd\n");
// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![
-// DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
-// DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
-// DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
-// ]
+// editor.selections.ranges::<Point>(cx),
+// [Point::new(2, 3)..Point::new(2, 3)]
// );
-// });
-// view.update(cx, |view, cx| {
-// view.change_selections(None, cx, |s| {
-// s.select_display_ranges([DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)])
-// });
-// });
-// view.update(cx, |view, cx| {
-// view.add_selection_above(&AddSelectionAbove, cx);
+// // We can remove trailing newlines
+// editor.join_lines(&JoinLines, cx);
+// assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd");
// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![
-// DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
-// DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
-// DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
-// DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
-// ]
+// editor.selections.ranges::<Point>(cx),
+// [Point::new(2, 3)..Point::new(2, 3)]
// );
-// });
-// view.update(cx, |view, cx| {
-// view.add_selection_below(&AddSelectionBelow, cx);
+// // We don't blow up on the last line
+// editor.join_lines(&JoinLines, cx);
+// assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd");
// assert_eq!(
-// view.selections.display_ranges(cx),
-// vec![
-// DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
-// DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
-// DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
-// ]
+// editor.selections.ranges::<Point>(cx),
+// [Point::new(2, 3)..Point::new(2, 3)]
// );
-// });
-// }
-// #[gpui::test]
-// async fn test_select_next(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |_| {});
-
-// let mut cx = EditorTestContext::new(cx).await;
-// cx.set_state("abc\nˇabc abc\ndefabc\nabc");
-
-// cx.update_editor(|e, cx| e.select_next(&SelectNext::default(), cx))
-// .unwrap();
-// cx.assert_editor_state("abc\n«abcˇ» abc\ndefabc\nabc");
-
-// cx.update_editor(|e, cx| e.select_next(&SelectNext::default(), cx))
-// .unwrap();
-// cx.assert_editor_state("abc\n«abcˇ» «abcˇ»\ndefabc\nabc");
-
-// cx.update_editor(|view, cx| view.undo_selection(&UndoSelection, cx));
-// cx.assert_editor_state("abc\n«abcˇ» abc\ndefabc\nabc");
-
-// cx.update_editor(|view, cx| view.redo_selection(&RedoSelection, cx));
-// cx.assert_editor_state("abc\n«abcˇ» «abcˇ»\ndefabc\nabc");
-
-// cx.update_editor(|e, cx| e.select_next(&SelectNext::default(), cx))
-// .unwrap();
-// cx.assert_editor_state("abc\n«abcˇ» «abcˇ»\ndefabc\n«abcˇ»");
-
-// cx.update_editor(|e, cx| e.select_next(&SelectNext::default(), cx))
-// .unwrap();
-// cx.assert_editor_state("«abcˇ»\n«abcˇ» «abcˇ»\ndefabc\n«abcˇ»");
-// }
-
-// #[gpui::test]
-// async fn test_select_previous(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |_| {});
-// {
-// // `Select previous` without a selection (selects wordwise)
-// let mut cx = EditorTestContext::new(cx).await;
-// cx.set_state("abc\nˇabc abc\ndefabc\nabc");
-
-// cx.update_editor(|e, cx| e.select_previous(&SelectPrevious::default(), cx))
-// .unwrap();
-// cx.assert_editor_state("abc\n«abcˇ» abc\ndefabc\nabc");
-
-// cx.update_editor(|e, cx| e.select_previous(&SelectPrevious::default(), cx))
-// .unwrap();
-// cx.assert_editor_state("«abcˇ»\n«abcˇ» abc\ndefabc\nabc");
-
-// cx.update_editor(|view, cx| view.undo_selection(&UndoSelection, cx));
-// cx.assert_editor_state("abc\n«abcˇ» abc\ndefabc\nabc");
-
-// cx.update_editor(|view, cx| view.redo_selection(&RedoSelection, cx));
-// cx.assert_editor_state("«abcˇ»\n«abcˇ» abc\ndefabc\nabc");
-
-// cx.update_editor(|e, cx| e.select_previous(&SelectPrevious::default(), cx))
-// .unwrap();
-// cx.assert_editor_state("«abcˇ»\n«abcˇ» abc\ndefabc\n«abcˇ»");
-
-// cx.update_editor(|e, cx| e.select_previous(&SelectPrevious::default(), cx))
-// .unwrap();
-// cx.assert_editor_state("«abcˇ»\n«abcˇ» «abcˇ»\ndefabc\n«abcˇ»");
-// }
-// {
-// // `Select previous` with a selection
-// let mut cx = EditorTestContext::new(cx).await;
-// cx.set_state("abc\n«ˇabc» abc\ndefabc\nabc");
-
-// cx.update_editor(|e, cx| e.select_previous(&SelectPrevious::default(), cx))
-// .unwrap();
-// cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndefabc\nabc");
-
-// cx.update_editor(|e, cx| e.select_previous(&SelectPrevious::default(), cx))
-// .unwrap();
-// cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndefabc\n«abcˇ»");
-
-// cx.update_editor(|view, cx| view.undo_selection(&UndoSelection, cx));
-// cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndefabc\nabc");
-
-// cx.update_editor(|view, cx| view.redo_selection(&RedoSelection, cx));
-// cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndefabc\n«abcˇ»");
-
-// cx.update_editor(|e, cx| e.select_previous(&SelectPrevious::default(), cx))
-// .unwrap();
-// cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndef«abcˇ»\n«abcˇ»");
-
-// cx.update_editor(|e, cx| e.select_previous(&SelectPrevious::default(), cx))
-// .unwrap();
-// cx.assert_editor_state("«abcˇ»\n«ˇabc» «abcˇ»\ndef«abcˇ»\n«abcˇ»");
-// }
-// }
-
-// #[gpui::test]
-// async fn test_select_larger_smaller_syntax_node(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |_| {});
-
-// let language = Arc::new(Language::new(
-// LanguageConfig::default(),
-// Some(tree_sitter_rust::language()),
-// ));
-
-// let text = r#"
-// use mod1::mod2::{mod3, mod4};
-
-// fn fn_1(param1: bool, param2: &str) {
-// let var1 = "text";
-// }
-// "#
-// .unindent();
-
-// let buffer =
-// cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, text).with_language(language, cx));
-// let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
-// let view = cx.add_window(|cx| build_editor(buffer, cx)).root(cx);
-// view.condition(cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
-// .await;
-
-// view.update(cx, |view, cx| {
-// view.change_selections(None, cx, |s| {
-// s.select_display_ranges([
-// DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
-// DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
-// DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
-// ]);
+// // reset to test indentation
+// editor.buffer.update(cx, |buffer, cx| {
+// buffer.edit(
+// [
+// (Point::new(1, 0)..Point::new(1, 2), " "),
+// (Point::new(2, 0)..Point::new(2, 3), " \n\td"),
+// ],
+// None,
+// cx,
+// )
// });
-// view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
-// });
-// assert_eq!(
-// view.update(cx, |view, cx| { view.selections.display_ranges(cx) }),
-// &[
-// DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
-// DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
-// DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
-// ]
-// );
-
-// view.update(cx, |view, cx| {
-// view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
-// });
-// assert_eq!(
-// view.update(cx, |view, cx| view.selections.display_ranges(cx)),
-// &[
-// DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
-// DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
-// ]
-// );
-
-// view.update(cx, |view, cx| {
-// view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
-// });
-// assert_eq!(
-// view.update(cx, |view, cx| view.selections.display_ranges(cx)),
-// &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
-// );
-
-// // Trying to expand the selected syntax node one more time has no effect.
-// view.update(cx, |view, cx| {
-// view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
-// });
-// assert_eq!(
-// view.update(cx, |view, cx| view.selections.display_ranges(cx)),
-// &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
-// );
-
-// view.update(cx, |view, cx| {
-// view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
-// });
-// assert_eq!(
-// view.update(cx, |view, cx| view.selections.display_ranges(cx)),
-// &[
-// DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
-// DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
-// ]
-// );
-// view.update(cx, |view, cx| {
-// view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
-// });
-// assert_eq!(
-// view.update(cx, |view, cx| view.selections.display_ranges(cx)),
-// &[
-// DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
-// DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
-// DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
-// ]
-// );
+// // We remove any leading spaces
+// assert_eq!(buffer.read(cx).text(), "aaa bbb\n c\n \n\td");
+// editor.change_selections(None, cx, |s| {
+// s.select_ranges([Point::new(0, 1)..Point::new(0, 1)])
+// });
+// editor.join_lines(&JoinLines, cx);
+// assert_eq!(buffer.read(cx).text(), "aaa bbb c\n \n\td");
-// view.update(cx, |view, cx| {
-// view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
-// });
-// assert_eq!(
-// view.update(cx, |view, cx| view.selections.display_ranges(cx)),
-// &[
-// DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
-// DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
-// DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
-// ]
-// );
+// // We don't insert a space for a line containing only spaces
+// editor.join_lines(&JoinLines, cx);
+// assert_eq!(buffer.read(cx).text(), "aaa bbb c\n\td");
-// // Trying to shrink the selected syntax node one more time has no effect.
-// view.update(cx, |view, cx| {
-// view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
-// });
-// assert_eq!(
-// view.update(cx, |view, cx| view.selections.display_ranges(cx)),
-// &[
-// DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
-// DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
-// DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
-// ]
-// );
+// // We ignore any leading tabs
+// editor.join_lines(&JoinLines, cx);
+// assert_eq!(buffer.read(cx).text(), "aaa bbb c d");
-// // Ensure that we keep expanding the selection if the larger selection starts or ends within
-// // a fold.
-// view.update(cx, |view, cx| {
-// view.fold_ranges(
-// vec![
-// Point::new(0, 21)..Point::new(0, 24),
-// Point::new(3, 20)..Point::new(3, 22),
-// ],
-// true,
-// cx,
-// );
-// view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
+// editor
// });
-// assert_eq!(
-// view.update(cx, |view, cx| view.selections.display_ranges(cx)),
-// &[
-// DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
-// DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
-// DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
-// ]
-// );
// }
// #[gpui::test]
-// async fn test_autoindent_selections(cx: &mut gpui::TestAppContext) {
+// fn test_join_lines_with_multi_selection(cx: &mut TestAppContext) {
// init_test(cx, |_| {});
-// let language = Arc::new(
-// Language::new(
-// LanguageConfig {
-// brackets: BracketPairConfig {
-// pairs: vec![
-// BracketPair {
-// start: "{".to_string(),
-// end: "}".to_string(),
-// close: false,
-// newline: true,
-// },
-// BracketPair {
-// start: "(".to_string(),
-// end: ")".to_string(),
-// close: false,
-// newline: true,
-// },
-// ],
-// ..Default::default()
-// },
-// ..Default::default()
-// },
-// Some(tree_sitter_rust::language()),
-// )
-// .with_indents_query(
-// r#"
-// (_ "(" ")" @end) @indent
-// (_ "{" "}" @end) @indent
-// "#,
-// )
-// .unwrap(),
-// );
+// cx.add_window(|cx| {
+// let buffer = MultiBuffer::build_simple("aaa\nbbb\nccc\nddd\n\n", cx);
+// let mut editor = build_editor(buffer.clone(), cx);
+// let buffer = buffer.read(cx).as_singleton().unwrap();
-// let text = "fn a() {}";
+// editor.change_selections(None, cx, |s| {
+// s.select_ranges([
+// Point::new(0, 2)..Point::new(1, 1),
+// Point::new(1, 2)..Point::new(1, 2),
+// Point::new(3, 1)..Point::new(3, 2),
+// ])
+// });
-// let buffer =
-// cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, text).with_language(language, cx));
-// let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
-// let editor = cx.add_window(|cx| build_editor(buffer, cx)).root(cx);
-// editor
-// .condition(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
-// .await;
+// editor.join_lines(&JoinLines, cx);
+// assert_eq!(buffer.read(cx).text(), "aaa bbb ccc\nddd\n");
-// editor.update(cx, |editor, cx| {
-// editor.change_selections(None, cx, |s| s.select_ranges([5..5, 8..8, 9..9]));
-// editor.newline(&Newline, cx);
-// assert_eq!(editor.text(cx), "fn a(\n \n) {\n \n}\n");
// assert_eq!(
-// editor.selections.ranges(cx),
-// &[
-// Point::new(1, 4)..Point::new(1, 4),
-// Point::new(3, 4)..Point::new(3, 4),
-// Point::new(5, 0)..Point::new(5, 0)
+// editor.selections.ranges::<Point>(cx),
+// [
+// Point::new(0, 7)..Point::new(0, 7),
+// Point::new(1, 3)..Point::new(1, 3)
// ]
// );
+// editor
// });
// }
-// #[gpui::test]
-// async fn test_autoclose_pairs(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |_| {});
+#[gpui::test]
+async fn test_manipulate_lines_with_single_selection(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+
+ let mut cx = EditorTestContext::new(cx).await;
+
+ // Test sort_lines_case_insensitive()
+ cx.set_state(indoc! {"
+ «z
+ y
+ x
+ Z
+ Y
+ Xˇ»
+ "});
+ cx.update_editor(|e, cx| e.sort_lines_case_insensitive(&SortLinesCaseInsensitive, cx));
+ cx.assert_editor_state(indoc! {"
+ «x
+ X
+ y
+ Y
+ z
+ Zˇ»
+ "});
+
+ // Test reverse_lines()
+ cx.set_state(indoc! {"
+ «5
+ 4
+ 3
+ 2
+ 1ˇ»
+ "});
+ cx.update_editor(|e, cx| e.reverse_lines(&ReverseLines, cx));
+ cx.assert_editor_state(indoc! {"
+ «1
+ 2
+ 3
+ 4
+ 5ˇ»
+ "});
+
+ // Skip testing shuffle_line()
+
+ // From here on out, test more complex cases of manipulate_lines() with a single driver method: sort_lines_case_sensitive()
+ // Since all methods calling manipulate_lines() are doing the exact same general thing (reordering lines)
+
+ // Don't manipulate when cursor is on single line, but expand the selection
+ cx.set_state(indoc! {"
+ ddˇdd
+ ccc
+ bb
+ a
+ "});
+ cx.update_editor(|e, cx| e.sort_lines_case_sensitive(&SortLinesCaseSensitive, cx));
+ cx.assert_editor_state(indoc! {"
+ «ddddˇ»
+ ccc
+ bb
+ a
+ "});
+
+ // Basic manipulate case
+ // Start selection moves to column 0
+ // End of selection shrinks to fit shorter line
+ cx.set_state(indoc! {"
+ dd«d
+ ccc
+ bb
+ aaaaaˇ»
+ "});
+ cx.update_editor(|e, cx| e.sort_lines_case_sensitive(&SortLinesCaseSensitive, cx));
+ cx.assert_editor_state(indoc! {"
+ «aaaaa
+ bb
+ ccc
+ dddˇ»
+ "});
+
+ // Manipulate case with newlines
+ cx.set_state(indoc! {"
+ dd«d
+ ccc
+
+ bb
+ aaaaa
+
+ ˇ»
+ "});
+ cx.update_editor(|e, cx| e.sort_lines_case_sensitive(&SortLinesCaseSensitive, cx));
+ cx.assert_editor_state(indoc! {"
+ «
+
+ aaaaa
+ bb
+ ccc
+ dddˇ»
+
+ "});
+}
-// let mut cx = EditorTestContext::new(cx).await;
+#[gpui::test]
+async fn test_manipulate_lines_with_multi_selection(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+
+ let mut cx = EditorTestContext::new(cx).await;
+
+ // Manipulate with multiple selections on a single line
+ cx.set_state(indoc! {"
+ dd«dd
+ cˇ»c«c
+ bb
+ aaaˇ»aa
+ "});
+ cx.update_editor(|e, cx| e.sort_lines_case_sensitive(&SortLinesCaseSensitive, cx));
+ cx.assert_editor_state(indoc! {"
+ «aaaaa
+ bb
+ ccc
+ ddddˇ»
+ "});
+
+ // Manipulate with multiple disjoin selections
+ cx.set_state(indoc! {"
+ 5«
+ 4
+ 3
+ 2
+ 1ˇ»
+
+ dd«dd
+ ccc
+ bb
+ aaaˇ»aa
+ "});
+ cx.update_editor(|e, cx| e.sort_lines_case_sensitive(&SortLinesCaseSensitive, cx));
+ cx.assert_editor_state(indoc! {"
+ «1
+ 2
+ 3
+ 4
+ 5ˇ»
+
+ «aaaaa
+ bb
+ ccc
+ ddddˇ»
+ "});
+}
-// let language = Arc::new(Language::new(
-// LanguageConfig {
-// brackets: BracketPairConfig {
-// pairs: vec![
-// BracketPair {
-// start: "{".to_string(),
-// end: "}".to_string(),
-// close: true,
-// newline: true,
-// },
-// BracketPair {
-// start: "(".to_string(),
-// end: ")".to_string(),
-// close: true,
-// newline: true,
-// },
-// BracketPair {
-// start: "/*".to_string(),
-// end: " */".to_string(),
-// close: true,
-// newline: true,
-// },
-// BracketPair {
-// start: "[".to_string(),
-// end: "]".to_string(),
-// close: false,
-// newline: true,
-// },
-// BracketPair {
-// start: "\"".to_string(),
-// end: "\"".to_string(),
-// close: true,
-// newline: false,
-// },
-// ],
-// ..Default::default()
-// },
-// autoclose_before: "})]".to_string(),
-// ..Default::default()
-// },
-// Some(tree_sitter_rust::language()),
-// ));
+#[gpui::test]
+async fn test_manipulate_text(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+
+ let mut cx = EditorTestContext::new(cx).await;
+
+ // Test convert_to_upper_case()
+ cx.set_state(indoc! {"
+ «hello worldˇ»
+ "});
+ cx.update_editor(|e, cx| e.convert_to_upper_case(&ConvertToUpperCase, cx));
+ cx.assert_editor_state(indoc! {"
+ «HELLO WORLDˇ»
+ "});
+
+ // Test convert_to_lower_case()
+ cx.set_state(indoc! {"
+ «HELLO WORLDˇ»
+ "});
+ cx.update_editor(|e, cx| e.convert_to_lower_case(&ConvertToLowerCase, cx));
+ cx.assert_editor_state(indoc! {"
+ «hello worldˇ»
+ "});
+
+ // Test multiple line, single selection case
+ // Test code hack that covers the fact that to_case crate doesn't support '\n' as a word boundary
+ cx.set_state(indoc! {"
+ «The quick brown
+ fox jumps over
+ the lazy dogˇ»
+ "});
+ cx.update_editor(|e, cx| e.convert_to_title_case(&ConvertToTitleCase, cx));
+ cx.assert_editor_state(indoc! {"
+ «The Quick Brown
+ Fox Jumps Over
+ The Lazy Dogˇ»
+ "});
+
+ // Test multiple line, single selection case
+ // Test code hack that covers the fact that to_case crate doesn't support '\n' as a word boundary
+ cx.set_state(indoc! {"
+ «The quick brown
+ fox jumps over
+ the lazy dogˇ»
+ "});
+ cx.update_editor(|e, cx| e.convert_to_upper_camel_case(&ConvertToUpperCamelCase, cx));
+ cx.assert_editor_state(indoc! {"
+ «TheQuickBrown
+ FoxJumpsOver
+ TheLazyDogˇ»
+ "});
+
+ // From here on out, test more complex cases of manipulate_text()
+
+ // Test no selection case - should affect words cursors are in
+ // Cursor at beginning, middle, and end of word
+ cx.set_state(indoc! {"
+ ˇhello big beauˇtiful worldˇ
+ "});
+ cx.update_editor(|e, cx| e.convert_to_upper_case(&ConvertToUpperCase, cx));
+ cx.assert_editor_state(indoc! {"
+ «HELLOˇ» big «BEAUTIFULˇ» «WORLDˇ»
+ "});
+
+ // Test multiple selections on a single line and across multiple lines
+ cx.set_state(indoc! {"
+ «Theˇ» quick «brown
+ foxˇ» jumps «overˇ»
+ the «lazyˇ» dog
+ "});
+ cx.update_editor(|e, cx| e.convert_to_upper_case(&ConvertToUpperCase, cx));
+ cx.assert_editor_state(indoc! {"
+ «THEˇ» quick «BROWN
+ FOXˇ» jumps «OVERˇ»
+ the «LAZYˇ» dog
+ "});
+
+ // Test case where text length grows
+ cx.set_state(indoc! {"
+ «tschüߡ»
+ "});
+ cx.update_editor(|e, cx| e.convert_to_upper_case(&ConvertToUpperCase, cx));
+ cx.assert_editor_state(indoc! {"
+ «TSCHÜSSˇ»
+ "});
+
+ // Test to make sure we don't crash when text shrinks
+ cx.set_state(indoc! {"
+ aaa_bbbˇ
+ "});
+ cx.update_editor(|e, cx| e.convert_to_lower_camel_case(&ConvertToLowerCamelCase, cx));
+ cx.assert_editor_state(indoc! {"
+ «aaaBbbˇ»
+ "});
+
+ // Test to make sure we all aware of the fact that each word can grow and shrink
+ // Final selections should be aware of this fact
+ cx.set_state(indoc! {"
+ aaa_bˇbb bbˇb_ccc ˇccc_ddd
+ "});
+ cx.update_editor(|e, cx| e.convert_to_lower_camel_case(&ConvertToLowerCamelCase, cx));
+ cx.assert_editor_state(indoc! {"
+ «aaaBbbˇ» «bbbCccˇ» «cccDddˇ»
+ "});
+}
-// let registry = Arc::new(LanguageRegistry::test());
-// registry.add(language.clone());
-// cx.update_buffer(|buffer, cx| {
-// buffer.set_language_registry(registry);
-// buffer.set_language(Some(language), cx);
-// });
+#[gpui::test]
+fn test_duplicate_line(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
-// cx.set_state(
-// &r#"
-// 🏀ˇ
-// εˇ
-// ❤️ˇ
-// "#
-// .unindent(),
-// );
+ let view = cx.add_window(|cx| {
+ let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
+ build_editor(buffer, cx)
+ });
+ view.update(cx, |view, cx| {
+ view.change_selections(None, cx, |s| {
+ s.select_display_ranges([
+ DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
+ DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
+ DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
+ DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
+ ])
+ });
+ view.duplicate_line(&DuplicateLine, cx);
+ assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ vec![
+ DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
+ DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
+ DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
+ DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
+ ]
+ );
+ });
+
+ let view = cx.add_window(|cx| {
+ let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
+ build_editor(buffer, cx)
+ });
+ view.update(cx, |view, cx| {
+ view.change_selections(None, cx, |s| {
+ s.select_display_ranges([
+ DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
+ DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
+ ])
+ });
+ view.duplicate_line(&DuplicateLine, cx);
+ assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ vec![
+ DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
+ DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
+ ]
+ );
+ });
+}
-// // autoclose multiple nested brackets at multiple cursors
-// cx.update_editor(|view, cx| {
-// view.handle_input("{", cx);
-// view.handle_input("{", cx);
-// view.handle_input("{", cx);
-// });
-// cx.assert_editor_state(
-// &"
-// 🏀{{{ˇ}}}
-// ε{{{ˇ}}}
-// ❤️{{{ˇ}}}
-// "
-// .unindent(),
-// );
+#[gpui::test]
+fn test_move_line_up_down(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
-// // insert a different closing bracket
-// cx.update_editor(|view, cx| {
-// view.handle_input(")", cx);
-// });
-// cx.assert_editor_state(
-// &"
-// 🏀{{{)ˇ}}}
-// ε{{{)ˇ}}}
-// ❤️{{{)ˇ}}}
-// "
-// .unindent(),
-// );
+ let view = cx.add_window(|cx| {
+ let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
+ build_editor(buffer, cx)
+ });
+ view.update(cx, |view, cx| {
+ view.fold_ranges(
+ vec![
+ Point::new(0, 2)..Point::new(1, 2),
+ Point::new(2, 3)..Point::new(4, 1),
+ Point::new(7, 0)..Point::new(8, 4),
+ ],
+ true,
+ cx,
+ );
+ view.change_selections(None, cx, |s| {
+ s.select_display_ranges([
+ DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
+ DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
+ DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
+ DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
+ ])
+ });
+ assert_eq!(
+ view.display_text(cx),
+ "aa⋯bbb\nccc⋯eeee\nfffff\nggggg\n⋯i\njjjjj"
+ );
+
+ view.move_line_up(&MoveLineUp, cx);
+ assert_eq!(
+ view.display_text(cx),
+ "aa⋯bbb\nccc⋯eeee\nggggg\n⋯i\njjjjj\nfffff"
+ );
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ vec![
+ DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
+ DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
+ DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
+ DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
+ ]
+ );
+ });
-// // skip over the auto-closed brackets when typing a closing bracket
-// cx.update_editor(|view, cx| {
-// view.move_right(&MoveRight, cx);
-// view.handle_input("}", cx);
-// view.handle_input("}", cx);
-// view.handle_input("}", cx);
-// });
-// cx.assert_editor_state(
-// &"
-// 🏀{{{)}}}}ˇ
-// ε{{{)}}}}ˇ
-// ❤️{{{)}}}}ˇ
-// "
-// .unindent(),
-// );
+ view.update(cx, |view, cx| {
+ view.move_line_down(&MoveLineDown, cx);
+ assert_eq!(
+ view.display_text(cx),
+ "ccc⋯eeee\naa⋯bbb\nfffff\nggggg\n⋯i\njjjjj"
+ );
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ vec![
+ DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
+ DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
+ DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
+ DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
+ ]
+ );
+ });
-// // autoclose multi-character pairs
-// cx.set_state(
-// &"
-// ˇ
-// ˇ
-// "
-// .unindent(),
-// );
-// cx.update_editor(|view, cx| {
-// view.handle_input("/", cx);
-// view.handle_input("*", cx);
-// });
-// cx.assert_editor_state(
-// &"
-// /*ˇ */
-// /*ˇ */
-// "
-// .unindent(),
-// );
+ view.update(cx, |view, cx| {
+ view.move_line_down(&MoveLineDown, cx);
+ assert_eq!(
+ view.display_text(cx),
+ "ccc⋯eeee\nfffff\naa⋯bbb\nggggg\n⋯i\njjjjj"
+ );
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ vec![
+ DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
+ DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
+ DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
+ DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
+ ]
+ );
+ });
-// // one cursor autocloses a multi-character pair, one cursor
-// // does not autoclose.
-// cx.set_state(
-// &"
-// /ˇ
-// ˇ
-// "
-// .unindent(),
-// );
-// cx.update_editor(|view, cx| view.handle_input("*", cx));
-// cx.assert_editor_state(
-// &"
-// /*ˇ */
-// *ˇ
-// "
-// .unindent(),
-// );
+ view.update(cx, |view, cx| {
+ view.move_line_up(&MoveLineUp, cx);
+ assert_eq!(
+ view.display_text(cx),
+ "ccc⋯eeee\naa⋯bbb\nggggg\n⋯i\njjjjj\nfffff"
+ );
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ vec![
+ DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
+ DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
+ DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
+ DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
+ ]
+ );
+ });
+}
-// // Don't autoclose if the next character isn't whitespace and isn't
-// // listed in the language's "autoclose_before" section.
-// cx.set_state("ˇa b");
-// cx.update_editor(|view, cx| view.handle_input("{", cx));
-// cx.assert_editor_state("{ˇa b");
-
-// // Don't autoclose if `close` is false for the bracket pair
-// cx.set_state("ˇ");
-// cx.update_editor(|view, cx| view.handle_input("[", cx));
-// cx.assert_editor_state("[ˇ");
-
-// // Surround with brackets if text is selected
-// cx.set_state("«aˇ» b");
-// cx.update_editor(|view, cx| view.handle_input("{", cx));
-// cx.assert_editor_state("{«aˇ»} b");
-
-// // Autclose pair where the start and end characters are the same
-// cx.set_state("aˇ");
-// cx.update_editor(|view, cx| view.handle_input("\"", cx));
-// cx.assert_editor_state("a\"ˇ\"");
-// cx.update_editor(|view, cx| view.handle_input("\"", cx));
-// cx.assert_editor_state("a\"\"ˇ");
-// }
+#[gpui::test]
+fn test_move_line_up_down_with_blocks(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+
+ let editor = cx.add_window(|cx| {
+ let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
+ build_editor(buffer, cx)
+ });
+ editor.update(cx, |editor, cx| {
+ let snapshot = editor.buffer.read(cx).snapshot(cx);
+ editor.insert_blocks(
+ [BlockProperties {
+ style: BlockStyle::Fixed,
+ position: snapshot.anchor_after(Point::new(2, 0)),
+ disposition: BlockDisposition::Below,
+ height: 1,
+ render: Arc::new(|_| div().render()),
+ }],
+ Some(Autoscroll::fit()),
+ cx,
+ );
+ editor.change_selections(None, cx, |s| {
+ s.select_ranges([Point::new(2, 0)..Point::new(2, 0)])
+ });
+ editor.move_line_down(&MoveLineDown, cx);
+ });
+}
+//todo!(test_transpose)
// #[gpui::test]
-// async fn test_autoclose_with_embedded_language(cx: &mut gpui::TestAppContext) {
+// fn test_transpose(cx: &mut TestAppContext) {
// init_test(cx, |_| {});
-// let mut cx = EditorTestContext::new(cx).await;
+// _ = cx.add_window(|cx| {
+// let mut editor = build_editor(MultiBuffer::build_simple("abc", cx), cx);
-// let html_language = Arc::new(
-// Language::new(
-// LanguageConfig {
-// name: "HTML".into(),
-// brackets: BracketPairConfig {
-// pairs: vec![
-// BracketPair {
-// start: "<".into(),
-// end: ">".into(),
-// close: true,
-// ..Default::default()
-// },
-// BracketPair {
-// start: "{".into(),
-// end: "}".into(),
-// close: true,
-// ..Default::default()
-// },
-// BracketPair {
-// start: "(".into(),
-// end: ")".into(),
-// close: true,
-// ..Default::default()
-// },
-// ],
-// ..Default::default()
-// },
-// autoclose_before: "})]>".into(),
-// ..Default::default()
-// },
-// Some(tree_sitter_html::language()),
-// )
-// .with_injection_query(
-// r#"
-// (script_element
-// (raw_text) @content
-// (#set! "language" "javascript"))
-// "#,
-// )
-// .unwrap(),
-// );
+// editor.change_selections(None, cx, |s| s.select_ranges([1..1]));
+// editor.transpose(&Default::default(), cx);
+// assert_eq!(editor.text(cx), "bac");
+// assert_eq!(editor.selections.ranges(cx), [2..2]);
-// let javascript_language = Arc::new(Language::new(
-// LanguageConfig {
-// name: "JavaScript".into(),
-// brackets: BracketPairConfig {
-// pairs: vec![
-// BracketPair {
-// start: "/*".into(),
-// end: " */".into(),
-// close: true,
-// ..Default::default()
-// },
-// BracketPair {
-// start: "{".into(),
-// end: "}".into(),
-// close: true,
-// ..Default::default()
-// },
-// BracketPair {
-// start: "(".into(),
-// end: ")".into(),
-// close: true,
-// ..Default::default()
-// },
-// ],
-// ..Default::default()
-// },
-// autoclose_before: "})]>".into(),
-// ..Default::default()
-// },
-// Some(tree_sitter_typescript::language_tsx()),
-// ));
+// editor.transpose(&Default::default(), cx);
+// assert_eq!(editor.text(cx), "bca");
+// assert_eq!(editor.selections.ranges(cx), [3..3]);
-// let registry = Arc::new(LanguageRegistry::test());
-// registry.add(html_language.clone());
-// registry.add(javascript_language.clone());
+// editor.transpose(&Default::default(), cx);
+// assert_eq!(editor.text(cx), "bac");
+// assert_eq!(editor.selections.ranges(cx), [3..3]);
-// cx.update_buffer(|buffer, cx| {
-// buffer.set_language_registry(registry);
-// buffer.set_language(Some(html_language), cx);
+// editor
// });
-// cx.set_state(
-// &r#"
-// <body>ˇ
-// <script>
-// var x = 1;ˇ
-// </script>
-// </body>ˇ
-// "#
-// .unindent(),
-// );
+// _ = cx.add_window(|cx| {
+// let mut editor = build_editor(MultiBuffer::build_simple("abc\nde", cx), cx);
-// // Precondition: different languages are active at different locations.
-// cx.update_editor(|editor, cx| {
-// let snapshot = editor.snapshot(cx);
-// let cursors = editor.selections.ranges::<usize>(cx);
-// let languages = cursors
-// .iter()
-// .map(|c| snapshot.language_at(c.start).unwrap().name())
-// .collect::<Vec<_>>();
-// assert_eq!(
-// languages,
-// &["HTML".into(), "JavaScript".into(), "HTML".into()]
-// );
-// });
+// editor.change_selections(None, cx, |s| s.select_ranges([3..3]));
+// editor.transpose(&Default::default(), cx);
+// assert_eq!(editor.text(cx), "acb\nde");
+// assert_eq!(editor.selections.ranges(cx), [3..3]);
-// // Angle brackets autoclose in HTML, but not JavaScript.
-// cx.update_editor(|editor, cx| {
-// editor.handle_input("<", cx);
-// editor.handle_input("a", cx);
-// });
-// cx.assert_editor_state(
-// &r#"
-// <body><aˇ>
-// <script>
-// var x = 1;<aˇ
-// </script>
-// </body><aˇ>
-// "#
-// .unindent(),
-// );
+// editor.change_selections(None, cx, |s| s.select_ranges([4..4]));
+// editor.transpose(&Default::default(), cx);
+// assert_eq!(editor.text(cx), "acbd\ne");
+// assert_eq!(editor.selections.ranges(cx), [5..5]);
-// // Curly braces and parens autoclose in both HTML and JavaScript.
-// cx.update_editor(|editor, cx| {
-// editor.handle_input(" b=", cx);
-// editor.handle_input("{", cx);
-// editor.handle_input("c", cx);
-// editor.handle_input("(", cx);
-// });
-// cx.assert_editor_state(
-// &r#"
-// <body><a b={c(ˇ)}>
-// <script>
-// var x = 1;<a b={c(ˇ)}
-// </script>
-// </body><a b={c(ˇ)}>
-// "#
-// .unindent(),
-// );
+// editor.transpose(&Default::default(), cx);
+// assert_eq!(editor.text(cx), "acbde\n");
+// assert_eq!(editor.selections.ranges(cx), [6..6]);
-// // Brackets that were already autoclosed are skipped.
-// cx.update_editor(|editor, cx| {
-// editor.handle_input(")", cx);
-// editor.handle_input("d", cx);
-// editor.handle_input("}", cx);
-// });
-// cx.assert_editor_state(
-// &r#"
-// <body><a b={c()d}ˇ>
-// <script>
-// var x = 1;<a b={c()d}ˇ
-// </script>
-// </body><a b={c()d}ˇ>
-// "#
-// .unindent(),
-// );
-// cx.update_editor(|editor, cx| {
-// editor.handle_input(">", cx);
+// editor.transpose(&Default::default(), cx);
+// assert_eq!(editor.text(cx), "acbd\ne");
+// assert_eq!(editor.selections.ranges(cx), [6..6]);
+
+// editor
// });
-// cx.assert_editor_state(
-// &r#"
-// <body><a b={c()d}>ˇ
-// <script>
-// var x = 1;<a b={c()d}>ˇ
-// </script>
-// </body><a b={c()d}>ˇ
-// "#
-// .unindent(),
-// );
-// // Reset
-// cx.set_state(
-// &r#"
-// <body>ˇ
-// <script>
-// var x = 1;ˇ
-// </script>
-// </body>ˇ
-// "#
-// .unindent(),
-// );
+// _ = cx.add_window(|cx| {
+// let mut editor = build_editor(MultiBuffer::build_simple("abc\nde", cx), cx);
-// cx.update_editor(|editor, cx| {
-// editor.handle_input("<", cx);
-// });
-// cx.assert_editor_state(
-// &r#"
-// <body><ˇ>
-// <script>
-// var x = 1;<ˇ
-// </script>
-// </body><ˇ>
-// "#
-// .unindent(),
-// );
+// editor.change_selections(None, cx, |s| s.select_ranges([1..1, 2..2, 4..4]));
+// editor.transpose(&Default::default(), cx);
+// assert_eq!(editor.text(cx), "bacd\ne");
+// assert_eq!(editor.selections.ranges(cx), [2..2, 3..3, 5..5]);
-// // When backspacing, the closing angle brackets are removed.
-// cx.update_editor(|editor, cx| {
-// editor.backspace(&Backspace, cx);
+// editor.transpose(&Default::default(), cx);
+// assert_eq!(editor.text(cx), "bcade\n");
+// assert_eq!(editor.selections.ranges(cx), [3..3, 4..4, 6..6]);
+
+// editor.transpose(&Default::default(), cx);
+// assert_eq!(editor.text(cx), "bcda\ne");
+// assert_eq!(editor.selections.ranges(cx), [4..4, 6..6]);
+
+// editor.transpose(&Default::default(), cx);
+// assert_eq!(editor.text(cx), "bcade\n");
+// assert_eq!(editor.selections.ranges(cx), [4..4, 6..6]);
+
+// editor.transpose(&Default::default(), cx);
+// assert_eq!(editor.text(cx), "bcaed\n");
+// assert_eq!(editor.selections.ranges(cx), [5..5, 6..6]);
+
+// editor
// });
-// cx.assert_editor_state(
-// &r#"
-// <body>ˇ
-// <script>
-// var x = 1;ˇ
-// </script>
-// </body>ˇ
-// "#
-// .unindent(),
-// );
-// // Block comments autoclose in JavaScript, but not HTML.
-// cx.update_editor(|editor, cx| {
-// editor.handle_input("/", cx);
-// editor.handle_input("*", cx);
+// _ = cx.add_window(|cx| {
+// let mut editor = build_editor(MultiBuffer::build_simple("🍐🏀✋", cx), cx);
+
+// editor.change_selections(None, cx, |s| s.select_ranges([4..4]));
+// editor.transpose(&Default::default(), cx);
+// assert_eq!(editor.text(cx), "🏀🍐✋");
+// assert_eq!(editor.selections.ranges(cx), [8..8]);
+
+// editor.transpose(&Default::default(), cx);
+// assert_eq!(editor.text(cx), "🏀✋🍐");
+// assert_eq!(editor.selections.ranges(cx), [11..11]);
+
+// editor.transpose(&Default::default(), cx);
+// assert_eq!(editor.text(cx), "🏀🍐✋");
+// assert_eq!(editor.selections.ranges(cx), [11..11]);
+
+// editor
// });
-// cx.assert_editor_state(
-// &r#"
-// <body>/*ˇ
-// <script>
-// var x = 1;/*ˇ */
-// </script>
-// </body>/*ˇ
-// "#
-// .unindent(),
-// );
// }
+//todo!(clipboard)
// #[gpui::test]
-// async fn test_autoclose_with_overrides(cx: &mut gpui::TestAppContext) {
+// async fn test_clipboard(cx: &mut gpui::TestAppContext) {
// init_test(cx, |_| {});
// let mut cx = EditorTestContext::new(cx).await;
-// let rust_language = Arc::new(
-// Language::new(
-// LanguageConfig {
-// name: "Rust".into(),
-// brackets: serde_json::from_value(json!([
-// { "start": "{", "end": "}", "close": true, "newline": true },
-// { "start": "\"", "end": "\"", "close": true, "newline": false, "not_in": ["string"] },
-// ]))
-// .unwrap(),
-// autoclose_before: "})]>".into(),
-// ..Default::default()
-// },
-// Some(tree_sitter_rust::language()),
-// )
-// .with_override_query("(string_literal) @string")
-// .unwrap(),
-// );
-
-// let registry = Arc::new(LanguageRegistry::test());
-// registry.add(rust_language.clone());
-
-// cx.update_buffer(|buffer, cx| {
-// buffer.set_language_registry(registry);
-// buffer.set_language(Some(rust_language), cx);
-// });
+// cx.set_state("«one✅ ˇ»two «three ˇ»four «five ˇ»six ");
+// cx.update_editor(|e, cx| e.cut(&Cut, cx));
+// cx.assert_editor_state("ˇtwo ˇfour ˇsix ");
-// cx.set_state(
-// &r#"
-// let x = ˇ
-// "#
-// .unindent(),
-// );
+// // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
+// cx.set_state("two ˇfour ˇsix ˇ");
+// cx.update_editor(|e, cx| e.paste(&Paste, cx));
+// cx.assert_editor_state("two one✅ ˇfour three ˇsix five ˇ");
-// // Inserting a quotation mark. A closing quotation mark is automatically inserted.
-// cx.update_editor(|editor, cx| {
-// editor.handle_input("\"", cx);
+// // Paste again but with only two cursors. Since the number of cursors doesn't
+// // match the number of slices in the clipboard, the entire clipboard text
+// // is pasted at each cursor.
+// cx.set_state("ˇtwo one✅ four three six five ˇ");
+// cx.update_editor(|e, cx| {
+// e.handle_input("( ", cx);
+// e.paste(&Paste, cx);
+// e.handle_input(") ", cx);
// });
// cx.assert_editor_state(
-// &r#"
-// let x = "ˇ"
-// "#
-// .unindent(),
+// &([
+// "( one✅ ",
+// "three ",
+// "five ) ˇtwo one✅ four three six five ( one✅ ",
+// "three ",
+// "five ) ˇ",
+// ]
+// .join("\n")),
// );
-// // Inserting another quotation mark. The cursor moves across the existing
-// // automatically-inserted quotation mark.
-// cx.update_editor(|editor, cx| {
-// editor.handle_input("\"", cx);
-// });
-// cx.assert_editor_state(
-// &r#"
-// let x = ""ˇ
-// "#
-// .unindent(),
-// );
+// // Cut with three selections, one of which is full-line.
+// cx.set_state(indoc! {"
+// 1«2ˇ»3
+// 4ˇ567
+// «8ˇ»9"});
+// cx.update_editor(|e, cx| e.cut(&Cut, cx));
+// cx.assert_editor_state(indoc! {"
+// 1ˇ3
+// ˇ9"});
-// // Reset
-// cx.set_state(
-// &r#"
-// let x = ˇ
-// "#
-// .unindent(),
-// );
+// // Paste with three selections, noticing how the copied selection that was full-line
+// // gets inserted before the second cursor.
+// cx.set_state(indoc! {"
+// 1ˇ3
+// 9ˇ
+// «oˇ»ne"});
+// cx.update_editor(|e, cx| e.paste(&Paste, cx));
+// cx.assert_editor_state(indoc! {"
+// 12ˇ3
+// 4567
+// 9ˇ
+// 8ˇne"});
-// // Inserting a quotation mark inside of a string. A second quotation mark is not inserted.
-// cx.update_editor(|editor, cx| {
-// editor.handle_input("\"", cx);
-// editor.handle_input(" ", cx);
-// editor.move_left(&Default::default(), cx);
-// editor.handle_input("\\", cx);
-// editor.handle_input("\"", cx);
-// });
-// cx.assert_editor_state(
-// &r#"
-// let x = "\"ˇ "
-// "#
-// .unindent(),
-// );
+// // Copy with a single cursor only, which writes the whole line into the clipboard.
+// cx.set_state(indoc! {"
+// The quick brown
+// fox juˇmps over
+// the lazy dog"});
+// cx.update_editor(|e, cx| e.copy(&Copy, cx));
+// cx.cx.assert_clipboard_content(Some("fox jumps over\n"));
-// // Inserting a closing quotation mark at the position of an automatically-inserted quotation
-// // mark. Nothing is inserted.
-// cx.update_editor(|editor, cx| {
-// editor.move_right(&Default::default(), cx);
-// editor.handle_input("\"", cx);
-// });
-// cx.assert_editor_state(
-// &r#"
-// let x = "\" "ˇ
-// "#
-// .unindent(),
-// );
+// // Paste with three selections, noticing how the copied full-line selection is inserted
+// // before the empty selections but replaces the selection that is non-empty.
+// cx.set_state(indoc! {"
+// Tˇhe quick brown
+// «foˇ»x jumps over
+// tˇhe lazy dog"});
+// cx.update_editor(|e, cx| e.paste(&Paste, cx));
+// cx.assert_editor_state(indoc! {"
+// fox jumps over
+// Tˇhe quick brown
+// fox jumps over
+// ˇx jumps over
+// fox jumps over
+// tˇhe lazy dog"});
// }
// #[gpui::test]
-// async fn test_surround_with_pair(cx: &mut gpui::TestAppContext) {
+// async fn test_paste_multiline(cx: &mut gpui::TestAppContext) {
// init_test(cx, |_| {});
+// let mut cx = EditorTestContext::new(cx).await;
// let language = Arc::new(Language::new(
-// LanguageConfig {
-// brackets: BracketPairConfig {
-// pairs: vec![
-// BracketPair {
-// start: "{".to_string(),
-// end: "}".to_string(),
-// close: true,
-// newline: true,
-// },
-// BracketPair {
-// start: "/* ".to_string(),
-// end: "*/".to_string(),
-// close: true,
-// ..Default::default()
-// },
-// ],
-// ..Default::default()
-// },
-// ..Default::default()
-// },
+// LanguageConfig::default(),
// Some(tree_sitter_rust::language()),
// ));
+// cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
-// let text = r#"
-// a
-// b
-// c
-// "#
-// .unindent();
-
-// let buffer =
-// cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, text).with_language(language, cx));
-// let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
-// let view = cx.add_window(|cx| build_editor(buffer, cx)).root(cx);
-// view.condition(cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
-// .await;
-
-// view.update(cx, |view, cx| {
-// view.change_selections(None, cx, |s| {
-// s.select_display_ranges([
-// DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
-// DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
-// DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
-// ])
-// });
-
-// view.handle_input("{", cx);
-// view.handle_input("{", cx);
-// view.handle_input("{", cx);
-// assert_eq!(
-// view.text(cx),
-// "
-// {{{a}}}
-// {{{b}}}
-// {{{c}}}
-// "
-// .unindent()
+// // Cut an indented block, without the leading whitespace.
+// cx.set_state(indoc! {"
+// const a: B = (
+// c(),
+// «d(
+// e,
+// f
+// )ˇ»
// );
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// [
-// DisplayPoint::new(0, 3)..DisplayPoint::new(0, 4),
-// DisplayPoint::new(1, 3)..DisplayPoint::new(1, 4),
-// DisplayPoint::new(2, 3)..DisplayPoint::new(2, 4)
-// ]
+// "});
+// cx.update_editor(|e, cx| e.cut(&Cut, cx));
+// cx.assert_editor_state(indoc! {"
+// const a: B = (
+// c(),
+// ˇ
// );
+// "});
-// view.undo(&Undo, cx);
-// view.undo(&Undo, cx);
-// view.undo(&Undo, cx);
-// assert_eq!(
-// view.text(cx),
-// "
-// a
-// b
-// c
-// "
-// .unindent()
-// );
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// [
-// DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
-// DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
-// DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1)
-// ]
+// // Paste it at the same position.
+// cx.update_editor(|e, cx| e.paste(&Paste, cx));
+// cx.assert_editor_state(indoc! {"
+// const a: B = (
+// c(),
+// d(
+// e,
+// f
+// )ˇ
// );
+// "});
-// // Ensure inserting the first character of a multi-byte bracket pair
-// // doesn't surround the selections with the bracket.
-// view.handle_input("/", cx);
-// assert_eq!(
-// view.text(cx),
-// "
-// /
-// /
-// /
-// "
-// .unindent()
+// // Paste it at a line with a lower indent level.
+// cx.set_state(indoc! {"
+// ˇ
+// const a: B = (
+// c(),
// );
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// [
-// DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
-// DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
-// DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1)
-// ]
+// "});
+// cx.update_editor(|e, cx| e.paste(&Paste, cx));
+// cx.assert_editor_state(indoc! {"
+// d(
+// e,
+// f
+// )ˇ
+// const a: B = (
+// c(),
// );
+// "});
-// view.undo(&Undo, cx);
-// assert_eq!(
-// view.text(cx),
-// "
-// a
-// b
-// c
-// "
-// .unindent()
-// );
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// [
-// DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
-// DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
-// DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1)
-// ]
-// );
+// // Cut an indented block, with the leading whitespace.
+// cx.set_state(indoc! {"
+// const a: B = (
+// c(),
+// « d(
+// e,
+// f
+// )
+// ˇ»);
+// "});
+// cx.update_editor(|e, cx| e.cut(&Cut, cx));
+// cx.assert_editor_state(indoc! {"
+// const a: B = (
+// c(),
+// ˇ);
+// "});
-// // Ensure inserting the last character of a multi-byte bracket pair
-// // doesn't surround the selections with the bracket.
-// view.handle_input("*", cx);
-// assert_eq!(
-// view.text(cx),
-// "
-// *
-// *
-// *
-// "
-// .unindent()
+// // Paste it at the same position.
+// cx.update_editor(|e, cx| e.paste(&Paste, cx));
+// cx.assert_editor_state(indoc! {"
+// const a: B = (
+// c(),
+// d(
+// e,
+// f
+// )
+// ˇ);
+// "});
+
+// // Paste it at a line with a higher indent level.
+// cx.set_state(indoc! {"
+// const a: B = (
+// c(),
+// d(
+// e,
+// fˇ
+// )
// );
-// assert_eq!(
-// view.selections.display_ranges(cx),
-// [
-// DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
-// DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
-// DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1)
-// ]
+// "});
+// cx.update_editor(|e, cx| e.paste(&Paste, cx));
+// cx.assert_editor_state(indoc! {"
+// const a: B = (
+// c(),
+// d(
+// e,
+// f d(
+// e,
+// f
+// )
+// ˇ
+// )
// );
-// });
+// "});
// }
-// #[gpui::test]
-// async fn test_delete_autoclose_pair(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |_| {});
+#[gpui::test]
+fn test_select_all(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
-// let language = Arc::new(Language::new(
-// LanguageConfig {
-// brackets: BracketPairConfig {
-// pairs: vec![BracketPair {
-// start: "{".to_string(),
-// end: "}".to_string(),
-// close: true,
-// newline: true,
-// }],
-// ..Default::default()
-// },
-// autoclose_before: "}".to_string(),
-// ..Default::default()
-// },
-// Some(tree_sitter_rust::language()),
-// ));
+ let view = cx.add_window(|cx| {
+ let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
+ build_editor(buffer, cx)
+ });
+ view.update(cx, |view, cx| {
+ view.select_all(&SelectAll, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
+ );
+ });
+}
-// let text = r#"
-// a
-// b
-// c
-// "#
-// .unindent();
-
-// let buffer =
-// cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, text).with_language(language, cx));
-// let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
-// let editor = cx.add_window(|cx| build_editor(buffer, cx)).root(cx);
-// editor
-// .condition(cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
-// .await;
+#[gpui::test]
+fn test_select_line(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
-// editor.update(cx, |editor, cx| {
-// editor.change_selections(None, cx, |s| {
-// s.select_ranges([
-// Point::new(0, 1)..Point::new(0, 1),
-// Point::new(1, 1)..Point::new(1, 1),
-// Point::new(2, 1)..Point::new(2, 1),
-// ])
-// });
+ let view = cx.add_window(|cx| {
+ let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
+ build_editor(buffer, cx)
+ });
+ view.update(cx, |view, cx| {
+ view.change_selections(None, cx, |s| {
+ s.select_display_ranges([
+ DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
+ DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
+ DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
+ DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
+ ])
+ });
+ view.select_line(&SelectLine, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ vec![
+ DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
+ DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
+ ]
+ );
+ });
-// editor.handle_input("{", cx);
-// editor.handle_input("{", cx);
-// editor.handle_input("_", cx);
-// assert_eq!(
-// editor.text(cx),
-// "
-// a{{_}}
-// b{{_}}
-// c{{_}}
-// "
-// .unindent()
-// );
-// assert_eq!(
-// editor.selections.ranges::<Point>(cx),
-// [
-// Point::new(0, 4)..Point::new(0, 4),
-// Point::new(1, 4)..Point::new(1, 4),
-// Point::new(2, 4)..Point::new(2, 4)
-// ]
-// );
+ view.update(cx, |view, cx| {
+ view.select_line(&SelectLine, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ vec![
+ DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
+ DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
+ ]
+ );
+ });
-// editor.backspace(&Default::default(), cx);
-// editor.backspace(&Default::default(), cx);
-// assert_eq!(
-// editor.text(cx),
-// "
-// a{}
-// b{}
-// c{}
-// "
-// .unindent()
-// );
-// assert_eq!(
-// editor.selections.ranges::<Point>(cx),
-// [
-// Point::new(0, 2)..Point::new(0, 2),
-// Point::new(1, 2)..Point::new(1, 2),
-// Point::new(2, 2)..Point::new(2, 2)
-// ]
-// );
+ view.update(cx, |view, cx| {
+ view.select_line(&SelectLine, cx);
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
+ );
+ });
+}
-// editor.delete_to_previous_word_start(&Default::default(), cx);
-// assert_eq!(
-// editor.text(cx),
-// "
-// a
-// b
-// c
-// "
-// .unindent()
-// );
-// assert_eq!(
-// editor.selections.ranges::<Point>(cx),
-// [
-// Point::new(0, 1)..Point::new(0, 1),
-// Point::new(1, 1)..Point::new(1, 1),
-// Point::new(2, 1)..Point::new(2, 1)
-// ]
-// );
-// });
-// }
+#[gpui::test]
+fn test_split_selection_into_lines(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+
+ let view = cx.add_window(|cx| {
+ let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
+ build_editor(buffer, cx)
+ });
+ view.update(cx, |view, cx| {
+ view.fold_ranges(
+ vec![
+ Point::new(0, 2)..Point::new(1, 2),
+ Point::new(2, 3)..Point::new(4, 1),
+ Point::new(7, 0)..Point::new(8, 4),
+ ],
+ true,
+ cx,
+ );
+ view.change_selections(None, cx, |s| {
+ s.select_display_ranges([
+ DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
+ DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
+ DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
+ DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
+ ])
+ });
+ assert_eq!(view.display_text(cx), "aa⋯bbb\nccc⋯eeee\nfffff\nggggg\n⋯i");
+ });
+
+ view.update(cx, |view, cx| {
+ view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
+ assert_eq!(
+ view.display_text(cx),
+ "aaaaa\nbbbbb\nccc⋯eeee\nfffff\nggggg\n⋯i"
+ );
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ [
+ DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
+ DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
+ DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
+ DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
+ ]
+ );
+ });
+
+ view.update(cx, |view, cx| {
+ view.change_selections(None, cx, |s| {
+ s.select_display_ranges([DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)])
+ });
+ view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
+ assert_eq!(
+ view.display_text(cx),
+ "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
+ );
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ [
+ DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
+ DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
+ DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
+ DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
+ DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
+ DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
+ DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
+ DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
+ ]
+ );
+ });
+}
+
+#[gpui::test]
+async fn test_add_selection_above_below(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+
+ let mut cx = EditorTestContext::new(cx).await;
+
+ // let buffer = MultiBuffer::build_simple("abc\ndefghi\n\njk\nlmno\n", cx);
+ cx.set_state(indoc!(
+ r#"abc
+ defˇghi
+
+ jk
+ nlmo
+ "#
+ ));
+
+ cx.update_editor(|editor, cx| {
+ editor.add_selection_above(&Default::default(), cx);
+ });
-// #[gpui::test]
-// async fn test_snippets(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |_| {});
+ cx.assert_editor_state(indoc!(
+ r#"abcˇ
+ defˇghi
-// let (text, insertion_ranges) = marked_text_ranges(
-// indoc! {"
-// a.ˇ b
-// a.ˇ b
-// a.ˇ b
-// "},
-// false,
-// );
+ jk
+ nlmo
+ "#
+ ));
-// let buffer = cx.update(|cx| MultiBuffer::build_simple(&text, cx));
-// let editor = cx.add_window(|cx| build_editor(buffer, cx)).root(cx);
+ cx.update_editor(|editor, cx| {
+ editor.add_selection_above(&Default::default(), cx);
+ });
-// editor.update(cx, |editor, cx| {
-// let snippet = Snippet::parse("f(${1:one}, ${2:two}, ${1:three})$0").unwrap();
+ cx.assert_editor_state(indoc!(
+ r#"abcˇ
+ defˇghi
-// editor
-// .insert_snippet(&insertion_ranges, snippet, cx)
-// .unwrap();
+ jk
+ nlmo
+ "#
+ ));
-// fn assert(editor: &mut Editor, cx: &mut ViewContext<Editor>, marked_text: &str) {
-// let (expected_text, selection_ranges) = marked_text_ranges(marked_text, false);
-// assert_eq!(editor.text(cx), expected_text);
-// assert_eq!(editor.selections.ranges::<usize>(cx), selection_ranges);
-// }
+ cx.update_editor(|view, cx| {
+ view.add_selection_below(&Default::default(), cx);
+ });
-// assert(
-// editor,
-// cx,
-// indoc! {"
-// a.f(«one», two, «three») b
-// a.f(«one», two, «three») b
-// a.f(«one», two, «three») b
-// "},
-// );
+ cx.assert_editor_state(indoc!(
+ r#"abc
+ defˇghi
-// // Can't move earlier than the first tab stop
-// assert!(!editor.move_to_prev_snippet_tabstop(cx));
-// assert(
-// editor,
-// cx,
-// indoc! {"
-// a.f(«one», two, «three») b
-// a.f(«one», two, «three») b
-// a.f(«one», two, «three») b
-// "},
-// );
+ jk
+ nlmo
+ "#
+ ));
-// assert!(editor.move_to_next_snippet_tabstop(cx));
-// assert(
-// editor,
-// cx,
-// indoc! {"
-// a.f(one, «two», three) b
-// a.f(one, «two», three) b
-// a.f(one, «two», three) b
-// "},
-// );
+ cx.update_editor(|view, cx| {
+ view.undo_selection(&Default::default(), cx);
+ });
-// editor.move_to_prev_snippet_tabstop(cx);
-// assert(
-// editor,
-// cx,
-// indoc! {"
-// a.f(«one», two, «three») b
-// a.f(«one», two, «three») b
-// a.f(«one», two, «three») b
-// "},
-// );
+ cx.assert_editor_state(indoc!(
+ r#"abcˇ
+ defˇghi
-// assert!(editor.move_to_next_snippet_tabstop(cx));
-// assert(
-// editor,
-// cx,
-// indoc! {"
-// a.f(one, «two», three) b
-// a.f(one, «two», three) b
-// a.f(one, «two», three) b
-// "},
-// );
-// assert!(editor.move_to_next_snippet_tabstop(cx));
-// assert(
-// editor,
-// cx,
-// indoc! {"
-// a.f(one, two, three)ˇ b
-// a.f(one, two, three)ˇ b
-// a.f(one, two, three)ˇ b
-// "},
-// );
+ jk
+ nlmo
+ "#
+ ));
-// // As soon as the last tab stop is reached, snippet state is gone
-// editor.move_to_prev_snippet_tabstop(cx);
-// assert(
-// editor,
-// cx,
-// indoc! {"
-// a.f(one, two, three)ˇ b
-// a.f(one, two, three)ˇ b
-// a.f(one, two, three)ˇ b
-// "},
-// );
-// });
-// }
+ cx.update_editor(|view, cx| {
+ view.redo_selection(&Default::default(), cx);
+ });
-// #[gpui::test]
-// async fn test_document_format_during_save(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |_| {});
+ cx.assert_editor_state(indoc!(
+ r#"abc
+ defˇghi
-// let mut language = Language::new(
-// LanguageConfig {
-// name: "Rust".into(),
-// path_suffixes: vec!["rs".to_string()],
-// ..Default::default()
-// },
-// Some(tree_sitter_rust::language()),
-// );
-// let mut fake_servers = language
-// .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
-// capabilities: lsp::ServerCapabilities {
-// document_formatting_provider: Some(lsp::OneOf::Left(true)),
-// ..Default::default()
-// },
-// ..Default::default()
-// }))
-// .await;
+ jk
+ nlmo
+ "#
+ ));
-// let fs = FakeFs::new(cx.background());
-// fs.insert_file("/file.rs", Default::default()).await;
+ cx.update_editor(|view, cx| {
+ view.add_selection_below(&Default::default(), cx);
+ });
-// let project = Project::test(fs, ["/file.rs".as_ref()], cx).await;
-// project.update(cx, |project, _| project.languages().add(Arc::new(language)));
-// let buffer = project
-// .update(cx, |project, cx| project.open_local_buffer("/file.rs", cx))
-// .await
-// .unwrap();
+ cx.assert_editor_state(indoc!(
+ r#"abc
+ defˇghi
-// cx.foreground().start_waiting();
-// let fake_server = fake_servers.next().await.unwrap();
+ jk
+ nlmˇo
+ "#
+ ));
-// let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
-// let editor = cx.add_window(|cx| build_editor(buffer, cx)).root(cx);
-// editor.update(cx, |editor, cx| editor.set_text("one\ntwo\nthree\n", cx));
-// assert!(cx.read(|cx| editor.is_dirty(cx)));
+ cx.update_editor(|view, cx| {
+ view.add_selection_below(&Default::default(), cx);
+ });
-// let save = editor.update(cx, |editor, cx| editor.save(project.clone(), cx));
-// fake_server
-// .handle_request::<lsp::request::Formatting, _, _>(move |params, _| async move {
-// assert_eq!(
-// params.text_document.uri,
-// lsp::Url::from_file_path("/file.rs").unwrap()
-// );
-// assert_eq!(params.options.tab_size, 4);
-// Ok(Some(vec![lsp::TextEdit::new(
-// lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(1, 0)),
-// ", ".to_string(),
-// )]))
-// })
-// .next()
-// .await;
-// cx.foreground().start_waiting();
-// save.await.unwrap();
-// assert_eq!(
-// editor.read_with(cx, |editor, cx| editor.text(cx)),
-// "one, two\nthree\n"
-// );
-// assert!(!cx.read(|cx| editor.is_dirty(cx)));
+ cx.assert_editor_state(indoc!(
+ r#"abc
+ defˇghi
-// editor.update(cx, |editor, cx| editor.set_text("one\ntwo\nthree\n", cx));
-// assert!(cx.read(|cx| editor.is_dirty(cx)));
+ jk
+ nlmˇo
+ "#
+ ));
-// // Ensure we can still save even if formatting hangs.
-// fake_server.handle_request::<lsp::request::Formatting, _, _>(move |params, _| async move {
-// assert_eq!(
-// params.text_document.uri,
-// lsp::Url::from_file_path("/file.rs").unwrap()
-// );
-// futures::future::pending::<()>().await;
-// unreachable!()
-// });
-// let save = editor.update(cx, |editor, cx| editor.save(project.clone(), cx));
-// cx.foreground().advance_clock(super::FORMAT_TIMEOUT);
-// cx.foreground().start_waiting();
-// save.await.unwrap();
-// assert_eq!(
-// editor.read_with(cx, |editor, cx| editor.text(cx)),
-// "one\ntwo\nthree\n"
-// );
-// assert!(!cx.read(|cx| editor.is_dirty(cx)));
-
-// // Set rust language override and assert overridden tabsize is sent to language server
-// update_test_language_settings(cx, |settings| {
-// settings.languages.insert(
-// "Rust".into(),
-// LanguageSettingsContent {
-// tab_size: NonZeroU32::new(8),
-// ..Default::default()
-// },
-// );
-// });
+ // change selections
+ cx.set_state(indoc!(
+ r#"abc
+ def«ˇg»hi
-// let save = editor.update(cx, |editor, cx| editor.save(project.clone(), cx));
-// fake_server
-// .handle_request::<lsp::request::Formatting, _, _>(move |params, _| async move {
-// assert_eq!(
-// params.text_document.uri,
-// lsp::Url::from_file_path("/file.rs").unwrap()
-// );
-// assert_eq!(params.options.tab_size, 8);
-// Ok(Some(vec![]))
-// })
-// .next()
-// .await;
-// cx.foreground().start_waiting();
-// save.await.unwrap();
-// }
+ jk
+ nlmo
+ "#
+ ));
-// #[gpui::test]
-// async fn test_range_format_during_save(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |_| {});
+ cx.update_editor(|view, cx| {
+ view.add_selection_below(&Default::default(), cx);
+ });
-// let mut language = Language::new(
-// LanguageConfig {
-// name: "Rust".into(),
-// path_suffixes: vec!["rs".to_string()],
-// ..Default::default()
-// },
-// Some(tree_sitter_rust::language()),
-// );
-// let mut fake_servers = language
-// .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
-// capabilities: lsp::ServerCapabilities {
-// document_range_formatting_provider: Some(lsp::OneOf::Left(true)),
-// ..Default::default()
-// },
-// ..Default::default()
-// }))
-// .await;
+ cx.assert_editor_state(indoc!(
+ r#"abc
+ def«ˇg»hi
-// let fs = FakeFs::new(cx.background());
-// fs.insert_file("/file.rs", Default::default()).await;
+ jk
+ nlm«ˇo»
+ "#
+ ));
-// let project = Project::test(fs, ["/file.rs".as_ref()], cx).await;
-// project.update(cx, |project, _| project.languages().add(Arc::new(language)));
-// let buffer = project
-// .update(cx, |project, cx| project.open_local_buffer("/file.rs", cx))
-// .await
-// .unwrap();
+ cx.update_editor(|view, cx| {
+ view.add_selection_below(&Default::default(), cx);
+ });
-// cx.foreground().start_waiting();
-// let fake_server = fake_servers.next().await.unwrap();
+ cx.assert_editor_state(indoc!(
+ r#"abc
+ def«ˇg»hi
-// let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
-// let editor = cx.add_window(|cx| build_editor(buffer, cx)).root(cx);
-// editor.update(cx, |editor, cx| editor.set_text("one\ntwo\nthree\n", cx));
-// assert!(cx.read(|cx| editor.is_dirty(cx)));
+ jk
+ nlm«ˇo»
+ "#
+ ));
-// let save = editor.update(cx, |editor, cx| editor.save(project.clone(), cx));
-// fake_server
-// .handle_request::<lsp::request::RangeFormatting, _, _>(move |params, _| async move {
-// assert_eq!(
-// params.text_document.uri,
-// lsp::Url::from_file_path("/file.rs").unwrap()
-// );
-// assert_eq!(params.options.tab_size, 4);
-// Ok(Some(vec![lsp::TextEdit::new(
-// lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(1, 0)),
-// ", ".to_string(),
-// )]))
-// })
-// .next()
-// .await;
-// cx.foreground().start_waiting();
-// save.await.unwrap();
-// assert_eq!(
-// editor.read_with(cx, |editor, cx| editor.text(cx)),
-// "one, two\nthree\n"
-// );
-// assert!(!cx.read(|cx| editor.is_dirty(cx)));
+ cx.update_editor(|view, cx| {
+ view.add_selection_above(&Default::default(), cx);
+ });
-// editor.update(cx, |editor, cx| editor.set_text("one\ntwo\nthree\n", cx));
-// assert!(cx.read(|cx| editor.is_dirty(cx)));
+ cx.assert_editor_state(indoc!(
+ r#"abc
+ def«ˇg»hi
-// // Ensure we can still save even if formatting hangs.
-// fake_server.handle_request::<lsp::request::RangeFormatting, _, _>(
-// move |params, _| async move {
-// assert_eq!(
-// params.text_document.uri,
-// lsp::Url::from_file_path("/file.rs").unwrap()
-// );
-// futures::future::pending::<()>().await;
-// unreachable!()
-// },
-// );
-// let save = editor.update(cx, |editor, cx| editor.save(project.clone(), cx));
-// cx.foreground().advance_clock(super::FORMAT_TIMEOUT);
-// cx.foreground().start_waiting();
-// save.await.unwrap();
-// assert_eq!(
-// editor.read_with(cx, |editor, cx| editor.text(cx)),
-// "one\ntwo\nthree\n"
-// );
-// assert!(!cx.read(|cx| editor.is_dirty(cx)));
-
-// // Set rust language override and assert overridden tabsize is sent to language server
-// update_test_language_settings(cx, |settings| {
-// settings.languages.insert(
-// "Rust".into(),
-// LanguageSettingsContent {
-// tab_size: NonZeroU32::new(8),
-// ..Default::default()
-// },
-// );
-// });
+ jk
+ nlmo
+ "#
+ ));
-// let save = editor.update(cx, |editor, cx| editor.save(project.clone(), cx));
-// fake_server
-// .handle_request::<lsp::request::RangeFormatting, _, _>(move |params, _| async move {
-// assert_eq!(
-// params.text_document.uri,
-// lsp::Url::from_file_path("/file.rs").unwrap()
-// );
-// assert_eq!(params.options.tab_size, 8);
-// Ok(Some(vec![]))
-// })
-// .next()
-// .await;
-// cx.foreground().start_waiting();
-// save.await.unwrap();
-// }
+ cx.update_editor(|view, cx| {
+ view.add_selection_above(&Default::default(), cx);
+ });
-// #[gpui::test]
-// async fn test_document_format_manual_trigger(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |settings| {
-// settings.defaults.formatter = Some(language_settings::Formatter::LanguageServer)
-// });
+ cx.assert_editor_state(indoc!(
+ r#"abc
+ def«ˇg»hi
-// let mut language = Language::new(
-// LanguageConfig {
-// name: "Rust".into(),
-// path_suffixes: vec!["rs".to_string()],
-// // Enable Prettier formatting for the same buffer, and ensure
-// // LSP is called instead of Prettier.
-// prettier_parser_name: Some("test_parser".to_string()),
-// ..Default::default()
-// },
-// Some(tree_sitter_rust::language()),
-// );
-// let mut fake_servers = language
-// .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
-// capabilities: lsp::ServerCapabilities {
-// document_formatting_provider: Some(lsp::OneOf::Left(true)),
-// ..Default::default()
-// },
-// ..Default::default()
-// }))
-// .await;
+ jk
+ nlmo
+ "#
+ ));
-// let fs = FakeFs::new(cx.background());
-// fs.insert_file("/file.rs", Default::default()).await;
+ // Change selections again
+ cx.set_state(indoc!(
+ r#"a«bc
+ defgˇ»hi
-// let project = Project::test(fs, ["/file.rs".as_ref()], cx).await;
-// project.update(cx, |project, _| {
-// project.languages().add(Arc::new(language));
-// });
-// let buffer = project
-// .update(cx, |project, cx| project.open_local_buffer("/file.rs", cx))
-// .await
-// .unwrap();
+ jk
+ nlmo
+ "#
+ ));
-// cx.foreground().start_waiting();
-// let fake_server = fake_servers.next().await.unwrap();
+ cx.update_editor(|view, cx| {
+ view.add_selection_below(&Default::default(), cx);
+ });
-// let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
-// let editor = cx.add_window(|cx| build_editor(buffer, cx)).root(cx);
-// editor.update(cx, |editor, cx| editor.set_text("one\ntwo\nthree\n", cx));
+ cx.assert_editor_state(indoc!(
+ r#"a«bcˇ»
+ d«efgˇ»hi
-// let format = editor.update(cx, |editor, cx| {
-// editor.perform_format(project.clone(), FormatTrigger::Manual, cx)
-// });
-// fake_server
-// .handle_request::<lsp::request::Formatting, _, _>(move |params, _| async move {
-// assert_eq!(
-// params.text_document.uri,
-// lsp::Url::from_file_path("/file.rs").unwrap()
-// );
-// assert_eq!(params.options.tab_size, 4);
-// Ok(Some(vec![lsp::TextEdit::new(
-// lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(1, 0)),
-// ", ".to_string(),
-// )]))
-// })
-// .next()
-// .await;
-// cx.foreground().start_waiting();
-// format.await.unwrap();
-// assert_eq!(
-// editor.read_with(cx, |editor, cx| editor.text(cx)),
-// "one, two\nthree\n"
-// );
+ j«kˇ»
+ nlmo
+ "#
+ ));
-// editor.update(cx, |editor, cx| editor.set_text("one\ntwo\nthree\n", cx));
-// // Ensure we don't lock if formatting hangs.
-// fake_server.handle_request::<lsp::request::Formatting, _, _>(move |params, _| async move {
-// assert_eq!(
-// params.text_document.uri,
-// lsp::Url::from_file_path("/file.rs").unwrap()
-// );
-// futures::future::pending::<()>().await;
-// unreachable!()
-// });
-// let format = editor.update(cx, |editor, cx| {
-// editor.perform_format(project, FormatTrigger::Manual, cx)
-// });
-// cx.foreground().advance_clock(super::FORMAT_TIMEOUT);
-// cx.foreground().start_waiting();
-// format.await.unwrap();
-// assert_eq!(
-// editor.read_with(cx, |editor, cx| editor.text(cx)),
-// "one\ntwo\nthree\n"
-// );
-// }
+ cx.update_editor(|view, cx| {
+ view.add_selection_below(&Default::default(), cx);
+ });
+ cx.assert_editor_state(indoc!(
+ r#"a«bcˇ»
+ d«efgˇ»hi
+
+ j«kˇ»
+ n«lmoˇ»
+ "#
+ ));
+ cx.update_editor(|view, cx| {
+ view.add_selection_above(&Default::default(), cx);
+ });
-// #[gpui::test]
-// async fn test_concurrent_format_requests(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |_| {});
+ cx.assert_editor_state(indoc!(
+ r#"a«bcˇ»
+ d«efgˇ»hi
-// let mut cx = EditorLspTestContext::new_rust(
-// lsp::ServerCapabilities {
-// document_formatting_provider: Some(lsp::OneOf::Left(true)),
-// ..Default::default()
-// },
-// cx,
-// )
-// .await;
+ j«kˇ»
+ nlmo
+ "#
+ ));
-// cx.set_state(indoc! {"
-// one.twoˇ
-// "});
+ // Change selections again
+ cx.set_state(indoc!(
+ r#"abc
+ d«ˇefghi
-// // The format request takes a long time. When it completes, it inserts
-// // a newline and an indent before the `.`
-// cx.lsp
-// .handle_request::<lsp::request::Formatting, _, _>(move |_, cx| {
-// let executor = cx.background();
-// async move {
-// executor.timer(Duration::from_millis(100)).await;
-// Ok(Some(vec![lsp::TextEdit {
-// range: lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(0, 3)),
-// new_text: "\n ".into(),
-// }]))
-// }
-// });
+ jk
+ nlm»o
+ "#
+ ));
-// // Submit a format request.
-// let format_1 = cx
-// .update_editor(|editor, cx| editor.format(&Format, cx))
-// .unwrap();
-// cx.foreground().run_until_parked();
+ cx.update_editor(|view, cx| {
+ view.add_selection_above(&Default::default(), cx);
+ });
-// // Submit a second format request.
-// let format_2 = cx
-// .update_editor(|editor, cx| editor.format(&Format, cx))
-// .unwrap();
-// cx.foreground().run_until_parked();
+ cx.assert_editor_state(indoc!(
+ r#"a«ˇbc»
+ d«ˇef»ghi
-// // Wait for both format requests to complete
-// cx.foreground().advance_clock(Duration::from_millis(200));
-// cx.foreground().start_waiting();
-// format_1.await.unwrap();
-// cx.foreground().start_waiting();
-// format_2.await.unwrap();
+ j«ˇk»
+ n«ˇlm»o
+ "#
+ ));
-// // The formatting edits only happens once.
-// cx.assert_editor_state(indoc! {"
-// one
-// .twoˇ
-// "});
-// }
+ cx.update_editor(|view, cx| {
+ view.add_selection_below(&Default::default(), cx);
+ });
-// #[gpui::test]
-// async fn test_strip_whitespace_and_format_via_lsp(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |settings| {
-// settings.defaults.formatter = Some(language_settings::Formatter::Auto)
-// });
+ cx.assert_editor_state(indoc!(
+ r#"abc
+ d«ˇef»ghi
-// let mut cx = EditorLspTestContext::new_rust(
-// lsp::ServerCapabilities {
-// document_formatting_provider: Some(lsp::OneOf::Left(true)),
-// ..Default::default()
-// },
-// cx,
-// )
-// .await;
+ j«ˇk»
+ n«ˇlm»o
+ "#
+ ));
+}
-// // Set up a buffer white some trailing whitespace and no trailing newline.
-// cx.set_state(
-// &[
-// "one ", //
-// "twoˇ", //
-// "three ", //
-// "four", //
-// ]
-// .join("\n"),
-// );
+#[gpui::test]
+async fn test_select_next(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |_| {});
-// // Submit a format request.
-// let format = cx
-// .update_editor(|editor, cx| editor.format(&Format, cx))
-// .unwrap();
+ let mut cx = EditorTestContext::new(cx).await;
+ cx.set_state("abc\nˇabc abc\ndefabc\nabc");
-// // Record which buffer changes have been sent to the language server
-// let buffer_changes = Arc::new(Mutex::new(Vec::new()));
-// cx.lsp
-// .handle_notification::<lsp::notification::DidChangeTextDocument, _>({
-// let buffer_changes = buffer_changes.clone();
-// move |params, _| {
-// buffer_changes.lock().extend(
-// params
-// .content_changes
-// .into_iter()
-// .map(|e| (e.range.unwrap(), e.text)),
-// );
-// }
-// });
+ cx.update_editor(|e, cx| e.select_next(&SelectNext::default(), cx))
+ .unwrap();
+ cx.assert_editor_state("abc\n«abcˇ» abc\ndefabc\nabc");
-// // Handle formatting requests to the language server.
-// cx.lsp.handle_request::<lsp::request::Formatting, _, _>({
-// let buffer_changes = buffer_changes.clone();
-// move |_, _| {
-// // When formatting is requested, trailing whitespace has already been stripped,
-// // and the trailing newline has already been added.
-// assert_eq!(
-// &buffer_changes.lock()[1..],
-// &[
-// (
-// lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(0, 4)),
-// "".into()
-// ),
-// (
-// lsp::Range::new(lsp::Position::new(2, 5), lsp::Position::new(2, 6)),
-// "".into()
-// ),
-// (
-// lsp::Range::new(lsp::Position::new(3, 4), lsp::Position::new(3, 4)),
-// "\n".into()
-// ),
-// ]
-// );
+ cx.update_editor(|e, cx| e.select_next(&SelectNext::default(), cx))
+ .unwrap();
+ cx.assert_editor_state("abc\n«abcˇ» «abcˇ»\ndefabc\nabc");
-// // Insert blank lines between each line of the buffer.
-// async move {
-// Ok(Some(vec![
-// lsp::TextEdit {
-// range: lsp::Range::new(lsp::Position::new(1, 0), lsp::Position::new(1, 0)),
-// new_text: "\n".into(),
-// },
-// lsp::TextEdit {
-// range: lsp::Range::new(lsp::Position::new(2, 0), lsp::Position::new(2, 0)),
-// new_text: "\n".into(),
-// },
-// ]))
-// }
-// }
-// });
+ cx.update_editor(|view, cx| view.undo_selection(&UndoSelection, cx));
+ cx.assert_editor_state("abc\n«abcˇ» abc\ndefabc\nabc");
+
+ cx.update_editor(|view, cx| view.redo_selection(&RedoSelection, cx));
+ cx.assert_editor_state("abc\n«abcˇ» «abcˇ»\ndefabc\nabc");
+
+ cx.update_editor(|e, cx| e.select_next(&SelectNext::default(), cx))
+ .unwrap();
+ cx.assert_editor_state("abc\n«abcˇ» «abcˇ»\ndefabc\n«abcˇ»");
+
+ cx.update_editor(|e, cx| e.select_next(&SelectNext::default(), cx))
+ .unwrap();
+ cx.assert_editor_state("«abcˇ»\n«abcˇ» «abcˇ»\ndefabc\n«abcˇ»");
+}
+
+#[gpui::test]
+async fn test_select_previous(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |_| {});
+ {
+ // `Select previous` without a selection (selects wordwise)
+ let mut cx = EditorTestContext::new(cx).await;
+ cx.set_state("abc\nˇabc abc\ndefabc\nabc");
+
+ cx.update_editor(|e, cx| e.select_previous(&SelectPrevious::default(), cx))
+ .unwrap();
+ cx.assert_editor_state("abc\n«abcˇ» abc\ndefabc\nabc");
+
+ cx.update_editor(|e, cx| e.select_previous(&SelectPrevious::default(), cx))
+ .unwrap();
+ cx.assert_editor_state("«abcˇ»\n«abcˇ» abc\ndefabc\nabc");
+
+ cx.update_editor(|view, cx| view.undo_selection(&UndoSelection, cx));
+ cx.assert_editor_state("abc\n«abcˇ» abc\ndefabc\nabc");
+
+ cx.update_editor(|view, cx| view.redo_selection(&RedoSelection, cx));
+ cx.assert_editor_state("«abcˇ»\n«abcˇ» abc\ndefabc\nabc");
+
+ cx.update_editor(|e, cx| e.select_previous(&SelectPrevious::default(), cx))
+ .unwrap();
+ cx.assert_editor_state("«abcˇ»\n«abcˇ» abc\ndefabc\n«abcˇ»");
+
+ cx.update_editor(|e, cx| e.select_previous(&SelectPrevious::default(), cx))
+ .unwrap();
+ cx.assert_editor_state("«abcˇ»\n«abcˇ» «abcˇ»\ndefabc\n«abcˇ»");
+ }
+ {
+ // `Select previous` with a selection
+ let mut cx = EditorTestContext::new(cx).await;
+ cx.set_state("abc\n«ˇabc» abc\ndefabc\nabc");
+
+ cx.update_editor(|e, cx| e.select_previous(&SelectPrevious::default(), cx))
+ .unwrap();
+ cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndefabc\nabc");
+
+ cx.update_editor(|e, cx| e.select_previous(&SelectPrevious::default(), cx))
+ .unwrap();
+ cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndefabc\n«abcˇ»");
+
+ cx.update_editor(|view, cx| view.undo_selection(&UndoSelection, cx));
+ cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndefabc\nabc");
+
+ cx.update_editor(|view, cx| view.redo_selection(&RedoSelection, cx));
+ cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndefabc\n«abcˇ»");
+
+ cx.update_editor(|e, cx| e.select_previous(&SelectPrevious::default(), cx))
+ .unwrap();
+ cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndef«abcˇ»\n«abcˇ»");
+
+ cx.update_editor(|e, cx| e.select_previous(&SelectPrevious::default(), cx))
+ .unwrap();
+ cx.assert_editor_state("«abcˇ»\n«ˇabc» «abcˇ»\ndef«abcˇ»\n«abcˇ»");
+ }
+}
-// // After formatting the buffer, the trailing whitespace is stripped,
-// // a newline is appended, and the edits provided by the language server
-// // have been applied.
-// format.await.unwrap();
-// cx.assert_editor_state(
-// &[
-// "one", //
-// "", //
-// "twoˇ", //
-// "", //
-// "three", //
-// "four", //
-// "", //
-// ]
-// .join("\n"),
-// );
+#[gpui::test]
+async fn test_select_larger_smaller_syntax_node(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |_| {});
-// // Undoing the formatting undoes the trailing whitespace removal, the
-// // trailing newline, and the LSP edits.
-// cx.update_buffer(|buffer, cx| buffer.undo(cx));
-// cx.assert_editor_state(
-// &[
-// "one ", //
-// "twoˇ", //
-// "three ", //
-// "four", //
-// ]
-// .join("\n"),
-// );
-// }
+ let language = Arc::new(Language::new(
+ LanguageConfig::default(),
+ Some(tree_sitter_rust::language()),
+ ));
-// #[gpui::test]
-// async fn test_completion(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |_| {});
+ let text = r#"
+ use mod1::mod2::{mod3, mod4};
-// let mut cx = EditorLspTestContext::new_rust(
-// lsp::ServerCapabilities {
-// completion_provider: Some(lsp::CompletionOptions {
-// trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
-// resolve_provider: Some(true),
-// ..Default::default()
-// }),
-// ..Default::default()
-// },
-// cx,
-// )
-// .await;
+ fn fn_1(param1: bool, param2: &str) {
+ let var1 = "text";
+ }
+ "#
+ .unindent();
-// cx.set_state(indoc! {"
-// oneˇ
-// two
-// three
-// "});
-// cx.simulate_keystroke(".");
-// handle_completion_request(
-// &mut cx,
-// indoc! {"
-// one.|<>
-// two
-// three
-// "},
-// vec!["first_completion", "second_completion"],
-// )
-// .await;
-// cx.condition(|editor, _| editor.context_menu_visible())
-// .await;
-// let apply_additional_edits = cx.update_editor(|editor, cx| {
-// editor.context_menu_next(&Default::default(), cx);
-// editor
-// .confirm_completion(&ConfirmCompletion::default(), cx)
-// .unwrap()
-// });
-// cx.assert_editor_state(indoc! {"
-// one.second_completionˇ
-// two
-// three
-// "});
+ let buffer = cx.build_model(|cx| {
+ Buffer::new(0, cx.entity_id().as_u64(), text).with_language(language, cx)
+ });
+ let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
+ let (view, mut cx) = cx.add_window_view(|cx| build_editor(buffer, cx));
+
+ view.condition::<crate::Event>(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
+ .await;
+
+ view.update(&mut cx, |view, cx| {
+ view.change_selections(None, cx, |s| {
+ s.select_display_ranges([
+ DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
+ DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
+ DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
+ ]);
+ });
+ view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
+ });
+ assert_eq!(
+ view.update(&mut cx, |view, cx| { view.selections.display_ranges(cx) }),
+ &[
+ DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
+ DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
+ DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
+ ]
+ );
+
+ view.update(&mut cx, |view, cx| {
+ view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
+ });
+ assert_eq!(
+ view.update(&mut cx, |view, cx| view.selections.display_ranges(cx)),
+ &[
+ DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
+ DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
+ ]
+ );
+
+ view.update(&mut cx, |view, cx| {
+ view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
+ });
+ assert_eq!(
+ view.update(&mut cx, |view, cx| view.selections.display_ranges(cx)),
+ &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
+ );
+
+ // Trying to expand the selected syntax node one more time has no effect.
+ view.update(&mut cx, |view, cx| {
+ view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
+ });
+ assert_eq!(
+ view.update(&mut cx, |view, cx| view.selections.display_ranges(cx)),
+ &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
+ );
-// handle_resolve_completion_request(
-// &mut cx,
-// Some(vec![
-// (
-// //This overlaps with the primary completion edit which is
-// //misbehavior from the LSP spec, test that we filter it out
-// indoc! {"
-// one.second_ˇcompletion
-// two
-// threeˇ
-// "},
-// "overlapping additional edit",
-// ),
-// (
-// indoc! {"
-// one.second_completion
-// two
-// threeˇ
-// "},
-// "\nadditional edit",
-// ),
-// ]),
-// )
-// .await;
-// apply_additional_edits.await.unwrap();
-// cx.assert_editor_state(indoc! {"
-// one.second_completionˇ
-// two
-// three
-// additional edit
-// "});
+ view.update(&mut cx, |view, cx| {
+ view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
+ });
+ assert_eq!(
+ view.update(&mut cx, |view, cx| view.selections.display_ranges(cx)),
+ &[
+ DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
+ DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
+ ]
+ );
+
+ view.update(&mut cx, |view, cx| {
+ view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
+ });
+ assert_eq!(
+ view.update(&mut cx, |view, cx| view.selections.display_ranges(cx)),
+ &[
+ DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
+ DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
+ DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
+ ]
+ );
+
+ view.update(&mut cx, |view, cx| {
+ view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
+ });
+ assert_eq!(
+ view.update(&mut cx, |view, cx| view.selections.display_ranges(cx)),
+ &[
+ DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
+ DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
+ DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
+ ]
+ );
+
+ // Trying to shrink the selected syntax node one more time has no effect.
+ view.update(&mut cx, |view, cx| {
+ view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
+ });
+ assert_eq!(
+ view.update(&mut cx, |view, cx| view.selections.display_ranges(cx)),
+ &[
+ DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
+ DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
+ DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
+ ]
+ );
+
+ // Ensure that we keep expanding the selection if the larger selection starts or ends within
+ // a fold.
+ view.update(&mut cx, |view, cx| {
+ view.fold_ranges(
+ vec![
+ Point::new(0, 21)..Point::new(0, 24),
+ Point::new(3, 20)..Point::new(3, 22),
+ ],
+ true,
+ cx,
+ );
+ view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
+ });
+ assert_eq!(
+ view.update(&mut cx, |view, cx| view.selections.display_ranges(cx)),
+ &[
+ DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
+ DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
+ DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
+ ]
+ );
+}
-// cx.set_state(indoc! {"
-// one.second_completion
-// twoˇ
-// threeˇ
-// additional edit
-// "});
-// cx.simulate_keystroke(" ");
-// assert!(cx.editor(|e, _| e.context_menu.read().is_none()));
-// cx.simulate_keystroke("s");
-// assert!(cx.editor(|e, _| e.context_menu.read().is_none()));
+#[gpui::test]
+async fn test_autoindent_selections(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |_| {});
+
+ let language = Arc::new(
+ Language::new(
+ LanguageConfig {
+ brackets: BracketPairConfig {
+ pairs: vec![
+ BracketPair {
+ start: "{".to_string(),
+ end: "}".to_string(),
+ close: false,
+ newline: true,
+ },
+ BracketPair {
+ start: "(".to_string(),
+ end: ")".to_string(),
+ close: false,
+ newline: true,
+ },
+ ],
+ ..Default::default()
+ },
+ ..Default::default()
+ },
+ Some(tree_sitter_rust::language()),
+ )
+ .with_indents_query(
+ r#"
+ (_ "(" ")" @end) @indent
+ (_ "{" "}" @end) @indent
+ "#,
+ )
+ .unwrap(),
+ );
+
+ let text = "fn a() {}";
+
+ let buffer = cx.build_model(|cx| {
+ Buffer::new(0, cx.entity_id().as_u64(), text).with_language(language, cx)
+ });
+ let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
+ let (editor, mut cx) = cx.add_window_view(|cx| build_editor(buffer, cx));
+ let cx = &mut cx;
+ editor
+ .condition::<crate::Event>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
+ .await;
+
+ editor.update(cx, |editor, cx| {
+ editor.change_selections(None, cx, |s| s.select_ranges([5..5, 8..8, 9..9]));
+ editor.newline(&Newline, cx);
+ assert_eq!(editor.text(cx), "fn a(\n \n) {\n \n}\n");
+ assert_eq!(
+ editor.selections.ranges(cx),
+ &[
+ Point::new(1, 4)..Point::new(1, 4),
+ Point::new(3, 4)..Point::new(3, 4),
+ Point::new(5, 0)..Point::new(5, 0)
+ ]
+ );
+ });
+}
-// cx.assert_editor_state(indoc! {"
-// one.second_completion
-// two sˇ
-// three sˇ
-// additional edit
-// "});
-// handle_completion_request(
-// &mut cx,
-// indoc! {"
-// one.second_completion
-// two s
-// three <s|>
-// additional edit
-// "},
-// vec!["fourth_completion", "fifth_completion", "sixth_completion"],
-// )
-// .await;
-// cx.condition(|editor, _| editor.context_menu_visible())
-// .await;
+#[gpui::test]
+async fn test_autoclose_pairs(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |_| {});
+
+ let mut cx = EditorTestContext::new(cx).await;
+
+ let language = Arc::new(Language::new(
+ LanguageConfig {
+ brackets: BracketPairConfig {
+ pairs: vec![
+ BracketPair {
+ start: "{".to_string(),
+ end: "}".to_string(),
+ close: true,
+ newline: true,
+ },
+ BracketPair {
+ start: "(".to_string(),
+ end: ")".to_string(),
+ close: true,
+ newline: true,
+ },
+ BracketPair {
+ start: "/*".to_string(),
+ end: " */".to_string(),
+ close: true,
+ newline: true,
+ },
+ BracketPair {
+ start: "[".to_string(),
+ end: "]".to_string(),
+ close: false,
+ newline: true,
+ },
+ BracketPair {
+ start: "\"".to_string(),
+ end: "\"".to_string(),
+ close: true,
+ newline: false,
+ },
+ ],
+ ..Default::default()
+ },
+ autoclose_before: "})]".to_string(),
+ ..Default::default()
+ },
+ Some(tree_sitter_rust::language()),
+ ));
+
+ let registry = Arc::new(LanguageRegistry::test());
+ registry.add(language.clone());
+ cx.update_buffer(|buffer, cx| {
+ buffer.set_language_registry(registry);
+ buffer.set_language(Some(language), cx);
+ });
-// cx.simulate_keystroke("i");
+ cx.set_state(
+ &r#"
+ 🏀ˇ
+ εˇ
+ ❤️ˇ
+ "#
+ .unindent(),
+ );
+
+ // autoclose multiple nested brackets at multiple cursors
+ cx.update_editor(|view, cx| {
+ view.handle_input("{", cx);
+ view.handle_input("{", cx);
+ view.handle_input("{", cx);
+ });
+ cx.assert_editor_state(
+ &"
+ 🏀{{{ˇ}}}
+ ε{{{ˇ}}}
+ ❤️{{{ˇ}}}
+ "
+ .unindent(),
+ );
+
+ // insert a different closing bracket
+ cx.update_editor(|view, cx| {
+ view.handle_input(")", cx);
+ });
+ cx.assert_editor_state(
+ &"
+ 🏀{{{)ˇ}}}
+ ε{{{)ˇ}}}
+ ❤️{{{)ˇ}}}
+ "
+ .unindent(),
+ );
+
+ // skip over the auto-closed brackets when typing a closing bracket
+ cx.update_editor(|view, cx| {
+ view.move_right(&MoveRight, cx);
+ view.handle_input("}", cx);
+ view.handle_input("}", cx);
+ view.handle_input("}", cx);
+ });
+ cx.assert_editor_state(
+ &"
+ 🏀{{{)}}}}ˇ
+ ε{{{)}}}}ˇ
+ ❤️{{{)}}}}ˇ
+ "
+ .unindent(),
+ );
+
+ // autoclose multi-character pairs
+ cx.set_state(
+ &"
+ ˇ
+ ˇ
+ "
+ .unindent(),
+ );
+ cx.update_editor(|view, cx| {
+ view.handle_input("/", cx);
+ view.handle_input("*", cx);
+ });
+ cx.assert_editor_state(
+ &"
+ /*ˇ */
+ /*ˇ */
+ "
+ .unindent(),
+ );
+
+ // one cursor autocloses a multi-character pair, one cursor
+ // does not autoclose.
+ cx.set_state(
+ &"
+ /ˇ
+ ˇ
+ "
+ .unindent(),
+ );
+ cx.update_editor(|view, cx| view.handle_input("*", cx));
+ cx.assert_editor_state(
+ &"
+ /*ˇ */
+ *ˇ
+ "
+ .unindent(),
+ );
+
+ // Don't autoclose if the next character isn't whitespace and isn't
+ // listed in the language's "autoclose_before" section.
+ cx.set_state("ˇa b");
+ cx.update_editor(|view, cx| view.handle_input("{", cx));
+ cx.assert_editor_state("{ˇa b");
+
+ // Don't autoclose if `close` is false for the bracket pair
+ cx.set_state("ˇ");
+ cx.update_editor(|view, cx| view.handle_input("[", cx));
+ cx.assert_editor_state("[ˇ");
+
+ // Surround with brackets if text is selected
+ cx.set_state("«aˇ» b");
+ cx.update_editor(|view, cx| view.handle_input("{", cx));
+ cx.assert_editor_state("{«aˇ»} b");
+
+ // Autclose pair where the start and end characters are the same
+ cx.set_state("aˇ");
+ cx.update_editor(|view, cx| view.handle_input("\"", cx));
+ cx.assert_editor_state("a\"ˇ\"");
+ cx.update_editor(|view, cx| view.handle_input("\"", cx));
+ cx.assert_editor_state("a\"\"ˇ");
+}
-// handle_completion_request(
-// &mut cx,
-// indoc! {"
-// one.second_completion
-// two si
-// three <si|>
-// additional edit
-// "},
-// vec!["fourth_completion", "fifth_completion", "sixth_completion"],
-// )
-// .await;
-// cx.condition(|editor, _| editor.context_menu_visible())
-// .await;
+#[gpui::test]
+async fn test_autoclose_with_embedded_language(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |_| {});
+
+ let mut cx = EditorTestContext::new(cx).await;
+
+ let html_language = Arc::new(
+ Language::new(
+ LanguageConfig {
+ name: "HTML".into(),
+ brackets: BracketPairConfig {
+ pairs: vec![
+ BracketPair {
+ start: "<".into(),
+ end: ">".into(),
+ close: true,
+ ..Default::default()
+ },
+ BracketPair {
+ start: "{".into(),
+ end: "}".into(),
+ close: true,
+ ..Default::default()
+ },
+ BracketPair {
+ start: "(".into(),
+ end: ")".into(),
+ close: true,
+ ..Default::default()
+ },
+ ],
+ ..Default::default()
+ },
+ autoclose_before: "})]>".into(),
+ ..Default::default()
+ },
+ Some(tree_sitter_html::language()),
+ )
+ .with_injection_query(
+ r#"
+ (script_element
+ (raw_text) @content
+ (#set! "language" "javascript"))
+ "#,
+ )
+ .unwrap(),
+ );
+
+ let javascript_language = Arc::new(Language::new(
+ LanguageConfig {
+ name: "JavaScript".into(),
+ brackets: BracketPairConfig {
+ pairs: vec![
+ BracketPair {
+ start: "/*".into(),
+ end: " */".into(),
+ close: true,
+ ..Default::default()
+ },
+ BracketPair {
+ start: "{".into(),
+ end: "}".into(),
+ close: true,
+ ..Default::default()
+ },
+ BracketPair {
+ start: "(".into(),
+ end: ")".into(),
+ close: true,
+ ..Default::default()
+ },
+ ],
+ ..Default::default()
+ },
+ autoclose_before: "})]>".into(),
+ ..Default::default()
+ },
+ Some(tree_sitter_typescript::language_tsx()),
+ ));
+
+ let registry = Arc::new(LanguageRegistry::test());
+ registry.add(html_language.clone());
+ registry.add(javascript_language.clone());
+
+ cx.update_buffer(|buffer, cx| {
+ buffer.set_language_registry(registry);
+ buffer.set_language(Some(html_language), cx);
+ });
-// let apply_additional_edits = cx.update_editor(|editor, cx| {
-// editor
-// .confirm_completion(&ConfirmCompletion::default(), cx)
-// .unwrap()
-// });
-// cx.assert_editor_state(indoc! {"
-// one.second_completion
-// two sixth_completionˇ
-// three sixth_completionˇ
-// additional edit
-// "});
+ cx.set_state(
+ &r#"
+ <body>ˇ
+ <script>
+ var x = 1;ˇ
+ </script>
+ </body>ˇ
+ "#
+ .unindent(),
+ );
+
+ // Precondition: different languages are active at different locations.
+ cx.update_editor(|editor, cx| {
+ let snapshot = editor.snapshot(cx);
+ let cursors = editor.selections.ranges::<usize>(cx);
+ let languages = cursors
+ .iter()
+ .map(|c| snapshot.language_at(c.start).unwrap().name())
+ .collect::<Vec<_>>();
+ assert_eq!(
+ languages,
+ &["HTML".into(), "JavaScript".into(), "HTML".into()]
+ );
+ });
-// handle_resolve_completion_request(&mut cx, None).await;
-// apply_additional_edits.await.unwrap();
+ // Angle brackets autoclose in HTML, but not JavaScript.
+ cx.update_editor(|editor, cx| {
+ editor.handle_input("<", cx);
+ editor.handle_input("a", cx);
+ });
+ cx.assert_editor_state(
+ &r#"
+ <body><aˇ>
+ <script>
+ var x = 1;<aˇ
+ </script>
+ </body><aˇ>
+ "#
+ .unindent(),
+ );
+
+ // Curly braces and parens autoclose in both HTML and JavaScript.
+ cx.update_editor(|editor, cx| {
+ editor.handle_input(" b=", cx);
+ editor.handle_input("{", cx);
+ editor.handle_input("c", cx);
+ editor.handle_input("(", cx);
+ });
+ cx.assert_editor_state(
+ &r#"
+ <body><a b={c(ˇ)}>
+ <script>
+ var x = 1;<a b={c(ˇ)}
+ </script>
+ </body><a b={c(ˇ)}>
+ "#
+ .unindent(),
+ );
+
+ // Brackets that were already autoclosed are skipped.
+ cx.update_editor(|editor, cx| {
+ editor.handle_input(")", cx);
+ editor.handle_input("d", cx);
+ editor.handle_input("}", cx);
+ });
+ cx.assert_editor_state(
+ &r#"
+ <body><a b={c()d}ˇ>
+ <script>
+ var x = 1;<a b={c()d}ˇ
+ </script>
+ </body><a b={c()d}ˇ>
+ "#
+ .unindent(),
+ );
+ cx.update_editor(|editor, cx| {
+ editor.handle_input(">", cx);
+ });
+ cx.assert_editor_state(
+ &r#"
+ <body><a b={c()d}>ˇ
+ <script>
+ var x = 1;<a b={c()d}>ˇ
+ </script>
+ </body><a b={c()d}>ˇ
+ "#
+ .unindent(),
+ );
+
+ // Reset
+ cx.set_state(
+ &r#"
+ <body>ˇ
+ <script>
+ var x = 1;ˇ
+ </script>
+ </body>ˇ
+ "#
+ .unindent(),
+ );
+
+ cx.update_editor(|editor, cx| {
+ editor.handle_input("<", cx);
+ });
+ cx.assert_editor_state(
+ &r#"
+ <body><ˇ>
+ <script>
+ var x = 1;<ˇ
+ </script>
+ </body><ˇ>
+ "#
+ .unindent(),
+ );
+
+ // When backspacing, the closing angle brackets are removed.
+ cx.update_editor(|editor, cx| {
+ editor.backspace(&Backspace, cx);
+ });
+ cx.assert_editor_state(
+ &r#"
+ <body>ˇ
+ <script>
+ var x = 1;ˇ
+ </script>
+ </body>ˇ
+ "#
+ .unindent(),
+ );
+
+ // Block comments autoclose in JavaScript, but not HTML.
+ cx.update_editor(|editor, cx| {
+ editor.handle_input("/", cx);
+ editor.handle_input("*", cx);
+ });
+ cx.assert_editor_state(
+ &r#"
+ <body>/*ˇ
+ <script>
+ var x = 1;/*ˇ */
+ </script>
+ </body>/*ˇ
+ "#
+ .unindent(),
+ );
+}
-// cx.update(|cx| {
-// cx.update_global::<SettingsStore, _, _>(|settings, cx| {
-// settings.update_user_settings::<EditorSettings>(cx, |settings| {
-// settings.show_completions_on_input = Some(false);
-// });
-// })
-// });
-// cx.set_state("editorˇ");
-// cx.simulate_keystroke(".");
-// assert!(cx.editor(|e, _| e.context_menu.read().is_none()));
-// cx.simulate_keystroke("c");
-// cx.simulate_keystroke("l");
-// cx.simulate_keystroke("o");
-// cx.assert_editor_state("editor.cloˇ");
-// assert!(cx.editor(|e, _| e.context_menu.read().is_none()));
-// cx.update_editor(|editor, cx| {
-// editor.show_completions(&ShowCompletions, cx);
-// });
-// handle_completion_request(&mut cx, "editor.<clo|>", vec!["close", "clobber"]).await;
-// cx.condition(|editor, _| editor.context_menu_visible())
-// .await;
-// let apply_additional_edits = cx.update_editor(|editor, cx| {
-// editor
-// .confirm_completion(&ConfirmCompletion::default(), cx)
-// .unwrap()
-// });
-// cx.assert_editor_state("editor.closeˇ");
-// handle_resolve_completion_request(&mut cx, None).await;
-// apply_additional_edits.await.unwrap();
-// }
+#[gpui::test]
+async fn test_autoclose_with_overrides(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |_| {});
+
+ let mut cx = EditorTestContext::new(cx).await;
+
+ let rust_language = Arc::new(
+ Language::new(
+ LanguageConfig {
+ name: "Rust".into(),
+ brackets: serde_json::from_value(json!([
+ { "start": "{", "end": "}", "close": true, "newline": true },
+ { "start": "\"", "end": "\"", "close": true, "newline": false, "not_in": ["string"] },
+ ]))
+ .unwrap(),
+ autoclose_before: "})]>".into(),
+ ..Default::default()
+ },
+ Some(tree_sitter_rust::language()),
+ )
+ .with_override_query("(string_literal) @string")
+ .unwrap(),
+ );
+
+ let registry = Arc::new(LanguageRegistry::test());
+ registry.add(rust_language.clone());
+
+ cx.update_buffer(|buffer, cx| {
+ buffer.set_language_registry(registry);
+ buffer.set_language(Some(rust_language), cx);
+ });
-// #[gpui::test]
-// async fn test_toggle_comment(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |_| {});
-// let mut cx = EditorTestContext::new(cx).await;
-// let language = Arc::new(Language::new(
-// LanguageConfig {
-// line_comment: Some("// ".into()),
-// ..Default::default()
-// },
-// Some(tree_sitter_rust::language()),
-// ));
-// cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
+ cx.set_state(
+ &r#"
+ let x = ˇ
+ "#
+ .unindent(),
+ );
-// // If multiple selections intersect a line, the line is only toggled once.
-// cx.set_state(indoc! {"
-// fn a() {
-// «//b();
-// ˇ»// «c();
-// //ˇ» d();
-// }
-// "});
+ // Inserting a quotation mark. A closing quotation mark is automatically inserted.
+ cx.update_editor(|editor, cx| {
+ editor.handle_input("\"", cx);
+ });
+ cx.assert_editor_state(
+ &r#"
+ let x = "ˇ"
+ "#
+ .unindent(),
+ );
+
+ // Inserting another quotation mark. The cursor moves across the existing
+ // automatically-inserted quotation mark.
+ cx.update_editor(|editor, cx| {
+ editor.handle_input("\"", cx);
+ });
+ cx.assert_editor_state(
+ &r#"
+ let x = ""ˇ
+ "#
+ .unindent(),
+ );
+
+ // Reset
+ cx.set_state(
+ &r#"
+ let x = ˇ
+ "#
+ .unindent(),
+ );
+
+ // Inserting a quotation mark inside of a string. A second quotation mark is not inserted.
+ cx.update_editor(|editor, cx| {
+ editor.handle_input("\"", cx);
+ editor.handle_input(" ", cx);
+ editor.move_left(&Default::default(), cx);
+ editor.handle_input("\\", cx);
+ editor.handle_input("\"", cx);
+ });
+ cx.assert_editor_state(
+ &r#"
+ let x = "\"ˇ "
+ "#
+ .unindent(),
+ );
+
+ // Inserting a closing quotation mark at the position of an automatically-inserted quotation
+ // mark. Nothing is inserted.
+ cx.update_editor(|editor, cx| {
+ editor.move_right(&Default::default(), cx);
+ editor.handle_input("\"", cx);
+ });
+ cx.assert_editor_state(
+ &r#"
+ let x = "\" "ˇ
+ "#
+ .unindent(),
+ );
+}
-// cx.update_editor(|e, cx| e.toggle_comments(&ToggleComments::default(), cx));
+#[gpui::test]
+async fn test_surround_with_pair(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |_| {});
+
+ let language = Arc::new(Language::new(
+ LanguageConfig {
+ brackets: BracketPairConfig {
+ pairs: vec![
+ BracketPair {
+ start: "{".to_string(),
+ end: "}".to_string(),
+ close: true,
+ newline: true,
+ },
+ BracketPair {
+ start: "/* ".to_string(),
+ end: "*/".to_string(),
+ close: true,
+ ..Default::default()
+ },
+ ],
+ ..Default::default()
+ },
+ ..Default::default()
+ },
+ Some(tree_sitter_rust::language()),
+ ));
+
+ let text = r#"
+ a
+ b
+ c
+ "#
+ .unindent();
+
+ let buffer = cx.build_model(|cx| {
+ Buffer::new(0, cx.entity_id().as_u64(), text).with_language(language, cx)
+ });
+ let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
+ let (view, mut cx) = cx.add_window_view(|cx| build_editor(buffer, cx));
+ let cx = &mut cx;
+ view.condition::<crate::Event>(cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
+ .await;
+
+ view.update(cx, |view, cx| {
+ view.change_selections(None, cx, |s| {
+ s.select_display_ranges([
+ DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
+ DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
+ DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
+ ])
+ });
-// cx.assert_editor_state(indoc! {"
-// fn a() {
-// «b();
-// c();
-// ˇ» d();
-// }
-// "});
+ view.handle_input("{", cx);
+ view.handle_input("{", cx);
+ view.handle_input("{", cx);
+ assert_eq!(
+ view.text(cx),
+ "
+ {{{a}}}
+ {{{b}}}
+ {{{c}}}
+ "
+ .unindent()
+ );
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ [
+ DisplayPoint::new(0, 3)..DisplayPoint::new(0, 4),
+ DisplayPoint::new(1, 3)..DisplayPoint::new(1, 4),
+ DisplayPoint::new(2, 3)..DisplayPoint::new(2, 4)
+ ]
+ );
+
+ view.undo(&Undo, cx);
+ view.undo(&Undo, cx);
+ view.undo(&Undo, cx);
+ assert_eq!(
+ view.text(cx),
+ "
+ a
+ b
+ c
+ "
+ .unindent()
+ );
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ [
+ DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
+ DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
+ DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1)
+ ]
+ );
+
+ // Ensure inserting the first character of a multi-byte bracket pair
+ // doesn't surround the selections with the bracket.
+ view.handle_input("/", cx);
+ assert_eq!(
+ view.text(cx),
+ "
+ /
+ /
+ /
+ "
+ .unindent()
+ );
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ [
+ DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
+ DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
+ DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1)
+ ]
+ );
+
+ view.undo(&Undo, cx);
+ assert_eq!(
+ view.text(cx),
+ "
+ a
+ b
+ c
+ "
+ .unindent()
+ );
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ [
+ DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
+ DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
+ DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1)
+ ]
+ );
+
+ // Ensure inserting the last character of a multi-byte bracket pair
+ // doesn't surround the selections with the bracket.
+ view.handle_input("*", cx);
+ assert_eq!(
+ view.text(cx),
+ "
+ *
+ *
+ *
+ "
+ .unindent()
+ );
+ assert_eq!(
+ view.selections.display_ranges(cx),
+ [
+ DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
+ DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
+ DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1)
+ ]
+ );
+ });
+}
-// // The comment prefix is inserted at the same column for every line in a
-// // selection.
-// cx.update_editor(|e, cx| e.toggle_comments(&ToggleComments::default(), cx));
+#[gpui::test]
+async fn test_delete_autoclose_pair(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |_| {});
+
+ let language = Arc::new(Language::new(
+ LanguageConfig {
+ brackets: BracketPairConfig {
+ pairs: vec![BracketPair {
+ start: "{".to_string(),
+ end: "}".to_string(),
+ close: true,
+ newline: true,
+ }],
+ ..Default::default()
+ },
+ autoclose_before: "}".to_string(),
+ ..Default::default()
+ },
+ Some(tree_sitter_rust::language()),
+ ));
+
+ let text = r#"
+ a
+ b
+ c
+ "#
+ .unindent();
+
+ let buffer = cx.build_model(|cx| {
+ Buffer::new(0, cx.entity_id().as_u64(), text).with_language(language, cx)
+ });
+ let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
+ let (editor, mut cx) = cx.add_window_view(|cx| build_editor(buffer, cx));
+ let cx = &mut cx;
+ editor
+ .condition::<crate::Event>(cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
+ .await;
+
+ editor.update(cx, |editor, cx| {
+ editor.change_selections(None, cx, |s| {
+ s.select_ranges([
+ Point::new(0, 1)..Point::new(0, 1),
+ Point::new(1, 1)..Point::new(1, 1),
+ Point::new(2, 1)..Point::new(2, 1),
+ ])
+ });
-// cx.assert_editor_state(indoc! {"
-// fn a() {
-// // «b();
-// // c();
-// ˇ»// d();
-// }
-// "});
+ editor.handle_input("{", cx);
+ editor.handle_input("{", cx);
+ editor.handle_input("_", cx);
+ assert_eq!(
+ editor.text(cx),
+ "
+ a{{_}}
+ b{{_}}
+ c{{_}}
+ "
+ .unindent()
+ );
+ assert_eq!(
+ editor.selections.ranges::<Point>(cx),
+ [
+ Point::new(0, 4)..Point::new(0, 4),
+ Point::new(1, 4)..Point::new(1, 4),
+ Point::new(2, 4)..Point::new(2, 4)
+ ]
+ );
+
+ editor.backspace(&Default::default(), cx);
+ editor.backspace(&Default::default(), cx);
+ assert_eq!(
+ editor.text(cx),
+ "
+ a{}
+ b{}
+ c{}
+ "
+ .unindent()
+ );
+ assert_eq!(
+ editor.selections.ranges::<Point>(cx),
+ [
+ Point::new(0, 2)..Point::new(0, 2),
+ Point::new(1, 2)..Point::new(1, 2),
+ Point::new(2, 2)..Point::new(2, 2)
+ ]
+ );
+
+ editor.delete_to_previous_word_start(&Default::default(), cx);
+ assert_eq!(
+ editor.text(cx),
+ "
+ a
+ b
+ c
+ "
+ .unindent()
+ );
+ assert_eq!(
+ editor.selections.ranges::<Point>(cx),
+ [
+ Point::new(0, 1)..Point::new(0, 1),
+ Point::new(1, 1)..Point::new(1, 1),
+ Point::new(2, 1)..Point::new(2, 1)
+ ]
+ );
+ });
+}
-// // If a selection ends at the beginning of a line, that line is not toggled.
-// cx.set_selections_state(indoc! {"
-// fn a() {
-// // b();
-// «// c();
-// ˇ» // d();
-// }
-// "});
+// todo!(select_anchor_ranges)
+// #[gpui::test]
+// async fn test_snippets(cx: &mut gpui::TestAppContext) {
+// init_test(cx, |_| {});
-// cx.update_editor(|e, cx| e.toggle_comments(&ToggleComments::default(), cx));
+// let (text, insertion_ranges) = marked_text_ranges(
+// indoc! {"
+// a.ˇ b
+// a.ˇ b
+// a.ˇ b
+// "},
+// false,
+// );
-// cx.assert_editor_state(indoc! {"
-// fn a() {
-// // b();
-// «c();
-// ˇ» // d();
-// }
-// "});
+// let buffer = cx.update(|cx| MultiBuffer::build_simple(&text, cx));
+// let (editor, mut cx) = cx.add_window_view(|cx| build_editor(buffer, cx));
+// let cx = &mut cx;
-// // If a selection span a single line and is empty, the line is toggled.
-// cx.set_state(indoc! {"
-// fn a() {
-// a();
-// b();
-// ˇ
-// }
-// "});
+// editor.update(cx, |editor, cx| {
+// let snippet = Snippet::parse("f(${1:one}, ${2:two}, ${1:three})$0").unwrap();
-// cx.update_editor(|e, cx| e.toggle_comments(&ToggleComments::default(), cx));
+// editor
+// .insert_snippet(&insertion_ranges, snippet, cx)
+// .unwrap();
-// cx.assert_editor_state(indoc! {"
-// fn a() {
-// a();
-// b();
-// //•ˇ
+// fn assert(editor: &mut Editor, cx: &mut ViewContext<Editor>, marked_text: &str) {
+// let (expected_text, selection_ranges) = marked_text_ranges(marked_text, false);
+// assert_eq!(editor.text(cx), expected_text);
+// assert_eq!(editor.selections.ranges::<usize>(cx), selection_ranges);
// }
-// "});
-// // If a selection span multiple lines, empty lines are not toggled.
-// cx.set_state(indoc! {"
-// fn a() {
-// «a();
+// assert(
+// editor,
+// cx,
+// indoc! {"
+// a.f(«one», two, «three») b
+// a.f(«one», two, «three») b
+// a.f(«one», two, «three») b
+// "},
+// );
-// c();ˇ»
-// }
-// "});
+// // Can't move earlier than the first tab stop
+// assert!(!editor.move_to_prev_snippet_tabstop(cx));
+// assert(
+// editor,
+// cx,
+// indoc! {"
+// a.f(«one», two, «three») b
+// a.f(«one», two, «three») b
+// a.f(«one», two, «three») b
+// "},
+// );
-// cx.update_editor(|e, cx| e.toggle_comments(&ToggleComments::default(), cx));
+// assert!(editor.move_to_next_snippet_tabstop(cx));
+// assert(
+// editor,
+// cx,
+// indoc! {"
+// a.f(one, «two», three) b
+// a.f(one, «two», three) b
+// a.f(one, «two», three) b
+// "},
+// );
-// cx.assert_editor_state(indoc! {"
-// fn a() {
-// // «a();
+// editor.move_to_prev_snippet_tabstop(cx);
+// assert(
+// editor,
+// cx,
+// indoc! {"
+// a.f(«one», two, «three») b
+// a.f(«one», two, «three») b
+// a.f(«one», two, «three») b
+// "},
+// );
-// // c();ˇ»
-// }
-// "});
+// assert!(editor.move_to_next_snippet_tabstop(cx));
+// assert(
+// editor,
+// cx,
+// indoc! {"
+// a.f(one, «two», three) b
+// a.f(one, «two», three) b
+// a.f(one, «two», three) b
+// "},
+// );
+// assert!(editor.move_to_next_snippet_tabstop(cx));
+// assert(
+// editor,
+// cx,
+// indoc! {"
+// a.f(one, two, three)ˇ b
+// a.f(one, two, three)ˇ b
+// a.f(one, two, three)ˇ b
+// "},
+// );
+
+// // As soon as the last tab stop is reached, snippet state is gone
+// editor.move_to_prev_snippet_tabstop(cx);
+// assert(
+// editor,
+// cx,
+// indoc! {"
+// a.f(one, two, three)ˇ b
+// a.f(one, two, three)ˇ b
+// a.f(one, two, three)ˇ b
+// "},
+// );
+// });
// }
-// #[gpui::test]
-// async fn test_advance_downward_on_toggle_comment(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |_| {});
+#[gpui::test]
+async fn test_document_format_during_save(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |_| {});
+
+ let mut language = Language::new(
+ LanguageConfig {
+ name: "Rust".into(),
+ path_suffixes: vec!["rs".to_string()],
+ ..Default::default()
+ },
+ Some(tree_sitter_rust::language()),
+ );
+ let mut fake_servers = language
+ .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities {
+ document_formatting_provider: Some(lsp::OneOf::Left(true)),
+ ..Default::default()
+ },
+ ..Default::default()
+ }))
+ .await;
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_file("/file.rs", Default::default()).await;
+
+ let project = Project::test(fs, ["/file.rs".as_ref()], cx).await;
+ project.update(cx, |project, _| project.languages().add(Arc::new(language)));
+ let buffer = project
+ .update(cx, |project, cx| project.open_local_buffer("/file.rs", cx))
+ .await
+ .unwrap();
+
+ cx.executor().start_waiting();
+ let fake_server = fake_servers.next().await.unwrap();
+
+ let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
+ let (editor, mut cx) = cx.add_window_view(|cx| build_editor(buffer, cx));
+ let cx = &mut cx;
+ editor.update(cx, |editor, cx| editor.set_text("one\ntwo\nthree\n", cx));
+ assert!(cx.read(|cx| editor.is_dirty(cx)));
+
+ let save = editor
+ .update(cx, |editor, cx| editor.save(project.clone(), cx))
+ .unwrap();
+ fake_server
+ .handle_request::<lsp::request::Formatting, _, _>(move |params, _| async move {
+ assert_eq!(
+ params.text_document.uri,
+ lsp::Url::from_file_path("/file.rs").unwrap()
+ );
+ assert_eq!(params.options.tab_size, 4);
+ Ok(Some(vec![lsp::TextEdit::new(
+ lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(1, 0)),
+ ", ".to_string(),
+ )]))
+ })
+ .next()
+ .await;
+ cx.executor().start_waiting();
+ let x = save.await;
+
+ assert_eq!(
+ editor.update(cx, |editor, cx| editor.text(cx)),
+ "one, two\nthree\n"
+ );
+ assert!(!cx.read(|cx| editor.is_dirty(cx)));
+
+ editor.update(cx, |editor, cx| editor.set_text("one\ntwo\nthree\n", cx));
+ assert!(cx.read(|cx| editor.is_dirty(cx)));
+
+ // Ensure we can still save even if formatting hangs.
+ fake_server.handle_request::<lsp::request::Formatting, _, _>(move |params, _| async move {
+ assert_eq!(
+ params.text_document.uri,
+ lsp::Url::from_file_path("/file.rs").unwrap()
+ );
+ futures::future::pending::<()>().await;
+ unreachable!()
+ });
+ let save = editor
+ .update(cx, |editor, cx| editor.save(project.clone(), cx))
+ .unwrap();
+ cx.executor().advance_clock(super::FORMAT_TIMEOUT);
+ cx.executor().start_waiting();
+ save.await;
+ assert_eq!(
+ editor.update(cx, |editor, cx| editor.text(cx)),
+ "one\ntwo\nthree\n"
+ );
+ assert!(!cx.read(|cx| editor.is_dirty(cx)));
+
+ // Set rust language override and assert overridden tabsize is sent to language server
+ update_test_language_settings(cx, |settings| {
+ settings.languages.insert(
+ "Rust".into(),
+ LanguageSettingsContent {
+ tab_size: NonZeroU32::new(8),
+ ..Default::default()
+ },
+ );
+ });
-// let language = Arc::new(Language::new(
-// LanguageConfig {
-// line_comment: Some("// ".into()),
-// ..Default::default()
-// },
-// Some(tree_sitter_rust::language()),
-// ));
+ let save = editor
+ .update(cx, |editor, cx| editor.save(project.clone(), cx))
+ .unwrap();
+ fake_server
+ .handle_request::<lsp::request::Formatting, _, _>(move |params, _| async move {
+ assert_eq!(
+ params.text_document.uri,
+ lsp::Url::from_file_path("/file.rs").unwrap()
+ );
+ assert_eq!(params.options.tab_size, 8);
+ Ok(Some(vec![]))
+ })
+ .next()
+ .await;
+ cx.executor().start_waiting();
+ save.await;
+}
-// let registry = Arc::new(LanguageRegistry::test());
-// registry.add(language.clone());
+#[gpui::test]
+async fn test_range_format_during_save(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |_| {});
+
+ let mut language = Language::new(
+ LanguageConfig {
+ name: "Rust".into(),
+ path_suffixes: vec!["rs".to_string()],
+ ..Default::default()
+ },
+ Some(tree_sitter_rust::language()),
+ );
+ let mut fake_servers = language
+ .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities {
+ document_range_formatting_provider: Some(lsp::OneOf::Left(true)),
+ ..Default::default()
+ },
+ ..Default::default()
+ }))
+ .await;
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_file("/file.rs", Default::default()).await;
+
+ let project = Project::test(fs, ["/file.rs".as_ref()], cx).await;
+ project.update(cx, |project, _| project.languages().add(Arc::new(language)));
+ let buffer = project
+ .update(cx, |project, cx| project.open_local_buffer("/file.rs", cx))
+ .await
+ .unwrap();
+
+ cx.executor().start_waiting();
+ let fake_server = fake_servers.next().await.unwrap();
+
+ let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
+ let (editor, mut cx) = cx.add_window_view(|cx| build_editor(buffer, cx));
+ let cx = &mut cx;
+ editor.update(cx, |editor, cx| editor.set_text("one\ntwo\nthree\n", cx));
+ assert!(cx.read(|cx| editor.is_dirty(cx)));
+
+ let save = editor
+ .update(cx, |editor, cx| editor.save(project.clone(), cx))
+ .unwrap();
+ fake_server
+ .handle_request::<lsp::request::RangeFormatting, _, _>(move |params, _| async move {
+ assert_eq!(
+ params.text_document.uri,
+ lsp::Url::from_file_path("/file.rs").unwrap()
+ );
+ assert_eq!(params.options.tab_size, 4);
+ Ok(Some(vec![lsp::TextEdit::new(
+ lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(1, 0)),
+ ", ".to_string(),
+ )]))
+ })
+ .next()
+ .await;
+ cx.executor().start_waiting();
+ save.await;
+ assert_eq!(
+ editor.update(cx, |editor, cx| editor.text(cx)),
+ "one, two\nthree\n"
+ );
+ assert!(!cx.read(|cx| editor.is_dirty(cx)));
+
+ editor.update(cx, |editor, cx| editor.set_text("one\ntwo\nthree\n", cx));
+ assert!(cx.read(|cx| editor.is_dirty(cx)));
+
+ // Ensure we can still save even if formatting hangs.
+ fake_server.handle_request::<lsp::request::RangeFormatting, _, _>(
+ move |params, _| async move {
+ assert_eq!(
+ params.text_document.uri,
+ lsp::Url::from_file_path("/file.rs").unwrap()
+ );
+ futures::future::pending::<()>().await;
+ unreachable!()
+ },
+ );
+ let save = editor
+ .update(cx, |editor, cx| editor.save(project.clone(), cx))
+ .unwrap();
+ cx.executor().advance_clock(super::FORMAT_TIMEOUT);
+ cx.executor().start_waiting();
+ save.await;
+ assert_eq!(
+ editor.update(cx, |editor, cx| editor.text(cx)),
+ "one\ntwo\nthree\n"
+ );
+ assert!(!cx.read(|cx| editor.is_dirty(cx)));
+
+ // Set rust language override and assert overridden tabsize is sent to language server
+ update_test_language_settings(cx, |settings| {
+ settings.languages.insert(
+ "Rust".into(),
+ LanguageSettingsContent {
+ tab_size: NonZeroU32::new(8),
+ ..Default::default()
+ },
+ );
+ });
-// let mut cx = EditorTestContext::new(cx).await;
-// cx.update_buffer(|buffer, cx| {
-// buffer.set_language_registry(registry);
-// buffer.set_language(Some(language), cx);
-// });
+ let save = editor
+ .update(cx, |editor, cx| editor.save(project.clone(), cx))
+ .unwrap();
+ fake_server
+ .handle_request::<lsp::request::RangeFormatting, _, _>(move |params, _| async move {
+ assert_eq!(
+ params.text_document.uri,
+ lsp::Url::from_file_path("/file.rs").unwrap()
+ );
+ assert_eq!(params.options.tab_size, 8);
+ Ok(Some(vec![]))
+ })
+ .next()
+ .await;
+ cx.executor().start_waiting();
+ save.await;
+}
-// let toggle_comments = &ToggleComments {
-// advance_downwards: true,
-// };
+#[gpui::test]
+async fn test_document_format_manual_trigger(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |settings| {
+ settings.defaults.formatter = Some(language_settings::Formatter::LanguageServer)
+ });
-// // Single cursor on one line -> advance
-// // Cursor moves horizontally 3 characters as well on non-blank line
-// cx.set_state(indoc!(
-// "fn a() {
-// ˇdog();
-// cat();
-// }"
-// ));
-// cx.update_editor(|editor, cx| {
-// editor.toggle_comments(toggle_comments, cx);
-// });
-// cx.assert_editor_state(indoc!(
-// "fn a() {
-// // dog();
-// catˇ();
-// }"
-// ));
+ let mut language = Language::new(
+ LanguageConfig {
+ name: "Rust".into(),
+ path_suffixes: vec!["rs".to_string()],
+ // Enable Prettier formatting for the same buffer, and ensure
+ // LSP is called instead of Prettier.
+ prettier_parser_name: Some("test_parser".to_string()),
+ ..Default::default()
+ },
+ Some(tree_sitter_rust::language()),
+ );
+ let mut fake_servers = language
+ .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities {
+ document_formatting_provider: Some(lsp::OneOf::Left(true)),
+ ..Default::default()
+ },
+ ..Default::default()
+ }))
+ .await;
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_file("/file.rs", Default::default()).await;
+
+ let project = Project::test(fs, ["/file.rs".as_ref()], cx).await;
+ project.update(cx, |project, _| {
+ project.languages().add(Arc::new(language));
+ });
+ let buffer = project
+ .update(cx, |project, cx| project.open_local_buffer("/file.rs", cx))
+ .await
+ .unwrap();
+
+ cx.executor().start_waiting();
+ let fake_server = fake_servers.next().await.unwrap();
+
+ let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
+ let (editor, mut cx) = cx.add_window_view(|cx| build_editor(buffer, cx));
+ let cx = &mut cx;
+ editor.update(cx, |editor, cx| editor.set_text("one\ntwo\nthree\n", cx));
+
+ let format = editor
+ .update(cx, |editor, cx| {
+ editor.perform_format(project.clone(), FormatTrigger::Manual, cx)
+ })
+ .unwrap();
+ fake_server
+ .handle_request::<lsp::request::Formatting, _, _>(move |params, _| async move {
+ assert_eq!(
+ params.text_document.uri,
+ lsp::Url::from_file_path("/file.rs").unwrap()
+ );
+ assert_eq!(params.options.tab_size, 4);
+ Ok(Some(vec![lsp::TextEdit::new(
+ lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(1, 0)),
+ ", ".to_string(),
+ )]))
+ })
+ .next()
+ .await;
+ cx.executor().start_waiting();
+ format.await;
+ assert_eq!(
+ editor.update(cx, |editor, cx| editor.text(cx)),
+ "one, two\nthree\n"
+ );
+
+ editor.update(cx, |editor, cx| editor.set_text("one\ntwo\nthree\n", cx));
+ // Ensure we don't lock if formatting hangs.
+ fake_server.handle_request::<lsp::request::Formatting, _, _>(move |params, _| async move {
+ assert_eq!(
+ params.text_document.uri,
+ lsp::Url::from_file_path("/file.rs").unwrap()
+ );
+ futures::future::pending::<()>().await;
+ unreachable!()
+ });
+ let format = editor
+ .update(cx, |editor, cx| {
+ editor.perform_format(project, FormatTrigger::Manual, cx)
+ })
+ .unwrap();
+ cx.executor().advance_clock(super::FORMAT_TIMEOUT);
+ cx.executor().start_waiting();
+ format.await;
+ assert_eq!(
+ editor.update(cx, |editor, cx| editor.text(cx)),
+ "one\ntwo\nthree\n"
+ );
+}
-// // Single selection on one line -> don't advance
-// cx.set_state(indoc!(
-// "fn a() {
-// «dog()ˇ»;
-// cat();
-// }"
-// ));
-// cx.update_editor(|editor, cx| {
-// editor.toggle_comments(toggle_comments, cx);
-// });
-// cx.assert_editor_state(indoc!(
-// "fn a() {
-// // «dog()ˇ»;
-// cat();
-// }"
-// ));
+#[gpui::test]
+async fn test_concurrent_format_requests(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |_| {});
+
+ let mut cx = EditorLspTestContext::new_rust(
+ lsp::ServerCapabilities {
+ document_formatting_provider: Some(lsp::OneOf::Left(true)),
+ ..Default::default()
+ },
+ cx,
+ )
+ .await;
+
+ cx.set_state(indoc! {"
+ one.twoˇ
+ "});
+
+ // The format request takes a long time. When it completes, it inserts
+ // a newline and an indent before the `.`
+ cx.lsp
+ .handle_request::<lsp::request::Formatting, _, _>(move |_, cx| {
+ let executor = cx.background_executor().clone();
+ async move {
+ executor.timer(Duration::from_millis(100)).await;
+ Ok(Some(vec![lsp::TextEdit {
+ range: lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(0, 3)),
+ new_text: "\n ".into(),
+ }]))
+ }
+ });
-// // Multiple cursors on one line -> advance
-// cx.set_state(indoc!(
-// "fn a() {
-// ˇdˇog();
-// cat();
-// }"
-// ));
-// cx.update_editor(|editor, cx| {
-// editor.toggle_comments(toggle_comments, cx);
-// });
-// cx.assert_editor_state(indoc!(
-// "fn a() {
-// // dog();
-// catˇ(ˇ);
-// }"
-// ));
+ // Submit a format request.
+ let format_1 = cx
+ .update_editor(|editor, cx| editor.format(&Format, cx))
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ // Submit a second format request.
+ let format_2 = cx
+ .update_editor(|editor, cx| editor.format(&Format, cx))
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ // Wait for both format requests to complete
+ cx.executor().advance_clock(Duration::from_millis(200));
+ cx.executor().start_waiting();
+ format_1.await.unwrap();
+ cx.executor().start_waiting();
+ format_2.await.unwrap();
+
+ // The formatting edits only happens once.
+ cx.assert_editor_state(indoc! {"
+ one
+ .twoˇ
+ "});
+}
-// // Multiple cursors on one line, with selection -> don't advance
-// cx.set_state(indoc!(
-// "fn a() {
-// ˇdˇog«()ˇ»;
-// cat();
-// }"
-// ));
-// cx.update_editor(|editor, cx| {
-// editor.toggle_comments(toggle_comments, cx);
-// });
-// cx.assert_editor_state(indoc!(
-// "fn a() {
-// // ˇdˇog«()ˇ»;
-// cat();
-// }"
-// ));
+#[gpui::test]
+async fn test_strip_whitespace_and_format_via_lsp(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |settings| {
+ settings.defaults.formatter = Some(language_settings::Formatter::Auto)
+ });
-// // Single cursor on one line -> advance
-// // Cursor moves to column 0 on blank line
-// cx.set_state(indoc!(
-// "fn a() {
-// ˇdog();
+ let mut cx = EditorLspTestContext::new_rust(
+ lsp::ServerCapabilities {
+ document_formatting_provider: Some(lsp::OneOf::Left(true)),
+ ..Default::default()
+ },
+ cx,
+ )
+ .await;
+
+ // Set up a buffer white some trailing whitespace and no trailing newline.
+ cx.set_state(
+ &[
+ "one ", //
+ "twoˇ", //
+ "three ", //
+ "four", //
+ ]
+ .join("\n"),
+ );
+
+ // Submit a format request.
+ let format = cx
+ .update_editor(|editor, cx| editor.format(&Format, cx))
+ .unwrap();
+
+ // Record which buffer changes have been sent to the language server
+ let buffer_changes = Arc::new(Mutex::new(Vec::new()));
+ cx.lsp
+ .handle_notification::<lsp::notification::DidChangeTextDocument, _>({
+ let buffer_changes = buffer_changes.clone();
+ move |params, _| {
+ buffer_changes.lock().extend(
+ params
+ .content_changes
+ .into_iter()
+ .map(|e| (e.range.unwrap(), e.text)),
+ );
+ }
+ });
-// cat();
-// }"
-// ));
-// cx.update_editor(|editor, cx| {
-// editor.toggle_comments(toggle_comments, cx);
-// });
-// cx.assert_editor_state(indoc!(
-// "fn a() {
-// // dog();
-// ˇ
-// cat();
-// }"
-// ));
+ // Handle formatting requests to the language server.
+ cx.lsp.handle_request::<lsp::request::Formatting, _, _>({
+ let buffer_changes = buffer_changes.clone();
+ move |_, _| {
+ // When formatting is requested, trailing whitespace has already been stripped,
+ // and the trailing newline has already been added.
+ assert_eq!(
+ &buffer_changes.lock()[1..],
+ &[
+ (
+ lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(0, 4)),
+ "".into()
+ ),
+ (
+ lsp::Range::new(lsp::Position::new(2, 5), lsp::Position::new(2, 6)),
+ "".into()
+ ),
+ (
+ lsp::Range::new(lsp::Position::new(3, 4), lsp::Position::new(3, 4)),
+ "\n".into()
+ ),
+ ]
+ );
+
+ // Insert blank lines between each line of the buffer.
+ async move {
+ Ok(Some(vec![
+ lsp::TextEdit {
+ range: lsp::Range::new(lsp::Position::new(1, 0), lsp::Position::new(1, 0)),
+ new_text: "\n".into(),
+ },
+ lsp::TextEdit {
+ range: lsp::Range::new(lsp::Position::new(2, 0), lsp::Position::new(2, 0)),
+ new_text: "\n".into(),
+ },
+ ]))
+ }
+ }
+ });
-// // Single cursor on one line -> advance
-// // Cursor starts and ends at column 0
-// cx.set_state(indoc!(
-// "fn a() {
-// ˇ dog();
-// cat();
-// }"
-// ));
-// cx.update_editor(|editor, cx| {
-// editor.toggle_comments(toggle_comments, cx);
-// });
-// cx.assert_editor_state(indoc!(
-// "fn a() {
-// // dog();
-// ˇ cat();
-// }"
-// ));
-// }
+ // After formatting the buffer, the trailing whitespace is stripped,
+ // a newline is appended, and the edits provided by the language server
+ // have been applied.
+ format.await.unwrap();
+ cx.assert_editor_state(
+ &[
+ "one", //
+ "", //
+ "twoˇ", //
+ "", //
+ "three", //
+ "four", //
+ "", //
+ ]
+ .join("\n"),
+ );
+
+ // Undoing the formatting undoes the trailing whitespace removal, the
+ // trailing newline, and the LSP edits.
+ cx.update_buffer(|buffer, cx| buffer.undo(cx));
+ cx.assert_editor_state(
+ &[
+ "one ", //
+ "twoˇ", //
+ "three ", //
+ "four", //
+ ]
+ .join("\n"),
+ );
+}
+//todo!(completion)
// #[gpui::test]
-// async fn test_toggle_block_comment(cx: &mut gpui::TestAppContext) {
+// async fn test_completion(cx: &mut gpui::TestAppContext) {
// init_test(cx, |_| {});
-// let mut cx = EditorTestContext::new(cx).await;
-
-// let html_language = Arc::new(
-// Language::new(
-// LanguageConfig {
-// name: "HTML".into(),
-// block_comment: Some(("<!-- ".into(), " -->".into())),
+// let mut cx = EditorLspTestContext::new_rust(
+// lsp::ServerCapabilities {
+// completion_provider: Some(lsp::CompletionOptions {
+// trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
+// resolve_provider: Some(true),
// ..Default::default()
-// },
-// Some(tree_sitter_html::language()),
-// )
-// .with_injection_query(
-// r#"
-// (script_element
-// (raw_text) @content
-// (#set! "language" "javascript"))
-// "#,
-// )
-// .unwrap(),
-// );
-
-// let javascript_language = Arc::new(Language::new(
-// LanguageConfig {
-// name: "JavaScript".into(),
-// line_comment: Some("// ".into()),
+// }),
// ..Default::default()
// },
-// Some(tree_sitter_typescript::language_tsx()),
-// ));
-
-// let registry = Arc::new(LanguageRegistry::test());
-// registry.add(html_language.clone());
-// registry.add(javascript_language.clone());
+// cx,
+// )
+// .await;
-// cx.update_buffer(|buffer, cx| {
-// buffer.set_language_registry(registry);
-// buffer.set_language(Some(html_language), cx);
+// cx.set_state(indoc! {"
+// oneˇ
+// two
+// three
+// "});
+// cx.simulate_keystroke(".");
+// handle_completion_request(
+// &mut cx,
+// indoc! {"
+// one.|<>
+// two
+// three
+// "},
+// vec!["first_completion", "second_completion"],
+// )
+// .await;
+// cx.condition(|editor, _| editor.context_menu_visible())
+// .await;
+// let apply_additional_edits = cx.update_editor(|editor, cx| {
+// editor.context_menu_next(&Default::default(), cx);
+// editor
+// .confirm_completion(&ConfirmCompletion::default(), cx)
+// .unwrap()
// });
+// cx.assert_editor_state(indoc! {"
+// one.second_completionˇ
+// two
+// three
+// "});
-// // Toggle comments for empty selections
-// cx.set_state(
-// &r#"
-// <p>A</p>ˇ
-// <p>B</p>ˇ
-// <p>C</p>ˇ
-// "#
-// .unindent(),
-// );
-// cx.update_editor(|editor, cx| editor.toggle_comments(&ToggleComments::default(), cx));
-// cx.assert_editor_state(
-// &r#"
-// <!-- <p>A</p>ˇ -->
-// <!-- <p>B</p>ˇ -->
-// <!-- <p>C</p>ˇ -->
-// "#
-// .unindent(),
-// );
-// cx.update_editor(|editor, cx| editor.toggle_comments(&ToggleComments::default(), cx));
-// cx.assert_editor_state(
-// &r#"
-// <p>A</p>ˇ
-// <p>B</p>ˇ
-// <p>C</p>ˇ
-// "#
-// .unindent(),
-// );
-
-// // Toggle comments for mixture of empty and non-empty selections, where
-// // multiple selections occupy a given line.
-// cx.set_state(
-// &r#"
-// <p>A«</p>
-// <p>ˇ»B</p>ˇ
-// <p>C«</p>
-// <p>ˇ»D</p>ˇ
-// "#
-// .unindent(),
-// );
-
-// cx.update_editor(|editor, cx| editor.toggle_comments(&ToggleComments::default(), cx));
-// cx.assert_editor_state(
-// &r#"
-// <!-- <p>A«</p>
-// <p>ˇ»B</p>ˇ -->
-// <!-- <p>C«</p>
-// <p>ˇ»D</p>ˇ -->
-// "#
-// .unindent(),
-// );
-// cx.update_editor(|editor, cx| editor.toggle_comments(&ToggleComments::default(), cx));
-// cx.assert_editor_state(
-// &r#"
-// <p>A«</p>
-// <p>ˇ»B</p>ˇ
-// <p>C«</p>
-// <p>ˇ»D</p>ˇ
-// "#
-// .unindent(),
-// );
-
-// // Toggle comments when different languages are active for different
-// // selections.
-// cx.set_state(
-// &r#"
-// ˇ<script>
-// ˇvar x = new Y();
-// ˇ</script>
-// "#
-// .unindent(),
-// );
-// cx.foreground().run_until_parked();
-// cx.update_editor(|editor, cx| editor.toggle_comments(&ToggleComments::default(), cx));
-// cx.assert_editor_state(
-// &r#"
-// <!-- ˇ<script> -->
-// // ˇvar x = new Y();
-// <!-- ˇ</script> -->
-// "#
-// .unindent(),
-// );
-// }
-
-// #[gpui::test]
-// fn test_editing_disjoint_excerpts(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
+// handle_resolve_completion_request(
+// &mut cx,
+// Some(vec![
+// (
+// //This overlaps with the primary completion edit which is
+// //misbehavior from the LSP spec, test that we filter it out
+// indoc! {"
+// one.second_ˇcompletion
+// two
+// threeˇ
+// "},
+// "overlapping additional edit",
+// ),
+// (
+// indoc! {"
+// one.second_completion
+// two
+// threeˇ
+// "},
+// "\nadditional edit",
+// ),
+// ]),
+// )
+// .await;
+// apply_additional_edits.await.unwrap();
+// cx.assert_editor_state(indoc! {"
+// one.second_completionˇ
+// two
+// three
+// additional edit
+// "});
-// let buffer = cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, sample_text(3, 4, 'a')));
-// let multibuffer = cx.add_model(|cx| {
-// let mut multibuffer = MultiBuffer::new(0);
-// multibuffer.push_excerpts(
-// buffer.clone(),
-// [
-// ExcerptRange {
-// context: Point::new(0, 0)..Point::new(0, 4),
-// primary: None,
-// },
-// ExcerptRange {
-// context: Point::new(1, 0)..Point::new(1, 4),
-// primary: None,
-// },
-// ],
-// cx,
-// );
-// assert_eq!(multibuffer.read(cx).text(), "aaaa\nbbbb");
-// multibuffer
-// });
+// cx.set_state(indoc! {"
+// one.second_completion
+// twoˇ
+// threeˇ
+// additional edit
+// "});
+// cx.simulate_keystroke(" ");
+// assert!(cx.editor(|e, _| e.context_menu.read().is_none()));
+// cx.simulate_keystroke("s");
+// assert!(cx.editor(|e, _| e.context_menu.read().is_none()));
-// let view = cx.add_window(|cx| build_editor(multibuffer, cx)).root(cx);
-// view.update(cx, |view, cx| {
-// assert_eq!(view.text(cx), "aaaa\nbbbb");
-// view.change_selections(None, cx, |s| {
-// s.select_ranges([
-// Point::new(0, 0)..Point::new(0, 0),
-// Point::new(1, 0)..Point::new(1, 0),
-// ])
-// });
+// cx.assert_editor_state(indoc! {"
+// one.second_completion
+// two sˇ
+// three sˇ
+// additional edit
+// "});
+// handle_completion_request(
+// &mut cx,
+// indoc! {"
+// one.second_completion
+// two s
+// three <s|>
+// additional edit
+// "},
+// vec!["fourth_completion", "fifth_completion", "sixth_completion"],
+// )
+// .await;
+// cx.condition(|editor, _| editor.context_menu_visible())
+// .await;
-// view.handle_input("X", cx);
-// assert_eq!(view.text(cx), "Xaaaa\nXbbbb");
-// assert_eq!(
-// view.selections.ranges(cx),
-// [
-// Point::new(0, 1)..Point::new(0, 1),
-// Point::new(1, 1)..Point::new(1, 1),
-// ]
-// );
+// cx.simulate_keystroke("i");
-// // Ensure the cursor's head is respected when deleting across an excerpt boundary.
-// view.change_selections(None, cx, |s| {
-// s.select_ranges([Point::new(0, 2)..Point::new(1, 2)])
-// });
-// view.backspace(&Default::default(), cx);
-// assert_eq!(view.text(cx), "Xa\nbbb");
-// assert_eq!(
-// view.selections.ranges(cx),
-// [Point::new(1, 0)..Point::new(1, 0)]
-// );
+// handle_completion_request(
+// &mut cx,
+// indoc! {"
+// one.second_completion
+// two si
+// three <si|>
+// additional edit
+// "},
+// vec!["fourth_completion", "fifth_completion", "sixth_completion"],
+// )
+// .await;
+// cx.condition(|editor, _| editor.context_menu_visible())
+// .await;
-// view.change_selections(None, cx, |s| {
-// s.select_ranges([Point::new(1, 1)..Point::new(0, 1)])
-// });
-// view.backspace(&Default::default(), cx);
-// assert_eq!(view.text(cx), "X\nbb");
-// assert_eq!(
-// view.selections.ranges(cx),
-// [Point::new(0, 1)..Point::new(0, 1)]
-// );
+// let apply_additional_edits = cx.update_editor(|editor, cx| {
+// editor
+// .confirm_completion(&ConfirmCompletion::default(), cx)
+// .unwrap()
// });
-// }
+// cx.assert_editor_state(indoc! {"
+// one.second_completion
+// two sixth_completionˇ
+// three sixth_completionˇ
+// additional edit
+// "});
-// #[gpui::test]
-// fn test_editing_overlapping_excerpts(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
+// handle_resolve_completion_request(&mut cx, None).await;
+// apply_additional_edits.await.unwrap();
-// let markers = vec![('[', ']').into(), ('(', ')').into()];
-// let (initial_text, mut excerpt_ranges) = marked_text_ranges_by(
-// indoc! {"
-// [aaaa
-// (bbbb]
-// cccc)",
-// },
-// markers.clone(),
-// );
-// let excerpt_ranges = markers.into_iter().map(|marker| {
-// let context = excerpt_ranges.remove(&marker).unwrap()[0].clone();
-// ExcerptRange {
-// context,
-// primary: None,
-// }
+// cx.update(|cx| {
+// cx.update_global::<SettingsStore, _, _>(|settings, cx| {
+// settings.update_user_settings::<EditorSettings>(cx, |settings| {
+// settings.show_completions_on_input = Some(false);
+// });
+// })
// });
-// let buffer = cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, initial_text));
-// let multibuffer = cx.add_model(|cx| {
-// let mut multibuffer = MultiBuffer::new(0);
-// multibuffer.push_excerpts(buffer, excerpt_ranges, cx);
-// multibuffer
+// cx.set_state("editorˇ");
+// cx.simulate_keystroke(".");
+// assert!(cx.editor(|e, _| e.context_menu.read().is_none()));
+// cx.simulate_keystroke("c");
+// cx.simulate_keystroke("l");
+// cx.simulate_keystroke("o");
+// cx.assert_editor_state("editor.cloˇ");
+// assert!(cx.editor(|e, _| e.context_menu.read().is_none()));
+// cx.update_editor(|editor, cx| {
+// editor.show_completions(&ShowCompletions, cx);
// });
-
-// let view = cx.add_window(|cx| build_editor(multibuffer, cx)).root(cx);
-// view.update(cx, |view, cx| {
-// let (expected_text, selection_ranges) = marked_text_ranges(
-// indoc! {"
-// aaaa
-// bˇbbb
-// bˇbbˇb
-// cccc"
-// },
-// true,
-// );
-// assert_eq!(view.text(cx), expected_text);
-// view.change_selections(None, cx, |s| s.select_ranges(selection_ranges));
-
-// view.handle_input("X", cx);
-
-// let (expected_text, expected_selections) = marked_text_ranges(
-// indoc! {"
-// aaaa
-// bXˇbbXb
-// bXˇbbXˇb
-// cccc"
-// },
-// false,
-// );
-// assert_eq!(view.text(cx), expected_text);
-// assert_eq!(view.selections.ranges(cx), expected_selections);
-
-// view.newline(&Newline, cx);
-// let (expected_text, expected_selections) = marked_text_ranges(
-// indoc! {"
-// aaaa
-// bX
-// ˇbbX
-// b
-// bX
-// ˇbbX
-// ˇb
-// cccc"
-// },
-// false,
-// );
-// assert_eq!(view.text(cx), expected_text);
-// assert_eq!(view.selections.ranges(cx), expected_selections);
+// handle_completion_request(&mut cx, "editor.<clo|>", vec!["close", "clobber"]).await;
+// cx.condition(|editor, _| editor.context_menu_visible())
+// .await;
+// let apply_additional_edits = cx.update_editor(|editor, cx| {
+// editor
+// .confirm_completion(&ConfirmCompletion::default(), cx)
+// .unwrap()
// });
+// cx.assert_editor_state("editor.closeˇ");
+// handle_resolve_completion_request(&mut cx, None).await;
+// apply_additional_edits.await.unwrap();
// }
-// #[gpui::test]
-// fn test_refresh_selections(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
+#[gpui::test]
+async fn test_toggle_comment(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |_| {});
+ let mut cx = EditorTestContext::new(cx).await;
+ let language = Arc::new(Language::new(
+ LanguageConfig {
+ line_comment: Some("// ".into()),
+ ..Default::default()
+ },
+ Some(tree_sitter_rust::language()),
+ ));
+ cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
+
+ // If multiple selections intersect a line, the line is only toggled once.
+ cx.set_state(indoc! {"
+ fn a() {
+ «//b();
+ ˇ»// «c();
+ //ˇ» d();
+ }
+ "});
+
+ cx.update_editor(|e, cx| e.toggle_comments(&ToggleComments::default(), cx));
+
+ cx.assert_editor_state(indoc! {"
+ fn a() {
+ «b();
+ c();
+ ˇ» d();
+ }
+ "});
+
+ // The comment prefix is inserted at the same column for every line in a
+ // selection.
+ cx.update_editor(|e, cx| e.toggle_comments(&ToggleComments::default(), cx));
+
+ cx.assert_editor_state(indoc! {"
+ fn a() {
+ // «b();
+ // c();
+ ˇ»// d();
+ }
+ "});
+
+ // If a selection ends at the beginning of a line, that line is not toggled.
+ cx.set_selections_state(indoc! {"
+ fn a() {
+ // b();
+ «// c();
+ ˇ» // d();
+ }
+ "});
+
+ cx.update_editor(|e, cx| e.toggle_comments(&ToggleComments::default(), cx));
+
+ cx.assert_editor_state(indoc! {"
+ fn a() {
+ // b();
+ «c();
+ ˇ» // d();
+ }
+ "});
+
+ // If a selection span a single line and is empty, the line is toggled.
+ cx.set_state(indoc! {"
+ fn a() {
+ a();
+ b();
+ ˇ
+ }
+ "});
+
+ cx.update_editor(|e, cx| e.toggle_comments(&ToggleComments::default(), cx));
+
+ cx.assert_editor_state(indoc! {"
+ fn a() {
+ a();
+ b();
+ //•ˇ
+ }
+ "});
+
+ // If a selection span multiple lines, empty lines are not toggled.
+ cx.set_state(indoc! {"
+ fn a() {
+ «a();
+
+ c();ˇ»
+ }
+ "});
+
+ cx.update_editor(|e, cx| e.toggle_comments(&ToggleComments::default(), cx));
+
+ cx.assert_editor_state(indoc! {"
+ fn a() {
+ // «a();
+
+ // c();ˇ»
+ }
+ "});
+}
-// let buffer = cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, sample_text(3, 4, 'a')));
-// let mut excerpt1_id = None;
-// let multibuffer = cx.add_model(|cx| {
-// let mut multibuffer = MultiBuffer::new(0);
-// excerpt1_id = multibuffer
-// .push_excerpts(
-// buffer.clone(),
-// [
-// ExcerptRange {
-// context: Point::new(0, 0)..Point::new(1, 4),
-// primary: None,
-// },
-// ExcerptRange {
-// context: Point::new(1, 0)..Point::new(2, 4),
-// primary: None,
-// },
-// ],
-// cx,
-// )
-// .into_iter()
-// .next();
-// assert_eq!(multibuffer.read(cx).text(), "aaaa\nbbbb\nbbbb\ncccc");
-// multibuffer
-// });
+#[gpui::test]
+async fn test_advance_downward_on_toggle_comment(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |_| {});
+
+ let language = Arc::new(Language::new(
+ LanguageConfig {
+ line_comment: Some("// ".into()),
+ ..Default::default()
+ },
+ Some(tree_sitter_rust::language()),
+ ));
+
+ let registry = Arc::new(LanguageRegistry::test());
+ registry.add(language.clone());
+
+ let mut cx = EditorTestContext::new(cx).await;
+ cx.update_buffer(|buffer, cx| {
+ buffer.set_language_registry(registry);
+ buffer.set_language(Some(language), cx);
+ });
-// let editor = cx
-// .add_window(|cx| {
-// let mut editor = build_editor(multibuffer.clone(), cx);
-// let snapshot = editor.snapshot(cx);
-// editor.change_selections(None, cx, |s| {
-// s.select_ranges([Point::new(1, 3)..Point::new(1, 3)])
-// });
-// editor.begin_selection(Point::new(2, 1).to_display_point(&snapshot), true, 1, cx);
-// assert_eq!(
-// editor.selections.ranges(cx),
-// [
-// Point::new(1, 3)..Point::new(1, 3),
-// Point::new(2, 1)..Point::new(2, 1),
-// ]
-// );
-// editor
-// })
-// .root(cx);
+ let toggle_comments = &ToggleComments {
+ advance_downwards: true,
+ };
+
+ // Single cursor on one line -> advance
+ // Cursor moves horizontally 3 characters as well on non-blank line
+ cx.set_state(indoc!(
+ "fn a() {
+ ˇdog();
+ cat();
+ }"
+ ));
+ cx.update_editor(|editor, cx| {
+ editor.toggle_comments(toggle_comments, cx);
+ });
+ cx.assert_editor_state(indoc!(
+ "fn a() {
+ // dog();
+ catˇ();
+ }"
+ ));
+
+ // Single selection on one line -> don't advance
+ cx.set_state(indoc!(
+ "fn a() {
+ «dog()ˇ»;
+ cat();
+ }"
+ ));
+ cx.update_editor(|editor, cx| {
+ editor.toggle_comments(toggle_comments, cx);
+ });
+ cx.assert_editor_state(indoc!(
+ "fn a() {
+ // «dog()ˇ»;
+ cat();
+ }"
+ ));
+
+ // Multiple cursors on one line -> advance
+ cx.set_state(indoc!(
+ "fn a() {
+ ˇdˇog();
+ cat();
+ }"
+ ));
+ cx.update_editor(|editor, cx| {
+ editor.toggle_comments(toggle_comments, cx);
+ });
+ cx.assert_editor_state(indoc!(
+ "fn a() {
+ // dog();
+ catˇ(ˇ);
+ }"
+ ));
+
+ // Multiple cursors on one line, with selection -> don't advance
+ cx.set_state(indoc!(
+ "fn a() {
+ ˇdˇog«()ˇ»;
+ cat();
+ }"
+ ));
+ cx.update_editor(|editor, cx| {
+ editor.toggle_comments(toggle_comments, cx);
+ });
+ cx.assert_editor_state(indoc!(
+ "fn a() {
+ // ˇdˇog«()ˇ»;
+ cat();
+ }"
+ ));
+
+ // Single cursor on one line -> advance
+ // Cursor moves to column 0 on blank line
+ cx.set_state(indoc!(
+ "fn a() {
+ ˇdog();
+
+ cat();
+ }"
+ ));
+ cx.update_editor(|editor, cx| {
+ editor.toggle_comments(toggle_comments, cx);
+ });
+ cx.assert_editor_state(indoc!(
+ "fn a() {
+ // dog();
+ ˇ
+ cat();
+ }"
+ ));
+
+ // Single cursor on one line -> advance
+ // Cursor starts and ends at column 0
+ cx.set_state(indoc!(
+ "fn a() {
+ ˇ dog();
+ cat();
+ }"
+ ));
+ cx.update_editor(|editor, cx| {
+ editor.toggle_comments(toggle_comments, cx);
+ });
+ cx.assert_editor_state(indoc!(
+ "fn a() {
+ // dog();
+ ˇ cat();
+ }"
+ ));
+}
-// // Refreshing selections is a no-op when excerpts haven't changed.
-// editor.update(cx, |editor, cx| {
-// editor.change_selections(None, cx, |s| s.refresh());
-// assert_eq!(
-// editor.selections.ranges(cx),
-// [
-// Point::new(1, 3)..Point::new(1, 3),
-// Point::new(2, 1)..Point::new(2, 1),
-// ]
-// );
-// });
+#[gpui::test]
+async fn test_toggle_block_comment(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |_| {});
+
+ let mut cx = EditorTestContext::new(cx).await;
+
+ let html_language = Arc::new(
+ Language::new(
+ LanguageConfig {
+ name: "HTML".into(),
+ block_comment: Some(("<!-- ".into(), " -->".into())),
+ ..Default::default()
+ },
+ Some(tree_sitter_html::language()),
+ )
+ .with_injection_query(
+ r#"
+ (script_element
+ (raw_text) @content
+ (#set! "language" "javascript"))
+ "#,
+ )
+ .unwrap(),
+ );
+
+ let javascript_language = Arc::new(Language::new(
+ LanguageConfig {
+ name: "JavaScript".into(),
+ line_comment: Some("// ".into()),
+ ..Default::default()
+ },
+ Some(tree_sitter_typescript::language_tsx()),
+ ));
+
+ let registry = Arc::new(LanguageRegistry::test());
+ registry.add(html_language.clone());
+ registry.add(javascript_language.clone());
+
+ cx.update_buffer(|buffer, cx| {
+ buffer.set_language_registry(registry);
+ buffer.set_language(Some(html_language), cx);
+ });
-// multibuffer.update(cx, |multibuffer, cx| {
-// multibuffer.remove_excerpts([excerpt1_id.unwrap()], cx);
-// });
-// editor.update(cx, |editor, cx| {
-// // Removing an excerpt causes the first selection to become degenerate.
-// assert_eq!(
-// editor.selections.ranges(cx),
-// [
-// Point::new(0, 0)..Point::new(0, 0),
-// Point::new(0, 1)..Point::new(0, 1)
-// ]
-// );
+ // Toggle comments for empty selections
+ cx.set_state(
+ &r#"
+ <p>A</p>ˇ
+ <p>B</p>ˇ
+ <p>C</p>ˇ
+ "#
+ .unindent(),
+ );
+ cx.update_editor(|editor, cx| editor.toggle_comments(&ToggleComments::default(), cx));
+ cx.assert_editor_state(
+ &r#"
+ <!-- <p>A</p>ˇ -->
+ <!-- <p>B</p>ˇ -->
+ <!-- <p>C</p>ˇ -->
+ "#
+ .unindent(),
+ );
+ cx.update_editor(|editor, cx| editor.toggle_comments(&ToggleComments::default(), cx));
+ cx.assert_editor_state(
+ &r#"
+ <p>A</p>ˇ
+ <p>B</p>ˇ
+ <p>C</p>ˇ
+ "#
+ .unindent(),
+ );
+
+ // Toggle comments for mixture of empty and non-empty selections, where
+ // multiple selections occupy a given line.
+ cx.set_state(
+ &r#"
+ <p>A«</p>
+ <p>ˇ»B</p>ˇ
+ <p>C«</p>
+ <p>ˇ»D</p>ˇ
+ "#
+ .unindent(),
+ );
+
+ cx.update_editor(|editor, cx| editor.toggle_comments(&ToggleComments::default(), cx));
+ cx.assert_editor_state(
+ &r#"
+ <!-- <p>A«</p>
+ <p>ˇ»B</p>ˇ -->
+ <!-- <p>C«</p>
+ <p>ˇ»D</p>ˇ -->
+ "#
+ .unindent(),
+ );
+ cx.update_editor(|editor, cx| editor.toggle_comments(&ToggleComments::default(), cx));
+ cx.assert_editor_state(
+ &r#"
+ <p>A«</p>
+ <p>ˇ»B</p>ˇ
+ <p>C«</p>
+ <p>ˇ»D</p>ˇ
+ "#
+ .unindent(),
+ );
+
+ // Toggle comments when different languages are active for different
+ // selections.
+ cx.set_state(
+ &r#"
+ ˇ<script>
+ ˇvar x = new Y();
+ ˇ</script>
+ "#
+ .unindent(),
+ );
+ cx.executor().run_until_parked();
+ cx.update_editor(|editor, cx| editor.toggle_comments(&ToggleComments::default(), cx));
+ cx.assert_editor_state(
+ &r#"
+ <!-- ˇ<script> -->
+ // ˇvar x = new Y();
+ <!-- ˇ</script> -->
+ "#
+ .unindent(),
+ );
+}
-// // Refreshing selections will relocate the first selection to the original buffer
-// // location.
-// editor.change_selections(None, cx, |s| s.refresh());
-// assert_eq!(
-// editor.selections.ranges(cx),
-// [
-// Point::new(0, 1)..Point::new(0, 1),
-// Point::new(0, 3)..Point::new(0, 3)
-// ]
-// );
-// assert!(editor.selections.pending_anchor().is_some());
-// });
-// }
+#[gpui::test]
+fn test_editing_disjoint_excerpts(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+
+ let buffer =
+ cx.build_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), sample_text(3, 4, 'a')));
+ let multibuffer = cx.build_model(|cx| {
+ let mut multibuffer = MultiBuffer::new(0);
+ multibuffer.push_excerpts(
+ buffer.clone(),
+ [
+ ExcerptRange {
+ context: Point::new(0, 0)..Point::new(0, 4),
+ primary: None,
+ },
+ ExcerptRange {
+ context: Point::new(1, 0)..Point::new(1, 4),
+ primary: None,
+ },
+ ],
+ cx,
+ );
+ assert_eq!(multibuffer.read(cx).text(), "aaaa\nbbbb");
+ multibuffer
+ });
-// #[gpui::test]
-// fn test_refresh_selections_while_selecting_with_mouse(cx: &mut TestAppContext) {
-// init_test(cx, |_| {});
+ let (view, mut cx) = cx.add_window_view(|cx| build_editor(multibuffer, cx));
+ let cx = &mut cx;
+ view.update(cx, |view, cx| {
+ assert_eq!(view.text(cx), "aaaa\nbbbb");
+ view.change_selections(None, cx, |s| {
+ s.select_ranges([
+ Point::new(0, 0)..Point::new(0, 0),
+ Point::new(1, 0)..Point::new(1, 0),
+ ])
+ });
-// let buffer = cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, sample_text(3, 4, 'a')));
-// let mut excerpt1_id = None;
-// let multibuffer = cx.add_model(|cx| {
-// let mut multibuffer = MultiBuffer::new(0);
-// excerpt1_id = multibuffer
-// .push_excerpts(
-// buffer.clone(),
-// [
-// ExcerptRange {
-// context: Point::new(0, 0)..Point::new(1, 4),
-// primary: None,
-// },
-// ExcerptRange {
-// context: Point::new(1, 0)..Point::new(2, 4),
-// primary: None,
-// },
-// ],
-// cx,
-// )
-// .into_iter()
-// .next();
-// assert_eq!(multibuffer.read(cx).text(), "aaaa\nbbbb\nbbbb\ncccc");
-// multibuffer
-// });
+ view.handle_input("X", cx);
+ assert_eq!(view.text(cx), "Xaaaa\nXbbbb");
+ assert_eq!(
+ view.selections.ranges(cx),
+ [
+ Point::new(0, 1)..Point::new(0, 1),
+ Point::new(1, 1)..Point::new(1, 1),
+ ]
+ );
+
+ // Ensure the cursor's head is respected when deleting across an excerpt boundary.
+ view.change_selections(None, cx, |s| {
+ s.select_ranges([Point::new(0, 2)..Point::new(1, 2)])
+ });
+ view.backspace(&Default::default(), cx);
+ assert_eq!(view.text(cx), "Xa\nbbb");
+ assert_eq!(
+ view.selections.ranges(cx),
+ [Point::new(1, 0)..Point::new(1, 0)]
+ );
+
+ view.change_selections(None, cx, |s| {
+ s.select_ranges([Point::new(1, 1)..Point::new(0, 1)])
+ });
+ view.backspace(&Default::default(), cx);
+ assert_eq!(view.text(cx), "X\nbb");
+ assert_eq!(
+ view.selections.ranges(cx),
+ [Point::new(0, 1)..Point::new(0, 1)]
+ );
+ });
+}
-// let editor = cx
-// .add_window(|cx| {
-// let mut editor = build_editor(multibuffer.clone(), cx);
-// let snapshot = editor.snapshot(cx);
-// editor.begin_selection(Point::new(1, 3).to_display_point(&snapshot), false, 1, cx);
-// assert_eq!(
-// editor.selections.ranges(cx),
-// [Point::new(1, 3)..Point::new(1, 3)]
-// );
-// editor
-// })
-// .root(cx);
+#[gpui::test]
+fn test_editing_overlapping_excerpts(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+
+ let markers = vec![('[', ']').into(), ('(', ')').into()];
+ let (initial_text, mut excerpt_ranges) = marked_text_ranges_by(
+ indoc! {"
+ [aaaa
+ (bbbb]
+ cccc)",
+ },
+ markers.clone(),
+ );
+ let excerpt_ranges = markers.into_iter().map(|marker| {
+ let context = excerpt_ranges.remove(&marker).unwrap()[0].clone();
+ ExcerptRange {
+ context,
+ primary: None,
+ }
+ });
+ let buffer = cx.build_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), initial_text));
+ let multibuffer = cx.build_model(|cx| {
+ let mut multibuffer = MultiBuffer::new(0);
+ multibuffer.push_excerpts(buffer, excerpt_ranges, cx);
+ multibuffer
+ });
-// multibuffer.update(cx, |multibuffer, cx| {
-// multibuffer.remove_excerpts([excerpt1_id.unwrap()], cx);
-// });
-// editor.update(cx, |editor, cx| {
-// assert_eq!(
-// editor.selections.ranges(cx),
-// [Point::new(0, 0)..Point::new(0, 0)]
-// );
+ let (view, mut cx) = cx.add_window_view(|cx| build_editor(multibuffer, cx));
+ let cx = &mut cx;
+ view.update(cx, |view, cx| {
+ let (expected_text, selection_ranges) = marked_text_ranges(
+ indoc! {"
+ aaaa
+ bˇbbb
+ bˇbbˇb
+ cccc"
+ },
+ true,
+ );
+ assert_eq!(view.text(cx), expected_text);
+ view.change_selections(None, cx, |s| s.select_ranges(selection_ranges));
+
+ view.handle_input("X", cx);
+
+ let (expected_text, expected_selections) = marked_text_ranges(
+ indoc! {"
+ aaaa
+ bXˇbbXb
+ bXˇbbXˇb
+ cccc"
+ },
+ false,
+ );
+ assert_eq!(view.text(cx), expected_text);
+ assert_eq!(view.selections.ranges(cx), expected_selections);
+
+ view.newline(&Newline, cx);
+ let (expected_text, expected_selections) = marked_text_ranges(
+ indoc! {"
+ aaaa
+ bX
+ ˇbbX
+ b
+ bX
+ ˇbbX
+ ˇb
+ cccc"
+ },
+ false,
+ );
+ assert_eq!(view.text(cx), expected_text);
+ assert_eq!(view.selections.ranges(cx), expected_selections);
+ });
+}
-// // Ensure we don't panic when selections are refreshed and that the pending selection is finalized.
-// editor.change_selections(None, cx, |s| s.refresh());
-// assert_eq!(
-// editor.selections.ranges(cx),
-// [Point::new(0, 3)..Point::new(0, 3)]
-// );
-// assert!(editor.selections.pending_anchor().is_some());
-// });
-// }
+#[gpui::test]
+fn test_refresh_selections(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+
+ let buffer =
+ cx.build_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), sample_text(3, 4, 'a')));
+ let mut excerpt1_id = None;
+ let multibuffer = cx.build_model(|cx| {
+ let mut multibuffer = MultiBuffer::new(0);
+ excerpt1_id = multibuffer
+ .push_excerpts(
+ buffer.clone(),
+ [
+ ExcerptRange {
+ context: Point::new(0, 0)..Point::new(1, 4),
+ primary: None,
+ },
+ ExcerptRange {
+ context: Point::new(1, 0)..Point::new(2, 4),
+ primary: None,
+ },
+ ],
+ cx,
+ )
+ .into_iter()
+ .next();
+ assert_eq!(multibuffer.read(cx).text(), "aaaa\nbbbb\nbbbb\ncccc");
+ multibuffer
+ });
-// #[gpui::test]
-// async fn test_extra_newline_insertion(cx: &mut gpui::TestAppContext) {
-// init_test(cx, |_| {});
+ let editor = cx.add_window(|cx| {
+ let mut editor = build_editor(multibuffer.clone(), cx);
+ let snapshot = editor.snapshot(cx);
+ editor.change_selections(None, cx, |s| {
+ s.select_ranges([Point::new(1, 3)..Point::new(1, 3)])
+ });
+ editor.begin_selection(Point::new(2, 1).to_display_point(&snapshot), true, 1, cx);
+ assert_eq!(
+ editor.selections.ranges(cx),
+ [
+ Point::new(1, 3)..Point::new(1, 3),
+ Point::new(2, 1)..Point::new(2, 1),
+ ]
+ );
+ editor
+ });
-// let language = Arc::new(
-// Language::new(
-// LanguageConfig {
-// brackets: BracketPairConfig {
-// pairs: vec![
-// BracketPair {
-// start: "{".to_string(),
-// end: "}".to_string(),
-// close: true,
-// newline: true,
-// },
-// BracketPair {
-// start: "/* ".to_string(),
-// end: " */".to_string(),
-// close: true,
-// newline: true,
-// },
-// ],
-// ..Default::default()
-// },
-// ..Default::default()
-// },
-// Some(tree_sitter_rust::language()),
-// )
-// .with_indents_query("")
-// .unwrap(),
-// );
+ // Refreshing selections is a no-op when excerpts haven't changed.
+ editor.update(cx, |editor, cx| {
+ editor.change_selections(None, cx, |s| s.refresh());
+ assert_eq!(
+ editor.selections.ranges(cx),
+ [
+ Point::new(1, 3)..Point::new(1, 3),
+ Point::new(2, 1)..Point::new(2, 1),
+ ]
+ );
+ });
-// let text = concat!(
-// "{ }\n", //
-// " x\n", //
-// " /* */\n", //
-// "x\n", //
-// "{{} }\n", //
-// );
+ multibuffer.update(cx, |multibuffer, cx| {
+ multibuffer.remove_excerpts([excerpt1_id.unwrap()], cx);
+ });
+ editor.update(cx, |editor, cx| {
+ // Removing an excerpt causes the first selection to become degenerate.
+ assert_eq!(
+ editor.selections.ranges(cx),
+ [
+ Point::new(0, 0)..Point::new(0, 0),
+ Point::new(0, 1)..Point::new(0, 1)
+ ]
+ );
+
+ // Refreshing selections will relocate the first selection to the original buffer
+ // location.
+ editor.change_selections(None, cx, |s| s.refresh());
+ assert_eq!(
+ editor.selections.ranges(cx),
+ [
+ Point::new(0, 1)..Point::new(0, 1),
+ Point::new(0, 3)..Point::new(0, 3)
+ ]
+ );
+ assert!(editor.selections.pending_anchor().is_some());
+ });
+}
-// let buffer =
-// cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, text).with_language(language, cx));
-// let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
-// let view = cx.add_window(|cx| build_editor(buffer, cx)).root(cx);
-// view.condition(cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
-// .await;
+#[gpui::test]
+fn test_refresh_selections_while_selecting_with_mouse(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+
+ let buffer =
+ cx.build_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), sample_text(3, 4, 'a')));
+ let mut excerpt1_id = None;
+ let multibuffer = cx.build_model(|cx| {
+ let mut multibuffer = MultiBuffer::new(0);
+ excerpt1_id = multibuffer
+ .push_excerpts(
+ buffer.clone(),
+ [
+ ExcerptRange {
+ context: Point::new(0, 0)..Point::new(1, 4),
+ primary: None,
+ },
+ ExcerptRange {
+ context: Point::new(1, 0)..Point::new(2, 4),
+ primary: None,
+ },
+ ],
+ cx,
+ )
+ .into_iter()
+ .next();
+ assert_eq!(multibuffer.read(cx).text(), "aaaa\nbbbb\nbbbb\ncccc");
+ multibuffer
+ });
-// view.update(cx, |view, cx| {
-// view.change_selections(None, cx, |s| {
-// s.select_display_ranges([
-// DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
-// DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
-// DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
-// ])
-// });
-// view.newline(&Newline, cx);
+ let editor = cx.add_window(|cx| {
+ let mut editor = build_editor(multibuffer.clone(), cx);
+ let snapshot = editor.snapshot(cx);
+ editor.begin_selection(Point::new(1, 3).to_display_point(&snapshot), false, 1, cx);
+ assert_eq!(
+ editor.selections.ranges(cx),
+ [Point::new(1, 3)..Point::new(1, 3)]
+ );
+ editor
+ });
-// assert_eq!(
-// view.buffer().read(cx).read(cx).text(),
-// concat!(
-// "{ \n", // Suppress rustfmt
-// "\n", //
-// "}\n", //
-// " x\n", //
-// " /* \n", //
-// " \n", //
-// " */\n", //
-// "x\n", //
-// "{{} \n", //
-// "}\n", //
-// )
-// );
-// });
-// }
+ multibuffer.update(cx, |multibuffer, cx| {
+ multibuffer.remove_excerpts([excerpt1_id.unwrap()], cx);
+ });
+ editor.update(cx, |editor, cx| {
+ assert_eq!(
+ editor.selections.ranges(cx),
+ [Point::new(0, 0)..Point::new(0, 0)]
+ );
+
+ // Ensure we don't panic when selections are refreshed and that the pending selection is finalized.
+ editor.change_selections(None, cx, |s| s.refresh());
+ assert_eq!(
+ editor.selections.ranges(cx),
+ [Point::new(0, 3)..Point::new(0, 3)]
+ );
+ assert!(editor.selections.pending_anchor().is_some());
+ });
+}
+
+#[gpui::test]
+async fn test_extra_newline_insertion(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |_| {});
+
+ let language = Arc::new(
+ Language::new(
+ LanguageConfig {
+ brackets: BracketPairConfig {
+ pairs: vec![
+ BracketPair {
+ start: "{".to_string(),
+ end: "}".to_string(),
+ close: true,
+ newline: true,
+ },
+ BracketPair {
+ start: "/* ".to_string(),
+ end: " */".to_string(),
+ close: true,
+ newline: true,
+ },
+ ],
+ ..Default::default()
+ },
+ ..Default::default()
+ },
+ Some(tree_sitter_rust::language()),
+ )
+ .with_indents_query("")
+ .unwrap(),
+ );
+
+ let text = concat!(
+ "{ }\n", //
+ " x\n", //
+ " /* */\n", //
+ "x\n", //
+ "{{} }\n", //
+ );
+
+ let buffer = cx.build_model(|cx| {
+ Buffer::new(0, cx.entity_id().as_u64(), text).with_language(language, cx)
+ });
+ let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
+ let (view, mut cx) = cx.add_window_view(|cx| build_editor(buffer, cx));
+ let cx = &mut cx;
+ view.condition::<crate::Event>(cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
+ .await;
+
+ view.update(cx, |view, cx| {
+ view.change_selections(None, cx, |s| {
+ s.select_display_ranges([
+ DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
+ DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
+ DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
+ ])
+ });
+ view.newline(&Newline, cx);
+
+ assert_eq!(
+ view.buffer().read(cx).read(cx).text(),
+ concat!(
+ "{ \n", // Suppress rustfmt
+ "\n", //
+ "}\n", //
+ " x\n", //
+ " /* \n", //
+ " \n", //
+ " */\n", //
+ "x\n", //
+ "{{} \n", //
+ "}\n", //
+ )
+ );
+ });
+}
+//todo!(finish editor tests)
// #[gpui::test]
// fn test_highlighted_ranges(cx: &mut TestAppContext) {
// init_test(cx, |_| {});
-// let editor = cx
-// .add_window(|cx| {
-// let buffer = MultiBuffer::build_simple(&sample_text(16, 8, 'a'), cx);
-// build_editor(buffer.clone(), cx)
-// })
-// .root(cx);
+// let editor = cx.add_window(|cx| {
+// let buffer = MultiBuffer::build_simple(&sample_text(16, 8, 'a'), cx);
+// build_editor(buffer.clone(), cx)
+// });
// editor.update(cx, |editor, cx| {
// struct Type1;
@@ -0,0 +1,2868 @@
+pub mod file_associations;
+mod project_panel_settings;
+use settings::Settings;
+
+use db::kvp::KEY_VALUE_STORE;
+use editor::{scroll::autoscroll::Autoscroll, Cancel, Editor};
+use file_associations::FileAssociations;
+
+use anyhow::{anyhow, Result};
+use gpui::{
+ actions, div, px, svg, uniform_list, Action, AppContext, AssetSource, AsyncAppContext,
+ AsyncWindowContext, ClipboardItem, Div, Element, Entity, EventEmitter, FocusEnabled,
+ FocusHandle, Model, ParentElement as _, Pixels, Point, PromptLevel, Render,
+ StatefulInteractive, StatefulInteractivity, Styled, Task, UniformListScrollHandle, View,
+ ViewContext, VisualContext as _, WeakView, WindowContext,
+};
+use menu::{Confirm, SelectNext, SelectPrev};
+use project::{
+ repository::GitFileStatus, Entry, EntryKind, Fs, Project, ProjectEntryId, ProjectPath,
+ Worktree, WorktreeId,
+};
+use project_panel_settings::{ProjectPanelDockPosition, ProjectPanelSettings};
+use serde::{Deserialize, Serialize};
+use smallvec::SmallVec;
+use std::{
+ cmp::Ordering,
+ collections::{hash_map, HashMap},
+ ffi::OsStr,
+ ops::Range,
+ path::Path,
+ sync::Arc,
+};
+use theme::ActiveTheme as _;
+use ui::{h_stack, v_stack};
+use unicase::UniCase;
+use util::TryFutureExt;
+use workspace::{
+ dock::{DockPosition, PanelEvent},
+ Workspace,
+};
+
+const PROJECT_PANEL_KEY: &'static str = "ProjectPanel";
+const NEW_ENTRY_ID: ProjectEntryId = ProjectEntryId::MAX;
+
+pub struct ProjectPanel {
+ project: Model<Project>,
+ fs: Arc<dyn Fs>,
+ list: UniformListScrollHandle,
+ focus_handle: FocusHandle,
+ visible_entries: Vec<(WorktreeId, Vec<Entry>)>,
+ last_worktree_root_id: Option<ProjectEntryId>,
+ expanded_dir_ids: HashMap<WorktreeId, Vec<ProjectEntryId>>,
+ selection: Option<Selection>,
+ edit_state: Option<EditState>,
+ filename_editor: View<Editor>,
+ clipboard_entry: Option<ClipboardEntry>,
+ dragged_entry_destination: Option<Arc<Path>>,
+ workspace: WeakView<Workspace>,
+ has_focus: bool,
+ width: Option<f32>,
+ pending_serialization: Task<Option<()>>,
+}
+
+#[derive(Copy, Clone, Debug)]
+struct Selection {
+ worktree_id: WorktreeId,
+ entry_id: ProjectEntryId,
+}
+
+#[derive(Clone, Debug)]
+struct EditState {
+ worktree_id: WorktreeId,
+ entry_id: ProjectEntryId,
+ is_new_entry: bool,
+ is_dir: bool,
+ processing_filename: Option<String>,
+}
+
+#[derive(Copy, Clone)]
+pub enum ClipboardEntry {
+ Copied {
+ worktree_id: WorktreeId,
+ entry_id: ProjectEntryId,
+ },
+ Cut {
+ worktree_id: WorktreeId,
+ entry_id: ProjectEntryId,
+ },
+}
+
+#[derive(Debug, PartialEq, Eq)]
+pub struct EntryDetails {
+ filename: String,
+ icon: Option<Arc<str>>,
+ path: Arc<Path>,
+ depth: usize,
+ kind: EntryKind,
+ is_ignored: bool,
+ is_expanded: bool,
+ is_selected: bool,
+ is_editing: bool,
+ is_processing: bool,
+ is_cut: bool,
+ git_status: Option<GitFileStatus>,
+}
+
+actions!(
+ ExpandSelectedEntry,
+ CollapseSelectedEntry,
+ CollapseAllEntries,
+ NewDirectory,
+ NewFile,
+ Copy,
+ CopyPath,
+ CopyRelativePath,
+ RevealInFinder,
+ OpenInTerminal,
+ Cut,
+ Paste,
+ Delete,
+ Rename,
+ Open,
+ ToggleFocus,
+ NewSearchInDirectory,
+);
+
+pub fn init_settings(cx: &mut AppContext) {
+ ProjectPanelSettings::register(cx);
+}
+
+pub fn init(assets: impl AssetSource, cx: &mut AppContext) {
+ init_settings(cx);
+ file_associations::init(assets, cx);
+
+ // cx.add_action(ProjectPanel::expand_selected_entry);
+ // cx.add_action(ProjectPanel::collapse_selected_entry);
+ // cx.add_action(ProjectPanel::collapse_all_entries);
+ // cx.add_action(ProjectPanel::select_prev);
+ // cx.add_action(ProjectPanel::select_next);
+ // cx.add_action(ProjectPanel::new_file);
+ // cx.add_action(ProjectPanel::new_directory);
+ // cx.add_action(ProjectPanel::rename);
+ // cx.add_async_action(ProjectPanel::delete);
+ // cx.add_async_action(ProjectPanel::confirm);
+ // cx.add_async_action(ProjectPanel::open_file);
+ // cx.add_action(ProjectPanel::cancel);
+ // cx.add_action(ProjectPanel::cut);
+ // cx.add_action(ProjectPanel::copy);
+ // cx.add_action(ProjectPanel::copy_path);
+ // cx.add_action(ProjectPanel::copy_relative_path);
+ // cx.add_action(ProjectPanel::reveal_in_finder);
+ // cx.add_action(ProjectPanel::open_in_terminal);
+ // cx.add_action(ProjectPanel::new_search_in_directory);
+ // cx.add_action(
+ // |this: &mut ProjectPanel, action: &Paste, cx: &mut ViewContext<ProjectPanel>| {
+ // this.paste(action, cx);
+ // },
+ // );
+}
+
+#[derive(Debug)]
+pub enum Event {
+ OpenedEntry {
+ entry_id: ProjectEntryId,
+ focus_opened_item: bool,
+ },
+ SplitEntry {
+ entry_id: ProjectEntryId,
+ },
+ DockPositionChanged,
+ Focus,
+ NewSearchInDirectory {
+ dir_entry: Entry,
+ },
+ ActivatePanel,
+}
+
+#[derive(Serialize, Deserialize)]
+struct SerializedProjectPanel {
+ width: Option<f32>,
+}
+
+impl ProjectPanel {
+ fn new(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> View<Self> {
+ let project = workspace.project().clone();
+ let project_panel = cx.build_view(|cx: &mut ViewContext<Self>| {
+ cx.observe(&project, |this, _, cx| {
+ this.update_visible_entries(None, cx);
+ cx.notify();
+ })
+ .detach();
+ let focus_handle = cx.focus_handle();
+
+ cx.on_focus(&focus_handle, Self::focus_in).detach();
+ cx.on_blur(&focus_handle, Self::focus_out).detach();
+
+ cx.subscribe(&project, |this, project, event, cx| match event {
+ project::Event::ActiveEntryChanged(Some(entry_id)) => {
+ if let Some(worktree_id) = project.read(cx).worktree_id_for_entry(*entry_id, cx)
+ {
+ this.expand_entry(worktree_id, *entry_id, cx);
+ this.update_visible_entries(Some((worktree_id, *entry_id)), cx);
+ this.autoscroll(cx);
+ cx.notify();
+ }
+ }
+ project::Event::ActivateProjectPanel => {
+ cx.emit(Event::ActivatePanel);
+ }
+ project::Event::WorktreeRemoved(id) => {
+ this.expanded_dir_ids.remove(id);
+ this.update_visible_entries(None, cx);
+ cx.notify();
+ }
+ _ => {}
+ })
+ .detach();
+
+ let filename_editor = cx.build_view(|cx| Editor::single_line(cx));
+
+ cx.subscribe(&filename_editor, |this, _, event, cx| match event {
+ editor::Event::BufferEdited | editor::Event::SelectionsChanged { .. } => {
+ this.autoscroll(cx);
+ }
+ _ => {}
+ })
+ .detach();
+
+ // cx.observe_focus(&filename_editor, |this, _, is_focused, cx| {
+ // if !is_focused
+ // && this
+ // .edit_state
+ // .as_ref()
+ // .map_or(false, |state| state.processing_filename.is_none())
+ // {
+ // this.edit_state = None;
+ // this.update_visible_entries(None, cx);
+ // }
+ // })
+ // .detach();
+
+ // cx.observe_global::<FileAssociations, _>(|_, cx| {
+ // cx.notify();
+ // })
+ // .detach();
+
+ let view_id = cx.view().entity_id();
+ let mut this = Self {
+ project: project.clone(),
+ fs: workspace.app_state().fs.clone(),
+ list: UniformListScrollHandle::new(),
+ focus_handle,
+ visible_entries: Default::default(),
+ last_worktree_root_id: Default::default(),
+ expanded_dir_ids: Default::default(),
+ selection: None,
+ edit_state: None,
+ filename_editor,
+ clipboard_entry: None,
+ // context_menu: cx.add_view(|cx| ContextMenu::new(view_id, cx)),
+ dragged_entry_destination: None,
+ workspace: workspace.weak_handle(),
+ has_focus: false,
+ width: None,
+ pending_serialization: Task::ready(None),
+ };
+ this.update_visible_entries(None, cx);
+
+ // Update the dock position when the setting changes.
+ // todo!()
+ // let mut old_dock_position = this.position(cx);
+ // cx.observe_global::<SettingsStore, _>(move |this, cx| {
+ // let new_dock_position = this.position(cx);
+ // if new_dock_position != old_dock_position {
+ // old_dock_position = new_dock_position;
+ // cx.emit(Event::DockPositionChanged);
+ // }
+ // })
+ // .detach();
+
+ this
+ });
+
+ cx.subscribe(&project_panel, {
+ let project_panel = project_panel.downgrade();
+ move |workspace, _, event, cx| match event {
+ &Event::OpenedEntry {
+ entry_id,
+ focus_opened_item,
+ } => {
+ if let Some(worktree) = project.read(cx).worktree_for_entry(entry_id, cx) {
+ if let Some(entry) = worktree.read(cx).entry_for_id(entry_id) {
+ workspace
+ .open_path(
+ ProjectPath {
+ worktree_id: worktree.read(cx).id(),
+ path: entry.path.clone(),
+ },
+ None,
+ focus_opened_item,
+ cx,
+ )
+ .detach_and_log_err(cx);
+ if !focus_opened_item {
+ if let Some(project_panel) = project_panel.upgrade() {
+ let focus_handle = project_panel.read(cx).focus_handle.clone();
+ cx.focus(&focus_handle);
+ }
+ }
+ }
+ }
+ }
+ &Event::SplitEntry { entry_id } => {
+ // if let Some(worktree) = project.read(cx).worktree_for_entry(entry_id, cx) {
+ // if let Some(entry) = worktree.read(cx).entry_for_id(entry_id) {
+ // workspace
+ // .split_path(
+ // ProjectPath {
+ // worktree_id: worktree.read(cx).id(),
+ // path: entry.path.clone(),
+ // },
+ // cx,
+ // )
+ // .detach_and_log_err(cx);
+ // }
+ // }
+ }
+ _ => {}
+ }
+ })
+ .detach();
+
+ project_panel
+ }
+
+ pub fn load(
+ workspace: WeakView<Workspace>,
+ cx: AsyncWindowContext,
+ ) -> Task<Result<View<Self>>> {
+ cx.spawn(|mut cx| async move {
+ // let serialized_panel = if let Some(panel) = cx
+ // .background_executor()
+ // .spawn(async move { KEY_VALUE_STORE.read_kvp(PROJECT_PANEL_KEY) })
+ // .await
+ // .log_err()
+ // .flatten()
+ // {
+ // Some(serde_json::from_str::<SerializedProjectPanel>(&panel)?)
+ // } else {
+ // None
+ // };
+ workspace.update(&mut cx, |workspace, cx| {
+ let panel = ProjectPanel::new(workspace, cx);
+ // if let Some(serialized_panel) = serialized_panel {
+ // panel.update(cx, |panel, cx| {
+ // panel.width = serialized_panel.width;
+ // cx.notify();
+ // });
+ // }
+ panel
+ })
+ })
+ }
+
+ fn serialize(&mut self, cx: &mut ViewContext<Self>) {
+ let width = self.width;
+ self.pending_serialization = cx.background_executor().spawn(
+ async move {
+ KEY_VALUE_STORE
+ .write_kvp(
+ PROJECT_PANEL_KEY.into(),
+ serde_json::to_string(&SerializedProjectPanel { width })?,
+ )
+ .await?;
+ anyhow::Ok(())
+ }
+ .log_err(),
+ );
+ }
+
+ fn focus_in(&mut self, cx: &mut ViewContext<Self>) {
+ if !self.has_focus {
+ self.has_focus = true;
+ cx.emit(Event::Focus);
+ }
+ }
+
+ fn focus_out(&mut self, _: &mut ViewContext<Self>) {
+ self.has_focus = false;
+ }
+
+ fn deploy_context_menu(
+ &mut self,
+ position: Point<Pixels>,
+ entry_id: ProjectEntryId,
+ cx: &mut ViewContext<Self>,
+ ) {
+ // let project = self.project.read(cx);
+
+ // let worktree_id = if let Some(id) = project.worktree_id_for_entry(entry_id, cx) {
+ // id
+ // } else {
+ // return;
+ // };
+
+ // self.selection = Some(Selection {
+ // worktree_id,
+ // entry_id,
+ // });
+
+ // let mut menu_entries = Vec::new();
+ // if let Some((worktree, entry)) = self.selected_entry(cx) {
+ // let is_root = Some(entry) == worktree.root_entry();
+ // if !project.is_remote() {
+ // menu_entries.push(ContextMenuItem::action(
+ // "Add Folder to Project",
+ // workspace::AddFolderToProject,
+ // ));
+ // if is_root {
+ // let project = self.project.clone();
+ // menu_entries.push(ContextMenuItem::handler("Remove from Project", move |cx| {
+ // project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
+ // }));
+ // }
+ // }
+ // menu_entries.push(ContextMenuItem::action("New File", NewFile));
+ // menu_entries.push(ContextMenuItem::action("New Folder", NewDirectory));
+ // menu_entries.push(ContextMenuItem::Separator);
+ // menu_entries.push(ContextMenuItem::action("Cut", Cut));
+ // menu_entries.push(ContextMenuItem::action("Copy", Copy));
+ // if let Some(clipboard_entry) = self.clipboard_entry {
+ // if clipboard_entry.worktree_id() == worktree.id() {
+ // menu_entries.push(ContextMenuItem::action("Paste", Paste));
+ // }
+ // }
+ // menu_entries.push(ContextMenuItem::Separator);
+ // menu_entries.push(ContextMenuItem::action("Copy Path", CopyPath));
+ // menu_entries.push(ContextMenuItem::action(
+ // "Copy Relative Path",
+ // CopyRelativePath,
+ // ));
+
+ // if entry.is_dir() {
+ // menu_entries.push(ContextMenuItem::Separator);
+ // }
+ // menu_entries.push(ContextMenuItem::action("Reveal in Finder", RevealInFinder));
+ // if entry.is_dir() {
+ // menu_entries.push(ContextMenuItem::action("Open in Terminal", OpenInTerminal));
+ // menu_entries.push(ContextMenuItem::action(
+ // "Search Inside",
+ // NewSearchInDirectory,
+ // ));
+ // }
+
+ // menu_entries.push(ContextMenuItem::Separator);
+ // menu_entries.push(ContextMenuItem::action("Rename", Rename));
+ // if !is_root {
+ // menu_entries.push(ContextMenuItem::action("Delete", Delete));
+ // }
+ // }
+
+ // // self.context_menu.update(cx, |menu, cx| {
+ // // menu.show(position, AnchorCorner::TopLeft, menu_entries, cx);
+ // // });
+
+ // cx.notify();
+ }
+
+ fn expand_selected_entry(&mut self, _: &ExpandSelectedEntry, cx: &mut ViewContext<Self>) {
+ if let Some((worktree, entry)) = self.selected_entry(cx) {
+ if entry.is_dir() {
+ let worktree_id = worktree.id();
+ let entry_id = entry.id;
+ let expanded_dir_ids =
+ if let Some(expanded_dir_ids) = self.expanded_dir_ids.get_mut(&worktree_id) {
+ expanded_dir_ids
+ } else {
+ return;
+ };
+
+ match expanded_dir_ids.binary_search(&entry_id) {
+ Ok(_) => self.select_next(&SelectNext, cx),
+ Err(ix) => {
+ self.project.update(cx, |project, cx| {
+ project.expand_entry(worktree_id, entry_id, cx);
+ });
+
+ expanded_dir_ids.insert(ix, entry_id);
+ self.update_visible_entries(None, cx);
+ cx.notify();
+ }
+ }
+ }
+ }
+ }
+
+ fn collapse_selected_entry(&mut self, _: &CollapseSelectedEntry, cx: &mut ViewContext<Self>) {
+ if let Some((worktree, mut entry)) = self.selected_entry(cx) {
+ let worktree_id = worktree.id();
+ let expanded_dir_ids =
+ if let Some(expanded_dir_ids) = self.expanded_dir_ids.get_mut(&worktree_id) {
+ expanded_dir_ids
+ } else {
+ return;
+ };
+
+ loop {
+ let entry_id = entry.id;
+ match expanded_dir_ids.binary_search(&entry_id) {
+ Ok(ix) => {
+ expanded_dir_ids.remove(ix);
+ self.update_visible_entries(Some((worktree_id, entry_id)), cx);
+ cx.notify();
+ break;
+ }
+ Err(_) => {
+ if let Some(parent_entry) =
+ entry.path.parent().and_then(|p| worktree.entry_for_path(p))
+ {
+ entry = parent_entry;
+ } else {
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ pub fn collapse_all_entries(&mut self, _: &CollapseAllEntries, cx: &mut ViewContext<Self>) {
+ self.expanded_dir_ids.clear();
+ self.update_visible_entries(None, cx);
+ cx.notify();
+ }
+
+ fn toggle_expanded(&mut self, entry_id: ProjectEntryId, cx: &mut ViewContext<Self>) {
+ if let Some(worktree_id) = self.project.read(cx).worktree_id_for_entry(entry_id, cx) {
+ if let Some(expanded_dir_ids) = self.expanded_dir_ids.get_mut(&worktree_id) {
+ self.project.update(cx, |project, cx| {
+ match expanded_dir_ids.binary_search(&entry_id) {
+ Ok(ix) => {
+ expanded_dir_ids.remove(ix);
+ }
+ Err(ix) => {
+ project.expand_entry(worktree_id, entry_id, cx);
+ expanded_dir_ids.insert(ix, entry_id);
+ }
+ }
+ });
+ self.update_visible_entries(Some((worktree_id, entry_id)), cx);
+ cx.focus(&self.focus_handle);
+ cx.notify();
+ }
+ }
+ }
+
+ fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
+ if let Some(selection) = self.selection {
+ let (mut worktree_ix, mut entry_ix, _) =
+ self.index_for_selection(selection).unwrap_or_default();
+ if entry_ix > 0 {
+ entry_ix -= 1;
+ } else if worktree_ix > 0 {
+ worktree_ix -= 1;
+ entry_ix = self.visible_entries[worktree_ix].1.len() - 1;
+ } else {
+ return;
+ }
+
+ let (worktree_id, worktree_entries) = &self.visible_entries[worktree_ix];
+ self.selection = Some(Selection {
+ worktree_id: *worktree_id,
+ entry_id: worktree_entries[entry_ix].id,
+ });
+ self.autoscroll(cx);
+ cx.notify();
+ } else {
+ self.select_first(cx);
+ }
+ }
+
+ fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
+ if let Some(task) = self.confirm_edit(cx) {
+ return Some(task);
+ }
+
+ None
+ }
+
+ fn open_file(&mut self, _: &Open, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
+ if let Some((_, entry)) = self.selected_entry(cx) {
+ if entry.is_file() {
+ self.open_entry(entry.id, true, cx);
+ }
+ }
+
+ None
+ }
+
+ fn confirm_edit(&mut self, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
+ let edit_state = self.edit_state.as_mut()?;
+ cx.focus(&self.focus_handle);
+
+ let worktree_id = edit_state.worktree_id;
+ let is_new_entry = edit_state.is_new_entry;
+ let is_dir = edit_state.is_dir;
+ let worktree = self.project.read(cx).worktree_for_id(worktree_id, cx)?;
+ let entry = worktree.read(cx).entry_for_id(edit_state.entry_id)?.clone();
+ let filename = self.filename_editor.read(cx).text(cx);
+
+ let path_already_exists = |path| worktree.read(cx).entry_for_path(path).is_some();
+ let edit_task;
+ let edited_entry_id;
+ if is_new_entry {
+ self.selection = Some(Selection {
+ worktree_id,
+ entry_id: NEW_ENTRY_ID,
+ });
+ let new_path = entry.path.join(&filename.trim_start_matches("/"));
+ if path_already_exists(new_path.as_path()) {
+ return None;
+ }
+
+ edited_entry_id = NEW_ENTRY_ID;
+ edit_task = self.project.update(cx, |project, cx| {
+ project.create_entry((worktree_id, &new_path), is_dir, cx)
+ })?;
+ } else {
+ let new_path = if let Some(parent) = entry.path.clone().parent() {
+ parent.join(&filename)
+ } else {
+ filename.clone().into()
+ };
+ if path_already_exists(new_path.as_path()) {
+ return None;
+ }
+
+ edited_entry_id = entry.id;
+ edit_task = self.project.update(cx, |project, cx| {
+ project.rename_entry(entry.id, new_path.as_path(), cx)
+ })?;
+ };
+
+ edit_state.processing_filename = Some(filename);
+ cx.notify();
+
+ Some(cx.spawn(|this, mut cx| async move {
+ let new_entry = edit_task.await;
+ this.update(&mut cx, |this, cx| {
+ this.edit_state.take();
+ cx.notify();
+ })?;
+
+ let new_entry = new_entry?;
+ this.update(&mut cx, |this, cx| {
+ if let Some(selection) = &mut this.selection {
+ if selection.entry_id == edited_entry_id {
+ selection.worktree_id = worktree_id;
+ selection.entry_id = new_entry.id;
+ this.expand_to_selection(cx);
+ }
+ }
+ this.update_visible_entries(None, cx);
+ if is_new_entry && !is_dir {
+ this.open_entry(new_entry.id, true, cx);
+ }
+ cx.notify();
+ })?;
+ Ok(())
+ }))
+ }
+
+ fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
+ self.edit_state = None;
+ self.update_visible_entries(None, cx);
+ cx.focus(&self.focus_handle);
+ cx.notify();
+ }
+
+ fn open_entry(
+ &mut self,
+ entry_id: ProjectEntryId,
+ focus_opened_item: bool,
+ cx: &mut ViewContext<Self>,
+ ) {
+ cx.emit(Event::OpenedEntry {
+ entry_id,
+ focus_opened_item,
+ });
+ }
+
+ fn split_entry(&mut self, entry_id: ProjectEntryId, cx: &mut ViewContext<Self>) {
+ cx.emit(Event::SplitEntry { entry_id });
+ }
+
+ fn new_file(&mut self, _: &NewFile, cx: &mut ViewContext<Self>) {
+ self.add_entry(false, cx)
+ }
+
+ fn new_directory(&mut self, _: &NewDirectory, cx: &mut ViewContext<Self>) {
+ self.add_entry(true, cx)
+ }
+
+ fn add_entry(&mut self, is_dir: bool, cx: &mut ViewContext<Self>) {
+ if let Some(Selection {
+ worktree_id,
+ entry_id,
+ }) = self.selection
+ {
+ let directory_id;
+ if let Some((worktree, expanded_dir_ids)) = self
+ .project
+ .read(cx)
+ .worktree_for_id(worktree_id, cx)
+ .zip(self.expanded_dir_ids.get_mut(&worktree_id))
+ {
+ let worktree = worktree.read(cx);
+ if let Some(mut entry) = worktree.entry_for_id(entry_id) {
+ loop {
+ if entry.is_dir() {
+ if let Err(ix) = expanded_dir_ids.binary_search(&entry.id) {
+ expanded_dir_ids.insert(ix, entry.id);
+ }
+ directory_id = entry.id;
+ break;
+ } else {
+ if let Some(parent_path) = entry.path.parent() {
+ if let Some(parent_entry) = worktree.entry_for_path(parent_path) {
+ entry = parent_entry;
+ continue;
+ }
+ }
+ return;
+ }
+ }
+ } else {
+ return;
+ };
+ } else {
+ return;
+ };
+
+ self.edit_state = Some(EditState {
+ worktree_id,
+ entry_id: directory_id,
+ is_new_entry: true,
+ is_dir,
+ processing_filename: None,
+ });
+ self.filename_editor.update(cx, |editor, cx| {
+ editor.clear(cx);
+ editor.focus(cx);
+ });
+ self.update_visible_entries(Some((worktree_id, NEW_ENTRY_ID)), cx);
+ self.autoscroll(cx);
+ cx.notify();
+ }
+ }
+
+ fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) {
+ if let Some(Selection {
+ worktree_id,
+ entry_id,
+ }) = self.selection
+ {
+ if let Some(worktree) = self.project.read(cx).worktree_for_id(worktree_id, cx) {
+ if let Some(entry) = worktree.read(cx).entry_for_id(entry_id) {
+ self.edit_state = Some(EditState {
+ worktree_id,
+ entry_id,
+ is_new_entry: false,
+ is_dir: entry.is_dir(),
+ processing_filename: None,
+ });
+ let file_name = entry
+ .path
+ .file_name()
+ .map(|s| s.to_string_lossy())
+ .unwrap_or_default()
+ .to_string();
+ let file_stem = entry.path.file_stem().map(|s| s.to_string_lossy());
+ let selection_end =
+ file_stem.map_or(file_name.len(), |file_stem| file_stem.len());
+ self.filename_editor.update(cx, |editor, cx| {
+ editor.set_text(file_name, cx);
+ editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
+ s.select_ranges([0..selection_end])
+ });
+ editor.focus(cx);
+ });
+ self.update_visible_entries(None, cx);
+ self.autoscroll(cx);
+ cx.notify();
+ }
+ }
+
+ // cx.update_global(|drag_and_drop: &mut DragAndDrop<Workspace>, cx| {
+ // drag_and_drop.cancel_dragging::<ProjectEntryId>(cx);
+ // })
+ }
+ }
+
+ fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
+ let Selection { entry_id, .. } = self.selection?;
+ let path = self.project.read(cx).path_for_entry(entry_id, cx)?.path;
+ let file_name = path.file_name()?;
+
+ let mut answer = cx.prompt(
+ PromptLevel::Info,
+ &format!("Delete {file_name:?}?"),
+ &["Delete", "Cancel"],
+ );
+ Some(cx.spawn(|this, mut cx| async move {
+ if answer.await != Ok(0) {
+ return Ok(());
+ }
+ this.update(&mut cx, |this, cx| {
+ this.project
+ .update(cx, |project, cx| project.delete_entry(entry_id, cx))
+ .ok_or_else(|| anyhow!("no such entry"))
+ })??
+ .await
+ }))
+ }
+
+ fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
+ if let Some(selection) = self.selection {
+ let (mut worktree_ix, mut entry_ix, _) =
+ self.index_for_selection(selection).unwrap_or_default();
+ if let Some((_, worktree_entries)) = self.visible_entries.get(worktree_ix) {
+ if entry_ix + 1 < worktree_entries.len() {
+ entry_ix += 1;
+ } else {
+ worktree_ix += 1;
+ entry_ix = 0;
+ }
+ }
+
+ if let Some((worktree_id, worktree_entries)) = self.visible_entries.get(worktree_ix) {
+ if let Some(entry) = worktree_entries.get(entry_ix) {
+ self.selection = Some(Selection {
+ worktree_id: *worktree_id,
+ entry_id: entry.id,
+ });
+ self.autoscroll(cx);
+ cx.notify();
+ }
+ }
+ } else {
+ self.select_first(cx);
+ }
+ }
+
+ fn select_first(&mut self, cx: &mut ViewContext<Self>) {
+ let worktree = self
+ .visible_entries
+ .first()
+ .and_then(|(worktree_id, _)| self.project.read(cx).worktree_for_id(*worktree_id, cx));
+ if let Some(worktree) = worktree {
+ let worktree = worktree.read(cx);
+ let worktree_id = worktree.id();
+ if let Some(root_entry) = worktree.root_entry() {
+ self.selection = Some(Selection {
+ worktree_id,
+ entry_id: root_entry.id,
+ });
+ self.autoscroll(cx);
+ cx.notify();
+ }
+ }
+ }
+
+ fn autoscroll(&mut self, cx: &mut ViewContext<Self>) {
+ if let Some((_, _, index)) = self.selection.and_then(|s| self.index_for_selection(s)) {
+ self.list.scroll_to_item(index);
+ cx.notify();
+ }
+ }
+
+ fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
+ if let Some((worktree, entry)) = self.selected_entry(cx) {
+ self.clipboard_entry = Some(ClipboardEntry::Cut {
+ worktree_id: worktree.id(),
+ entry_id: entry.id,
+ });
+ cx.notify();
+ }
+ }
+
+ fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
+ if let Some((worktree, entry)) = self.selected_entry(cx) {
+ self.clipboard_entry = Some(ClipboardEntry::Copied {
+ worktree_id: worktree.id(),
+ entry_id: entry.id,
+ });
+ cx.notify();
+ }
+ }
+
+ fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) -> Option<()> {
+ if let Some((worktree, entry)) = self.selected_entry(cx) {
+ let clipboard_entry = self.clipboard_entry?;
+ if clipboard_entry.worktree_id() != worktree.id() {
+ return None;
+ }
+
+ let clipboard_entry_file_name = self
+ .project
+ .read(cx)
+ .path_for_entry(clipboard_entry.entry_id(), cx)?
+ .path
+ .file_name()?
+ .to_os_string();
+
+ let mut new_path = entry.path.to_path_buf();
+ if entry.is_file() {
+ new_path.pop();
+ }
+
+ new_path.push(&clipboard_entry_file_name);
+ let extension = new_path.extension().map(|e| e.to_os_string());
+ let file_name_without_extension = Path::new(&clipboard_entry_file_name).file_stem()?;
+ let mut ix = 0;
+ while worktree.entry_for_path(&new_path).is_some() {
+ new_path.pop();
+
+ let mut new_file_name = file_name_without_extension.to_os_string();
+ new_file_name.push(" copy");
+ if ix > 0 {
+ new_file_name.push(format!(" {}", ix));
+ }
+ if let Some(extension) = extension.as_ref() {
+ new_file_name.push(".");
+ new_file_name.push(extension);
+ }
+
+ new_path.push(new_file_name);
+ ix += 1;
+ }
+
+ if clipboard_entry.is_cut() {
+ if let Some(task) = self.project.update(cx, |project, cx| {
+ project.rename_entry(clipboard_entry.entry_id(), new_path, cx)
+ }) {
+ task.detach_and_log_err(cx)
+ }
+ } else if let Some(task) = self.project.update(cx, |project, cx| {
+ project.copy_entry(clipboard_entry.entry_id(), new_path, cx)
+ }) {
+ task.detach_and_log_err(cx)
+ }
+ }
+ None
+ }
+
+ fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
+ if let Some((worktree, entry)) = self.selected_entry(cx) {
+ cx.write_to_clipboard(ClipboardItem::new(
+ worktree
+ .abs_path()
+ .join(&entry.path)
+ .to_string_lossy()
+ .to_string(),
+ ));
+ }
+ }
+
+ fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
+ if let Some((_, entry)) = self.selected_entry(cx) {
+ cx.write_to_clipboard(ClipboardItem::new(entry.path.to_string_lossy().to_string()));
+ }
+ }
+
+ fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
+ if let Some((worktree, entry)) = self.selected_entry(cx) {
+ cx.reveal_path(&worktree.abs_path().join(&entry.path));
+ }
+ }
+
+ fn open_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
+ todo!()
+ // if let Some((worktree, entry)) = self.selected_entry(cx) {
+ // let window = cx.window();
+ // let view_id = cx.view_id();
+ // let path = worktree.abs_path().join(&entry.path);
+
+ // cx.app_context()
+ // .spawn(|mut cx| async move {
+ // window.dispatch_action(
+ // view_id,
+ // &workspace::OpenTerminal {
+ // working_directory: path,
+ // },
+ // &mut cx,
+ // );
+ // })
+ // .detach();
+ // }
+ }
+
+ pub fn new_search_in_directory(
+ &mut self,
+ _: &NewSearchInDirectory,
+ cx: &mut ViewContext<Self>,
+ ) {
+ if let Some((_, entry)) = self.selected_entry(cx) {
+ if entry.is_dir() {
+ cx.emit(Event::NewSearchInDirectory {
+ dir_entry: entry.clone(),
+ });
+ }
+ }
+ }
+
+ fn move_entry(
+ &mut self,
+ entry_to_move: ProjectEntryId,
+ destination: ProjectEntryId,
+ destination_is_file: bool,
+ cx: &mut ViewContext<Self>,
+ ) {
+ let destination_worktree = self.project.update(cx, |project, cx| {
+ let entry_path = project.path_for_entry(entry_to_move, cx)?;
+ let destination_entry_path = project.path_for_entry(destination, cx)?.path.clone();
+
+ let mut destination_path = destination_entry_path.as_ref();
+ if destination_is_file {
+ destination_path = destination_path.parent()?;
+ }
+
+ let mut new_path = destination_path.to_path_buf();
+ new_path.push(entry_path.path.file_name()?);
+ if new_path != entry_path.path.as_ref() {
+ let task = project.rename_entry(entry_to_move, new_path, cx)?;
+ cx.foreground_executor().spawn(task).detach_and_log_err(cx);
+ }
+
+ Some(project.worktree_id_for_entry(destination, cx)?)
+ });
+
+ if let Some(destination_worktree) = destination_worktree {
+ self.expand_entry(destination_worktree, destination, cx);
+ }
+ }
+
+ fn index_for_selection(&self, selection: Selection) -> Option<(usize, usize, usize)> {
+ let mut entry_index = 0;
+ let mut visible_entries_index = 0;
+ for (worktree_index, (worktree_id, worktree_entries)) in
+ self.visible_entries.iter().enumerate()
+ {
+ if *worktree_id == selection.worktree_id {
+ for entry in worktree_entries {
+ if entry.id == selection.entry_id {
+ return Some((worktree_index, entry_index, visible_entries_index));
+ } else {
+ visible_entries_index += 1;
+ entry_index += 1;
+ }
+ }
+ break;
+ } else {
+ visible_entries_index += worktree_entries.len();
+ }
+ }
+ None
+ }
+
+ pub fn selected_entry<'a>(
+ &self,
+ cx: &'a AppContext,
+ ) -> Option<(&'a Worktree, &'a project::Entry)> {
+ let (worktree, entry) = self.selected_entry_handle(cx)?;
+ Some((worktree.read(cx), entry))
+ }
+
+ fn selected_entry_handle<'a>(
+ &self,
+ cx: &'a AppContext,
+ ) -> Option<(Model<Worktree>, &'a project::Entry)> {
+ let selection = self.selection?;
+ let project = self.project.read(cx);
+ let worktree = project.worktree_for_id(selection.worktree_id, cx)?;
+ let entry = worktree.read(cx).entry_for_id(selection.entry_id)?;
+ Some((worktree, entry))
+ }
+
+ fn expand_to_selection(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
+ let (worktree, entry) = self.selected_entry(cx)?;
+ let expanded_dir_ids = self.expanded_dir_ids.entry(worktree.id()).or_default();
+
+ for path in entry.path.ancestors() {
+ let Some(entry) = worktree.entry_for_path(path) else {
+ continue;
+ };
+ if entry.is_dir() {
+ if let Err(idx) = expanded_dir_ids.binary_search(&entry.id) {
+ expanded_dir_ids.insert(idx, entry.id);
+ }
+ }
+ }
+
+ Some(())
+ }
+
+ fn update_visible_entries(
+ &mut self,
+ new_selected_entry: Option<(WorktreeId, ProjectEntryId)>,
+ cx: &mut ViewContext<Self>,
+ ) {
+ let project = self.project.read(cx);
+ self.last_worktree_root_id = project
+ .visible_worktrees(cx)
+ .rev()
+ .next()
+ .and_then(|worktree| worktree.read(cx).root_entry())
+ .map(|entry| entry.id);
+
+ self.visible_entries.clear();
+ for worktree in project.visible_worktrees(cx) {
+ let snapshot = worktree.read(cx).snapshot();
+ let worktree_id = snapshot.id();
+
+ let expanded_dir_ids = match self.expanded_dir_ids.entry(worktree_id) {
+ hash_map::Entry::Occupied(e) => e.into_mut(),
+ hash_map::Entry::Vacant(e) => {
+ // The first time a worktree's root entry becomes available,
+ // mark that root entry as expanded.
+ if let Some(entry) = snapshot.root_entry() {
+ e.insert(vec![entry.id]).as_slice()
+ } else {
+ &[]
+ }
+ }
+ };
+
+ let mut new_entry_parent_id = None;
+ let mut new_entry_kind = EntryKind::Dir;
+ if let Some(edit_state) = &self.edit_state {
+ if edit_state.worktree_id == worktree_id && edit_state.is_new_entry {
+ new_entry_parent_id = Some(edit_state.entry_id);
+ new_entry_kind = if edit_state.is_dir {
+ EntryKind::Dir
+ } else {
+ EntryKind::File(Default::default())
+ };
+ }
+ }
+
+ let mut visible_worktree_entries = Vec::new();
+ let mut entry_iter = snapshot.entries(true);
+
+ while let Some(entry) = entry_iter.entry() {
+ visible_worktree_entries.push(entry.clone());
+ if Some(entry.id) == new_entry_parent_id {
+ visible_worktree_entries.push(Entry {
+ id: NEW_ENTRY_ID,
+ kind: new_entry_kind,
+ path: entry.path.join("\0").into(),
+ inode: 0,
+ mtime: entry.mtime,
+ is_symlink: false,
+ is_ignored: false,
+ is_external: false,
+ git_status: entry.git_status,
+ });
+ }
+ if expanded_dir_ids.binary_search(&entry.id).is_err()
+ && entry_iter.advance_to_sibling()
+ {
+ continue;
+ }
+ entry_iter.advance();
+ }
+
+ snapshot.propagate_git_statuses(&mut visible_worktree_entries);
+
+ visible_worktree_entries.sort_by(|entry_a, entry_b| {
+ let mut components_a = entry_a.path.components().peekable();
+ let mut components_b = entry_b.path.components().peekable();
+ loop {
+ match (components_a.next(), components_b.next()) {
+ (Some(component_a), Some(component_b)) => {
+ let a_is_file = components_a.peek().is_none() && entry_a.is_file();
+ let b_is_file = components_b.peek().is_none() && entry_b.is_file();
+ let ordering = a_is_file.cmp(&b_is_file).then_with(|| {
+ let name_a =
+ UniCase::new(component_a.as_os_str().to_string_lossy());
+ let name_b =
+ UniCase::new(component_b.as_os_str().to_string_lossy());
+ name_a.cmp(&name_b)
+ });
+ if !ordering.is_eq() {
+ return ordering;
+ }
+ }
+ (Some(_), None) => break Ordering::Greater,
+ (None, Some(_)) => break Ordering::Less,
+ (None, None) => break Ordering::Equal,
+ }
+ }
+ });
+ self.visible_entries
+ .push((worktree_id, visible_worktree_entries));
+ }
+
+ if let Some((worktree_id, entry_id)) = new_selected_entry {
+ self.selection = Some(Selection {
+ worktree_id,
+ entry_id,
+ });
+ }
+ }
+
+ fn expand_entry(
+ &mut self,
+ worktree_id: WorktreeId,
+ entry_id: ProjectEntryId,
+ cx: &mut ViewContext<Self>,
+ ) {
+ self.project.update(cx, |project, cx| {
+ if let Some((worktree, expanded_dir_ids)) = project
+ .worktree_for_id(worktree_id, cx)
+ .zip(self.expanded_dir_ids.get_mut(&worktree_id))
+ {
+ project.expand_entry(worktree_id, entry_id, cx);
+ let worktree = worktree.read(cx);
+
+ if let Some(mut entry) = worktree.entry_for_id(entry_id) {
+ loop {
+ if let Err(ix) = expanded_dir_ids.binary_search(&entry.id) {
+ expanded_dir_ids.insert(ix, entry.id);
+ }
+
+ if let Some(parent_entry) =
+ entry.path.parent().and_then(|p| worktree.entry_for_path(p))
+ {
+ entry = parent_entry;
+ } else {
+ break;
+ }
+ }
+ }
+ }
+ });
+ }
+
+ fn for_each_visible_entry(
+ &self,
+ range: Range<usize>,
+ cx: &mut ViewContext<ProjectPanel>,
+ mut callback: impl FnMut(ProjectEntryId, EntryDetails, &mut ViewContext<ProjectPanel>),
+ ) {
+ let mut ix = 0;
+ for (worktree_id, visible_worktree_entries) in &self.visible_entries {
+ if ix >= range.end {
+ return;
+ }
+
+ if ix + visible_worktree_entries.len() <= range.start {
+ ix += visible_worktree_entries.len();
+ continue;
+ }
+
+ let end_ix = range.end.min(ix + visible_worktree_entries.len());
+ let (git_status_setting, show_file_icons, show_folder_icons) = {
+ let settings = ProjectPanelSettings::get_global(cx);
+ (
+ settings.git_status,
+ settings.file_icons,
+ settings.folder_icons,
+ )
+ };
+ if let Some(worktree) = self.project.read(cx).worktree_for_id(*worktree_id, cx) {
+ let snapshot = worktree.read(cx).snapshot();
+ let root_name = OsStr::new(snapshot.root_name());
+ let expanded_entry_ids = self
+ .expanded_dir_ids
+ .get(&snapshot.id())
+ .map(Vec::as_slice)
+ .unwrap_or(&[]);
+
+ let entry_range = range.start.saturating_sub(ix)..end_ix - ix;
+ for entry in visible_worktree_entries[entry_range].iter() {
+ let status = git_status_setting.then(|| entry.git_status).flatten();
+ let is_expanded = expanded_entry_ids.binary_search(&entry.id).is_ok();
+ let icon = match entry.kind {
+ EntryKind::File(_) => {
+ if show_file_icons {
+ Some(FileAssociations::get_icon(&entry.path, cx))
+ } else {
+ None
+ }
+ }
+ _ => {
+ if show_folder_icons {
+ Some(FileAssociations::get_folder_icon(is_expanded, cx))
+ } else {
+ Some(FileAssociations::get_chevron_icon(is_expanded, cx))
+ }
+ }
+ };
+
+ let mut details = EntryDetails {
+ filename: entry
+ .path
+ .file_name()
+ .unwrap_or(root_name)
+ .to_string_lossy()
+ .to_string(),
+ icon,
+ path: entry.path.clone(),
+ depth: entry.path.components().count(),
+ kind: entry.kind,
+ is_ignored: entry.is_ignored,
+ is_expanded,
+ is_selected: self.selection.map_or(false, |e| {
+ e.worktree_id == snapshot.id() && e.entry_id == entry.id
+ }),
+ is_editing: false,
+ is_processing: false,
+ is_cut: self
+ .clipboard_entry
+ .map_or(false, |e| e.is_cut() && e.entry_id() == entry.id),
+ git_status: status,
+ };
+
+ if let Some(edit_state) = &self.edit_state {
+ let is_edited_entry = if edit_state.is_new_entry {
+ entry.id == NEW_ENTRY_ID
+ } else {
+ entry.id == edit_state.entry_id
+ };
+
+ if is_edited_entry {
+ if let Some(processing_filename) = &edit_state.processing_filename {
+ details.is_processing = true;
+ details.filename.clear();
+ details.filename.push_str(processing_filename);
+ } else {
+ if edit_state.is_new_entry {
+ details.filename.clear();
+ }
+ details.is_editing = true;
+ }
+ }
+ }
+
+ callback(entry.id, details, cx);
+ }
+ }
+ ix = end_ix;
+ }
+ }
+
+ fn render_entry_visual_element(
+ details: &EntryDetails,
+ editor: Option<&View<Editor>>,
+ padding: Pixels,
+ cx: &mut ViewContext<Self>,
+ ) -> Div<Self> {
+ let show_editor = details.is_editing && !details.is_processing;
+
+ let theme = cx.theme();
+ let filename_text_color = details
+ .git_status
+ .as_ref()
+ .map(|status| match status {
+ GitFileStatus::Added => theme.styles.status.created,
+ GitFileStatus::Modified => theme.styles.status.modified,
+ GitFileStatus::Conflict => theme.styles.status.conflict,
+ })
+ .unwrap_or(theme.styles.status.info);
+
+ h_stack()
+ .child(if let Some(icon) = &details.icon {
+ div().child(svg().path(icon.to_string()))
+ } else {
+ div()
+ })
+ .child(
+ if let (Some(editor), true) = (editor, show_editor) {
+ div().child(editor.clone())
+ } else {
+ div().child(details.filename.clone())
+ }
+ .ml_1(),
+ )
+ .pl(padding)
+ }
+
+ fn render_entry(
+ entry_id: ProjectEntryId,
+ details: EntryDetails,
+ editor: &View<Editor>,
+ // dragged_entry_destination: &mut Option<Arc<Path>>,
+ // theme: &theme::ProjectPanel,
+ cx: &mut ViewContext<Self>,
+ ) -> Div<Self, StatefulInteractivity<Self>> {
+ let kind = details.kind;
+ let settings = ProjectPanelSettings::get_global(cx);
+ const INDENT_SIZE: Pixels = px(16.0);
+ let padding = INDENT_SIZE + details.depth as f32 * px(settings.indent_size);
+ let show_editor = details.is_editing && !details.is_processing;
+
+ Self::render_entry_visual_element(&details, Some(editor), padding, cx)
+ .id(entry_id.to_proto() as usize)
+ .on_click(move |this, event, cx| {
+ if !show_editor {
+ if kind.is_dir() {
+ this.toggle_expanded(entry_id, cx);
+ } else {
+ if event.down.modifiers.command {
+ this.split_entry(entry_id, cx);
+ } else {
+ this.open_entry(entry_id, event.up.click_count > 1, cx);
+ }
+ }
+ }
+ })
+ // .on_down(MouseButton::Right, move |event, this, cx| {
+ // this.deploy_context_menu(event.position, entry_id, cx);
+ // })
+ // .on_up(MouseButton::Left, move |_, this, cx| {
+ // if let Some((_, dragged_entry)) = cx
+ // .global::<DragAndDrop<Workspace>>()
+ // .currently_dragged::<ProjectEntryId>(cx.window())
+ // {
+ // this.move_entry(
+ // *dragged_entry,
+ // entry_id,
+ // matches!(details.kind, EntryKind::File(_)),
+ // cx,
+ // );
+ // }
+ // })
+ }
+}
+
+impl Render for ProjectPanel {
+ type Element = Div<Self, StatefulInteractivity<Self>, FocusEnabled<Self>>;
+
+ fn render(&mut self, cx: &mut gpui::ViewContext<Self>) -> Self::Element {
+ enum ProjectPanel {}
+ let theme = cx.theme();
+ let last_worktree_root_id = self.last_worktree_root_id;
+
+ let has_worktree = self.visible_entries.len() != 0;
+
+ if has_worktree {
+ div()
+ .id("project-panel")
+ .track_focus(&self.focus_handle)
+ .child(
+ uniform_list(
+ "entries",
+ self.visible_entries
+ .iter()
+ .map(|(_, worktree_entries)| worktree_entries.len())
+ .sum(),
+ |this: &mut Self, range, cx| {
+ let mut items = SmallVec::new();
+ this.for_each_visible_entry(range, cx, |id, details, cx| {
+ items.push(Self::render_entry(
+ id,
+ details,
+ &this.filename_editor,
+ // &mut dragged_entry_destination,
+ cx,
+ ));
+ });
+ items
+ },
+ )
+ .track_scroll(self.list.clone()),
+ )
+ } else {
+ v_stack()
+ .id("empty-project_panel")
+ .track_focus(&self.focus_handle)
+ }
+ }
+}
+
+impl EventEmitter<Event> for ProjectPanel {}
+
+impl EventEmitter<PanelEvent> for ProjectPanel {}
+
+impl workspace::dock::Panel for ProjectPanel {
+ fn position(&self, cx: &WindowContext) -> DockPosition {
+ match ProjectPanelSettings::get_global(cx).dock {
+ ProjectPanelDockPosition::Left => DockPosition::Left,
+ ProjectPanelDockPosition::Right => DockPosition::Right,
+ }
+ }
+
+ fn position_is_valid(&self, position: DockPosition) -> bool {
+ matches!(position, DockPosition::Left | DockPosition::Right)
+ }
+
+ fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
+ settings::update_settings_file::<ProjectPanelSettings>(
+ self.fs.clone(),
+ cx,
+ move |settings| {
+ let dock = match position {
+ DockPosition::Left | DockPosition::Bottom => ProjectPanelDockPosition::Left,
+ DockPosition::Right => ProjectPanelDockPosition::Right,
+ };
+ settings.dock = Some(dock);
+ },
+ );
+ }
+
+ fn size(&self, cx: &WindowContext) -> f32 {
+ self.width
+ .unwrap_or_else(|| ProjectPanelSettings::get_global(cx).default_width)
+ }
+
+ fn set_size(&mut self, size: Option<f32>, cx: &mut ViewContext<Self>) {
+ self.width = size;
+ self.serialize(cx);
+ cx.notify();
+ }
+
+ fn icon_path(&self, _: &WindowContext) -> Option<&'static str> {
+ Some("icons/project.svg")
+ }
+
+ fn icon_tooltip(&self) -> (String, Option<Box<dyn Action>>) {
+ ("Project Panel".into(), Some(Box::new(ToggleFocus)))
+ }
+
+ // fn should_change_position_on_event(event: &Self::Event) -> bool {
+ // matches!(event, Event::DockPositionChanged)
+ // }
+
+ fn has_focus(&self, _: &WindowContext) -> bool {
+ self.has_focus
+ }
+
+ fn persistent_name(&self) -> &'static str {
+ "Project Panel"
+ }
+
+ fn focus_handle(&self, _cx: &WindowContext) -> FocusHandle {
+ self.focus_handle.clone()
+ }
+
+ // fn is_focus_event(event: &Self::Event) -> bool {
+ // matches!(event, Event::Focus)
+ // }
+}
+
+impl ClipboardEntry {
+ fn is_cut(&self) -> bool {
+ matches!(self, Self::Cut { .. })
+ }
+
+ fn entry_id(&self) -> ProjectEntryId {
+ match self {
+ ClipboardEntry::Copied { entry_id, .. } | ClipboardEntry::Cut { entry_id, .. } => {
+ *entry_id
+ }
+ }
+ }
+
+ fn worktree_id(&self) -> WorktreeId {
+ match self {
+ ClipboardEntry::Copied { worktree_id, .. }
+ | ClipboardEntry::Cut { worktree_id, .. } => *worktree_id,
+ }
+ }
+}
+
+// todo!()
+// #[cfg(test)]
+// mod tests {
+// use super::*;
+// use gpui::{AnyWindowHandle, TestAppContext, View, WindowHandle};
+// use pretty_assertions::assert_eq;
+// use project::FakeFs;
+// use serde_json::json;
+// use settings::SettingsStore;
+// use std::{
+// collections::HashSet,
+// path::{Path, PathBuf},
+// sync::atomic::{self, AtomicUsize},
+// };
+// use workspace::{pane, AppState};
+
+// #[gpui::test]
+// async fn test_visible_list(cx: &mut gpui::TestAppContext) {
+// init_test(cx);
+
+// let fs = FakeFs::new(cx.executor().clone());
+// fs.insert_tree(
+// "/root1",
+// json!({
+// ".dockerignore": "",
+// ".git": {
+// "HEAD": "",
+// },
+// "a": {
+// "0": { "q": "", "r": "", "s": "" },
+// "1": { "t": "", "u": "" },
+// "2": { "v": "", "w": "", "x": "", "y": "" },
+// },
+// "b": {
+// "3": { "Q": "" },
+// "4": { "R": "", "S": "", "T": "", "U": "" },
+// },
+// "C": {
+// "5": {},
+// "6": { "V": "", "W": "" },
+// "7": { "X": "" },
+// "8": { "Y": {}, "Z": "" }
+// }
+// }),
+// )
+// .await;
+// fs.insert_tree(
+// "/root2",
+// json!({
+// "d": {
+// "9": ""
+// },
+// "e": {}
+// }),
+// )
+// .await;
+
+// let project = Project::test(fs.clone(), ["/root1".as_ref(), "/root2".as_ref()], cx).await;
+// let workspace = cx
+// .add_window(|cx| Workspace::test_new(project.clone(), cx))
+// .root(cx);
+// let panel = workspace.update(cx, |workspace, cx| ProjectPanel::new(workspace, cx));
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..50, cx),
+// &[
+// "v root1",
+// " > .git",
+// " > a",
+// " > b",
+// " > C",
+// " .dockerignore",
+// "v root2",
+// " > d",
+// " > e",
+// ]
+// );
+
+// toggle_expand_dir(&panel, "root1/b", cx);
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..50, cx),
+// &[
+// "v root1",
+// " > .git",
+// " > a",
+// " v b <== selected",
+// " > 3",
+// " > 4",
+// " > C",
+// " .dockerignore",
+// "v root2",
+// " > d",
+// " > e",
+// ]
+// );
+
+// assert_eq!(
+// visible_entries_as_strings(&panel, 6..9, cx),
+// &[
+// //
+// " > C",
+// " .dockerignore",
+// "v root2",
+// ]
+// );
+// }
+
+// #[gpui::test(iterations = 30)]
+// async fn test_editing_files(cx: &mut gpui::TestAppContext) {
+// init_test(cx);
+
+// let fs = FakeFs::new(cx.background());
+// fs.insert_tree(
+// "/root1",
+// json!({
+// ".dockerignore": "",
+// ".git": {
+// "HEAD": "",
+// },
+// "a": {
+// "0": { "q": "", "r": "", "s": "" },
+// "1": { "t": "", "u": "" },
+// "2": { "v": "", "w": "", "x": "", "y": "" },
+// },
+// "b": {
+// "3": { "Q": "" },
+// "4": { "R": "", "S": "", "T": "", "U": "" },
+// },
+// "C": {
+// "5": {},
+// "6": { "V": "", "W": "" },
+// "7": { "X": "" },
+// "8": { "Y": {}, "Z": "" }
+// }
+// }),
+// )
+// .await;
+// fs.insert_tree(
+// "/root2",
+// json!({
+// "d": {
+// "9": ""
+// },
+// "e": {}
+// }),
+// )
+// .await;
+
+// let project = Project::test(fs.clone(), ["/root1".as_ref(), "/root2".as_ref()], cx).await;
+// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
+// let workspace = window.root(cx);
+// let panel = workspace.update(cx, |workspace, cx| ProjectPanel::new(workspace, cx));
+
+// select_path(&panel, "root1", cx);
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v root1 <== selected",
+// " > .git",
+// " > a",
+// " > b",
+// " > C",
+// " .dockerignore",
+// "v root2",
+// " > d",
+// " > e",
+// ]
+// );
+
+// // Add a file with the root folder selected. The filename editor is placed
+// // before the first file in the root folder.
+// panel.update(cx, |panel, cx| panel.new_file(&NewFile, cx));
+// window.read_with(cx, |cx| {
+// let panel = panel.read(cx);
+// assert!(panel.filename_editor.is_focused(cx));
+// });
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v root1",
+// " > .git",
+// " > a",
+// " > b",
+// " > C",
+// " [EDITOR: ''] <== selected",
+// " .dockerignore",
+// "v root2",
+// " > d",
+// " > e",
+// ]
+// );
+
+// let confirm = panel.update(cx, |panel, cx| {
+// panel
+// .filename_editor
+// .update(cx, |editor, cx| editor.set_text("the-new-filename", cx));
+// panel.confirm(&Confirm, cx).unwrap()
+// });
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v root1",
+// " > .git",
+// " > a",
+// " > b",
+// " > C",
+// " [PROCESSING: 'the-new-filename'] <== selected",
+// " .dockerignore",
+// "v root2",
+// " > d",
+// " > e",
+// ]
+// );
+
+// confirm.await.unwrap();
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v root1",
+// " > .git",
+// " > a",
+// " > b",
+// " > C",
+// " .dockerignore",
+// " the-new-filename <== selected",
+// "v root2",
+// " > d",
+// " > e",
+// ]
+// );
+
+// select_path(&panel, "root1/b", cx);
+// panel.update(cx, |panel, cx| panel.new_file(&NewFile, cx));
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v root1",
+// " > .git",
+// " > a",
+// " v b",
+// " > 3",
+// " > 4",
+// " [EDITOR: ''] <== selected",
+// " > C",
+// " .dockerignore",
+// " the-new-filename",
+// ]
+// );
+
+// panel
+// .update(cx, |panel, cx| {
+// panel
+// .filename_editor
+// .update(cx, |editor, cx| editor.set_text("another-filename.txt", cx));
+// panel.confirm(&Confirm, cx).unwrap()
+// })
+// .await
+// .unwrap();
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v root1",
+// " > .git",
+// " > a",
+// " v b",
+// " > 3",
+// " > 4",
+// " another-filename.txt <== selected",
+// " > C",
+// " .dockerignore",
+// " the-new-filename",
+// ]
+// );
+
+// select_path(&panel, "root1/b/another-filename.txt", cx);
+// panel.update(cx, |panel, cx| panel.rename(&Rename, cx));
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v root1",
+// " > .git",
+// " > a",
+// " v b",
+// " > 3",
+// " > 4",
+// " [EDITOR: 'another-filename.txt'] <== selected",
+// " > C",
+// " .dockerignore",
+// " the-new-filename",
+// ]
+// );
+
+// let confirm = panel.update(cx, |panel, cx| {
+// panel.filename_editor.update(cx, |editor, cx| {
+// let file_name_selections = editor.selections.all::<usize>(cx);
+// assert_eq!(file_name_selections.len(), 1, "File editing should have a single selection, but got: {file_name_selections:?}");
+// let file_name_selection = &file_name_selections[0];
+// assert_eq!(file_name_selection.start, 0, "Should select the file name from the start");
+// assert_eq!(file_name_selection.end, "another-filename".len(), "Should not select file extension");
+
+// editor.set_text("a-different-filename.tar.gz", cx)
+// });
+// panel.confirm(&Confirm, cx).unwrap()
+// });
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v root1",
+// " > .git",
+// " > a",
+// " v b",
+// " > 3",
+// " > 4",
+// " [PROCESSING: 'a-different-filename.tar.gz'] <== selected",
+// " > C",
+// " .dockerignore",
+// " the-new-filename",
+// ]
+// );
+
+// confirm.await.unwrap();
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v root1",
+// " > .git",
+// " > a",
+// " v b",
+// " > 3",
+// " > 4",
+// " a-different-filename.tar.gz <== selected",
+// " > C",
+// " .dockerignore",
+// " the-new-filename",
+// ]
+// );
+
+// panel.update(cx, |panel, cx| panel.rename(&Rename, cx));
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v root1",
+// " > .git",
+// " > a",
+// " v b",
+// " > 3",
+// " > 4",
+// " [EDITOR: 'a-different-filename.tar.gz'] <== selected",
+// " > C",
+// " .dockerignore",
+// " the-new-filename",
+// ]
+// );
+
+// panel.update(cx, |panel, cx| {
+// panel.filename_editor.update(cx, |editor, cx| {
+// let file_name_selections = editor.selections.all::<usize>(cx);
+// assert_eq!(file_name_selections.len(), 1, "File editing should have a single selection, but got: {file_name_selections:?}");
+// let file_name_selection = &file_name_selections[0];
+// assert_eq!(file_name_selection.start, 0, "Should select the file name from the start");
+// assert_eq!(file_name_selection.end, "a-different-filename.tar".len(), "Should not select file extension, but still may select anything up to the last dot");
+
+// });
+// panel.cancel(&Cancel, cx)
+// });
+
+// panel.update(cx, |panel, cx| panel.new_directory(&NewDirectory, cx));
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v root1",
+// " > .git",
+// " > a",
+// " v b",
+// " > [EDITOR: ''] <== selected",
+// " > 3",
+// " > 4",
+// " a-different-filename.tar.gz",
+// " > C",
+// " .dockerignore",
+// ]
+// );
+
+// let confirm = panel.update(cx, |panel, cx| {
+// panel
+// .filename_editor
+// .update(cx, |editor, cx| editor.set_text("new-dir", cx));
+// panel.confirm(&Confirm, cx).unwrap()
+// });
+// panel.update(cx, |panel, cx| panel.select_next(&Default::default(), cx));
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v root1",
+// " > .git",
+// " > a",
+// " v b",
+// " > [PROCESSING: 'new-dir']",
+// " > 3 <== selected",
+// " > 4",
+// " a-different-filename.tar.gz",
+// " > C",
+// " .dockerignore",
+// ]
+// );
+
+// confirm.await.unwrap();
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v root1",
+// " > .git",
+// " > a",
+// " v b",
+// " > 3 <== selected",
+// " > 4",
+// " > new-dir",
+// " a-different-filename.tar.gz",
+// " > C",
+// " .dockerignore",
+// ]
+// );
+
+// panel.update(cx, |panel, cx| panel.rename(&Default::default(), cx));
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v root1",
+// " > .git",
+// " > a",
+// " v b",
+// " > [EDITOR: '3'] <== selected",
+// " > 4",
+// " > new-dir",
+// " a-different-filename.tar.gz",
+// " > C",
+// " .dockerignore",
+// ]
+// );
+
+// // Dismiss the rename editor when it loses focus.
+// workspace.update(cx, |_, cx| cx.focus_self());
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v root1",
+// " > .git",
+// " > a",
+// " v b",
+// " > 3 <== selected",
+// " > 4",
+// " > new-dir",
+// " a-different-filename.tar.gz",
+// " > C",
+// " .dockerignore",
+// ]
+// );
+// }
+
+// #[gpui::test(iterations = 30)]
+// async fn test_adding_directories_via_file(cx: &mut gpui::TestAppContext) {
+// init_test(cx);
+
+// let fs = FakeFs::new(cx.background());
+// fs.insert_tree(
+// "/root1",
+// json!({
+// ".dockerignore": "",
+// ".git": {
+// "HEAD": "",
+// },
+// "a": {
+// "0": { "q": "", "r": "", "s": "" },
+// "1": { "t": "", "u": "" },
+// "2": { "v": "", "w": "", "x": "", "y": "" },
+// },
+// "b": {
+// "3": { "Q": "" },
+// "4": { "R": "", "S": "", "T": "", "U": "" },
+// },
+// "C": {
+// "5": {},
+// "6": { "V": "", "W": "" },
+// "7": { "X": "" },
+// "8": { "Y": {}, "Z": "" }
+// }
+// }),
+// )
+// .await;
+// fs.insert_tree(
+// "/root2",
+// json!({
+// "d": {
+// "9": ""
+// },
+// "e": {}
+// }),
+// )
+// .await;
+
+// let project = Project::test(fs.clone(), ["/root1".as_ref(), "/root2".as_ref()], cx).await;
+// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
+// let workspace = window.root(cx);
+// let panel = workspace.update(cx, |workspace, cx| ProjectPanel::new(workspace, cx));
+
+// select_path(&panel, "root1", cx);
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v root1 <== selected",
+// " > .git",
+// " > a",
+// " > b",
+// " > C",
+// " .dockerignore",
+// "v root2",
+// " > d",
+// " > e",
+// ]
+// );
+
+// // Add a file with the root folder selected. The filename editor is placed
+// // before the first file in the root folder.
+// panel.update(cx, |panel, cx| panel.new_file(&NewFile, cx));
+// window.read_with(cx, |cx| {
+// let panel = panel.read(cx);
+// assert!(panel.filename_editor.is_focused(cx));
+// });
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v root1",
+// " > .git",
+// " > a",
+// " > b",
+// " > C",
+// " [EDITOR: ''] <== selected",
+// " .dockerignore",
+// "v root2",
+// " > d",
+// " > e",
+// ]
+// );
+
+// let confirm = panel.update(cx, |panel, cx| {
+// panel.filename_editor.update(cx, |editor, cx| {
+// editor.set_text("/bdir1/dir2/the-new-filename", cx)
+// });
+// panel.confirm(&Confirm, cx).unwrap()
+// });
+
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v root1",
+// " > .git",
+// " > a",
+// " > b",
+// " > C",
+// " [PROCESSING: '/bdir1/dir2/the-new-filename'] <== selected",
+// " .dockerignore",
+// "v root2",
+// " > d",
+// " > e",
+// ]
+// );
+
+// confirm.await.unwrap();
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..13, cx),
+// &[
+// "v root1",
+// " > .git",
+// " > a",
+// " > b",
+// " v bdir1",
+// " v dir2",
+// " the-new-filename <== selected",
+// " > C",
+// " .dockerignore",
+// "v root2",
+// " > d",
+// " > e",
+// ]
+// );
+// }
+
+// #[gpui::test]
+// async fn test_copy_paste(cx: &mut gpui::TestAppContext) {
+// init_test(cx);
+
+// let fs = FakeFs::new(cx.background());
+// fs.insert_tree(
+// "/root1",
+// json!({
+// "one.two.txt": "",
+// "one.txt": ""
+// }),
+// )
+// .await;
+
+// let project = Project::test(fs.clone(), ["/root1".as_ref()], cx).await;
+// let workspace = cx
+// .add_window(|cx| Workspace::test_new(project.clone(), cx))
+// .root(cx);
+// let panel = workspace.update(cx, |workspace, cx| ProjectPanel::new(workspace, cx));
+
+// panel.update(cx, |panel, cx| {
+// panel.select_next(&Default::default(), cx);
+// panel.select_next(&Default::default(), cx);
+// });
+
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..50, cx),
+// &[
+// //
+// "v root1",
+// " one.two.txt <== selected",
+// " one.txt",
+// ]
+// );
+
+// // Regression test - file name is created correctly when
+// // the copied file's name contains multiple dots.
+// panel.update(cx, |panel, cx| {
+// panel.copy(&Default::default(), cx);
+// panel.paste(&Default::default(), cx);
+// });
+// cx.foreground().run_until_parked();
+
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..50, cx),
+// &[
+// //
+// "v root1",
+// " one.two copy.txt",
+// " one.two.txt <== selected",
+// " one.txt",
+// ]
+// );
+
+// panel.update(cx, |panel, cx| {
+// panel.paste(&Default::default(), cx);
+// });
+// cx.foreground().run_until_parked();
+
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..50, cx),
+// &[
+// //
+// "v root1",
+// " one.two copy 1.txt",
+// " one.two copy.txt",
+// " one.two.txt <== selected",
+// " one.txt",
+// ]
+// );
+// }
+
+// #[gpui::test]
+// async fn test_remove_opened_file(cx: &mut gpui::TestAppContext) {
+// init_test_with_editor(cx);
+
+// let fs = FakeFs::new(cx.background());
+// fs.insert_tree(
+// "/src",
+// json!({
+// "test": {
+// "first.rs": "// First Rust file",
+// "second.rs": "// Second Rust file",
+// "third.rs": "// Third Rust file",
+// }
+// }),
+// )
+// .await;
+
+// let project = Project::test(fs.clone(), ["/src".as_ref()], cx).await;
+// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
+// let workspace = window.root(cx);
+// let panel = workspace.update(cx, |workspace, cx| ProjectPanel::new(workspace, cx));
+
+// toggle_expand_dir(&panel, "src/test", cx);
+// select_path(&panel, "src/test/first.rs", cx);
+// panel.update(cx, |panel, cx| panel.open_file(&Open, cx));
+// cx.foreground().run_until_parked();
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v src",
+// " v test",
+// " first.rs <== selected",
+// " second.rs",
+// " third.rs"
+// ]
+// );
+// ensure_single_file_is_opened(window, "test/first.rs", cx);
+
+// submit_deletion(window.into(), &panel, cx);
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v src",
+// " v test",
+// " second.rs",
+// " third.rs"
+// ],
+// "Project panel should have no deleted file, no other file is selected in it"
+// );
+// ensure_no_open_items_and_panes(window.into(), &workspace, cx);
+
+// select_path(&panel, "src/test/second.rs", cx);
+// panel.update(cx, |panel, cx| panel.open_file(&Open, cx));
+// cx.foreground().run_until_parked();
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v src",
+// " v test",
+// " second.rs <== selected",
+// " third.rs"
+// ]
+// );
+// ensure_single_file_is_opened(window, "test/second.rs", cx);
+
+// window.update(cx, |cx| {
+// let active_items = workspace
+// .read(cx)
+// .panes()
+// .iter()
+// .filter_map(|pane| pane.read(cx).active_item())
+// .collect::<Vec<_>>();
+// assert_eq!(active_items.len(), 1);
+// let open_editor = active_items
+// .into_iter()
+// .next()
+// .unwrap()
+// .downcast::<Editor>()
+// .expect("Open item should be an editor");
+// open_editor.update(cx, |editor, cx| editor.set_text("Another text!", cx));
+// });
+// submit_deletion(window.into(), &panel, cx);
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &["v src", " v test", " third.rs"],
+// "Project panel should have no deleted file, with one last file remaining"
+// );
+// ensure_no_open_items_and_panes(window.into(), &workspace, cx);
+// }
+
+// #[gpui::test]
+// async fn test_create_duplicate_items(cx: &mut gpui::TestAppContext) {
+// init_test_with_editor(cx);
+
+// let fs = FakeFs::new(cx.background());
+// fs.insert_tree(
+// "/src",
+// json!({
+// "test": {
+// "first.rs": "// First Rust file",
+// "second.rs": "// Second Rust file",
+// "third.rs": "// Third Rust file",
+// }
+// }),
+// )
+// .await;
+
+// let project = Project::test(fs.clone(), ["/src".as_ref()], cx).await;
+// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
+// let workspace = window.root(cx);
+// let panel = workspace.update(cx, |workspace, cx| ProjectPanel::new(workspace, cx));
+
+// select_path(&panel, "src/", cx);
+// panel.update(cx, |panel, cx| panel.confirm(&Confirm, cx));
+// cx.foreground().run_until_parked();
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &["v src <== selected", " > test"]
+// );
+// panel.update(cx, |panel, cx| panel.new_directory(&NewDirectory, cx));
+// window.read_with(cx, |cx| {
+// let panel = panel.read(cx);
+// assert!(panel.filename_editor.is_focused(cx));
+// });
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &["v src", " > [EDITOR: ''] <== selected", " > test"]
+// );
+// panel.update(cx, |panel, cx| {
+// panel
+// .filename_editor
+// .update(cx, |editor, cx| editor.set_text("test", cx));
+// assert!(
+// panel.confirm(&Confirm, cx).is_none(),
+// "Should not allow to confirm on conflicting new directory name"
+// )
+// });
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &["v src", " > test"],
+// "File list should be unchanged after failed folder create confirmation"
+// );
+
+// select_path(&panel, "src/test/", cx);
+// panel.update(cx, |panel, cx| panel.confirm(&Confirm, cx));
+// cx.foreground().run_until_parked();
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &["v src", " > test <== selected"]
+// );
+// panel.update(cx, |panel, cx| panel.new_file(&NewFile, cx));
+// window.read_with(cx, |cx| {
+// let panel = panel.read(cx);
+// assert!(panel.filename_editor.is_focused(cx));
+// });
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v src",
+// " v test",
+// " [EDITOR: ''] <== selected",
+// " first.rs",
+// " second.rs",
+// " third.rs"
+// ]
+// );
+// panel.update(cx, |panel, cx| {
+// panel
+// .filename_editor
+// .update(cx, |editor, cx| editor.set_text("first.rs", cx));
+// assert!(
+// panel.confirm(&Confirm, cx).is_none(),
+// "Should not allow to confirm on conflicting new file name"
+// )
+// });
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v src",
+// " v test",
+// " first.rs",
+// " second.rs",
+// " third.rs"
+// ],
+// "File list should be unchanged after failed file create confirmation"
+// );
+
+// select_path(&panel, "src/test/first.rs", cx);
+// panel.update(cx, |panel, cx| panel.confirm(&Confirm, cx));
+// cx.foreground().run_until_parked();
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v src",
+// " v test",
+// " first.rs <== selected",
+// " second.rs",
+// " third.rs"
+// ],
+// );
+// panel.update(cx, |panel, cx| panel.rename(&Rename, cx));
+// window.read_with(cx, |cx| {
+// let panel = panel.read(cx);
+// assert!(panel.filename_editor.is_focused(cx));
+// });
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v src",
+// " v test",
+// " [EDITOR: 'first.rs'] <== selected",
+// " second.rs",
+// " third.rs"
+// ]
+// );
+// panel.update(cx, |panel, cx| {
+// panel
+// .filename_editor
+// .update(cx, |editor, cx| editor.set_text("second.rs", cx));
+// assert!(
+// panel.confirm(&Confirm, cx).is_none(),
+// "Should not allow to confirm on conflicting file rename"
+// )
+// });
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v src",
+// " v test",
+// " first.rs <== selected",
+// " second.rs",
+// " third.rs"
+// ],
+// "File list should be unchanged after failed rename confirmation"
+// );
+// }
+
+// #[gpui::test]
+// async fn test_new_search_in_directory_trigger(cx: &mut gpui::TestAppContext) {
+// init_test_with_editor(cx);
+
+// let fs = FakeFs::new(cx.background());
+// fs.insert_tree(
+// "/src",
+// json!({
+// "test": {
+// "first.rs": "// First Rust file",
+// "second.rs": "// Second Rust file",
+// "third.rs": "// Third Rust file",
+// }
+// }),
+// )
+// .await;
+
+// let project = Project::test(fs.clone(), ["/src".as_ref()], cx).await;
+// let workspace = cx
+// .add_window(|cx| Workspace::test_new(project.clone(), cx))
+// .root(cx);
+// let panel = workspace.update(cx, |workspace, cx| ProjectPanel::new(workspace, cx));
+
+// let new_search_events_count = Arc::new(AtomicUsize::new(0));
+// let _subscription = panel.update(cx, |_, cx| {
+// let subcription_count = Arc::clone(&new_search_events_count);
+// cx.subscribe(&cx.handle(), move |_, _, event, _| {
+// if matches!(event, Event::NewSearchInDirectory { .. }) {
+// subcription_count.fetch_add(1, atomic::Ordering::SeqCst);
+// }
+// })
+// });
+
+// toggle_expand_dir(&panel, "src/test", cx);
+// select_path(&panel, "src/test/first.rs", cx);
+// panel.update(cx, |panel, cx| panel.confirm(&Confirm, cx));
+// cx.foreground().run_until_parked();
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v src",
+// " v test",
+// " first.rs <== selected",
+// " second.rs",
+// " third.rs"
+// ]
+// );
+// panel.update(cx, |panel, cx| {
+// panel.new_search_in_directory(&NewSearchInDirectory, cx)
+// });
+// assert_eq!(
+// new_search_events_count.load(atomic::Ordering::SeqCst),
+// 0,
+// "Should not trigger new search in directory when called on a file"
+// );
+
+// select_path(&panel, "src/test", cx);
+// panel.update(cx, |panel, cx| panel.confirm(&Confirm, cx));
+// cx.foreground().run_until_parked();
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v src",
+// " v test <== selected",
+// " first.rs",
+// " second.rs",
+// " third.rs"
+// ]
+// );
+// panel.update(cx, |panel, cx| {
+// panel.new_search_in_directory(&NewSearchInDirectory, cx)
+// });
+// assert_eq!(
+// new_search_events_count.load(atomic::Ordering::SeqCst),
+// 1,
+// "Should trigger new search in directory when called on a directory"
+// );
+// }
+
+// #[gpui::test]
+// async fn test_collapse_all_entries(cx: &mut gpui::TestAppContext) {
+// init_test_with_editor(cx);
+
+// let fs = FakeFs::new(cx.background());
+// fs.insert_tree(
+// "/project_root",
+// json!({
+// "dir_1": {
+// "nested_dir": {
+// "file_a.py": "# File contents",
+// "file_b.py": "# File contents",
+// "file_c.py": "# File contents",
+// },
+// "file_1.py": "# File contents",
+// "file_2.py": "# File contents",
+// "file_3.py": "# File contents",
+// },
+// "dir_2": {
+// "file_1.py": "# File contents",
+// "file_2.py": "# File contents",
+// "file_3.py": "# File contents",
+// }
+// }),
+// )
+// .await;
+
+// let project = Project::test(fs.clone(), ["/project_root".as_ref()], cx).await;
+// let workspace = cx
+// .add_window(|cx| Workspace::test_new(project.clone(), cx))
+// .root(cx);
+// let panel = workspace.update(cx, |workspace, cx| ProjectPanel::new(workspace, cx));
+
+// panel.update(cx, |panel, cx| {
+// panel.collapse_all_entries(&CollapseAllEntries, cx)
+// });
+// cx.foreground().run_until_parked();
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &["v project_root", " > dir_1", " > dir_2",]
+// );
+
+// // Open dir_1 and make sure nested_dir was collapsed when running collapse_all_entries
+// toggle_expand_dir(&panel, "project_root/dir_1", cx);
+// cx.foreground().run_until_parked();
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &[
+// "v project_root",
+// " v dir_1 <== selected",
+// " > nested_dir",
+// " file_1.py",
+// " file_2.py",
+// " file_3.py",
+// " > dir_2",
+// ]
+// );
+// }
+
+// #[gpui::test]
+// async fn test_new_file_move(cx: &mut gpui::TestAppContext) {
+// init_test(cx);
+
+// let fs = FakeFs::new(cx.background());
+// fs.as_fake().insert_tree("/root", json!({})).await;
+// let project = Project::test(fs, ["/root".as_ref()], cx).await;
+// let workspace = cx
+// .add_window(|cx| Workspace::test_new(project.clone(), cx))
+// .root(cx);
+// let panel = workspace.update(cx, |workspace, cx| ProjectPanel::new(workspace, cx));
+
+// // Make a new buffer with no backing file
+// workspace.update(cx, |workspace, cx| {
+// Editor::new_file(workspace, &Default::default(), cx)
+// });
+
+// // "Save as"" the buffer, creating a new backing file for it
+// let task = workspace.update(cx, |workspace, cx| {
+// workspace.save_active_item(workspace::SaveIntent::Save, cx)
+// });
+
+// cx.foreground().run_until_parked();
+// cx.simulate_new_path_selection(|_| Some(PathBuf::from("/root/new")));
+// task.await.unwrap();
+
+// // Rename the file
+// select_path(&panel, "root/new", cx);
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &["v root", " new <== selected"]
+// );
+// panel.update(cx, |panel, cx| panel.rename(&Rename, cx));
+// panel.update(cx, |panel, cx| {
+// panel
+// .filename_editor
+// .update(cx, |editor, cx| editor.set_text("newer", cx));
+// });
+// panel
+// .update(cx, |panel, cx| panel.confirm(&Confirm, cx))
+// .unwrap()
+// .await
+// .unwrap();
+
+// cx.foreground().run_until_parked();
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &["v root", " newer <== selected"]
+// );
+
+// workspace
+// .update(cx, |workspace, cx| {
+// workspace.save_active_item(workspace::SaveIntent::Save, cx)
+// })
+// .await
+// .unwrap();
+
+// cx.foreground().run_until_parked();
+// // assert that saving the file doesn't restore "new"
+// assert_eq!(
+// visible_entries_as_strings(&panel, 0..10, cx),
+// &["v root", " newer <== selected"]
+// );
+// }
+
+// fn toggle_expand_dir(
+// panel: &View<ProjectPanel>,
+// path: impl AsRef<Path>,
+// cx: &mut TestAppContext,
+// ) {
+// let path = path.as_ref();
+// panel.update(cx, |panel, cx| {
+// for worktree in panel.project.read(cx).worktrees().collect::<Vec<_>>() {
+// let worktree = worktree.read(cx);
+// if let Ok(relative_path) = path.strip_prefix(worktree.root_name()) {
+// let entry_id = worktree.entry_for_path(relative_path).unwrap().id;
+// panel.toggle_expanded(entry_id, cx);
+// return;
+// }
+// }
+// panic!("no worktree for path {:?}", path);
+// });
+// }
+
+// fn select_path(panel: &View<ProjectPanel>, path: impl AsRef<Path>, cx: &mut TestAppContext) {
+// let path = path.as_ref();
+// panel.update(cx, |panel, cx| {
+// for worktree in panel.project.read(cx).worktrees().collect::<Vec<_>>() {
+// let worktree = worktree.read(cx);
+// if let Ok(relative_path) = path.strip_prefix(worktree.root_name()) {
+// let entry_id = worktree.entry_for_path(relative_path).unwrap().id;
+// panel.selection = Some(Selection {
+// worktree_id: worktree.id(),
+// entry_id,
+// });
+// return;
+// }
+// }
+// panic!("no worktree for path {:?}", path);
+// });
+// }
+
+// fn visible_entries_as_strings(
+// panel: &View<ProjectPanel>,
+// range: Range<usize>,
+// cx: &mut TestAppContext,
+// ) -> Vec<String> {
+// let mut result = Vec::new();
+// let mut project_entries = HashSet::new();
+// let mut has_editor = false;
+
+// panel.update(cx, |panel, cx| {
+// panel.for_each_visible_entry(range, cx, |project_entry, details, _| {
+// if details.is_editing {
+// assert!(!has_editor, "duplicate editor entry");
+// has_editor = true;
+// } else {
+// assert!(
+// project_entries.insert(project_entry),
+// "duplicate project entry {:?} {:?}",
+// project_entry,
+// details
+// );
+// }
+
+// let indent = " ".repeat(details.depth);
+// let icon = if details.kind.is_dir() {
+// if details.is_expanded {
+// "v "
+// } else {
+// "> "
+// }
+// } else {
+// " "
+// };
+// let name = if details.is_editing {
+// format!("[EDITOR: '{}']", details.filename)
+// } else if details.is_processing {
+// format!("[PROCESSING: '{}']", details.filename)
+// } else {
+// details.filename.clone()
+// };
+// let selected = if details.is_selected {
+// " <== selected"
+// } else {
+// ""
+// };
+// result.push(format!("{indent}{icon}{name}{selected}"));
+// });
+// });
+
+// result
+// }
+
+// fn init_test(cx: &mut TestAppContext) {
+// cx.foreground().forbid_parking();
+// cx.update(|cx| {
+// cx.set_global(SettingsStore::test(cx));
+// init_settings(cx);
+// theme::init(cx);
+// language::init(cx);
+// editor::init_settings(cx);
+// crate::init((), cx);
+// workspace::init_settings(cx);
+// client::init_settings(cx);
+// Project::init_settings(cx);
+// });
+// }
+
+// fn init_test_with_editor(cx: &mut TestAppContext) {
+// cx.foreground().forbid_parking();
+// cx.update(|cx| {
+// let app_state = AppState::test(cx);
+// theme::init(cx);
+// init_settings(cx);
+// language::init(cx);
+// editor::init(cx);
+// pane::init(cx);
+// crate::init((), cx);
+// workspace::init(app_state.clone(), cx);
+// Project::init_settings(cx);
+// });
+// }
+
+// fn ensure_single_file_is_opened(
+// window: WindowHandle<Workspace>,
+// expected_path: &str,
+// cx: &mut TestAppContext,
+// ) {
+// window.update_root(cx, |workspace, cx| {
+// let worktrees = workspace.worktrees(cx).collect::<Vec<_>>();
+// assert_eq!(worktrees.len(), 1);
+// let worktree_id = WorktreeId::from_usize(worktrees[0].id());
+
+// let open_project_paths = workspace
+// .panes()
+// .iter()
+// .filter_map(|pane| pane.read(cx).active_item()?.project_path(cx))
+// .collect::<Vec<_>>();
+// assert_eq!(
+// open_project_paths,
+// vec![ProjectPath {
+// worktree_id,
+// path: Arc::from(Path::new(expected_path))
+// }],
+// "Should have opened file, selected in project panel"
+// );
+// });
+// }
+
+// fn submit_deletion(
+// window: AnyWindowHandle,
+// panel: &View<ProjectPanel>,
+// cx: &mut TestAppContext,
+// ) {
+// assert!(
+// !window.has_pending_prompt(cx),
+// "Should have no prompts before the deletion"
+// );
+// panel.update(cx, |panel, cx| {
+// panel
+// .delete(&Delete, cx)
+// .expect("Deletion start")
+// .detach_and_log_err(cx);
+// });
+// assert!(
+// window.has_pending_prompt(cx),
+// "Should have a prompt after the deletion"
+// );
+// window.simulate_prompt_answer(0, cx);
+// assert!(
+// !window.has_pending_prompt(cx),
+// "Should have no prompts after prompt was replied to"
+// );
+// cx.foreground().run_until_parked();
+// }
+
+// fn ensure_no_open_items_and_panes(
+// window: AnyWindowHandle,
+// workspace: &View<Workspace>,
+// cx: &mut TestAppContext,
+// ) {
+// assert!(
+// !window.has_pending_prompt(cx),
+// "Should have no prompts after deletion operation closes the file"
+// );
+// window.read_with(cx, |cx| {
+// let open_project_paths = workspace
+// .read(cx)
+// .panes()
+// .iter()
+// .filter_map(|pane| pane.read(cx).active_item()?.project_path(cx))
+// .collect::<Vec<_>>();
+// assert!(
+// open_project_paths.is_empty(),
+// "Deleted file's buffer should be closed, but got open files: {open_project_paths:?}"
+// );
+// });
+// }
+// }