Search code examples
listvimline

Vim - jump back to previous position when moving multiple lines at once


When I use Vim, I often times use motions commands when moving lines.
For example if I want to move 20 lines down, I press 20j.
Now after having "jumped" 20 lines down, if I want to go back again to my previous position, I have to enter 20k.

Is there a way to jump to my previous position without typing 20k?
For example, by somehow adding the previous position to Vims jump list, then I could use <c-o> to jump back.

(By the way, I only want to jump back when I move more that one line at once).


Solution

  • I have the following on my ~/.vimrc file :

    " It adds motions like 25j and 30k to the jump list, so you can cycle
    " through them with control-o and control-i.
    " source: https://www.vi-improved.org/vim-tips/
    nnoremap <expr> j v:count ? (v:count > 5 ? "m'" . v:count : '') . 'j' : 'gj'
    nnoremap <expr> k v:count ? (v:count > 5 ? "m'" . v:count : '') . 'k' : 'gk'
    

    In my case, line movements bigger than 5 lines are added to the jump list.