editor_events.rs

 1use editor::{EditorBlurred, EditorFocused, EditorMode, EditorReleased, Event};
 2use gpui::AppContext;
 3
 4use crate::{state::Mode, Vim};
 5
 6pub fn init(cx: &mut AppContext) {
 7    cx.subscribe_global(focused).detach();
 8    cx.subscribe_global(blurred).detach();
 9    cx.subscribe_global(released).detach();
10}
11
12fn focused(EditorFocused(editor): &EditorFocused, cx: &mut AppContext) {
13    Vim::update(cx, |vim, cx| {
14        vim.update_active_editor(cx, |previously_active_editor, cx| {
15            Vim::unhook_vim_settings(previously_active_editor, cx);
16        });
17
18        vim.active_editor = Some(editor.downgrade());
19        vim.editor_subscription = Some(cx.subscribe(editor, |editor, event, cx| match event {
20            Event::SelectionsChanged { local: true } => {
21                let editor = editor.read(cx);
22                if editor.leader_replica_id().is_none() {
23                    let newest_empty = editor.selections.newest::<usize>(cx).is_empty();
24                    local_selections_changed(newest_empty, cx);
25                }
26            }
27            Event::InputIgnored { text } => {
28                Vim::active_editor_input_ignored(text.clone(), cx);
29            }
30            _ => {}
31        }));
32
33        if vim.enabled {
34            let editor = editor.read(cx);
35            let editor_mode = editor.mode();
36            let newest_selection_empty = editor.selections.newest::<usize>(cx).is_empty();
37
38            if editor_mode == EditorMode::Full && !newest_selection_empty {
39                vim.switch_mode(Mode::Visual { line: false }, true, cx);
40            }
41        }
42
43        vim.sync_vim_settings(cx);
44    });
45}
46
47fn blurred(EditorBlurred(editor): &EditorBlurred, cx: &mut AppContext) {
48    Vim::update(cx, |vim, cx| {
49        if let Some(previous_editor) = vim.active_editor.clone() {
50            if previous_editor == editor.clone() {
51                vim.active_editor = None;
52            }
53        }
54
55        cx.update_window(editor.window_id(), |cx| {
56            editor.update(cx, |editor, cx| Vim::unhook_vim_settings(editor, cx))
57        });
58    })
59}
60
61fn released(EditorReleased(editor): &EditorReleased, cx: &mut AppContext) {
62    cx.update_default_global(|vim: &mut Vim, _| {
63        if let Some(previous_editor) = vim.active_editor.clone() {
64            if previous_editor == editor.clone() {
65                vim.active_editor = None;
66            }
67        }
68    });
69}
70
71fn local_selections_changed(newest_empty: bool, cx: &mut AppContext) {
72    Vim::update(cx, |vim, cx| {
73        if vim.enabled && vim.state.mode == Mode::Normal && !newest_empty {
74            vim.switch_mode(Mode::Visual { line: false }, false, cx)
75        }
76    })
77}