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