gotgenes
gotgenes

Reputation: 40029

Create normal mode command that accepts a number as an argument in Vim

How do you create a normal mode command which accepts a number as part of it? Examples include 6>> (indents 6 lines of text), 2dw (deletes 2 words), and 23yy (copies 23 lines to the copy buffer). Is there a way to do this using nmap or its ilk?

Specifically, I would like to create a mapping such that if I enter

<leader>4bu

in Normal mode, Vim will do

:4buf<CR>

Upvotes: 0

Views: 154

Answers (2)

ZyX
ZyX

Reputation: 53604

  1. Use nnoremap, not nmap.
  2. Number supplied to last normal-mode command is accessible via v:count variable, so, for example, the following mapping will add supplied number to the buffer text number times:

    nnoremap ,a a<C-r>=v:count<CR><Esc>
    

    The reason why 20,a will add 20 20 times is because 20,a is rewritten as 20a<C-r>.... To avoid that you may use

    nnoremap ,a :<C-u>call feedkeys("a".v:count."\e", "n")<CR>
    

    . <C-u> will discard the count for the ex command but it is still accessible from v:count variable.

Upvotes: 2

Raimondi
Raimondi

Reputation: 5303

You need to define your own operator, see:

:help :map-operator

Upvotes: 3

Related Questions