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