neovim_backed_test_context.rs

  1use editor::test::editor_test_context::ContextHandle;
  2use gpui::{px, size, Context};
  3use indoc::indoc;
  4use settings::SettingsStore;
  5use std::{
  6    ops::{Deref, DerefMut},
  7    panic, thread,
  8};
  9
 10use collections::{HashMap, HashSet};
 11use language::language_settings::{AllLanguageSettings, SoftWrap};
 12use util::test::marked_text_offsets;
 13
 14use super::{neovim_connection::NeovimConnection, NeovimBackedBindingTestContext, VimTestContext};
 15use crate::state::Mode;
 16
 17pub const SUPPORTED_FEATURES: &[ExemptionFeatures] = &[];
 18
 19/// Enum representing features we have tests for but which don't work, yet. Used
 20/// to add exemptions and automatically
 21#[derive(PartialEq, Eq)]
 22pub enum ExemptionFeatures {
 23    // MOTIONS
 24    // When an operator completes at the end of the file, an extra newline is left
 25    OperatorLastNewlineRemains,
 26
 27    // OBJECTS
 28    // Resulting position after the operation is slightly incorrect for unintuitive reasons.
 29    IncorrectLandingPosition,
 30    // Operator around the text object at the end of the line doesn't remove whitespace.
 31    AroundObjectLeavesWhitespaceAtEndOfLine,
 32    // Sentence object on empty lines
 33    SentenceOnEmptyLines,
 34    // Whitespace isn't included with text objects at the start of the line
 35    SentenceAtStartOfLineWithWhitespace,
 36    // Whitespace around sentences is slightly incorrect when starting between sentences
 37    AroundSentenceStartingBetweenIncludesWrongWhitespace,
 38    // Non empty selection with text objects in visual mode
 39    NonEmptyVisualTextObjects,
 40    // Sentence Doesn't backtrack when its at the end of the file
 41    SentenceAfterPunctuationAtEndOfFile,
 42}
 43
 44impl ExemptionFeatures {
 45    pub fn supported(&self) -> bool {
 46        SUPPORTED_FEATURES.contains(self)
 47    }
 48}
 49
 50pub struct NeovimBackedTestContext {
 51    cx: VimTestContext,
 52    // Lookup for exempted assertions. Keyed by the insertion text, and with a value indicating which
 53    // bindings are exempted. If None, all bindings are ignored for that insertion text.
 54    exemptions: HashMap<String, Option<HashSet<String>>>,
 55    pub(crate) neovim: NeovimConnection,
 56
 57    last_set_state: Option<String>,
 58    recent_keystrokes: Vec<String>,
 59
 60    is_dirty: bool,
 61}
 62
 63impl NeovimBackedTestContext {
 64    pub async fn new(cx: &mut gpui::TestAppContext) -> NeovimBackedTestContext {
 65        #[cfg(feature = "neovim")]
 66        cx.executor().allow_parking();
 67        // rust stores the name of the test on the current thread.
 68        // We use this to automatically name a file that will store
 69        // the neovim connection's requests/responses so that we can
 70        // run without neovim on CI.
 71        let thread = thread::current();
 72        let test_name = thread
 73            .name()
 74            .expect("thread is not named")
 75            .split(':')
 76            .last()
 77            .unwrap()
 78            .to_string();
 79        Self {
 80            cx: VimTestContext::new(cx, true).await,
 81            exemptions: Default::default(),
 82            neovim: NeovimConnection::new(test_name).await,
 83
 84            last_set_state: None,
 85            recent_keystrokes: Default::default(),
 86            is_dirty: false,
 87        }
 88    }
 89
 90    pub fn add_initial_state_exemptions(
 91        &mut self,
 92        marked_positions: &str,
 93        missing_feature: ExemptionFeatures, // Feature required to support this exempted test case
 94    ) {
 95        if !missing_feature.supported() {
 96            let (unmarked_text, cursor_offsets) = marked_text_offsets(marked_positions);
 97
 98            for cursor_offset in cursor_offsets.iter() {
 99                let mut marked_text = unmarked_text.clone();
100                marked_text.insert(*cursor_offset, 'ˇ');
101
102                // None represents all key bindings being exempted for that initial state
103                self.exemptions.insert(marked_text, None);
104            }
105        }
106    }
107
108    pub async fn simulate_shared_keystroke(&mut self, keystroke_text: &str) -> ContextHandle {
109        self.neovim.send_keystroke(keystroke_text).await;
110        self.simulate_keystroke(keystroke_text)
111    }
112
113    pub async fn simulate_shared_keystrokes<const COUNT: usize>(
114        &mut self,
115        keystroke_texts: [&str; COUNT],
116    ) {
117        for keystroke_text in keystroke_texts.into_iter() {
118            self.recent_keystrokes.push(keystroke_text.to_string());
119            self.neovim.send_keystroke(keystroke_text).await;
120        }
121        self.simulate_keystrokes(keystroke_texts);
122    }
123
124    pub async fn set_shared_state(&mut self, marked_text: &str) {
125        let mode = if marked_text.contains('»') {
126            Mode::Visual
127        } else {
128            Mode::Normal
129        };
130        self.set_state(marked_text, mode);
131        self.last_set_state = Some(marked_text.to_string());
132        self.recent_keystrokes = Vec::new();
133        self.neovim.set_state(marked_text).await;
134        self.is_dirty = true;
135    }
136
137    pub async fn set_shared_wrap(&mut self, columns: u32) {
138        if columns < 12 {
139            panic!("nvim doesn't support columns < 12")
140        }
141        self.neovim.set_option("wrap").await;
142        self.neovim
143            .set_option(&format!("columns={}", columns))
144            .await;
145
146        self.update(|cx| {
147            cx.update_global(|settings: &mut SettingsStore, cx| {
148                settings.update_user_settings::<AllLanguageSettings>(cx, |settings| {
149                    settings.defaults.soft_wrap = Some(SoftWrap::PreferredLineLength);
150                    settings.defaults.preferred_line_length = Some(columns);
151                });
152            })
153        })
154    }
155
156    pub async fn set_scroll_height(&mut self, rows: u32) {
157        // match Zed's scrolling behavior
158        self.neovim.set_option(&format!("scrolloff={}", 3)).await;
159        // +2 to account for the vim command UI at the bottom.
160        self.neovim.set_option(&format!("lines={}", rows + 2)).await;
161        let (line_height, visible_line_count) = self.editor(|editor, cx| {
162            (
163                editor
164                    .style()
165                    .unwrap()
166                    .text
167                    .line_height_in_pixels(cx.rem_size()),
168                editor.visible_line_count().unwrap(),
169            )
170        });
171
172        let window = self.window;
173        let margin = self
174            .update_window(window, |_, cx| {
175                cx.viewport_size().height - line_height * visible_line_count
176            })
177            .unwrap();
178
179        self.simulate_window_resize(
180            self.window,
181            size(px(1000.), margin + (rows as f32) * line_height),
182        );
183    }
184
185    pub async fn set_neovim_option(&mut self, option: &str) {
186        self.neovim.set_option(option).await;
187    }
188
189    pub async fn assert_shared_state(&mut self, marked_text: &str) {
190        self.is_dirty = false;
191        let marked_text = marked_text.replace('•', " ");
192        let neovim = self.neovim_state().await;
193        let neovim_mode = self.neovim_mode().await;
194        let editor = self.editor_state();
195        let editor_mode = self.mode();
196        if neovim == marked_text && neovim == editor && neovim_mode == editor_mode {
197            return;
198        }
199        let initial_state = self
200            .last_set_state
201            .as_ref()
202            .unwrap_or(&"N/A".to_string())
203            .clone();
204
205        let message = if neovim != marked_text {
206            "Test is incorrect (currently expected != neovim_state)"
207        } else {
208            "Editor does not match nvim behaviour"
209        };
210        panic!(
211            indoc! {"{}
212                # initial state:
213                {}
214                # keystrokes:
215                {}
216                # currently expected:
217                {}
218                # neovim ({}):
219                {}
220                # zed ({}):
221                {}"},
222            message,
223            initial_state,
224            self.recent_keystrokes.join(" "),
225            marked_text.replace(" \n", "\n"),
226            neovim_mode,
227            neovim.replace(" \n", "\n"),
228            editor_mode,
229            editor.replace(" \n", "\n"),
230        )
231    }
232
233    pub async fn assert_shared_clipboard(&mut self, text: &str) {
234        let neovim = self.neovim.read_register('"').await;
235        let editor = self.read_from_clipboard().unwrap().text().clone();
236
237        if text == neovim && text == editor {
238            return;
239        }
240
241        let message = if neovim != text {
242            "Test is incorrect (currently expected != neovim)"
243        } else {
244            "Editor does not match nvim behaviour"
245        };
246
247        let initial_state = self
248            .last_set_state
249            .as_ref()
250            .unwrap_or(&"N/A".to_string())
251            .clone();
252
253        panic!(
254            indoc! {"{}
255                # initial state:
256                {}
257                # keystrokes:
258                {}
259                # currently expected:
260                {}
261                # neovim clipboard:
262                {}
263                # zed clipboard:
264                {}"},
265            message,
266            initial_state,
267            self.recent_keystrokes.join(" "),
268            text,
269            neovim,
270            editor
271        )
272    }
273
274    pub async fn neovim_state(&mut self) -> String {
275        self.neovim.marked_text().await
276    }
277
278    pub async fn neovim_mode(&mut self) -> Mode {
279        self.neovim.mode().await.unwrap()
280    }
281
282    pub async fn assert_shared_mode(&mut self, mode: Mode) {
283        let neovim = self.neovim_mode().await;
284        let editor = self.cx.mode();
285
286        if neovim != mode || editor != mode {
287            panic!(
288                indoc! {"Test failed (zed does not match nvim behaviour)
289                    # desired mode:
290                    {:?}
291                    # neovim mode:
292                    {:?}
293                    # zed mode:
294                    {:?}"},
295                mode, neovim, editor,
296            )
297        }
298    }
299
300    pub async fn assert_state_matches(&mut self) {
301        self.is_dirty = false;
302        let neovim = self.neovim_state().await;
303        let neovim_mode = self.neovim_mode().await;
304        let editor = self.editor_state();
305        let editor_mode = self.mode();
306        let initial_state = self
307            .last_set_state
308            .as_ref()
309            .unwrap_or(&"N/A".to_string())
310            .clone();
311
312        if neovim != editor || neovim_mode != editor_mode {
313            panic!(
314                indoc! {"Test failed (zed does not match nvim behaviour)
315                    # initial state:
316                    {}
317                    # keystrokes:
318                    {}
319                    # neovim ({}):
320                    {}
321                    # zed ({}):
322                    {}"},
323                initial_state,
324                self.recent_keystrokes.join(" "),
325                neovim_mode,
326                neovim,
327                editor_mode,
328                editor,
329            )
330        }
331    }
332
333    pub async fn assert_binding_matches<const COUNT: usize>(
334        &mut self,
335        keystrokes: [&str; COUNT],
336        initial_state: &str,
337    ) {
338        if let Some(possible_exempted_keystrokes) = self.exemptions.get(initial_state) {
339            match possible_exempted_keystrokes {
340                Some(exempted_keystrokes) => {
341                    if exempted_keystrokes.contains(&format!("{keystrokes:?}")) {
342                        // This keystroke was exempted for this insertion text
343                        return;
344                    }
345                }
346                None => {
347                    // All keystrokes for this insertion text are exempted
348                    return;
349                }
350            }
351        }
352
353        let _state_context = self.set_shared_state(initial_state).await;
354        let _keystroke_context = self.simulate_shared_keystrokes(keystrokes).await;
355        self.assert_state_matches().await;
356    }
357
358    pub async fn assert_binding_matches_all<const COUNT: usize>(
359        &mut self,
360        keystrokes: [&str; COUNT],
361        marked_positions: &str,
362    ) {
363        let (unmarked_text, cursor_offsets) = marked_text_offsets(marked_positions);
364
365        for cursor_offset in cursor_offsets.iter() {
366            let mut marked_text = unmarked_text.clone();
367            marked_text.insert(*cursor_offset, 'ˇ');
368
369            self.assert_binding_matches(keystrokes, &marked_text).await;
370        }
371    }
372
373    pub fn each_marked_position(&self, marked_positions: &str) -> Vec<String> {
374        let (unmarked_text, cursor_offsets) = marked_text_offsets(marked_positions);
375        let mut ret = Vec::with_capacity(cursor_offsets.len());
376
377        for cursor_offset in cursor_offsets.iter() {
378            let mut marked_text = unmarked_text.clone();
379            marked_text.insert(*cursor_offset, 'ˇ');
380            ret.push(marked_text)
381        }
382
383        ret
384    }
385
386    pub async fn assert_neovim_compatible<const COUNT: usize>(
387        &mut self,
388        marked_positions: &str,
389        keystrokes: [&str; COUNT],
390    ) {
391        self.set_shared_state(&marked_positions).await;
392        self.simulate_shared_keystrokes(keystrokes).await;
393        self.assert_state_matches().await;
394    }
395
396    pub async fn assert_matches_neovim<const COUNT: usize>(
397        &mut self,
398        marked_positions: &str,
399        keystrokes: [&str; COUNT],
400        result: &str,
401    ) {
402        self.set_shared_state(marked_positions).await;
403        self.simulate_shared_keystrokes(keystrokes).await;
404        self.assert_shared_state(result).await;
405    }
406
407    pub async fn assert_binding_matches_all_exempted<const COUNT: usize>(
408        &mut self,
409        keystrokes: [&str; COUNT],
410        marked_positions: &str,
411        feature: ExemptionFeatures,
412    ) {
413        if SUPPORTED_FEATURES.contains(&feature) {
414            self.assert_binding_matches_all(keystrokes, marked_positions)
415                .await
416        }
417    }
418
419    pub fn binding<const COUNT: usize>(
420        self,
421        keystrokes: [&'static str; COUNT],
422    ) -> NeovimBackedBindingTestContext<COUNT> {
423        NeovimBackedBindingTestContext::new(keystrokes, self)
424    }
425}
426
427impl Deref for NeovimBackedTestContext {
428    type Target = VimTestContext;
429
430    fn deref(&self) -> &Self::Target {
431        &self.cx
432    }
433}
434
435impl DerefMut for NeovimBackedTestContext {
436    fn deref_mut(&mut self) -> &mut Self::Target {
437        &mut self.cx
438    }
439}
440
441// a common mistake in tests is to call set_shared_state when
442// you mean asswert_shared_state. This notices that and lets
443// you know.
444impl Drop for NeovimBackedTestContext {
445    fn drop(&mut self) {
446        if self.is_dirty {
447            panic!("Test context was dropped after set_shared_state before assert_shared_state")
448        }
449    }
450}
451
452#[cfg(test)]
453mod test {
454    use crate::test::NeovimBackedTestContext;
455    use gpui::TestAppContext;
456
457    #[gpui::test]
458    async fn neovim_backed_test_context_works(cx: &mut TestAppContext) {
459        let mut cx = NeovimBackedTestContext::new(cx).await;
460        cx.assert_state_matches().await;
461        cx.set_shared_state("This is a tesˇt").await;
462        cx.assert_state_matches().await;
463    }
464}