Shersh
Shersh

Reputation: 9169

How to auto save file in VSCode on Esc when using Vim extension?

I wonder, how can I save current file automatically in VSCode after leaving insert mode in Vim by pressing Esc key?

Upvotes: 3

Views: 5088

Answers (2)

horace he
horace he

Reputation: 447

Replacing <Esc> with <Esc>:w<Enter> works, but this is probably a slightly more elegant solution (if you have other save commands you'd like to run for example).

    "vim.insertModeKeyBindingsNonRecursive": [
    {
        "before": [
            "<Esc>"
        ],
        "after": [
            "<Esc>"
        ],
        "commands": [
            "workbench.action.files.save"
        ]
    }
],

Upvotes: 8

Decay42
Decay42

Reputation: 872

You can add an insertModeKeyBinding to the Esc key in your settings.json like this:

"vim.insertModeKeyBindingsNonRecursive": [
    {
        "before": ["<Esc>"],
        "after": ["<Esc>", ":", "w", "<Enter>"]
    }
]

Note that this will ONLY save if you go from insert mode to normal mode with the Esc key.

edit: After a bit of testing, I found out you need to stay in insert mode for around 2 seconds after your last change for it to work, otherwise it won't see the <Esc> keystroke as a single event.

As a workaround, you could map to <leader><Esc>, if you need it instantly.

"vim.insertModeKeyBindingsNonRecursive": [
    {
        "before": ["<leader>", "<Esc>"],
        "after": ["<Esc>", ":", "w", "<Enter>"]
    }
]

Upvotes: 3

Related Questions