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