vim_test_context.rs

  1use std::ops::{Deref, DerefMut};
  2
  3use editor::test::editor_lsp_test_context::EditorLspTestContext;
  4use gpui::{Context, Entity, SemanticVersion, UpdateGlobal};
  5use search::{BufferSearchBar, project_search::ProjectSearchBar};
  6
  7use crate::{state::Operator, *};
  8
  9pub struct VimTestContext {
 10    cx: EditorLspTestContext,
 11}
 12
 13impl VimTestContext {
 14    pub fn init(cx: &mut gpui::TestAppContext) {
 15        if cx.has_global::<VimGlobals>() {
 16            return;
 17        }
 18        env_logger::try_init().ok();
 19        cx.update(|cx| {
 20            let settings = SettingsStore::test(cx);
 21            cx.set_global(settings);
 22            release_channel::init(SemanticVersion::default(), cx);
 23            command_palette::init(cx);
 24            project_panel::init(cx);
 25            git_ui::init(cx);
 26            crate::init(cx);
 27            search::init(cx);
 28            theme::init(theme::LoadThemes::JustBase, cx);
 29            settings_ui::init(cx);
 30        });
 31    }
 32
 33    pub async fn new(cx: &mut gpui::TestAppContext, enabled: bool) -> VimTestContext {
 34        Self::init(cx);
 35        let lsp = EditorLspTestContext::new_rust(Default::default(), cx).await;
 36        Self::new_with_lsp(lsp, enabled)
 37    }
 38
 39    pub async fn new_html(cx: &mut gpui::TestAppContext) -> VimTestContext {
 40        Self::init(cx);
 41        Self::new_with_lsp(EditorLspTestContext::new_html(cx).await, true)
 42    }
 43
 44    pub async fn new_markdown_with_rust(cx: &mut gpui::TestAppContext) -> VimTestContext {
 45        Self::init(cx);
 46        Self::new_with_lsp(EditorLspTestContext::new_markdown_with_rust(cx).await, true)
 47    }
 48
 49    pub async fn new_typescript(cx: &mut gpui::TestAppContext) -> VimTestContext {
 50        Self::init(cx);
 51        Self::new_with_lsp(
 52            EditorLspTestContext::new_typescript(
 53                lsp::ServerCapabilities {
 54                    completion_provider: Some(lsp::CompletionOptions {
 55                        trigger_characters: Some(vec![".".to_string()]),
 56                        ..Default::default()
 57                    }),
 58                    rename_provider: Some(lsp::OneOf::Right(lsp::RenameOptions {
 59                        prepare_provider: Some(true),
 60                        work_done_progress_options: Default::default(),
 61                    })),
 62                    ..Default::default()
 63                },
 64                cx,
 65            )
 66            .await,
 67            true,
 68        )
 69    }
 70
 71    pub async fn new_tsx(cx: &mut gpui::TestAppContext) -> VimTestContext {
 72        Self::init(cx);
 73        Self::new_with_lsp(
 74            EditorLspTestContext::new_tsx(
 75                lsp::ServerCapabilities {
 76                    completion_provider: Some(lsp::CompletionOptions {
 77                        trigger_characters: Some(vec![".".to_string()]),
 78                        ..Default::default()
 79                    }),
 80                    rename_provider: Some(lsp::OneOf::Right(lsp::RenameOptions {
 81                        prepare_provider: Some(true),
 82                        work_done_progress_options: Default::default(),
 83                    })),
 84                    ..Default::default()
 85                },
 86                cx,
 87            )
 88            .await,
 89            true,
 90        )
 91    }
 92
 93    pub fn init_keybindings(enabled: bool, cx: &mut App) {
 94        SettingsStore::update_global(cx, |store, cx| {
 95            store.update_user_settings(cx, |s| s.vim_mode = Some(enabled));
 96        });
 97        let mut default_key_bindings = settings::KeymapFile::load_asset_allow_partial_failure(
 98            "keymaps/default-macos.json",
 99            cx,
100        )
101        .unwrap();
102        for key_binding in &mut default_key_bindings {
103            key_binding.set_meta(settings::KeybindSource::Default.meta());
104        }
105        cx.bind_keys(default_key_bindings);
106        if enabled {
107            let vim_key_bindings = settings::KeymapFile::load_asset(
108                "keymaps/vim.json",
109                Some(settings::KeybindSource::Vim),
110                cx,
111            )
112            .unwrap();
113            cx.bind_keys(vim_key_bindings);
114        }
115    }
116
117    pub fn new_with_lsp(mut cx: EditorLspTestContext, enabled: bool) -> VimTestContext {
118        cx.update(|_, cx| {
119            Self::init_keybindings(enabled, cx);
120        });
121
122        // Setup search toolbars and keypress hook
123        cx.update_workspace(|workspace, window, cx| {
124            workspace.active_pane().update(cx, |pane, cx| {
125                pane.toolbar().update(cx, |toolbar, cx| {
126                    let buffer_search_bar = cx.new(|cx| BufferSearchBar::new(None, window, cx));
127                    toolbar.add_item(buffer_search_bar, window, cx);
128
129                    let project_search_bar = cx.new(|_| ProjectSearchBar::new());
130                    toolbar.add_item(project_search_bar, window, cx);
131                })
132            });
133            workspace.status_bar().update(cx, |status_bar, cx| {
134                let vim_mode_indicator = cx.new(|cx| ModeIndicator::new(window, cx));
135                status_bar.add_right_item(vim_mode_indicator, window, cx);
136            });
137        });
138
139        Self { cx }
140    }
141
142    pub fn update_entity<F, T, R>(&mut self, entity: Entity<T>, update: F) -> R
143    where
144        T: 'static,
145        F: FnOnce(&mut T, &mut Window, &mut Context<T>) -> R + 'static,
146    {
147        let window = self.window;
148        self.update_window(window, move |_, window, cx| {
149            entity.update(cx, |t, cx| update(t, window, cx))
150        })
151        .unwrap()
152    }
153
154    pub fn workspace<F, T>(&mut self, update: F) -> T
155    where
156        F: FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
157    {
158        self.cx.update_workspace(update)
159    }
160
161    pub fn enable_vim(&mut self) {
162        self.cx.update(|_, cx| {
163            SettingsStore::update_global(cx, |store, cx| {
164                store.update_user_settings(cx, |s| s.vim_mode = Some(true));
165            });
166        })
167    }
168
169    pub fn disable_vim(&mut self) {
170        self.cx.update(|_, cx| {
171            SettingsStore::update_global(cx, |store, cx| {
172                store.update_user_settings(cx, |s| s.vim_mode = Some(false));
173            });
174        })
175    }
176
177    pub fn enable_helix(&mut self) {
178        self.cx.update(|_, cx| {
179            SettingsStore::update_global(cx, |store, cx| {
180                store.update_user_settings(cx, |s| s.helix_mode = Some(true));
181            });
182        })
183    }
184
185    pub fn mode(&mut self) -> Mode {
186        self.update_editor(|editor, _, cx| editor.addon::<VimAddon>().unwrap().entity.read(cx).mode)
187    }
188
189    pub fn forced_motion(&mut self) -> bool {
190        self.update_editor(|_, _, cx| cx.global::<VimGlobals>().forced_motion)
191    }
192
193    pub fn active_operator(&mut self) -> Option<Operator> {
194        self.update_editor(|editor, _, cx| {
195            editor
196                .addon::<VimAddon>()
197                .unwrap()
198                .entity
199                .read(cx)
200                .operator_stack
201                .last()
202                .cloned()
203        })
204    }
205
206    pub fn set_state(&mut self, text: &str, mode: Mode) {
207        self.cx.set_state(text);
208        let vim =
209            self.update_editor(|editor, _window, _cx| editor.addon::<VimAddon>().cloned().unwrap());
210
211        self.update(|window, cx| {
212            vim.entity.update(cx, |vim, cx| {
213                vim.switch_mode(mode, true, window, cx);
214            });
215        });
216        self.cx.cx.cx.run_until_parked();
217    }
218
219    #[track_caller]
220    pub fn assert_state(&mut self, text: &str, mode: Mode) {
221        self.assert_editor_state(text);
222        assert_eq!(self.mode(), mode, "{}", self.assertion_context());
223    }
224
225    pub fn assert_binding(
226        &mut self,
227        keystrokes: &str,
228        initial_state: &str,
229        initial_mode: Mode,
230        state_after: &str,
231        mode_after: Mode,
232    ) {
233        self.set_state(initial_state, initial_mode);
234        self.cx.simulate_keystrokes(keystrokes);
235        self.cx.assert_editor_state(state_after);
236        assert_eq!(self.mode(), mode_after, "{}", self.assertion_context());
237        assert_eq!(self.active_operator(), None, "{}", self.assertion_context());
238    }
239
240    pub fn assert_binding_normal(
241        &mut self,
242        keystrokes: &str,
243        initial_state: &str,
244        state_after: &str,
245    ) {
246        self.set_state(initial_state, Mode::Normal);
247        self.cx.simulate_keystrokes(keystrokes);
248        self.cx.assert_editor_state(state_after);
249        assert_eq!(self.mode(), Mode::Normal, "{}", self.assertion_context());
250        assert_eq!(self.active_operator(), None, "{}", self.assertion_context());
251    }
252
253    pub fn shared_clipboard(&mut self) -> VimClipboard {
254        VimClipboard {
255            editor: self
256                .read_from_clipboard()
257                .map(|item| item.text().unwrap())
258                .unwrap_or_default(),
259        }
260    }
261}
262
263pub struct VimClipboard {
264    editor: String,
265}
266
267impl VimClipboard {
268    #[track_caller]
269    pub fn assert_eq(&self, expected: &str) {
270        assert_eq!(self.editor, expected);
271    }
272}
273
274impl Deref for VimTestContext {
275    type Target = EditorLspTestContext;
276
277    fn deref(&self) -> &Self::Target {
278        &self.cx
279    }
280}
281
282impl DerefMut for VimTestContext {
283    fn deref_mut(&mut self) -> &mut Self::Target {
284        &mut self.cx
285    }
286}