DasOhmoff San
DasOhmoff San

Reputation: 975

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).

Upvotes: 2

Views: 522

Answers (2)

SergioAraujo
SergioAraujo

Reputation: 11820

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.

Upvotes: 5

romainl
romainl

Reputation: 196781

The problem, here, is that j and k are not "jumps". When you do 20j you are really doing jjjjjjjjjjjjjjjjjjjj but very quickly so you would have to turn those arbitrary motions into proper jumps for <C-o> to work. How to do so is explained under :help jumplist:

You can explicitly add a jump by setting the ' mark with "m'".

In practice:

m'20j

then <C-o> or '' or `` to go back.

There are smarter ways to move around, though, that don't require you to count lines and that are actual jumps, like :help / and :help ?.

Upvotes: 5

Related Questions