1use gpui::{AppContext as _, UpdateGlobal, px, size};
2use indoc::indoc;
3use settings::SettingsStore;
4use std::{
5 ops::{Deref, DerefMut},
6 panic, thread,
7};
8
9use language::language_settings::SoftWrap;
10use util::test::marked_text_offsets;
11
12use super::{VimTestContext, neovim_connection::NeovimConnection};
13use crate::state::{Mode, VimGlobals};
14
15pub struct NeovimBackedTestContext {
16 pub(crate) 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 behavior)
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 behavior"
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 register: char,
98 neovim: String,
99 editor: String,
100 state: SharedState,
101}
102
103impl SharedClipboard {
104 #[track_caller]
105 pub fn assert_eq(&self, expected: &str) {
106 if expected == self.neovim && self.neovim == self.editor {
107 return;
108 }
109
110 let message = if expected != self.neovim {
111 "Test is incorrect (currently expected != neovim_state)"
112 } else {
113 "Editor does not match nvim behavior"
114 };
115
116 panic!(
117 indoc! {"{}
118 # initial state:
119 {}
120 # keystrokes:
121 {}
122 # currently expected: {:?}
123 # neovim register \"{}: {:?}
124 # zed register \"{}: {:?}"},
125 message,
126 self.state.initial,
127 self.state.recent_keystrokes,
128 expected,
129 self.register,
130 self.neovim,
131 self.register,
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 .next_back()
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 new_html(cx: &mut gpui::TestAppContext) -> NeovimBackedTestContext {
163 #[cfg(feature = "neovim")]
164 cx.executor().allow_parking();
165 // rust stores the name of the test on the current thread.
166 // We use this to automatically name a file that will store
167 // the neovim connection's requests/responses so that we can
168 // run without neovim on CI.
169 let thread = thread::current();
170 let test_name = thread
171 .name()
172 .expect("thread is not named")
173 .split(':')
174 .next_back()
175 .unwrap()
176 .to_string();
177 Self {
178 cx: VimTestContext::new_html(cx).await,
179 neovim: NeovimConnection::new(test_name).await,
180
181 last_set_state: None,
182 recent_keystrokes: Default::default(),
183 }
184 }
185
186 pub async fn new_markdown_with_rust(cx: &mut gpui::TestAppContext) -> NeovimBackedTestContext {
187 #[cfg(feature = "neovim")]
188 cx.executor().allow_parking();
189 let thread = thread::current();
190 let test_name = thread
191 .name()
192 .expect("thread is not named")
193 .split(':')
194 .next_back()
195 .unwrap()
196 .to_string();
197 Self {
198 cx: VimTestContext::new_markdown_with_rust(cx).await,
199 neovim: NeovimConnection::new(test_name).await,
200
201 last_set_state: None,
202 recent_keystrokes: Default::default(),
203 }
204 }
205
206 pub async fn new_typescript(cx: &mut gpui::TestAppContext) -> NeovimBackedTestContext {
207 #[cfg(feature = "neovim")]
208 cx.executor().allow_parking();
209 // rust stores the name of the test on the current thread.
210 // We use this to automatically name a file that will store
211 // the neovim connection's requests/responses so that we can
212 // run without neovim on CI.
213 let thread = thread::current();
214 let test_name = thread
215 .name()
216 .expect("thread is not named")
217 .split(':')
218 .next_back()
219 .unwrap()
220 .to_string();
221 Self {
222 cx: VimTestContext::new_typescript(cx).await,
223 neovim: NeovimConnection::new(test_name).await,
224
225 last_set_state: None,
226 recent_keystrokes: Default::default(),
227 }
228 }
229
230 pub async fn new_tsx(cx: &mut gpui::TestAppContext) -> NeovimBackedTestContext {
231 #[cfg(feature = "neovim")]
232 cx.executor().allow_parking();
233 let thread = thread::current();
234 let test_name = thread
235 .name()
236 .expect("thread is not named")
237 .split(':')
238 .next_back()
239 .unwrap()
240 .to_string();
241 Self {
242 cx: VimTestContext::new_tsx(cx).await,
243 neovim: NeovimConnection::new(test_name).await,
244
245 last_set_state: None,
246 recent_keystrokes: Default::default(),
247 }
248 }
249
250 pub async fn set_shared_state(&mut self, marked_text: &str) {
251 let mode = if marked_text.contains('»') {
252 Mode::Visual
253 } else {
254 Mode::Normal
255 };
256 self.set_state(marked_text, mode);
257 self.last_set_state = Some(marked_text.to_string());
258 self.recent_keystrokes = Vec::new();
259 self.neovim.set_state(marked_text).await;
260 }
261
262 pub async fn simulate_shared_keystrokes(&mut self, keystroke_texts: &str) {
263 for keystroke_text in keystroke_texts.split(' ') {
264 self.recent_keystrokes.push(keystroke_text.to_string());
265 self.neovim.send_keystroke(keystroke_text).await;
266 }
267 self.simulate_keystrokes(keystroke_texts);
268 }
269
270 #[must_use]
271 pub async fn simulate(&mut self, keystrokes: &str, initial_state: &str) -> SharedState {
272 self.set_shared_state(initial_state).await;
273 self.simulate_shared_keystrokes(keystrokes).await;
274 self.shared_state().await
275 }
276
277 pub async fn set_shared_wrap(&mut self, columns: u32) {
278 if columns < 12 {
279 panic!("nvim doesn't support columns < 12")
280 }
281 self.neovim.set_option("wrap").await;
282 self.neovim
283 .set_option(&format!("columns={}", columns))
284 .await;
285
286 self.update(|_, cx| {
287 SettingsStore::update_global(cx, |settings, cx| {
288 settings.update_user_settings(cx, |settings| {
289 settings.project.all_languages.defaults.soft_wrap =
290 Some(SoftWrap::PreferredLineLength);
291 settings
292 .project
293 .all_languages
294 .defaults
295 .preferred_line_length = Some(columns);
296 });
297 })
298 })
299 }
300
301 pub async fn set_scroll_height(&mut self, rows: u32) {
302 // match Zed's scrolling behavior
303 self.neovim.set_option(&format!("scrolloff={}", 3)).await;
304 // +2 to account for the vim command UI at the bottom.
305 self.neovim.set_option(&format!("lines={}", rows + 2)).await;
306 let (line_height, visible_line_count) = self.editor(|editor, window, _cx| {
307 (
308 editor
309 .style()
310 .unwrap()
311 .text
312 .line_height_in_pixels(window.rem_size()),
313 editor.visible_line_count().unwrap(),
314 )
315 });
316
317 let window = self.window;
318 let margin = self
319 .update_window(window, |_, window, _cx| {
320 window.viewport_size().height - line_height * (visible_line_count as f32)
321 })
322 .unwrap();
323
324 self.simulate_window_resize(
325 self.window,
326 size(px(1000.), margin + (rows as f32) * line_height),
327 );
328 }
329
330 pub async fn set_neovim_option(&mut self, option: &str) {
331 self.neovim.set_option(option).await;
332 }
333
334 #[must_use]
335 pub async fn shared_clipboard(&mut self) -> SharedClipboard {
336 SharedClipboard {
337 register: '"',
338 state: self.shared_state().await,
339 neovim: self.neovim.read_register('"').await,
340 editor: self.read_from_clipboard().unwrap().text().unwrap(),
341 }
342 }
343
344 #[must_use]
345 pub async fn shared_register(&mut self, register: char) -> SharedClipboard {
346 SharedClipboard {
347 register,
348 state: self.shared_state().await,
349 neovim: self.neovim.read_register(register).await,
350 editor: self.update(|_, cx| {
351 cx.global::<VimGlobals>()
352 .registers
353 .get(®ister)
354 .cloned()
355 .unwrap_or_default()
356 .text
357 .into()
358 }),
359 }
360 }
361
362 #[must_use]
363 pub async fn shared_state(&mut self) -> SharedState {
364 let (mode, marked_text) = self.neovim.state().await;
365 SharedState {
366 neovim: marked_text,
367 neovim_mode: mode,
368 editor: self.editor_state(),
369 editor_mode: self.mode(),
370 initial: self
371 .last_set_state
372 .as_ref()
373 .cloned()
374 .unwrap_or("N/A".to_string()),
375 recent_keystrokes: self.recent_keystrokes.join(" "),
376 }
377 }
378
379 #[must_use]
380 pub async fn simulate_at_each_offset(
381 &mut self,
382 keystrokes: &str,
383 marked_positions: &str,
384 ) -> SharedState {
385 let (unmarked_text, cursor_offsets) = marked_text_offsets(marked_positions);
386
387 for cursor_offset in cursor_offsets.iter() {
388 let mut marked_text = unmarked_text.clone();
389 marked_text.insert(*cursor_offset, 'ˇ');
390
391 let state = self.simulate(keystrokes, &marked_text).await;
392 if state.neovim != state.editor || state.neovim_mode != state.editor_mode {
393 return state;
394 }
395 }
396
397 SharedState::default()
398 }
399}
400
401impl Deref for NeovimBackedTestContext {
402 type Target = VimTestContext;
403
404 fn deref(&self) -> &Self::Target {
405 &self.cx
406 }
407}
408
409impl DerefMut for NeovimBackedTestContext {
410 fn deref_mut(&mut self) -> &mut Self::Target {
411 &mut self.cx
412 }
413}
414
415#[cfg(test)]
416mod test {
417 use crate::test::NeovimBackedTestContext;
418 use gpui::TestAppContext;
419
420 #[gpui::test]
421 async fn neovim_backed_test_context_works(cx: &mut TestAppContext) {
422 let mut cx = NeovimBackedTestContext::new(cx).await;
423 cx.shared_state().await.assert_matches();
424 cx.set_shared_state("This is a tesˇt").await;
425 cx.shared_state().await.assert_matches();
426 }
427}