neovim_backed_test_context.rs

  1use editor::scroll::VERTICAL_SCROLL_MARGIN;
  2use indoc::indoc;
  3use settings::SettingsStore;
  4use std::{
  5    ops::{Deref, DerefMut},
  6    panic, thread,
  7};
  8
  9use collections::{HashMap, HashSet};
 10use gpui::{geometry::vector::vec2f, ContextHandle};
 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<'a> {
 51    cx: VimTestContext<'a>,
 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    neovim: NeovimConnection,
 56
 57    last_set_state: Option<String>,
 58    recent_keystrokes: Vec<String>,
 59
 60    is_dirty: bool,
 61}
 62
 63impl<'a> NeovimBackedTestContext<'a> {
 64    pub async fn new(cx: &'a mut gpui::TestAppContext) -> NeovimBackedTestContext<'a> {
 65        // rust stores the name of the test on the current thread.
 66        // We use this to automatically name a file that will store
 67        // the neovim connection's requests/responses so that we can
 68        // run without neovim on CI.
 69        let thread = thread::current();
 70        let test_name = thread
 71            .name()
 72            .expect("thread is not named")
 73            .split(":")
 74            .last()
 75            .unwrap()
 76            .to_string();
 77        Self {
 78            cx: VimTestContext::new(cx, true).await,
 79            exemptions: Default::default(),
 80            neovim: NeovimConnection::new(test_name).await,
 81
 82            last_set_state: None,
 83            recent_keystrokes: Default::default(),
 84            is_dirty: false,
 85        }
 86    }
 87
 88    pub fn add_initial_state_exemptions(
 89        &mut self,
 90        marked_positions: &str,
 91        missing_feature: ExemptionFeatures, // Feature required to support this exempted test case
 92    ) {
 93        if !missing_feature.supported() {
 94            let (unmarked_text, cursor_offsets) = marked_text_offsets(marked_positions);
 95
 96            for cursor_offset in cursor_offsets.iter() {
 97                let mut marked_text = unmarked_text.clone();
 98                marked_text.insert(*cursor_offset, 'ˇ');
 99
100                // None represents all key bindings being exempted for that initial state
101                self.exemptions.insert(marked_text, None);
102            }
103        }
104    }
105
106    pub async fn simulate_shared_keystroke(&mut self, keystroke_text: &str) -> ContextHandle {
107        self.neovim.send_keystroke(keystroke_text).await;
108        self.simulate_keystroke(keystroke_text)
109    }
110
111    pub async fn simulate_shared_keystrokes<const COUNT: usize>(
112        &mut self,
113        keystroke_texts: [&str; COUNT],
114    ) {
115        for keystroke_text in keystroke_texts.into_iter() {
116            self.recent_keystrokes.push(keystroke_text.to_string());
117            self.neovim.send_keystroke(keystroke_text).await;
118        }
119        self.simulate_keystrokes(keystroke_texts);
120    }
121
122    pub async fn set_shared_state(&mut self, marked_text: &str) {
123        let mode = if marked_text.contains("»") {
124            Mode::Visual
125        } else {
126            Mode::Normal
127        };
128        self.set_state(marked_text, mode);
129        self.last_set_state = Some(marked_text.to_string());
130        self.recent_keystrokes = Vec::new();
131        self.neovim.set_state(marked_text).await;
132        self.is_dirty = true;
133    }
134
135    pub async fn set_shared_wrap(&mut self, columns: u32) {
136        if columns < 12 {
137            panic!("nvim doesn't support columns < 12")
138        }
139        self.neovim.set_option("wrap").await;
140        self.neovim
141            .set_option(&format!("columns={}", columns))
142            .await;
143
144        self.update(|cx| {
145            cx.update_global(|settings: &mut SettingsStore, cx| {
146                settings.update_user_settings::<AllLanguageSettings>(cx, |settings| {
147                    settings.defaults.soft_wrap = Some(SoftWrap::PreferredLineLength);
148                    settings.defaults.preferred_line_length = Some(columns);
149                });
150            })
151        })
152    }
153
154    pub async fn set_scroll_height(&mut self, rows: u32) {
155        // match Zed's scrolling behavior
156        self.neovim
157            .set_option(&format!("scrolloff={}", VERTICAL_SCROLL_MARGIN))
158            .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 window = self.window;
162        let line_height =
163            self.editor(|editor, cx| editor.style(cx).text.line_height(cx.font_cache()));
164
165        window.simulate_resize(vec2f(1000., (rows as f32) * line_height), &mut self.cx);
166    }
167
168    pub async fn set_neovim_option(&mut self, option: &str) {
169        self.neovim.set_option(option).await;
170    }
171
172    pub async fn assert_shared_state(&mut self, marked_text: &str) {
173        self.is_dirty = false;
174        let marked_text = marked_text.replace("", " ");
175        let neovim = self.neovim_state().await;
176        let editor = self.editor_state();
177        if neovim == marked_text && neovim == editor {
178            return;
179        }
180        let initial_state = self
181            .last_set_state
182            .as_ref()
183            .unwrap_or(&"N/A".to_string())
184            .clone();
185
186        let message = if neovim != marked_text {
187            "Test is incorrect (currently expected != neovim_state)"
188        } else {
189            "Editor does not match nvim behaviour"
190        };
191        panic!(
192            indoc! {"{}
193                # initial state:
194                {}
195                # keystrokes:
196                {}
197                # currently expected:
198                {}
199                # neovim state:
200                {}
201                # zed state:
202                {}"},
203            message,
204            initial_state,
205            self.recent_keystrokes.join(" "),
206            marked_text.replace(" \n", "\n"),
207            neovim.replace(" \n", "\n"),
208            editor.replace(" \n", "\n")
209        )
210    }
211
212    pub async fn assert_shared_clipboard(&mut self, text: &str) {
213        let neovim = self.neovim.read_register('"').await;
214        let editor = self
215            .platform()
216            .read_from_clipboard()
217            .unwrap()
218            .text()
219            .clone();
220
221        if text == neovim && text == editor {
222            return;
223        }
224
225        let message = if neovim != text {
226            "Test is incorrect (currently expected != neovim)"
227        } else {
228            "Editor does not match nvim behaviour"
229        };
230
231        let initial_state = self
232            .last_set_state
233            .as_ref()
234            .unwrap_or(&"N/A".to_string())
235            .clone();
236
237        panic!(
238            indoc! {"{}
239                # initial state:
240                {}
241                # keystrokes:
242                {}
243                # currently expected:
244                {}
245                # neovim clipboard:
246                {}
247                # zed clipboard:
248                {}"},
249            message,
250            initial_state,
251            self.recent_keystrokes.join(" "),
252            text,
253            neovim,
254            editor
255        )
256    }
257
258    pub async fn neovim_state(&mut self) -> String {
259        self.neovim.marked_text().await
260    }
261
262    pub async fn neovim_mode(&mut self) -> Mode {
263        self.neovim.mode().await.unwrap()
264    }
265
266    pub async fn assert_state_matches(&mut self) {
267        self.is_dirty = false;
268        let neovim = self.neovim_state().await;
269        let editor = self.editor_state();
270        let initial_state = self
271            .last_set_state
272            .as_ref()
273            .unwrap_or(&"N/A".to_string())
274            .clone();
275
276        if neovim != editor {
277            panic!(
278                indoc! {"Test failed (zed does not match nvim behaviour)
279                    # initial state:
280                    {}
281                    # keystrokes:
282                    {}
283                    # neovim state:
284                    {}
285                    # zed state:
286                    {}"},
287                initial_state,
288                self.recent_keystrokes.join(" "),
289                neovim,
290                editor,
291            )
292        }
293    }
294
295    pub async fn assert_binding_matches<const COUNT: usize>(
296        &mut self,
297        keystrokes: [&str; COUNT],
298        initial_state: &str,
299    ) {
300        if let Some(possible_exempted_keystrokes) = self.exemptions.get(initial_state) {
301            match possible_exempted_keystrokes {
302                Some(exempted_keystrokes) => {
303                    if exempted_keystrokes.contains(&format!("{keystrokes:?}")) {
304                        // This keystroke was exempted for this insertion text
305                        return;
306                    }
307                }
308                None => {
309                    // All keystrokes for this insertion text are exempted
310                    return;
311                }
312            }
313        }
314
315        let _state_context = self.set_shared_state(initial_state).await;
316        let _keystroke_context = self.simulate_shared_keystrokes(keystrokes).await;
317        self.assert_state_matches().await;
318    }
319
320    pub async fn assert_binding_matches_all<const COUNT: usize>(
321        &mut self,
322        keystrokes: [&str; COUNT],
323        marked_positions: &str,
324    ) {
325        let (unmarked_text, cursor_offsets) = marked_text_offsets(marked_positions);
326
327        for cursor_offset in cursor_offsets.iter() {
328            let mut marked_text = unmarked_text.clone();
329            marked_text.insert(*cursor_offset, 'ˇ');
330
331            self.assert_binding_matches(keystrokes, &marked_text).await;
332        }
333    }
334
335    pub fn each_marked_position(&self, marked_positions: &str) -> Vec<String> {
336        let (unmarked_text, cursor_offsets) = marked_text_offsets(marked_positions);
337        let mut ret = Vec::with_capacity(cursor_offsets.len());
338
339        for cursor_offset in cursor_offsets.iter() {
340            let mut marked_text = unmarked_text.clone();
341            marked_text.insert(*cursor_offset, 'ˇ');
342            ret.push(marked_text)
343        }
344
345        ret
346    }
347
348    pub async fn assert_neovim_compatible<const COUNT: usize>(
349        &mut self,
350        marked_positions: &str,
351        keystrokes: [&str; COUNT],
352    ) {
353        self.set_shared_state(&marked_positions).await;
354        self.simulate_shared_keystrokes(keystrokes).await;
355        self.assert_state_matches().await;
356    }
357
358    pub async fn assert_matches_neovim<const COUNT: usize>(
359        &mut self,
360        marked_positions: &str,
361        keystrokes: [&str; COUNT],
362        result: &str,
363    ) {
364        self.set_shared_state(marked_positions).await;
365        self.simulate_shared_keystrokes(keystrokes).await;
366        self.assert_shared_state(result).await;
367    }
368
369    pub async fn assert_binding_matches_all_exempted<const COUNT: usize>(
370        &mut self,
371        keystrokes: [&str; COUNT],
372        marked_positions: &str,
373        feature: ExemptionFeatures,
374    ) {
375        if SUPPORTED_FEATURES.contains(&feature) {
376            self.assert_binding_matches_all(keystrokes, marked_positions)
377                .await
378        }
379    }
380
381    pub fn binding<const COUNT: usize>(
382        self,
383        keystrokes: [&'static str; COUNT],
384    ) -> NeovimBackedBindingTestContext<'a, COUNT> {
385        NeovimBackedBindingTestContext::new(keystrokes, self)
386    }
387}
388
389impl<'a> Deref for NeovimBackedTestContext<'a> {
390    type Target = VimTestContext<'a>;
391
392    fn deref(&self) -> &Self::Target {
393        &self.cx
394    }
395}
396
397impl<'a> DerefMut for NeovimBackedTestContext<'a> {
398    fn deref_mut(&mut self) -> &mut Self::Target {
399        &mut self.cx
400    }
401}
402
403// a common mistake in tests is to call set_shared_state when
404// you mean asswert_shared_state. This notices that and lets
405// you know.
406impl<'a> Drop for NeovimBackedTestContext<'a> {
407    fn drop(&mut self) {
408        if self.is_dirty {
409            panic!("Test context was dropped after set_shared_state before assert_shared_state")
410        }
411    }
412}
413
414#[cfg(test)]
415mod test {
416    use gpui::TestAppContext;
417
418    use crate::test::NeovimBackedTestContext;
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.assert_state_matches().await;
424        cx.set_shared_state("This is a tesˇt").await;
425        cx.assert_state_matches().await;
426    }
427}