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
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With