vim_test_context.rs

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