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