1use gpui::{px, size, Context, UpdateGlobal};
2use indoc::indoc;
3use settings::SettingsStore;
4use std::{
5 ops::{Deref, DerefMut},
6 panic, thread,
7};
8
9use language::language_settings::{AllLanguageSettings, SoftWrap};
10use util::test::marked_text_offsets;
11
12use super::{neovim_connection::NeovimConnection, VimTestContext};
13use crate::state::Mode;
14
15pub struct NeovimBackedTestContext {
16 cx: VimTestContext,
17 pub(crate) neovim: NeovimConnection,
18
19 last_set_state: Option<String>,
20 recent_keystrokes: Vec<String>,
21}
22
23#[derive(Default)]
24pub struct SharedState {
25 neovim: String,
26 editor: String,
27 initial: String,
28 neovim_mode: Mode,
29 editor_mode: Mode,
30 recent_keystrokes: String,
31}
32
33impl SharedState {
34 #[track_caller]
35 pub fn assert_matches(&self) {
36 if self.neovim != self.editor || self.neovim_mode != self.editor_mode {
37 panic!(
38 indoc! {"Test failed (zed does not match nvim behaviour)
39 # initial state:
40 {}
41 # keystrokes:
42 {}
43 # neovim ({}):
44 {}
45 # zed ({}):
46 {}"},
47 self.initial,
48 self.recent_keystrokes,
49 self.neovim_mode,
50 self.neovim,
51 self.editor_mode,
52 self.editor,
53 )
54 }
55 }
56
57 #[track_caller]
58 pub fn assert_eq(&mut self, marked_text: &str) {
59 let marked_text = marked_text.replace('•', " ");
60 if self.neovim == marked_text
61 && self.neovim == self.editor
62 && self.neovim_mode == self.editor_mode
63 {
64 return;
65 }
66
67 let message = if self.neovim != marked_text {
68 "Test is incorrect (currently expected != neovim_state)"
69 } else {
70 "Editor does not match nvim behaviour"
71 };
72 panic!(
73 indoc! {"{}
74 # initial state:
75 {}
76 # keystrokes:
77 {}
78 # currently expected:
79 {}
80 # neovim ({}):
81 {}
82 # zed ({}):
83 {}"},
84 message,
85 self.initial,
86 self.recent_keystrokes,
87 marked_text.replace(" \n", "•\n"),
88 self.neovim_mode,
89 self.neovim.replace(" \n", "•\n"),
90 self.editor_mode,
91 self.editor.replace(" \n", "•\n"),
92 )
93 }
94}
95
96pub struct SharedClipboard {
97 neovim: String,
98 editor: String,
99 state: SharedState,
100}
101
102impl SharedClipboard {
103 #[track_caller]
104 pub fn assert_eq(&self, expected: &str) {
105 if expected == self.neovim && self.neovim == self.editor {
106 return;
107 }
108
109 let message = if expected == self.neovim {
110 "Test is incorrect (currently expected != neovim_state)"
111 } else {
112 "Editor does not match nvim behaviour"
113 };
114
115 panic!(
116 indoc! {"{}
117 # initial state:
118 {}
119 # keystrokes:
120 {}
121 # currently expected:
122 {}
123 # neovim clipboard:
124 {}
125 # zed clipboard:
126 {}"},
127 message,
128 self.state.initial,
129 self.state.recent_keystrokes,
130 expected,
131 self.neovim,
132 self.editor
133 )
134 }
135}
136
137impl NeovimBackedTestContext {
138 pub async fn new(cx: &mut gpui::TestAppContext) -> NeovimBackedTestContext {
139 #[cfg(feature = "neovim")]
140 cx.executor().allow_parking();
141 // rust stores the name of the test on the current thread.
142 // We use this to automatically name a file that will store
143 // the neovim connection's requests/responses so that we can
144 // run without neovim on CI.
145 let thread = thread::current();
146 let test_name = thread
147 .name()
148 .expect("thread is not named")
149 .split(':')
150 .last()
151 .unwrap()
152 .to_string();
153 Self {
154 cx: VimTestContext::new(cx, true).await,
155 neovim: NeovimConnection::new(test_name).await,
156
157 last_set_state: None,
158 recent_keystrokes: Default::default(),
159 }
160 }
161
162 pub async fn set_shared_state(&mut self, marked_text: &str) {
163 let mode = if marked_text.contains('»') {
164 Mode::Visual
165 } else {
166 Mode::Normal
167 };
168 self.set_state(marked_text, mode);
169 self.last_set_state = Some(marked_text.to_string());
170 self.recent_keystrokes = Vec::new();
171 self.neovim.set_state(marked_text).await;
172 }
173
174 pub async fn simulate_shared_keystrokes(&mut self, keystroke_texts: &str) {
175 for keystroke_text in keystroke_texts.split(' ') {
176 self.recent_keystrokes.push(keystroke_text.to_string());
177 self.neovim.send_keystroke(keystroke_text).await;
178 }
179 self.simulate_keystrokes(keystroke_texts);
180 }
181
182 #[must_use]
183 pub async fn simulate(&mut self, keystrokes: &str, initial_state: &str) -> SharedState {
184 self.set_shared_state(initial_state).await;
185 self.simulate_shared_keystrokes(keystrokes).await;
186 self.shared_state().await
187 }
188
189 pub async fn set_shared_wrap(&mut self, columns: u32) {
190 if columns < 12 {
191 panic!("nvim doesn't support columns < 12")
192 }
193 self.neovim.set_option("wrap").await;
194 self.neovim
195 .set_option(&format!("columns={}", columns))
196 .await;
197
198 self.update(|cx| {
199 SettingsStore::update_global(cx, |settings, cx| {
200 settings.update_user_settings::<AllLanguageSettings>(cx, |settings| {
201 settings.defaults.soft_wrap = Some(SoftWrap::PreferredLineLength);
202 settings.defaults.preferred_line_length = Some(columns);
203 });
204 })
205 })
206 }
207
208 pub async fn set_scroll_height(&mut self, rows: u32) {
209 // match Zed's scrolling behavior
210 self.neovim.set_option(&format!("scrolloff={}", 3)).await;
211 // +2 to account for the vim command UI at the bottom.
212 self.neovim.set_option(&format!("lines={}", rows + 2)).await;
213 let (line_height, visible_line_count) = self.editor(|editor, cx| {
214 (
215 editor
216 .style()
217 .unwrap()
218 .text
219 .line_height_in_pixels(cx.rem_size()),
220 editor.visible_line_count().unwrap(),
221 )
222 });
223
224 let window = self.window;
225 let margin = self
226 .update_window(window, |_, cx| {
227 cx.viewport_size().height - line_height * visible_line_count
228 })
229 .unwrap();
230
231 self.simulate_window_resize(
232 self.window,
233 size(px(1000.), margin + (rows as f32) * line_height),
234 );
235 }
236
237 pub async fn set_neovim_option(&mut self, option: &str) {
238 self.neovim.set_option(option).await;
239 }
240
241 #[must_use]
242 pub async fn shared_clipboard(&mut self) -> SharedClipboard {
243 SharedClipboard {
244 state: self.shared_state().await,
245 neovim: self.neovim.read_register('"').await,
246 editor: self.read_from_clipboard().unwrap().text().clone(),
247 }
248 }
249
250 #[must_use]
251 pub async fn shared_state(&mut self) -> SharedState {
252 let (mode, marked_text) = self.neovim.state().await;
253 SharedState {
254 neovim: marked_text,
255 neovim_mode: mode,
256 editor: self.editor_state(),
257 editor_mode: self.mode(),
258 initial: self
259 .last_set_state
260 .as_ref()
261 .cloned()
262 .unwrap_or("N/A".to_string()),
263 recent_keystrokes: self.recent_keystrokes.join(" "),
264 }
265 }
266
267 #[must_use]
268 pub async fn simulate_at_each_offset(
269 &mut self,
270 keystrokes: &str,
271 marked_positions: &str,
272 ) -> SharedState {
273 let (unmarked_text, cursor_offsets) = marked_text_offsets(marked_positions);
274
275 for cursor_offset in cursor_offsets.iter() {
276 let mut marked_text = unmarked_text.clone();
277 marked_text.insert(*cursor_offset, 'ˇ');
278
279 let state = self.simulate(keystrokes, &marked_text).await;
280 if state.neovim != state.editor || state.neovim_mode != state.editor_mode {
281 return state;
282 }
283 }
284
285 SharedState::default()
286 }
287}
288
289impl Deref for NeovimBackedTestContext {
290 type Target = VimTestContext;
291
292 fn deref(&self) -> &Self::Target {
293 &self.cx
294 }
295}
296
297impl DerefMut for NeovimBackedTestContext {
298 fn deref_mut(&mut self) -> &mut Self::Target {
299 &mut self.cx
300 }
301}
302
303#[cfg(test)]
304mod test {
305 use crate::test::NeovimBackedTestContext;
306 use gpui::TestAppContext;
307
308 #[gpui::test]
309 async fn neovim_backed_test_context_works(cx: &mut TestAppContext) {
310 let mut cx = NeovimBackedTestContext::new(cx).await;
311 cx.shared_state().await.assert_matches();
312 cx.set_shared_state("This is a tesˇt").await;
313 cx.shared_state().await.assert_matches();
314 }
315}