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