I use vim a lot to edit tex files. When I have lines spanning multiple display lines, most of the time I want to navigate through them with gj not j (i.e. according to displayed lines, not physical lines).

I tried putting the following lines in my .vimrc but, not surprisingly, got an error message recursive mapping:

nmap j gj
nmap gj j

How do I properly swap the effects of two commands?


There are a couple of ways you can do this. My first thought was to do it this way:

nnoremap j :normal! gj<CR>
nnoremap gj :normal! j<CR>

Call the original gj or j using normal mode; the exclamation mark prevents them from being associated with any current mappings.

See :help normal for more details.

A simpler method was provided in the comments by @statox:

nnoremap j gj
nnoremap gj j

A non-recursive mapping is also prevented from being recognised during subsequent mappings.

  • 2
    Wouldn't nnoremap j gj and nnoremap gj j be enough? – statox Aug 17 '18 at 11:32
  • @statox that's also what I just realized (see comment under other answer) – Bananach Aug 17 '18 at 11:33
  • 1
    @Bananach Just so you know: in the future, you'll probably always want to use the nonrecursive version of the map commands. I wrote a little about that here (in the "common pitfalls" section) along with some useful stuff to know when you play with mappings :) – statox Aug 17 '18 at 11:43
  • 1
    For an in-depth exploration of replacing movement keys with their g counterparts, two good resources are vim.wikia.com/wiki/Move_cursor_by_display_lines_when_wrapping and reddit.com/r/vim/comments/2k4cbr/problem_with_gj_and_gk – Simon Alford Aug 17 '18 at 15:23
  • 1
    Thanks @statox that checks out and I have added it to the answer – cryptarch Aug 17 '18 at 20:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.