18

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

2 Answers 2

22

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>
Sign up to request clarification or add additional context in comments.

Comments

5

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.

1 Comment

That is almost what I want. Ideally I would like all arguments to be interpreted as a string. In the end, I went with: command -nargs=1 FW execute "echo \"" '<args>' "\""

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.