Vim - can I pass multiple args to a custom command without writing a function

1

I have written following custom command in my .vimrc file:

command! -nargs=+ Sub :%s/<args>/g

It allows me to substitute one word for another and is executed like this:

:Sub <word>/<new word>

I would prefer to write commands with multiple args, like this:

:Sub <word> <new word>

Am I able to rewrite the command to accept multiple arguments?

Ideally I would like something like this:

command! -nargs=+ Sub :%s/<arg1>/<arg2>/g

Thank you in advance.

Alex Mckay

Posted 2019-01-26T14:33:02.890

Reputation: 13

Answers

1

Do the parsing on your own

If you use :help <q-args>, you get a quoted string that you can split() into the two space-separated parts:

command! -nargs=+ Sub execute '%substitute/' . split(<q-args>, ' ')[0] . '/' . split(<q-args>, ' ')[1] . '/g'

We can avoid parsing this twice with a bit of metaprogramming (call()) and printf():

command! -nargs=+ Sub execute call('printf', ['%%substitute/%s/%s/g'] + split(<q-args>, ' '))

This works, but error handling still isn't good (if you only pass one arg, it'll complain with E766: Insufficient arguments for printf()). You'll get more control by extracting the code into a :function.

Vim can parse arguments

A separate :function also allows Vim to do the argument parsing for you, via :help <f-args>.

command! -nargs=+ Sub call Sub(<f-args>)
function! Sub( ... )
    execute printf('%%substitute/%s/%s/g', a:1, a:2)
endfunction

With a function, you can easily check for the correct number of arguments:

function! Sub( ... )
    if a:0 != 2
        echo "Need two arguments"
        return
    endif
    ...

The downside of a function is that errors (e.g. the pattern doesn't match, buffer is not modifiable) cause a multi-line, unfriendly error message. try...catch would have to be used to derive a nice, single-line error message.

Bonus: Where to take it from there

  • As you're hiding the :s command (and the used delimiters) from the user, I think it shouldn't be required that the delimiters need to be escaped. Use escape(a:1, '/') instead of a:1 / a:2.
  • With :help :command-range, you can still default the command to work on the entire buffer, but also allow to pass other ranges.

Also consider whether the command really pulls its weight. Regardless of the used parsing, whitespace in arguments are problematic, a downside that the original :s doesn't have. The only benefit I see is that it's a bit easier to type, but the same can also be achieve via mapping(s) that pre-fill the command-line with an incomplete :s command, and position the cursor right in the middle.

Ingo Karkat

Posted 2019-01-26T14:33:02.890

Reputation: 19 513