2

I'm trying to make a vim function that takes a variable and uses that as part of a shell command and buts it into the current buffer.

I tried using read but that just interprets the var as a string.

For instance, as an exaple

function MyFunc(var1)
    read !ls a:var1
end function

This looks for a dir called a:var1. Is there a way to do what I'm asking?

1

2 Answers 2

3

You're close. When you want to use a variable in an Ex command you need to use :execute. This command takes a Vim expression as arguments, evaluates the expression, and runs the resulting string as an Ex command. During this process variables are resolved into their values.

Before evaluation all of the arguments are concatenated together. :execute inserts spaces between the arguments. You can also do the concatenation yourself and pass a single string argument. (You may want to do this if you don't want the just noted space separation.)

For your case you have some fixed/static text ("read !ls") and one variable. For the multiple argument approach you could use either one of these:

exe "r !ls" a:var1
exe "r" "!ls" a:var1

The single string argument approach would look like this:

exe "r !ls " . a:var1

Notice how the . (string concat) operator joins the command string with the variable. In this case the variable is resolved into it's value before it's passed to :exe but the end result is the same.

0
1

You can also use the system() function to execute an external command and capture its output. In that case, it's more natural to use variable contents, since the function takes a string already, so you don't need to use :execute to interpolate the variable contents into the command.

In order to put the result of the expression into the current buffer, you can use the :put command, which can take a = followed by an expression:

:put =system('ls '.a:var1)

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.