Assigning save (:w<cr>) to <leader>w in vim

1.5k Views Asked by At

I want to be able to save a file in vim while in the insert mode. I thought of using the following shortcut:

inoremap <leader>w <Esc>:w<cr> 

While the shortcut saves the file in the insert mode, it leaves the cursor one spot ahead of where the cursor would be if I physically typed out the keys Esc :w followed by Enter. This is a problem because when I use the shortcut whenever I am at the end of a line, it takes me to the next line, and I have to then come back to the spot where I initiated the save.

Any help would be appreciated on how I can map <leader>w to the exact actions that occur in Vim when I physically type out the Esc :w followed by Enter key sequence.

I should add that if I instead use the following key-mapping, things work exactly as I want:

inoremap <C-s> <esc>:w<CR>

However, I would like to avoid pressing CTRL and s at the same time. It is possible there is some problem with the <leader>, but I cannot figure out what it is (I am using , as my leader key).

3

There are 3 best solutions below

0
On BEST ANSWER

Though one could discuss the suitability of your insert-mode mapping, the root cause of your problem is a trailing space in the mapping definition; i.e. Vim reads this as follows:

inoremap <leader>w <Esc>:w<cr><Space>

You'll even see this in the :imap <Leader>w output! <Space> in normal mode advances the cursor one to the right (like l); that explains the unexpected move.

0
On

Why not simply doing

inoremap <leader>w <Esc>h:w<cr> 

(not the additional h for going back one character)?

0
On

Try this instead:

inoremap <silent> <leader>w <C-o>:w<CR>

The idea is Ctrl-o can be used to run commands directly from insert mode. See :help i_CTRL-O for details.