2

By default, vim lets you type 5G (5 then shift + g) to go to line 5. Instead, I don't want to have to press the shift key. Pressing <S-g> does something different than just 5<S-g>. How can I remap a command that takes a number for repeated executions?

Something like: nnoremap <number>g <number>G

5
nnoremap g G

But this will not work well, as there are a lot of key mapping beginning with g. So Vim has to wait a timeout (default 1000 msec) to be sure that no other key is pressed after the g. The g could be the start of 'gg' or 'g$' or ...

So after you pressed 5g nothing will happen for one second. Than the cursor jumps to line 5.

If you want to know about the other key mappings starting with 'g' just enter ':help g' and then hit <tab>. Lots of stuff.

  • Thanks for this. I realized soon after remapping g was a bad idea haha! Ill check out the help text for that command. – triplethreat78 May 4 at 23:14
2

Even though OP accepted the existing answer this feels incomplete to me.

First, the answer has a well-considered warning about remapping g but there is no mention of <count>gg as a near-synonym for <count>G. (They differ only when the count is omitted. By default gg goes to the first line and G to the last.). Perhaps entering 5gg is less annoying to OP than 5 Shift+G and we have a nice, easy workaround...

The other thing that feels unaddressed is the subject of the question which is notably more generic than what has actually been discussed. It happens to be a good question, about applying a repeat count to a mapped command, but folks who come here from google will have to keep looking if it's not answered. So...

From Normal mode, if one precedes a command with a count and that command enters a vimscript/ex context we can retrieve the count from that context with the built-in variable v:count.

I'll use it in an example applicable to the more specific question we've been addressing...

nnoremap XX :<C-U>exe 'norm! ' . v:count . 'G'<CR>

In place of XX choose any key or keys you like better than Shift+G and this will give you a replacement for <count>G.

FYI about the use of <C-U> (see :h c_CTRL-U): this is required to clear the command line before the mapped command is applied. Normally when we enter a number followed by : the command line is pre-populated with a line range. In this case we don't want that.

  • 1
    Nice to know <count>gg. You might need to explain <c-u>, some user might consider it as a mistake, they don't know :h N: . You command also need a trailing <cr>. – dedowsdi May 5 at 11:30
  • @dedowsdi Thanks for the heads up about the <cr> that I left off. And you're right about explaining <c-u>...I was being lazy and planned to fill it out later. :) – B Layer May 5 at 22:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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