0

In vim, is there a more elegant way to jump to a line number under the cursor than

map gn "nyw@nG

"gn" or some other key combo? This necessitates ensuring the cursor is at the beginning of the string of numbers. Also, this macro COULD be a bit hazardous depending on what's in register "n".

Not entirely sure even why this works: @n means to execute what's in register n (a number), not concatenate it with the "G".

Functions with something like

call cursor(expand("<cword>"),1)

don't seem to work either.

Thoughts?

1 Answer 1

6

I would recommend this:

nnoremap gn yiw:exec (@" =~ '^\d\+$' ? 'norm @"G' : '')<cr>

It fixes a lot of the problems you have mentioned, for example:

  • this necessitates ensuring the cursor is at the beginning of the word ("word" here means string of numbers).

    Using yiw instead of yw fixes this problem. Read up on text objects!

  • also, this macro COULD be a bit hazardous depending on what's in register "n".

    This will only execute any code if your cursor is over a number. Otherwise it does nothing.

There are also some other advantages:

  • Using nnoremap instead of map is the best practice. It will save you a lot of headaches down the road! (more info)

  • It doesn't mess with your @n register.

not entirely sure even why this works: @n means to execute what's in register n (a number), not concatenate it with the "G".

Typing @n inserts the text inside the register n into the typeahead buffer, exactly as if you had typed it. So if a command is unfinished, it will sit there (as if you had typed it) waiting for the command to finish. You could even run a macro like

3d

which will sit there waiting for a motion, before deleting three of those motions.

1
  • 1
    expertly done, explained. an important distinction (for me at least) is the how the command is interpreted wrt @n is not "execute n", it's a modifier being held in a "command line" (for lack of a better term) until the line is complete with the motion. this is perfectly clear now.
    – wmmso
    Feb 3, 2017 at 21:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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