1use editor::{EditorBlurred, EditorCreated, EditorFocused, EditorMode, EditorReleased};
2use gpui::MutableAppContext;
3
4use crate::{state::Mode, Vim};
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: &mut Vim, cx| {
15 vim.editors.insert(editor.id(), editor.downgrade());
16 vim.sync_vim_settings(cx);
17 })
18}
19
20fn editor_focused(EditorFocused(editor): &EditorFocused, cx: &mut MutableAppContext) {
21 Vim::update(cx, |vim, cx| {
22 vim.active_editor = Some(editor.downgrade());
23 vim.selection_subscription = Some(cx.subscribe(editor, |editor, event, cx| {
24 if editor.read(cx).leader_replica_id().is_none() {
25 if let editor::Event::SelectionsChanged { local: true } = event {
26 let newest_empty = editor.read(cx).selections.newest::<usize>(cx).is_empty();
27 editor_local_selections_changed(newest_empty, cx);
28 }
29 }
30 }));
31
32 if !vim.enabled {
33 return;
34 }
35
36 let editor = editor.read(cx);
37 let editor_mode = editor.mode();
38 let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();
39
40 if editor_mode == EditorMode::Full && !newest_selection_empty {
41 vim.switch_mode(Mode::Visual { line: false }, true, cx);
42 }
43 });
44}
45
46fn editor_blurred(EditorBlurred(editor): &EditorBlurred, cx: &mut MutableAppContext) {
47 Vim::update(cx, |vim, cx| {
48 if let Some(previous_editor) = vim.active_editor.clone() {
49 if previous_editor == editor.clone() {
50 vim.active_editor = None;
51 }
52 }
53 vim.sync_vim_settings(cx);
54 })
55}
56
57fn editor_released(EditorReleased(editor): &EditorReleased, cx: &mut MutableAppContext) {
58 cx.update_default_global(|vim: &mut Vim, _| {
59 vim.editors.remove(&editor.id());
60 if let Some(previous_editor) = vim.active_editor.clone() {
61 if previous_editor == editor.clone() {
62 vim.active_editor = None;
63 }
64 }
65 });
66}
67
68fn editor_local_selections_changed(newest_empty: bool, cx: &mut MutableAppContext) {
69 Vim::update(cx, |vim, cx| {
70 if vim.enabled && vim.state.mode == Mode::Normal && !newest_empty {
71 vim.switch_mode(Mode::Visual { line: false }, false, cx)
72 }
73 })
74}