fronthem
fronthem

Reputation: 4139

Pass multiple numbers from keyboard via vim normal mode as arguments of function

e.g. In normal mode I type

123 456<Enter>

I would like to pass numbers 123 and 456 to be arguments of vim function.

Code example:

function! PrintNum(A, B)
    echo A B
endfunction

nmap A B<Enter> call PrintNum(A, B)

where A and B could be any numbers with space delimiter. Note that function PrintNum() is just used for testing that two numbers are passed through the function correctly.

Upvotes: 0

Views: 98

Answers (1)

Ingo Karkat
Ingo Karkat

Reputation: 172520

direct answer

Here's what you're asking for, with the caveat that this is highly ususual:

function! PrintNum(b)
    echo g:a a:b
endfunction

nnoremap <silent> <Space> :<C-u>let g:a = v:count<CR>
nnoremap <silent> <Enter> :<C-u>call PrintNum(v:count)<CR>

canonical Vim style

Mappings usually only take a count and/or a register. If you need more, usually a custom command is used:

command! -nargs=+ PrintNum call PrintNum(<f-args>)

If that is too much to type, you can define a trigger mapping, so you only need to enter the numbers and acknowledge with Enter:

nnoremap <Enter> :PrintNum<Space>

alternative

Or, the mapping could query for the parameters:

nnoremap <Enter> :call PrintNum(input('First number: '), input('Second number: '))<CR>

Upvotes: 3

Related Questions