Search code examples
vimmappingvim-macros

VIM Mapping doesn't work properly when I create macros


I started studying VIM around 3 days ago. And now I'm stuck creating macros.

On the beginning of learning VIM I created mapping: jk -> ESC for convenience (inoremap jk <ESC>). Now my macros works correctly only if I pressed ESC; with jk they don't work properly.

For example I create macros to add : to the beginning and end of line:

'I' + ':' + 'ESC' + 'A' + ':' + 'ESC'

@a macros: I exited insert mode with jk.
@b macros: I exited insert mode with <ESC>.

If apply @a to the line example, I don't get the colon at the end... I end up with:

:example

If apply @b to the line example, I do get the colon at the end... I end up with:

:example:

Output of command - :registers (macros aren't the same): enter image description here

~/.vimrc :

1 syntax on " highlight syntax 
2 set number " show line numbers
3 set hlsearch " highlight all results
4 set noswapfile " disable the swapfile
5 set ignorecase " ignore case in search
6 set incsearch " show search results as you type
7 " set spell spelllang=en_us " misspelled words are automatically underlined
8 
9 inoremap jk <ESC> " type 'jk' for leaving insert mode

Q: How to make behavior of 'jk' and 'ESC' equal when recording macros.

P.S. Sorry if the explanation is not smooth, this is my first question and I tried to make it as simple as possible.


Solution

  • You need to move the comment up.

    Instead of:

    inoremap jk <ESC> " type 'jk' for leaving insert mode
    

    Do:

    " type 'jk' for leaving insert mode
    inoremap jk <ESC>
    

    Vim interprets this comment as part of your mapping.

    See "Why does remapping make the cursor jump?" for additional information.