6

Let's say I've got the following function :

function! SomeFunction()

    return "/tmp/foo"

endfunction
  • If I type : :echo SomeFunction()

The function is evaluated and the output in vim is the string "/tmp/foo".

  • If I type : :edit SomeFunction()

The function is not evaluated, instead of opening the file /tmp/foo a buffer called SomeFunction() is opened.

  • If I type !cat SomeFunction(), the function is not evaluated, the shell complains with the error :

zsh: parse error near `()' shell returned 1

  • If I type execute "!cat " . SomeFunction(), the function is evaluated and the content of /tmp/foo is displayed in the shell.

  • If I'm editing the file foo which contains the text hello world and I type !cat %, % is evaluated (or expanded ?) and the shell displays hello world.

I'm a little confused by all those differences.

In which context is a function or a special character like % (current file) and # (alternate file) automatically evaluated / expanded and why ?

4

It depends on the Ex command you're trying to use.

The Vim documentation on echo and edit comes in useful here as it tells you what each Ex command it expects.

:echo according to Vim's documentation takes an expression, and expressions can be function calls in Vimscript.

:edit on the other hand expects an +opt, followed by a +cmd. Conveniently, the Vim documentation also explains what the +opt and +cmd can be.

To solve your problem, you can use the :execute Ex command instead to evaluate a function like so:

:execute("edit " . SomeFunction())

If you ever become confused if an Ex command takes an expression, option, command or something else, remember to always check the Vim documentation as it will let you know what the Ex command is expecting. A trick is to prepend the Ex command with a : (i.e. :help :echo for the help page on :echo) so that you will find the correct match.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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