1use editor::{EditorBlurred, EditorCreated, EditorFocused, EditorMode, EditorReleased};
2use gpui::MutableAppContext;
3
4use crate::{mode::Mode, SwitchMode, VimState};
5
6pub fn init(cx: &mut MutableAppContext) {
7 cx.subscribe_global(editor_created).detach();
8 cx.subscribe_global(editor_focused).detach();
9 cx.subscribe_global(editor_blurred).detach();
10 cx.subscribe_global(editor_released).detach();
11}
12
13fn editor_created(EditorCreated(editor): &EditorCreated, cx: &mut MutableAppContext) {
14 cx.update_default_global(|vim_state: &mut VimState, cx| {
15 vim_state.editors.insert(editor.id(), editor.downgrade());
16 if vim_state.enabled {
17 VimState::update_cursor_shapes(cx);
18 }
19 })
20}
21
22fn editor_focused(EditorFocused(editor): &EditorFocused, cx: &mut MutableAppContext) {
23 let mode = if matches!(editor.read(cx).mode(), EditorMode::SingleLine) {
24 Mode::Insert
25 } else {
26 Mode::Normal
27 };
28
29 cx.update_default_global(|vim_state: &mut VimState, _| {
30 vim_state.active_editor = Some(editor.downgrade());
31 });
32 VimState::switch_mode(&SwitchMode(mode), cx);
33}
34
35fn editor_blurred(EditorBlurred(editor): &EditorBlurred, cx: &mut MutableAppContext) {
36 cx.update_default_global(|vim_state: &mut VimState, _| {
37 if let Some(previous_editor) = vim_state.active_editor.clone() {
38 if previous_editor == editor.clone() {
39 vim_state.active_editor = None;
40 }
41 }
42 });
43 editor.update(cx, |editor, _| {
44 editor.remove_keymap_context_layer::<VimState>();
45 })
46}
47
48fn editor_released(EditorReleased(editor): &EditorReleased, cx: &mut MutableAppContext) {
49 cx.update_default_global(|vim_state: &mut VimState, _| {
50 vim_state.editors.remove(&editor.id());
51 if let Some(previous_editor) = vim_state.active_editor.clone() {
52 if previous_editor == editor.clone() {
53 vim_state.active_editor = None;
54 }
55 }
56 });
57}