6

Why is let foo = $HOME valid and let foo = $HOME/bar invalid in vimscript?

I have tried let foo = "$HOME/bar" but it is the equivalent of foo = '$HOME/bar' in shell script, $HOME is not expanded.

What is the canonical way to do the equivalent of foo = $HOME/bar (valid in shell) in vimscript?

11

VimScript is more of a programming language. So the following won't work just like in C.

let foo = $HOME/bar

It's division.

let foo = "$HOME/bar"

Inside quoted string only "backslashes" are pre-processed.

Therefore, you must do one of

  1. concatenation: let foo = $HOME..'/bar'
  2. printf: let foo = printf('%s/bar', $HOME)
  3. expand: let foo = expand('$HOME/bar') or let foo = expand('~/bar')
  4. substitute: let foo = substitute('$HOME/bar', '$\(\w\+\)', '\=getenv(submatch(1))', 'g')

... and so on

Note that expand() is also allowed to spawn the shell (so thing like expand('$RANDOM') could also work). Could be good or not.

5

You need to use explicit string concatenation here, since :let wants an expression and the /bar looks like a division by a variable named "bar".

What you want here is:

let foo = $HOME . '/bar'

Note that . is the Vim operator for string concatenation here.

2
  • 1
    I noticed that Matt used .. in their answer. I thought perhaps that was a typo, since I never knew of .. before. However, looking at the documentation (:h expr-..), I see: "For String concatenation '..' is preferred, since '.' is ambiguous, it is also used for |Dict| member access and floating point numbers. When |vimscript-version| is 2 or higher, using '.' is not allowed.". TIL.
    – JoL
    May 20 at 15:49
  • @JoL Yeah .. is the "new" string concatenation operator. But . still works (and I'm guessing it will still be around for a long while), so I still tend to use it (in general and in my answers here) since it should still work in older versions of Vim as well.
    – filbranden
    May 20 at 16:08

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.