Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing and using arguments to command in Vim script

Tags:

vim

How can I use functions in a user defined command? As a simple specific example:

How would I write a command that echos the argument passed to it?

I have this:

command -nargs=1 FW execute ":echo ".<args>

But when I run:

:FW something

I get:

E121: Undefined variable: something

E15: Invalid expression: ":echo".something

like image 330
Tom Avatar asked Jul 31 '14 11:07

Tom


2 Answers

Because :echo takes an expression, a string must be quoted. This is so common that Vim has a special notation for it; See :help <q-args>. Now, for :execute, you'd need another level of quoting (and based on your comments it seems you went down that road):

:command! -nargs=1 FW execute "echo" string(<q-args>)

Also, you don't need to concatenate explicitly with .; the :execute command does that implicitly, and you can leave off the :.

But this double-quoting isn't necessary; you can skip the :execute:

:command! -nargs=1 FW echo <q-args>
like image 113
Ingo Karkat Avatar answered Sep 20 '22 12:09

Ingo Karkat


You don't need a colon when you pass commands to "execute", it executes as if you were already in command mode.

You also don't need to concatenate strings with "." with execute if you want spaces between them, by default it concatenates multiple arguments with spaces.

I tried escaping args so that it would be concatenated as a string, this seems to work:

command -nargs=1 FW execute "echo" '<args>'

Is this what you were trying to achieve?

:h execute and :h user-commands are good reading.

edit: some tests on this:

:FW "test"

test

:FW &shellslash

1

:FW 45

45

:FW "2+2"

"2+2"

:FW 2+2

4

As always, "execute" will execute anything you pass to it, so be careful.

like image 34
tbros Avatar answered Sep 23 '22 12:09

tbros