neovim_backed_test_context.rs

  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, Vim};
 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 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                {}
124                # neovim register \"{}:
125                {}
126                # zed register \"{}:
127                {}"},
128            message,
129            self.state.initial,
130            self.state.recent_keystrokes,
131            expected,
132            self.register,
133            self.neovim,
134            self.register,
135            self.editor
136        )
137    }
138}
139
140impl NeovimBackedTestContext {
141    pub async fn new(cx: &mut gpui::TestAppContext) -> NeovimBackedTestContext {
142        #[cfg(feature = "neovim")]
143        cx.executor().allow_parking();
144        // rust stores the name of the test on the current thread.
145        // We use this to automatically name a file that will store
146        // the neovim connection's requests/responses so that we can
147        // run without neovim on CI.
148        let thread = thread::current();
149        let test_name = thread
150            .name()
151            .expect("thread is not named")
152            .split(':')
153            .last()
154            .unwrap()
155            .to_string();
156        Self {
157            cx: VimTestContext::new(cx, true).await,
158            neovim: NeovimConnection::new(test_name).await,
159
160            last_set_state: None,
161            recent_keystrokes: Default::default(),
162        }
163    }
164
165    pub async fn set_shared_state(&mut self, marked_text: &str) {
166        let mode = if marked_text.contains('»') {
167            Mode::Visual
168        } else {
169            Mode::Normal
170        };
171        self.set_state(marked_text, mode);
172        self.last_set_state = Some(marked_text.to_string());
173        self.recent_keystrokes = Vec::new();
174        self.neovim.set_state(marked_text).await;
175    }
176
177    pub async fn simulate_shared_keystrokes(&mut self, keystroke_texts: &str) {
178        for keystroke_text in keystroke_texts.split(' ') {
179            self.recent_keystrokes.push(keystroke_text.to_string());
180            self.neovim.send_keystroke(keystroke_text).await;
181        }
182        self.simulate_keystrokes(keystroke_texts);
183    }
184
185    #[must_use]
186    pub async fn simulate(&mut self, keystrokes: &str, initial_state: &str) -> SharedState {
187        self.set_shared_state(initial_state).await;
188        self.simulate_shared_keystrokes(keystrokes).await;
189        self.shared_state().await
190    }
191
192    pub async fn set_shared_wrap(&mut self, columns: u32) {
193        if columns < 12 {
194            panic!("nvim doesn't support columns < 12")
195        }
196        self.neovim.set_option("wrap").await;
197        self.neovim
198            .set_option(&format!("columns={}", columns))
199            .await;
200
201        self.update(|cx| {
202            SettingsStore::update_global(cx, |settings, cx| {
203                settings.update_user_settings::<AllLanguageSettings>(cx, |settings| {
204                    settings.defaults.soft_wrap = Some(SoftWrap::PreferredLineLength);
205                    settings.defaults.preferred_line_length = Some(columns);
206                });
207            })
208        })
209    }
210
211    pub async fn set_scroll_height(&mut self, rows: u32) {
212        // match Zed's scrolling behavior
213        self.neovim.set_option(&format!("scrolloff={}", 3)).await;
214        // +2 to account for the vim command UI at the bottom.
215        self.neovim.set_option(&format!("lines={}", rows + 2)).await;
216        let (line_height, visible_line_count) = self.editor(|editor, cx| {
217            (
218                editor
219                    .style()
220                    .unwrap()
221                    .text
222                    .line_height_in_pixels(cx.rem_size()),
223                editor.visible_line_count().unwrap(),
224            )
225        });
226
227        let window = self.window;
228        let margin = self
229            .update_window(window, |_, cx| {
230                cx.viewport_size().height - line_height * visible_line_count
231            })
232            .unwrap();
233
234        self.simulate_window_resize(
235            self.window,
236            size(px(1000.), margin + (rows as f32) * line_height),
237        );
238    }
239
240    pub async fn set_neovim_option(&mut self, option: &str) {
241        self.neovim.set_option(option).await;
242    }
243
244    #[must_use]
245    pub async fn shared_clipboard(&mut self) -> SharedClipboard {
246        SharedClipboard {
247            register: '"',
248            state: self.shared_state().await,
249            neovim: self.neovim.read_register('"').await,
250            editor: self
251                .read_from_clipboard()
252                .unwrap()
253                .text()
254                .unwrap()
255                .to_owned(),
256        }
257    }
258
259    #[must_use]
260    pub async fn shared_register(&mut self, register: char) -> SharedClipboard {
261        SharedClipboard {
262            register,
263            state: self.shared_state().await,
264            neovim: self.neovim.read_register(register).await,
265            editor: self.update(|cx| {
266                Vim::read(cx)
267                    .workspace_state
268                    .registers
269                    .get(&register)
270                    .cloned()
271                    .unwrap_or_default()
272                    .text
273                    .into()
274            }),
275        }
276    }
277
278    #[must_use]
279    pub async fn shared_state(&mut self) -> SharedState {
280        let (mode, marked_text) = self.neovim.state().await;
281        SharedState {
282            neovim: marked_text,
283            neovim_mode: mode,
284            editor: self.editor_state(),
285            editor_mode: self.mode(),
286            initial: self
287                .last_set_state
288                .as_ref()
289                .cloned()
290                .unwrap_or("N/A".to_string()),
291            recent_keystrokes: self.recent_keystrokes.join(" "),
292        }
293    }
294
295    #[must_use]
296    pub async fn simulate_at_each_offset(
297        &mut self,
298        keystrokes: &str,
299        marked_positions: &str,
300    ) -> SharedState {
301        let (unmarked_text, cursor_offsets) = marked_text_offsets(marked_positions);
302
303        for cursor_offset in cursor_offsets.iter() {
304            let mut marked_text = unmarked_text.clone();
305            marked_text.insert(*cursor_offset, 'ˇ');
306
307            let state = self.simulate(keystrokes, &marked_text).await;
308            if state.neovim != state.editor || state.neovim_mode != state.editor_mode {
309                return state;
310            }
311        }
312
313        SharedState::default()
314    }
315}
316
317impl Deref for NeovimBackedTestContext {
318    type Target = VimTestContext;
319
320    fn deref(&self) -> &Self::Target {
321        &self.cx
322    }
323}
324
325impl DerefMut for NeovimBackedTestContext {
326    fn deref_mut(&mut self) -> &mut Self::Target {
327        &mut self.cx
328    }
329}
330
331#[cfg(test)]
332mod test {
333    use crate::test::NeovimBackedTestContext;
334    use gpui::TestAppContext;
335
336    #[gpui::test]
337    async fn neovim_backed_test_context_works(cx: &mut TestAppContext) {
338        let mut cx = NeovimBackedTestContext::new(cx).await;
339        cx.shared_state().await.assert_matches();
340        cx.set_shared_state("This is a tesˇt").await;
341        cx.shared_state().await.assert_matches();
342    }
343}