Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have relativenumber enabled and often navigate to a specific line by pressing 25k or 7j, etc. The problem is that after I've changed the line I often find myself wanting to go back to where I was before moving. So I press CTRL-O but this fails because j/k movements are not added to the movement history. What happens instead is that I appear to move back twice.

What would be ideal is if Vim added to the move history anytime I perform a j/k operation with a multiplier. Is something like this possible?

share|improve this question
up vote 2 down vote accepted

Here is a mapping for j / k that achieves this:

:nnoremap <silent> k :<C-U>execute 'normal!' (v:count > 1 ? "m'" . v:count : '') . 'k'<CR>
:nnoremap <silent> j :<C-U>execute 'normal!' (v:count > 1 ? "m'" . v:count : '') . 'j'<CR>

Credit: I've first seen this here.

share|improve this answer
Perfect, thanks! – eventualEntropy Jan 22 '13 at 15:25

I don't believe Vim provides any way to add motions to the jumplist, but if you really want to be able to jump back with '' and treat motions somewhat like jumps, you could do something like this:

function! MarkJ()
    mark '
    return "j"

nnoremap <expr> j MarkJ()

MarkJ() manually sets the ' mark, adding that line to the jumplist (always at column 0, though), and then returns j to the mapping. Unfortunately, you would have to do the same for each motion.

I can't think of any way to easily limit this to motions with multipliers, but following the getchar() example under :help map-expr, it would theoretically be possible to define a set of functions and mappings that would only call MarkX() if the motion follows a multiplier. This is pretty contrived, though, and might become expensive enough to decrease performance.

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .