0

I am struggling with this line (Vim9script):

command! -nargs=? MyCommand :call <sid>MyFunc(???)

What I would like to do is to replace the ??? in the MyFunc call in the above example so that I have the following effect:

if <f-args>
    :call <sid>MyFunc(readfile(<f-args>))
else
    :call <sid>MyFunc(g:some_defaults)

How to do that?

EDIT: a partial solution that I found is the following:

command! -nargs=? -complete=file MyCommand {
    var items: list<string> 
    if empty(<f-args>)
        items = g:some_defaults
    else
        items = readfile(<f-args>) 
    endif
    MyFunc(items)
}

But if I call it without arguments, i.e. :MyCommand I get E119: Not enough arguments for function: empty

It looks like that the problems boils down in checking if the arg is passed or not during the custom command is invokation, i.e. I don't understand how to discriminate if the command is invoked as :MyCommand or :MyCommand somefile in my custom command definition.

2 Answers 2

1

When calling a function, a default argument can be used to distinguish

vim9script
def MyFunc(arg: string = "NOTSET")
    if arg == "NOTSET"
        echo "No passed arg"
    else
        echo "passed arg " .. arg
    endif
enddef

command! -nargs=? MyCommand call <SID>MyFunc(<f-args>)

When using inline block command, use "<args>"

vim9script
command! -nargs=? MyCommand2 {
    if "<args>" == ""
        echo "No passed arg"
    else
        echo "passed arg <args>"
    endif
}
0

SOLVED: The solution I found is to check if the arg is passed in the called function

def MyFunc(...arg: list<string>)
    if empty(arg)
        echo "No passed arg"
    else
        echo "passed arg"
    endif
enddef

command! -nargs=? MyCommand :call <sid>MyFunc(<f-args>)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.