0

To call a custom operator with a mapping, one can do

nnoremap <Plug>(Foo) :set opfunc=Baa<CR>g@

so that <Plug>(Foo) expects a motion, after which the function Baa is called.
Here, Baa takes in a single type argument, and processes the '[ and '] marks accordingly.

Now, how can I add argument(s) to Baa, and call it with a mapping?

That is, suppose I have

function! Baa(type, arg1)
  " do stuff ...
  " process a:arg1
endfunction

How would I map <Plug>(Foo)?
(arg1 is allowed to vary, depending on the context.)

1

operatorfunc is very limited and can't take arguments or be set to e.g., lambdas. A "standard" way to handle this situation is to use an expression map to a setup wrapper function, and keep the argument in a global or script-context variable. This means unfortunately that the operator is not reentrant, but this is rarely needed.

This is the approach taken in the popular plugin vim-commentary: [1].

Here is another example of a "repeatable command" which is similar to an operator that takes arguments:

function! RepWincmd(...)
    execute (v:count ? v:count : s:state[1]) 'wincmd' s:state[0]
endfunction

function! s:setup(rep, ...)
    let s:state = [a:rep, v:count ? v:count : get(a:000, 0, 1)]
    set operatorfunc=RepWincmd
    return 'g@l'
endfunction

nnoremap <expr> <c-w>- <sid>setup('-', 3)
nnoremap <expr> <c-w>+ <sid>setup('+', 3)
nnoremap <expr> <c-w>< <sid>setup('<', 5)
nnoremap <expr> <c-w>> <sid>setup('>', 5)
1
  • Thanks for your answer! Indeed, I suspected that opfuncs would not have such functionality. (1) vim-commentary uses multiple arguments, to allow for multiple purposes: to call itself, use as an operator, or with a range. However, those variable arguments are used for a different purposes from what I have in mind. (2) Accessing via a script or global variable is what I was seeking. Though it seems unnatural (since it is external from the function), it is a viable option. (3) Nice tip to use an operator for repeatability!
    – husB
    Jun 25 at 3:40

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.