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(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(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(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(cx, |s| s.helix_mode = Some(true));
157            });
158        })
159    }
160
161    pub fn mode(&mut self) -> Mode {
162        self.update_editor(|editor, _, cx| editor.addon::<VimAddon>().unwrap().entity.read(cx).mode)
163    }
164
165    pub fn forced_motion(&mut self) -> bool {
166        self.update_editor(|_, _, cx| cx.global::<VimGlobals>().forced_motion)
167    }
168
169    pub fn active_operator(&mut self) -> Option<Operator> {
170        self.update_editor(|editor, _, cx| {
171            editor
172                .addon::<VimAddon>()
173                .unwrap()
174                .entity
175                .read(cx)
176                .operator_stack
177                .last()
178                .cloned()
179        })
180    }
181
182    pub fn set_state(&mut self, text: &str, mode: Mode) {
183        self.cx.set_state(text);
184        let vim =
185            self.update_editor(|editor, _window, _cx| editor.addon::<VimAddon>().cloned().unwrap());
186
187        self.update(|window, cx| {
188            vim.entity.update(cx, |vim, cx| {
189                vim.switch_mode(mode, true, window, cx);
190            });
191        });
192        self.cx.cx.cx.run_until_parked();
193    }
194
195    #[track_caller]
196    pub fn assert_state(&mut self, text: &str, mode: Mode) {
197        self.assert_editor_state(text);
198        assert_eq!(self.mode(), mode, "{}", self.assertion_context());
199    }
200
201    pub fn assert_binding(
202        &mut self,
203        keystrokes: &str,
204        initial_state: &str,
205        initial_mode: Mode,
206        state_after: &str,
207        mode_after: Mode,
208    ) {
209        self.set_state(initial_state, initial_mode);
210        self.cx.simulate_keystrokes(keystrokes);
211        self.cx.assert_editor_state(state_after);
212        assert_eq!(self.mode(), mode_after, "{}", self.assertion_context());
213        assert_eq!(self.active_operator(), None, "{}", self.assertion_context());
214    }
215
216    pub fn assert_binding_normal(
217        &mut self,
218        keystrokes: &str,
219        initial_state: &str,
220        state_after: &str,
221    ) {
222        self.set_state(initial_state, Mode::Normal);
223        self.cx.simulate_keystrokes(keystrokes);
224        self.cx.assert_editor_state(state_after);
225        assert_eq!(self.mode(), Mode::Normal, "{}", self.assertion_context());
226        assert_eq!(self.active_operator(), None, "{}", self.assertion_context());
227    }
228
229    pub fn shared_clipboard(&mut self) -> VimClipboard {
230        VimClipboard {
231            editor: self
232                .read_from_clipboard()
233                .map(|item| item.text().unwrap())
234                .unwrap_or_default(),
235        }
236    }
237}
238
239pub struct VimClipboard {
240    editor: String,
241}
242
243impl VimClipboard {
244    #[track_caller]
245    pub fn assert_eq(&self, expected: &str) {
246        assert_eq!(self.editor, expected);
247    }
248}
249
250impl Deref for VimTestContext {
251    type Target = EditorLspTestContext;
252
253    fn deref(&self) -> &Self::Target {
254        &self.cx
255    }
256}
257
258impl DerefMut for VimTestContext {
259    fn deref_mut(&mut self) -> &mut Self::Target {
260        &mut self.cx
261    }
262}