Question

In order to save time in Vim, I came up with an idea. To map :w key binding to Esc in both normal mode and insert mode. However it only works in insert mode whereas in normal mode things are getting messy when I open a new file. This is what I added in .vimrc:

:inoremap <Esc> <Esc>:w<CR>
:nnoremap <Esc> :w<CR>

As I said the first command alone, works fine. But adding the second command, keys are messed up ESPECIALLY when I open a new file. For instance, although I have explicitly added in .vimrc:

map <up> <nop>
map <down> <nop>
map <left> <nop>
map <right> <nop>

by adding the second command for the normal mode, pressing up down left or right keys cause to enter in insert mode and add A B C D.

Could you help me to achieve my idea?

Was it helpful?

Solution

Information on Vim FAQ 10.9 may be useful:

10.9. When I use my arrow keys, Vim changes modes, inserts weird characters
     in my document but doesn't move the cursor properly. What's going on?

There are a couple of things that could be going on: either you are using
Vim over a slow connection or Vim doesn't understand the key sequence that
your keyboard is generating.

If you are working over a slow connection (such as a 2400 bps modem), you
can try to set the 'timeout' or 'ttimeout' option. These options, combined
with the 'timeoutlen' and 'ttimeoutlen' options, may fix the problem.

The preceding procedure will not work correctly if your terminal sends key
codes that Vim does not understand. In this situation, your best option is
to map your key sequence to a matching cursor movement command and save
these mappings in a file. You can then ":source" the file whenever you work
from that terminal.

For more information, read 

    |'timeout'|
    |'ttimeout'|
    |'timeoutlen'|
    |'ttimeoutlen'|
    |:map|
    |vt100-cursor-keys|

From :h vt100-cursor-keys:

Other terminals (e.g., vt100 and xterm) have cursor keys that send <Esc>OA,
<Esc>OB, etc. ...

So probably your nnoremap is causing the Esc on the arrow's key sequence to save the file, and the remaining characters are being interpreted alone, so the A is entering insert mode.

You could consider using option 'autowriteall', or using a different mapping to save your file; these are defined in $VIMRUNTIME\mswin.vim:

" Use CTRL-S for saving, also in Insert mode
noremap <C-S>       :update<CR>
vnoremap <C-S>      <C-C>:update<CR>
inoremap <C-S>      <C-O>:update<CR>

The :update command is similar to :w, but only writes only if the file has been modified.

OTHER TIPS

Also, you can use

autocmd InsertLeave * write

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top