neovim_backed_test_context.rs

  1use editor::{scroll::VERTICAL_SCROLL_MARGIN, 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
159            .set_option(&format!("scrolloff={}", VERTICAL_SCROLL_MARGIN))
160            .await;
161        // +2 to account for the vim command UI at the bottom.
162        self.neovim.set_option(&format!("lines={}", rows + 2)).await;
163        let (line_height, visible_line_count) = self.editor(|editor, cx| {
164            (
165                editor
166                    .style()
167                    .unwrap()
168                    .text
169                    .line_height_in_pixels(cx.rem_size()),
170                editor.visible_line_count().unwrap(),
171            )
172        });
173
174        let window = self.window;
175        let margin = self
176            .update_window(window, |_, cx| {
177                cx.viewport_size().height - line_height * visible_line_count
178            })
179            .unwrap();
180
181        self.simulate_window_resize(
182            self.window,
183            size(px(1000.), margin + (rows as f32) * line_height),
184        );
185    }
186
187    pub async fn set_neovim_option(&mut self, option: &str) {
188        self.neovim.set_option(option).await;
189    }
190
191    pub async fn assert_shared_state(&mut self, marked_text: &str) {
192        self.is_dirty = false;
193        let marked_text = marked_text.replace("", " ");
194        let neovim = self.neovim_state().await;
195        let editor = self.editor_state();
196        if neovim == marked_text && neovim == editor {
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 state:
219                {}
220                # zed state:
221                {}"},
222            message,
223            initial_state,
224            self.recent_keystrokes.join(" "),
225            marked_text.replace(" \n", "\n"),
226            neovim.replace(" \n", "\n"),
227            editor.replace(" \n", "\n")
228        )
229    }
230
231    pub async fn assert_shared_clipboard(&mut self, text: &str) {
232        let neovim = self.neovim.read_register('"').await;
233        let editor = self.read_from_clipboard().unwrap().text().clone();
234
235        if text == neovim && text == editor {
236            return;
237        }
238
239        let message = if neovim != text {
240            "Test is incorrect (currently expected != neovim)"
241        } else {
242            "Editor does not match nvim behaviour"
243        };
244
245        let initial_state = self
246            .last_set_state
247            .as_ref()
248            .unwrap_or(&"N/A".to_string())
249            .clone();
250
251        panic!(
252            indoc! {"{}
253                # initial state:
254                {}
255                # keystrokes:
256                {}
257                # currently expected:
258                {}
259                # neovim clipboard:
260                {}
261                # zed clipboard:
262                {}"},
263            message,
264            initial_state,
265            self.recent_keystrokes.join(" "),
266            text,
267            neovim,
268            editor
269        )
270    }
271
272    pub async fn neovim_state(&mut self) -> String {
273        self.neovim.marked_text().await
274    }
275
276    pub async fn neovim_mode(&mut self) -> Mode {
277        self.neovim.mode().await.unwrap()
278    }
279
280    pub async fn assert_shared_mode(&mut self, mode: Mode) {
281        let neovim = self.neovim_mode().await;
282        let editor = self.cx.mode();
283
284        if neovim != mode || editor != mode {
285            panic!(
286                indoc! {"Test failed (zed does not match nvim behaviour)
287                    # desired mode:
288                    {:?}
289                    # neovim mode:
290                    {:?}
291                    # zed mode:
292                    {:?}"},
293                mode, neovim, editor,
294            )
295        }
296    }
297
298    pub async fn assert_state_matches(&mut self) {
299        self.is_dirty = false;
300        let neovim = self.neovim_state().await;
301        let editor = self.editor_state();
302        let initial_state = self
303            .last_set_state
304            .as_ref()
305            .unwrap_or(&"N/A".to_string())
306            .clone();
307
308        if neovim != editor {
309            panic!(
310                indoc! {"Test failed (zed does not match nvim behaviour)
311                    # initial state:
312                    {}
313                    # keystrokes:
314                    {}
315                    # neovim state:
316                    {}
317                    # zed state:
318                    {}"},
319                initial_state,
320                self.recent_keystrokes.join(" "),
321                neovim,
322                editor,
323            )
324        }
325    }
326
327    pub async fn assert_binding_matches<const COUNT: usize>(
328        &mut self,
329        keystrokes: [&str; COUNT],
330        initial_state: &str,
331    ) {
332        if let Some(possible_exempted_keystrokes) = self.exemptions.get(initial_state) {
333            match possible_exempted_keystrokes {
334                Some(exempted_keystrokes) => {
335                    if exempted_keystrokes.contains(&format!("{keystrokes:?}")) {
336                        // This keystroke was exempted for this insertion text
337                        return;
338                    }
339                }
340                None => {
341                    // All keystrokes for this insertion text are exempted
342                    return;
343                }
344            }
345        }
346
347        let _state_context = self.set_shared_state(initial_state).await;
348        let _keystroke_context = self.simulate_shared_keystrokes(keystrokes).await;
349        self.assert_state_matches().await;
350    }
351
352    pub async fn assert_binding_matches_all<const COUNT: usize>(
353        &mut self,
354        keystrokes: [&str; COUNT],
355        marked_positions: &str,
356    ) {
357        let (unmarked_text, cursor_offsets) = marked_text_offsets(marked_positions);
358
359        for cursor_offset in cursor_offsets.iter() {
360            let mut marked_text = unmarked_text.clone();
361            marked_text.insert(*cursor_offset, 'ˇ');
362
363            self.assert_binding_matches(keystrokes, &marked_text).await;
364        }
365    }
366
367    pub fn each_marked_position(&self, marked_positions: &str) -> Vec<String> {
368        let (unmarked_text, cursor_offsets) = marked_text_offsets(marked_positions);
369        let mut ret = Vec::with_capacity(cursor_offsets.len());
370
371        for cursor_offset in cursor_offsets.iter() {
372            let mut marked_text = unmarked_text.clone();
373            marked_text.insert(*cursor_offset, 'ˇ');
374            ret.push(marked_text)
375        }
376
377        ret
378    }
379
380    pub async fn assert_neovim_compatible<const COUNT: usize>(
381        &mut self,
382        marked_positions: &str,
383        keystrokes: [&str; COUNT],
384    ) {
385        self.set_shared_state(&marked_positions).await;
386        self.simulate_shared_keystrokes(keystrokes).await;
387        self.assert_state_matches().await;
388    }
389
390    pub async fn assert_matches_neovim<const COUNT: usize>(
391        &mut self,
392        marked_positions: &str,
393        keystrokes: [&str; COUNT],
394        result: &str,
395    ) {
396        self.set_shared_state(marked_positions).await;
397        self.simulate_shared_keystrokes(keystrokes).await;
398        self.assert_shared_state(result).await;
399    }
400
401    pub async fn assert_binding_matches_all_exempted<const COUNT: usize>(
402        &mut self,
403        keystrokes: [&str; COUNT],
404        marked_positions: &str,
405        feature: ExemptionFeatures,
406    ) {
407        if SUPPORTED_FEATURES.contains(&feature) {
408            self.assert_binding_matches_all(keystrokes, marked_positions)
409                .await
410        }
411    }
412
413    pub fn binding<const COUNT: usize>(
414        self,
415        keystrokes: [&'static str; COUNT],
416    ) -> NeovimBackedBindingTestContext<COUNT> {
417        NeovimBackedBindingTestContext::new(keystrokes, self)
418    }
419}
420
421impl Deref for NeovimBackedTestContext {
422    type Target = VimTestContext;
423
424    fn deref(&self) -> &Self::Target {
425        &self.cx
426    }
427}
428
429impl DerefMut for NeovimBackedTestContext {
430    fn deref_mut(&mut self) -> &mut Self::Target {
431        &mut self.cx
432    }
433}
434
435// a common mistake in tests is to call set_shared_state when
436// you mean asswert_shared_state. This notices that and lets
437// you know.
438impl Drop for NeovimBackedTestContext {
439    fn drop(&mut self) {
440        if self.is_dirty {
441            panic!("Test context was dropped after set_shared_state before assert_shared_state")
442        }
443    }
444}
445
446#[cfg(test)]
447mod test {
448    use crate::test::NeovimBackedTestContext;
449    use gpui::TestAppContext;
450
451    #[gpui::test]
452    async fn neovim_backed_test_context_works(cx: &mut TestAppContext) {
453        let mut cx = NeovimBackedTestContext::new(cx).await;
454        cx.assert_state_matches().await;
455        cx.set_shared_state("This is a tesˇt").await;
456        cx.assert_state_matches().await;
457    }
458}