0

In my shell, I can use curly braces to isolate the names of environment variables.

For example, if I have two env vars, ONE and TWO, equal to 1 and 2, then

> echo "$ONE_$TWO"
ONE_: Undefined variable
> echo "${ONE}_${TWO}"
1_2

I like to try something similar with Vim's expand() function, but the curly braces don't help.

:echo expand('$ONE_$TWO')
$ONE_$TWO
:echo expand('${ONE}_${TWO}')
$ONE_$TWO
3
  • You may not need expand if the variables are already known to vim (:help expr-env-expand): :echo $ONE .. '_' .. $TWO
    – D. Ben Knoble
    Jan 27, 2023 at 15:58
  • Yes, this is true. If I were to construct a string on my own using Vimscript, I would do it like this with the dot (or VIm9 double dot). However, my plugin is being used my my colleagues who are not as experienced with Vimscript. I included an option for a user to define a non-default path in their .vimrc. If a user defines a string containing env vars, then I'd like give that string to the expand() function in my plugin. My end-users would have an easier time putting curly braces around the env var (just like in a shell script) than to use Vimscript. Jan 27, 2023 at 19:56
  • There is also a string interpolation syntax I’ve forgotten (maybe a $ prefix?)
    – D. Ben Knoble
    Jan 27, 2023 at 22:36

1 Answer 1

1

If you put any character that is invalid in an environment variable name after the environment variable name, it will force the expansion. Example:

ec expand('$SHELL-$HOME')

Output:

/bin/zsh-/home/wilson

Then you can replace all instances of the invalid character with an underscore:

ec expand('$SHELL-$HOME')->substitute('-', '_', 'g')

Output:

/bin/zsh_/home/wilson

I recommend you define your own function in your vimrc for this

function! Exp(str)
    return expand(a:str)->substitute('-', '_', 'g')
endf

Then run ec Exp('$SHELL-$HOME') as needed.

Or you could even do:

function! Exp(str)
    return expand(a:str->substitute('_', '-', 'g'))->substitute('-', '_', 'g')
endf

and run it as ec Exp('$SHELL_$HOME'). The only concern is if the unexpanded string contains hyphens or if the values of the environment variables contain hyphens.

Of course, it doesn't have to be a hyphen, it could be anything other than an alphanumeric or underscore. You might come up with some weird character that will definitely never cause undesired results. You could even use a single closing curly brace and use expand('$SHELL}_$HOME')->substitute('}', '', 'g'), as long as the result will definitely not contain any } characters.

Your Answer

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

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