fronthem
fronthem

Reputation: 4139

Pass digit keys in normal mode as an argument of vim's function

I want to see the output message:

1234

when I type 1234<Enter> in normal mode of vim.

I've tried to write some vim script here

function! PrintNum(n)
    echo n
endfunction

nmap n<Enter> call PrintNum(n)

where n here is just a dummy variable that represents regex \d+.

How could I use some kind of regex in map command?

Note that I'm also not sure if I should use nmap.

Upvotes: 2

Views: 326

Answers (1)

Ingo Karkat
Ingo Karkat

Reputation: 172778

Here it is:

function! PrintNum(n)
    echo a:n
endfunction

nnoremap <silent> <Enter> :<C-u>call PrintNum(v:count)<CR>

Explanation

  • There are no dummy variables in a mapping; it's executed just as typed. However, the special variable v:count gets the number that can be put before any command.
  • Here, I've passed this into the function as argument n (internally referenced as a:n), but I could have used v:count also directly inside the function.
  • The : command by default turns a count into a range, as we want a separate :call, we remove this range via <C-u>.
  • The mapping (command-line mode) is concluded by pressing Enter: <CR>. The <silent> avoids that you briefly see the mapped keys.
  • You should use :noremap; it makes the mapping immune to remapping and recursion.

Upvotes: 3

Related Questions