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