vim2 compiling (but mostly commented out)

This commit is contained in:
Conrad Irwin
2023-12-08 18:47:14 +00:00
parent 7a9f764aa0
commit 32837d67be
146 changed files with 22013 additions and 10 deletions
@@ -0,0 +1,95 @@
use std::ops::{Deref, DerefMut};
use crate::state::Mode;
use super::{ExemptionFeatures, NeovimBackedTestContext, SUPPORTED_FEATURES};
pub struct NeovimBackedBindingTestContext<'a, const COUNT: usize> {
cx: NeovimBackedTestContext<'a>,
keystrokes_under_test: [&'static str; COUNT],
}
impl<'a, const COUNT: usize> NeovimBackedBindingTestContext<'a, COUNT> {
pub fn new(
keystrokes_under_test: [&'static str; COUNT],
cx: NeovimBackedTestContext<'a>,
) -> Self {
Self {
cx,
keystrokes_under_test,
}
}
pub fn consume(self) -> NeovimBackedTestContext<'a> {
self.cx
}
pub fn binding<const NEW_COUNT: usize>(
self,
keystrokes: [&'static str; NEW_COUNT],
) -> NeovimBackedBindingTestContext<'a, NEW_COUNT> {
self.consume().binding(keystrokes)
}
pub async fn assert(&mut self, marked_positions: &str) {
self.cx
.assert_binding_matches(self.keystrokes_under_test, marked_positions)
.await;
}
pub async fn assert_exempted(&mut self, marked_positions: &str, feature: ExemptionFeatures) {
if SUPPORTED_FEATURES.contains(&feature) {
self.cx
.assert_binding_matches(self.keystrokes_under_test, marked_positions)
.await
}
}
pub fn assert_manual(
&mut self,
initial_state: &str,
mode_before: Mode,
state_after: &str,
mode_after: Mode,
) {
self.cx.assert_binding(
self.keystrokes_under_test,
initial_state,
mode_before,
state_after,
mode_after,
);
}
pub async fn assert_all(&mut self, marked_positions: &str) {
self.cx
.assert_binding_matches_all(self.keystrokes_under_test, marked_positions)
.await
}
pub async fn assert_all_exempted(
&mut self,
marked_positions: &str,
feature: ExemptionFeatures,
) {
if SUPPORTED_FEATURES.contains(&feature) {
self.cx
.assert_binding_matches_all(self.keystrokes_under_test, marked_positions)
.await
}
}
}
impl<'a, const COUNT: usize> Deref for NeovimBackedBindingTestContext<'a, COUNT> {
type Target = NeovimBackedTestContext<'a>;
fn deref(&self) -> &Self::Target {
&self.cx
}
}
impl<'a, const COUNT: usize> DerefMut for NeovimBackedBindingTestContext<'a, COUNT> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.cx
}
}
@@ -0,0 +1,427 @@
use editor::scroll::VERTICAL_SCROLL_MARGIN;
use indoc::indoc;
use settings::SettingsStore;
use std::{
ops::{Deref, DerefMut},
panic, thread,
};
use collections::{HashMap, HashSet};
use gpui::{geometry::vector::vec2f, ContextHandle};
use language::language_settings::{AllLanguageSettings, SoftWrap};
use util::test::marked_text_offsets;
use super::{neovim_connection::NeovimConnection, NeovimBackedBindingTestContext, VimTestContext};
use crate::state::Mode;
pub const SUPPORTED_FEATURES: &[ExemptionFeatures] = &[];
/// Enum representing features we have tests for but which don't work, yet. Used
/// to add exemptions and automatically
#[derive(PartialEq, Eq)]
pub enum ExemptionFeatures {
// MOTIONS
// When an operator completes at the end of the file, an extra newline is left
OperatorLastNewlineRemains,
// OBJECTS
// Resulting position after the operation is slightly incorrect for unintuitive reasons.
IncorrectLandingPosition,
// Operator around the text object at the end of the line doesn't remove whitespace.
AroundObjectLeavesWhitespaceAtEndOfLine,
// Sentence object on empty lines
SentenceOnEmptyLines,
// Whitespace isn't included with text objects at the start of the line
SentenceAtStartOfLineWithWhitespace,
// Whitespace around sentences is slightly incorrect when starting between sentences
AroundSentenceStartingBetweenIncludesWrongWhitespace,
// Non empty selection with text objects in visual mode
NonEmptyVisualTextObjects,
// Sentence Doesn't backtrack when its at the end of the file
SentenceAfterPunctuationAtEndOfFile,
}
impl ExemptionFeatures {
pub fn supported(&self) -> bool {
SUPPORTED_FEATURES.contains(self)
}
}
pub struct NeovimBackedTestContext<'a> {
cx: VimTestContext<'a>,
// Lookup for exempted assertions. Keyed by the insertion text, and with a value indicating which
// bindings are exempted. If None, all bindings are ignored for that insertion text.
exemptions: HashMap<String, Option<HashSet<String>>>,
neovim: NeovimConnection,
last_set_state: Option<String>,
recent_keystrokes: Vec<String>,
is_dirty: bool,
}
impl<'a> NeovimBackedTestContext<'a> {
pub async fn new(cx: &'a mut gpui::TestAppContext) -> NeovimBackedTestContext<'a> {
// rust stores the name of the test on the current thread.
// We use this to automatically name a file that will store
// the neovim connection's requests/responses so that we can
// run without neovim on CI.
let thread = thread::current();
let test_name = thread
.name()
.expect("thread is not named")
.split(":")
.last()
.unwrap()
.to_string();
Self {
cx: VimTestContext::new(cx, true).await,
exemptions: Default::default(),
neovim: NeovimConnection::new(test_name).await,
last_set_state: None,
recent_keystrokes: Default::default(),
is_dirty: false,
}
}
pub fn add_initial_state_exemptions(
&mut self,
marked_positions: &str,
missing_feature: ExemptionFeatures, // Feature required to support this exempted test case
) {
if !missing_feature.supported() {
let (unmarked_text, cursor_offsets) = marked_text_offsets(marked_positions);
for cursor_offset in cursor_offsets.iter() {
let mut marked_text = unmarked_text.clone();
marked_text.insert(*cursor_offset, 'ˇ');
// None represents all key bindings being exempted for that initial state
self.exemptions.insert(marked_text, None);
}
}
}
pub async fn simulate_shared_keystroke(&mut self, keystroke_text: &str) -> ContextHandle {
self.neovim.send_keystroke(keystroke_text).await;
self.simulate_keystroke(keystroke_text)
}
pub async fn simulate_shared_keystrokes<const COUNT: usize>(
&mut self,
keystroke_texts: [&str; COUNT],
) {
for keystroke_text in keystroke_texts.into_iter() {
self.recent_keystrokes.push(keystroke_text.to_string());
self.neovim.send_keystroke(keystroke_text).await;
}
self.simulate_keystrokes(keystroke_texts);
}
pub async fn set_shared_state(&mut self, marked_text: &str) {
let mode = if marked_text.contains("»") {
Mode::Visual
} else {
Mode::Normal
};
self.set_state(marked_text, mode);
self.last_set_state = Some(marked_text.to_string());
self.recent_keystrokes = Vec::new();
self.neovim.set_state(marked_text).await;
self.is_dirty = true;
}
pub async fn set_shared_wrap(&mut self, columns: u32) {
if columns < 12 {
panic!("nvim doesn't support columns < 12")
}
self.neovim.set_option("wrap").await;
self.neovim
.set_option(&format!("columns={}", columns))
.await;
self.update(|cx| {
cx.update_global(|settings: &mut SettingsStore, cx| {
settings.update_user_settings::<AllLanguageSettings>(cx, |settings| {
settings.defaults.soft_wrap = Some(SoftWrap::PreferredLineLength);
settings.defaults.preferred_line_length = Some(columns);
});
})
})
}
pub async fn set_scroll_height(&mut self, rows: u32) {
// match Zed's scrolling behavior
self.neovim
.set_option(&format!("scrolloff={}", VERTICAL_SCROLL_MARGIN))
.await;
// +2 to account for the vim command UI at the bottom.
self.neovim.set_option(&format!("lines={}", rows + 2)).await;
let window = self.window;
let line_height =
self.editor(|editor, cx| editor.style().text.line_height(cx.font_cache()));
window.simulate_resize(vec2f(1000., (rows as f32) * line_height), &mut self.cx);
}
pub async fn set_neovim_option(&mut self, option: &str) {
self.neovim.set_option(option).await;
}
pub async fn assert_shared_state(&mut self, marked_text: &str) {
self.is_dirty = false;
let marked_text = marked_text.replace("", " ");
let neovim = self.neovim_state().await;
let editor = self.editor_state();
if neovim == marked_text && neovim == editor {
return;
}
let initial_state = self
.last_set_state
.as_ref()
.unwrap_or(&"N/A".to_string())
.clone();
let message = if neovim != marked_text {
"Test is incorrect (currently expected != neovim_state)"
} else {
"Editor does not match nvim behaviour"
};
panic!(
indoc! {"{}
# initial state:
{}
# keystrokes:
{}
# currently expected:
{}
# neovim state:
{}
# zed state:
{}"},
message,
initial_state,
self.recent_keystrokes.join(" "),
marked_text.replace(" \n", "\n"),
neovim.replace(" \n", "\n"),
editor.replace(" \n", "\n")
)
}
pub async fn assert_shared_clipboard(&mut self, text: &str) {
let neovim = self.neovim.read_register('"').await;
let editor = self
.platform()
.read_from_clipboard()
.unwrap()
.text()
.clone();
if text == neovim && text == editor {
return;
}
let message = if neovim != text {
"Test is incorrect (currently expected != neovim)"
} else {
"Editor does not match nvim behaviour"
};
let initial_state = self
.last_set_state
.as_ref()
.unwrap_or(&"N/A".to_string())
.clone();
panic!(
indoc! {"{}
# initial state:
{}
# keystrokes:
{}
# currently expected:
{}
# neovim clipboard:
{}
# zed clipboard:
{}"},
message,
initial_state,
self.recent_keystrokes.join(" "),
text,
neovim,
editor
)
}
pub async fn neovim_state(&mut self) -> String {
self.neovim.marked_text().await
}
pub async fn neovim_mode(&mut self) -> Mode {
self.neovim.mode().await.unwrap()
}
pub async fn assert_state_matches(&mut self) {
self.is_dirty = false;
let neovim = self.neovim_state().await;
let editor = self.editor_state();
let initial_state = self
.last_set_state
.as_ref()
.unwrap_or(&"N/A".to_string())
.clone();
if neovim != editor {
panic!(
indoc! {"Test failed (zed does not match nvim behaviour)
# initial state:
{}
# keystrokes:
{}
# neovim state:
{}
# zed state:
{}"},
initial_state,
self.recent_keystrokes.join(" "),
neovim,
editor,
)
}
}
pub async fn assert_binding_matches<const COUNT: usize>(
&mut self,
keystrokes: [&str; COUNT],
initial_state: &str,
) {
if let Some(possible_exempted_keystrokes) = self.exemptions.get(initial_state) {
match possible_exempted_keystrokes {
Some(exempted_keystrokes) => {
if exempted_keystrokes.contains(&format!("{keystrokes:?}")) {
// This keystroke was exempted for this insertion text
return;
}
}
None => {
// All keystrokes for this insertion text are exempted
return;
}
}
}
let _state_context = self.set_shared_state(initial_state).await;
let _keystroke_context = self.simulate_shared_keystrokes(keystrokes).await;
self.assert_state_matches().await;
}
pub async fn assert_binding_matches_all<const COUNT: usize>(
&mut self,
keystrokes: [&str; COUNT],
marked_positions: &str,
) {
let (unmarked_text, cursor_offsets) = marked_text_offsets(marked_positions);
for cursor_offset in cursor_offsets.iter() {
let mut marked_text = unmarked_text.clone();
marked_text.insert(*cursor_offset, 'ˇ');
self.assert_binding_matches(keystrokes, &marked_text).await;
}
}
pub fn each_marked_position(&self, marked_positions: &str) -> Vec<String> {
let (unmarked_text, cursor_offsets) = marked_text_offsets(marked_positions);
let mut ret = Vec::with_capacity(cursor_offsets.len());
for cursor_offset in cursor_offsets.iter() {
let mut marked_text = unmarked_text.clone();
marked_text.insert(*cursor_offset, 'ˇ');
ret.push(marked_text)
}
ret
}
pub async fn assert_neovim_compatible<const COUNT: usize>(
&mut self,
marked_positions: &str,
keystrokes: [&str; COUNT],
) {
self.set_shared_state(&marked_positions).await;
self.simulate_shared_keystrokes(keystrokes).await;
self.assert_state_matches().await;
}
pub async fn assert_matches_neovim<const COUNT: usize>(
&mut self,
marked_positions: &str,
keystrokes: [&str; COUNT],
result: &str,
) {
self.set_shared_state(marked_positions).await;
self.simulate_shared_keystrokes(keystrokes).await;
self.assert_shared_state(result).await;
}
pub async fn assert_binding_matches_all_exempted<const COUNT: usize>(
&mut self,
keystrokes: [&str; COUNT],
marked_positions: &str,
feature: ExemptionFeatures,
) {
if SUPPORTED_FEATURES.contains(&feature) {
self.assert_binding_matches_all(keystrokes, marked_positions)
.await
}
}
pub fn binding<const COUNT: usize>(
self,
keystrokes: [&'static str; COUNT],
) -> NeovimBackedBindingTestContext<'a, COUNT> {
NeovimBackedBindingTestContext::new(keystrokes, self)
}
}
impl<'a> Deref for NeovimBackedTestContext<'a> {
type Target = VimTestContext<'a>;
fn deref(&self) -> &Self::Target {
&self.cx
}
}
impl<'a> DerefMut for NeovimBackedTestContext<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.cx
}
}
// a common mistake in tests is to call set_shared_state when
// you mean asswert_shared_state. This notices that and lets
// you know.
impl<'a> Drop for NeovimBackedTestContext<'a> {
fn drop(&mut self) {
if self.is_dirty {
panic!("Test context was dropped after set_shared_state before assert_shared_state")
}
}
}
#[cfg(test)]
mod test {
use gpui::TestAppContext;
use crate::test::NeovimBackedTestContext;
#[gpui::test]
async fn neovim_backed_test_context_works(cx: &mut TestAppContext) {
let mut cx = NeovimBackedTestContext::new(cx).await;
cx.assert_state_matches().await;
cx.set_shared_state("This is a tesˇt").await;
cx.assert_state_matches().await;
}
}
+591
View File
@@ -0,0 +1,591 @@
use std::path::PathBuf;
#[cfg(feature = "neovim")]
use std::{
cmp,
ops::{Deref, DerefMut, Range},
};
#[cfg(feature = "neovim")]
use async_compat::Compat;
#[cfg(feature = "neovim")]
use async_trait::async_trait;
#[cfg(feature = "neovim")]
use gpui::keymap_matcher::Keystroke;
#[cfg(feature = "neovim")]
use language::Point;
#[cfg(feature = "neovim")]
use nvim_rs::{
create::tokio::new_child_cmd, error::LoopError, Handler, Neovim, UiAttachOptions, Value,
};
#[cfg(feature = "neovim")]
use parking_lot::ReentrantMutex;
use serde::{Deserialize, Serialize};
#[cfg(feature = "neovim")]
use tokio::{
process::{Child, ChildStdin, Command},
task::JoinHandle,
};
use crate::state::Mode;
use collections::VecDeque;
// Neovim doesn't like to be started simultaneously from multiple threads. We use this lock
// to ensure we are only constructing one neovim connection at a time.
#[cfg(feature = "neovim")]
static NEOVIM_LOCK: ReentrantMutex<()> = ReentrantMutex::new(());
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub enum NeovimData {
Put { state: String },
Key(String),
Get { state: String, mode: Option<Mode> },
ReadRegister { name: char, value: String },
SetOption { value: String },
}
pub struct NeovimConnection {
data: VecDeque<NeovimData>,
#[cfg(feature = "neovim")]
test_case_id: String,
#[cfg(feature = "neovim")]
nvim: Neovim<nvim_rs::compat::tokio::Compat<ChildStdin>>,
#[cfg(feature = "neovim")]
_join_handle: JoinHandle<Result<(), Box<LoopError>>>,
#[cfg(feature = "neovim")]
_child: Child,
}
impl NeovimConnection {
pub async fn new(test_case_id: String) -> Self {
#[cfg(feature = "neovim")]
let handler = NvimHandler {};
#[cfg(feature = "neovim")]
let (nvim, join_handle, child) = Compat::new(async {
// Ensure we don't create neovim connections in parallel
let _lock = NEOVIM_LOCK.lock();
let (nvim, join_handle, child) = new_child_cmd(
&mut Command::new("nvim")
.arg("--embed")
.arg("--clean")
// disable swap (otherwise after about 1000 test runs you run out of swap file names)
.arg("-n")
// disable writing files (just in case)
.arg("-m"),
handler,
)
.await
.expect("Could not connect to neovim process");
nvim.ui_attach(100, 100, &UiAttachOptions::default())
.await
.expect("Could not attach to ui");
// Makes system act a little more like zed in terms of indentation
nvim.set_option("smartindent", nvim_rs::Value::Boolean(true))
.await
.expect("Could not set smartindent on startup");
(nvim, join_handle, child)
})
.await;
Self {
#[cfg(feature = "neovim")]
data: Default::default(),
#[cfg(not(feature = "neovim"))]
data: Self::read_test_data(&test_case_id),
#[cfg(feature = "neovim")]
test_case_id,
#[cfg(feature = "neovim")]
nvim,
#[cfg(feature = "neovim")]
_join_handle: join_handle,
#[cfg(feature = "neovim")]
_child: child,
}
}
// Sends a keystroke to the neovim process.
#[cfg(feature = "neovim")]
pub async fn send_keystroke(&mut self, keystroke_text: &str) {
let mut keystroke = Keystroke::parse(keystroke_text).unwrap();
if keystroke.key == "<" {
keystroke.key = "lt".to_string()
}
let special = keystroke.shift
|| keystroke.ctrl
|| keystroke.alt
|| keystroke.cmd
|| keystroke.key.len() > 1;
let start = if special { "<" } else { "" };
let shift = if keystroke.shift { "S-" } else { "" };
let ctrl = if keystroke.ctrl { "C-" } else { "" };
let alt = if keystroke.alt { "M-" } else { "" };
let cmd = if keystroke.cmd { "D-" } else { "" };
let end = if special { ">" } else { "" };
let key = format!("{start}{shift}{ctrl}{alt}{cmd}{}{end}", keystroke.key);
self.data
.push_back(NeovimData::Key(keystroke_text.to_string()));
self.nvim
.input(&key)
.await
.expect("Could not input keystroke");
}
#[cfg(not(feature = "neovim"))]
pub async fn send_keystroke(&mut self, keystroke_text: &str) {
if matches!(self.data.front(), Some(NeovimData::Get { .. })) {
self.data.pop_front();
}
assert_eq!(
self.data.pop_front(),
Some(NeovimData::Key(keystroke_text.to_string())),
"operation does not match recorded script. re-record with --features=neovim"
);
}
#[cfg(feature = "neovim")]
pub async fn set_state(&mut self, marked_text: &str) {
let (text, selections) = parse_state(&marked_text);
let nvim_buffer = self
.nvim
.get_current_buf()
.await
.expect("Could not get neovim buffer");
let lines = text
.split('\n')
.map(|line| line.to_string())
.collect::<Vec<_>>();
nvim_buffer
.set_lines(0, -1, false, lines)
.await
.expect("Could not set nvim buffer text");
self.nvim
.input("<escape>")
.await
.expect("Could not send escape to nvim");
self.nvim
.input("<escape>")
.await
.expect("Could not send escape to nvim");
let nvim_window = self
.nvim
.get_current_win()
.await
.expect("Could not get neovim window");
if selections.len() != 1 {
panic!("must have one selection");
}
let selection = &selections[0];
let cursor = selection.start;
nvim_window
.set_cursor((cursor.row as i64 + 1, cursor.column as i64))
.await
.expect("Could not set nvim cursor position");
if !selection.is_empty() {
self.nvim
.input("v")
.await
.expect("could not enter visual mode");
let cursor = selection.end;
nvim_window
.set_cursor((cursor.row as i64 + 1, cursor.column as i64))
.await
.expect("Could not set nvim cursor position");
}
if let Some(NeovimData::Get { mode, state }) = self.data.back() {
if *mode == Some(Mode::Normal) && *state == marked_text {
return;
}
}
self.data.push_back(NeovimData::Put {
state: marked_text.to_string(),
})
}
#[cfg(not(feature = "neovim"))]
pub async fn set_state(&mut self, marked_text: &str) {
if let Some(NeovimData::Get { mode, state: text }) = self.data.front() {
if *mode == Some(Mode::Normal) && *text == marked_text {
return;
}
self.data.pop_front();
}
assert_eq!(
self.data.pop_front(),
Some(NeovimData::Put {
state: marked_text.to_string()
}),
"operation does not match recorded script. re-record with --features=neovim"
);
}
#[cfg(feature = "neovim")]
pub async fn set_option(&mut self, value: &str) {
self.nvim
.command_output(format!("set {}", value).as_str())
.await
.unwrap();
self.data.push_back(NeovimData::SetOption {
value: value.to_string(),
})
}
#[cfg(not(feature = "neovim"))]
pub async fn set_option(&mut self, value: &str) {
if let Some(NeovimData::Get { .. }) = self.data.front() {
self.data.pop_front();
};
assert_eq!(
self.data.pop_front(),
Some(NeovimData::SetOption {
value: value.to_string(),
}),
"operation does not match recorded script. re-record with --features=neovim"
);
}
#[cfg(not(feature = "neovim"))]
pub async fn read_register(&mut self, register: char) -> String {
if let Some(NeovimData::Get { .. }) = self.data.front() {
self.data.pop_front();
};
if let Some(NeovimData::ReadRegister { name, value }) = self.data.pop_front() {
if name == register {
return value;
}
}
panic!("operation does not match recorded script. re-record with --features=neovim")
}
#[cfg(feature = "neovim")]
pub async fn read_register(&mut self, name: char) -> String {
let value = self
.nvim
.command_output(format!("echo getreg('{}')", name).as_str())
.await
.unwrap();
self.data.push_back(NeovimData::ReadRegister {
name,
value: value.clone(),
});
value
}
#[cfg(feature = "neovim")]
async fn read_position(&mut self, cmd: &str) -> u32 {
self.nvim
.command_output(cmd)
.await
.unwrap()
.parse::<u32>()
.unwrap()
}
#[cfg(feature = "neovim")]
pub async fn state(&mut self) -> (Option<Mode>, String) {
let nvim_buffer = self
.nvim
.get_current_buf()
.await
.expect("Could not get neovim buffer");
let text = nvim_buffer
.get_lines(0, -1, false)
.await
.expect("Could not get buffer text")
.join("\n");
// nvim columns are 1-based, so -1.
let mut cursor_row = self.read_position("echo line('.')").await - 1;
let mut cursor_col = self.read_position("echo col('.')").await - 1;
let mut selection_row = self.read_position("echo line('v')").await - 1;
let mut selection_col = self.read_position("echo col('v')").await - 1;
let total_rows = self.read_position("echo line('$')").await - 1;
let nvim_mode_text = self
.nvim
.get_mode()
.await
.expect("Could not get mode")
.into_iter()
.find_map(|(key, value)| {
if key.as_str() == Some("mode") {
Some(value.as_str().unwrap().to_owned())
} else {
None
}
})
.expect("Could not find mode value");
let mode = match nvim_mode_text.as_ref() {
"i" => Some(Mode::Insert),
"n" => Some(Mode::Normal),
"v" => Some(Mode::Visual),
"V" => Some(Mode::VisualLine),
"\x16" => Some(Mode::VisualBlock),
_ => None,
};
let mut selections = Vec::new();
// Vim uses the index of the first and last character in the selection
// Zed uses the index of the positions between the characters, so we need
// to add one to the end in visual mode.
match mode {
Some(Mode::VisualBlock) if selection_row != cursor_row => {
// in zed we fake a block selecrtion by using multiple cursors (one per line)
// this code emulates that.
// to deal with casees where the selection is not perfectly rectangular we extract
// the content of the selection via the "a register to get the shape correctly.
self.nvim.input("\"aygv").await.unwrap();
let content = self.nvim.command_output("echo getreg('a')").await.unwrap();
let lines = content.split("\n").collect::<Vec<_>>();
let top = cmp::min(selection_row, cursor_row);
let left = cmp::min(selection_col, cursor_col);
for row in top..=cmp::max(selection_row, cursor_row) {
let content = if row - top >= lines.len() as u32 {
""
} else {
lines[(row - top) as usize]
};
let line_len = self
.read_position(format!("echo strlen(getline({}))", row + 1).as_str())
.await;
if left > line_len {
continue;
}
let start = Point::new(row, left);
let end = Point::new(row, left + content.len() as u32);
if cursor_col >= selection_col {
selections.push(start..end)
} else {
selections.push(end..start)
}
}
}
Some(Mode::Visual) | Some(Mode::VisualLine) | Some(Mode::VisualBlock) => {
if selection_col > cursor_col {
let selection_line_length =
self.read_position("echo strlen(getline(line('v')))").await;
if selection_line_length > selection_col {
selection_col += 1;
} else if selection_row < total_rows {
selection_col = 0;
selection_row += 1;
}
} else {
let cursor_line_length =
self.read_position("echo strlen(getline(line('.')))").await;
if cursor_line_length > cursor_col {
cursor_col += 1;
} else if cursor_row < total_rows {
cursor_col = 0;
cursor_row += 1;
}
}
selections.push(
Point::new(selection_row, selection_col)..Point::new(cursor_row, cursor_col),
)
}
Some(Mode::Insert) | Some(Mode::Normal) | None => selections
.push(Point::new(selection_row, selection_col)..Point::new(cursor_row, cursor_col)),
}
let ranges = encode_ranges(&text, &selections);
let state = NeovimData::Get {
mode,
state: ranges.clone(),
};
if self.data.back() != Some(&state) {
self.data.push_back(state.clone());
}
(mode, ranges)
}
#[cfg(not(feature = "neovim"))]
pub async fn state(&mut self) -> (Option<Mode>, String) {
if let Some(NeovimData::Get { state: raw, mode }) = self.data.front() {
(*mode, raw.to_string())
} else {
panic!("operation does not match recorded script. re-record with --features=neovim");
}
}
pub async fn mode(&mut self) -> Option<Mode> {
self.state().await.0
}
pub async fn marked_text(&mut self) -> String {
self.state().await.1
}
fn test_data_path(test_case_id: &str) -> PathBuf {
let mut data_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
data_path.push("test_data");
data_path.push(format!("{}.json", test_case_id));
data_path
}
#[cfg(not(feature = "neovim"))]
fn read_test_data(test_case_id: &str) -> VecDeque<NeovimData> {
let path = Self::test_data_path(test_case_id);
let json = std::fs::read_to_string(path).expect(
"Could not read test data. Is it generated? Try running test with '--features neovim'",
);
let mut result = VecDeque::new();
for line in json.lines() {
result.push_back(
serde_json::from_str(line)
.expect("invalid test data. regenerate it with '--features neovim'"),
);
}
result
}
#[cfg(feature = "neovim")]
fn write_test_data(test_case_id: &str, data: &VecDeque<NeovimData>) {
let path = Self::test_data_path(test_case_id);
let mut json = Vec::new();
for entry in data {
serde_json::to_writer(&mut json, entry).unwrap();
json.push(b'\n');
}
std::fs::create_dir_all(path.parent().unwrap())
.expect("could not create test data directory");
std::fs::write(path, json).expect("could not write out test data");
}
}
#[cfg(feature = "neovim")]
impl Deref for NeovimConnection {
type Target = Neovim<nvim_rs::compat::tokio::Compat<ChildStdin>>;
fn deref(&self) -> &Self::Target {
&self.nvim
}
}
#[cfg(feature = "neovim")]
impl DerefMut for NeovimConnection {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.nvim
}
}
#[cfg(feature = "neovim")]
impl Drop for NeovimConnection {
fn drop(&mut self) {
Self::write_test_data(&self.test_case_id, &self.data);
}
}
#[cfg(feature = "neovim")]
#[derive(Clone)]
struct NvimHandler {}
#[cfg(feature = "neovim")]
#[async_trait]
impl Handler for NvimHandler {
type Writer = nvim_rs::compat::tokio::Compat<ChildStdin>;
async fn handle_request(
&self,
_event_name: String,
_arguments: Vec<Value>,
_neovim: Neovim<Self::Writer>,
) -> Result<Value, Value> {
unimplemented!();
}
async fn handle_notify(
&self,
_event_name: String,
_arguments: Vec<Value>,
_neovim: Neovim<Self::Writer>,
) {
}
}
#[cfg(feature = "neovim")]
fn parse_state(marked_text: &str) -> (String, Vec<Range<Point>>) {
let (text, ranges) = util::test::marked_text_ranges(marked_text, true);
let point_ranges = ranges
.into_iter()
.map(|byte_range| {
let mut point_range = Point::zero()..Point::zero();
let mut ix = 0;
let mut position = Point::zero();
for c in text.chars().chain(['\0']) {
if ix == byte_range.start {
point_range.start = position;
}
if ix == byte_range.end {
point_range.end = position;
}
let len_utf8 = c.len_utf8();
ix += len_utf8;
if c == '\n' {
position.row += 1;
position.column = 0;
} else {
position.column += len_utf8 as u32;
}
}
point_range
})
.collect::<Vec<_>>();
(text, point_ranges)
}
#[cfg(feature = "neovim")]
fn encode_ranges(text: &str, point_ranges: &Vec<Range<Point>>) -> String {
let byte_ranges = point_ranges
.into_iter()
.map(|range| {
let mut byte_range = 0..0;
let mut ix = 0;
let mut position = Point::zero();
for c in text.chars().chain(['\0']) {
if position == range.start {
byte_range.start = ix;
}
if position == range.end {
byte_range.end = ix;
}
let len_utf8 = c.len_utf8();
ix += len_utf8;
if c == '\n' {
position.row += 1;
position.column = 0;
} else {
position.column += len_utf8 as u32;
}
}
byte_range
})
.collect::<Vec<_>>();
util::test::generate_marked_text(text, &byte_ranges[..], true)
}
+165
View File
@@ -0,0 +1,165 @@
use std::ops::{Deref, DerefMut};
use editor::test::{
editor_lsp_test_context::EditorLspTestContext, editor_test_context::EditorTestContext,
};
use futures::Future;
use gpui::{Context, View, VisualContext};
use lsp::request;
use search::BufferSearchBar;
use crate::{state::Operator, *};
pub struct VimTestContext<'a> {
cx: EditorLspTestContext<'a>,
}
impl<'a> VimTestContext<'a> {
pub async fn new(cx: &'a mut gpui::TestAppContext, enabled: bool) -> VimTestContext<'a> {
let lsp = EditorLspTestContext::new_rust(Default::default(), cx).await;
Self::new_with_lsp(lsp, enabled)
}
pub async fn new_typescript(cx: &'a mut gpui::TestAppContext) -> VimTestContext<'a> {
Self::new_with_lsp(
EditorLspTestContext::new_typescript(Default::default(), cx).await,
true,
)
}
pub fn new_with_lsp(mut cx: EditorLspTestContext<'a>, enabled: bool) -> VimTestContext<'a> {
cx.update(|cx| {
search::init(cx);
crate::init(cx);
command_palette::init(cx);
});
cx.update(|cx| {
cx.update_global(|store: &mut SettingsStore, cx| {
store.update_user_settings::<VimModeSetting>(cx, |s| *s = Some(enabled));
});
settings::KeymapFile::load_asset("keymaps/default.json", cx).unwrap();
settings::KeymapFile::load_asset("keymaps/vim.json", cx).unwrap();
});
// Setup search toolbars and keypress hook
cx.update_workspace(|workspace, cx| {
observe_keystrokes(cx);
workspace.active_pane().update(cx, |pane, cx| {
pane.toolbar().update(cx, |toolbar, cx| {
let buffer_search_bar = cx.build_view(BufferSearchBar::new);
toolbar.add_item(buffer_search_bar, cx);
// todo!();
// let project_search_bar = cx.add_view(|_| ProjectSearchBar::new());
// toolbar.add_item(project_search_bar, cx);
})
});
workspace.status_bar().update(cx, |status_bar, cx| {
let vim_mode_indicator = cx.build_view(ModeIndicator::new);
status_bar.add_right_item(vim_mode_indicator, cx);
});
});
Self { cx }
}
pub fn update_view<F, T, R>(&mut self, view: View<T>, update: F) -> R
where
F: FnOnce(&mut T, &mut ViewContext<T>) -> R,
{
self.update_window(self.window, |_, cx| view.update(cx, update))
.unwrap()
}
pub fn workspace<F, T>(&mut self, update: F) -> T
where
F: FnOnce(&mut Workspace, &mut ViewContext<Workspace>) -> T,
{
self.update_window(self.window, |_, cx| self.cx.workspace.update(cx, update))
.unwrap()
}
pub fn enable_vim(&mut self) {
self.cx.update(|cx| {
cx.update_global(|store: &mut SettingsStore, cx| {
store.update_user_settings::<VimModeSetting>(cx, |s| *s = Some(true));
});
})
}
pub fn disable_vim(&mut self) {
self.cx.update(|cx| {
cx.update_global(|store: &mut SettingsStore, cx| {
store.update_user_settings::<VimModeSetting>(cx, |s| *s = Some(false));
});
})
}
pub fn mode(&mut self) -> Mode {
self.cx.read(|cx| cx.global::<Vim>().state().mode)
}
pub fn active_operator(&mut self) -> Option<Operator> {
self.cx
.read(|cx| cx.global::<Vim>().state().operator_stack.last().copied())
}
pub fn set_state(&mut self, text: &str, mode: Mode) {
let window = self.window;
self.cx.set_state(text);
self.update_window(window, |_, cx| {
Vim::update(cx, |vim, cx| {
vim.switch_mode(mode, true, cx);
})
});
self.cx.cx.cx.run_until_parked();
}
#[track_caller]
pub fn assert_state(&mut self, text: &str, mode: Mode) {
self.assert_editor_state(text);
assert_eq!(self.mode(), mode, "{}", self.assertion_context());
}
pub fn assert_binding<const COUNT: usize>(
&mut self,
keystrokes: [&str; COUNT],
initial_state: &str,
initial_mode: Mode,
state_after: &str,
mode_after: Mode,
) {
self.set_state(initial_state, initial_mode);
self.cx.simulate_keystrokes(keystrokes);
self.cx.assert_editor_state(state_after);
assert_eq!(self.mode(), mode_after, "{}", self.assertion_context());
assert_eq!(self.active_operator(), None, "{}", self.assertion_context());
}
pub fn handle_request<T, F, Fut>(
&self,
handler: F,
) -> futures::channel::mpsc::UnboundedReceiver<()>
where
T: 'static + request::Request,
T::Params: 'static + Send,
F: 'static + Send + FnMut(lsp::Url, T::Params, gpui::AsyncAppContext) -> Fut,
Fut: 'static + Send + Future<Output = Result<T::Result>>,
{
self.cx.handle_request::<T, F, Fut>(handler)
}
}
impl<'a> Deref for VimTestContext<'a> {
type Target = EditorTestContext<'a>;
fn deref(&self) -> &Self::Target {
&self.cx
}
}
impl<'a> DerefMut for VimTestContext<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.cx
}
}