简体   繁体   中英

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 .

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 <Cu> .
  • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM