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    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        // 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 (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_state_matches(&mut self) {
279        self.is_dirty = false;
280        let neovim = self.neovim_state().await;
281        let editor = self.editor_state();
282        let initial_state = self
283            .last_set_state
284            .as_ref()
285            .unwrap_or(&"N/A".to_string())
286            .clone();
287
288        if neovim != editor {
289            panic!(
290                indoc! {"Test failed (zed does not match nvim behaviour)
291                    # initial state:
292                    {}
293                    # keystrokes:
294                    {}
295                    # neovim state:
296                    {}
297                    # zed state:
298                    {}"},
299                initial_state,
300                self.recent_keystrokes.join(" "),
301                neovim,
302                editor,
303            )
304        }
305    }
306
307    pub async fn assert_binding_matches<const COUNT: usize>(
308        &mut self,
309        keystrokes: [&str; COUNT],
310        initial_state: &str,
311    ) {
312        if let Some(possible_exempted_keystrokes) = self.exemptions.get(initial_state) {
313            match possible_exempted_keystrokes {
314                Some(exempted_keystrokes) => {
315                    if exempted_keystrokes.contains(&format!("{keystrokes:?}")) {
316                        // This keystroke was exempted for this insertion text
317                        return;
318                    }
319                }
320                None => {
321                    // All keystrokes for this insertion text are exempted
322                    return;
323                }
324            }
325        }
326
327        let _state_context = self.set_shared_state(initial_state).await;
328        let _keystroke_context = self.simulate_shared_keystrokes(keystrokes).await;
329        self.assert_state_matches().await;
330    }
331
332    pub async fn assert_binding_matches_all<const COUNT: usize>(
333        &mut self,
334        keystrokes: [&str; COUNT],
335        marked_positions: &str,
336    ) {
337        let (unmarked_text, cursor_offsets) = marked_text_offsets(marked_positions);
338
339        for cursor_offset in cursor_offsets.iter() {
340            let mut marked_text = unmarked_text.clone();
341            marked_text.insert(*cursor_offset, 'ˇ');
342
343            self.assert_binding_matches(keystrokes, &marked_text).await;
344        }
345    }
346
347    pub fn each_marked_position(&self, marked_positions: &str) -> Vec<String> {
348        let (unmarked_text, cursor_offsets) = marked_text_offsets(marked_positions);
349        let mut ret = Vec::with_capacity(cursor_offsets.len());
350
351        for cursor_offset in cursor_offsets.iter() {
352            let mut marked_text = unmarked_text.clone();
353            marked_text.insert(*cursor_offset, 'ˇ');
354            ret.push(marked_text)
355        }
356
357        ret
358    }
359
360    pub async fn assert_neovim_compatible<const COUNT: usize>(
361        &mut self,
362        marked_positions: &str,
363        keystrokes: [&str; COUNT],
364    ) {
365        self.set_shared_state(&marked_positions).await;
366        self.simulate_shared_keystrokes(keystrokes).await;
367        self.assert_state_matches().await;
368    }
369
370    pub async fn assert_matches_neovim<const COUNT: usize>(
371        &mut self,
372        marked_positions: &str,
373        keystrokes: [&str; COUNT],
374        result: &str,
375    ) {
376        self.set_shared_state(marked_positions).await;
377        self.simulate_shared_keystrokes(keystrokes).await;
378        self.assert_shared_state(result).await;
379    }
380
381    pub async fn assert_binding_matches_all_exempted<const COUNT: usize>(
382        &mut self,
383        keystrokes: [&str; COUNT],
384        marked_positions: &str,
385        feature: ExemptionFeatures,
386    ) {
387        if SUPPORTED_FEATURES.contains(&feature) {
388            self.assert_binding_matches_all(keystrokes, marked_positions)
389                .await
390        }
391    }
392
393    pub fn binding<const COUNT: usize>(
394        self,
395        keystrokes: [&'static str; COUNT],
396    ) -> NeovimBackedBindingTestContext<COUNT> {
397        NeovimBackedBindingTestContext::new(keystrokes, self)
398    }
399}
400
401impl Deref for NeovimBackedTestContext {
402    type Target = VimTestContext;
403
404    fn deref(&self) -> &Self::Target {
405        &self.cx
406    }
407}
408
409impl DerefMut for NeovimBackedTestContext {
410    fn deref_mut(&mut self) -> &mut Self::Target {
411        &mut self.cx
412    }
413}
414
415// a common mistake in tests is to call set_shared_state when
416// you mean asswert_shared_state. This notices that and lets
417// you know.
418impl Drop for NeovimBackedTestContext {
419    fn drop(&mut self) {
420        if self.is_dirty {
421            panic!("Test context was dropped after set_shared_state before assert_shared_state")
422        }
423    }
424}
425
426#[cfg(test)]
427mod test {
428    use crate::test::NeovimBackedTestContext;
429    use gpui::TestAppContext;
430
431    #[gpui::test]
432    async fn neovim_backed_test_context_works(cx: &mut TestAppContext) {
433        let mut cx = NeovimBackedTestContext::new(cx).await;
434        cx.assert_state_matches().await;
435        cx.set_shared_state("This is a tesˇt").await;
436        cx.assert_state_matches().await;
437    }
438}