Many commands in Vim, including :botright
and :vsplit
, expect plain text, no variables or expressions ( see :help 41.3
and :help expression
to know what a expression means). But there are commands that do expect variables and/or expressions, such as :echo
and :execute
.
String interpolation is common in many programming languages such as Groovy, Kotlin, Perl, PHP, Python, Ruby, Scala, and Swift, and most Unix shells, but not Vimscript. However, when a Vim command expects an expression, it can evaluate variables and use the concatenation operator (the dot .
) to obtain the same effect.
So it would be great if we could use the content of a variable, rather than just plain text, to issue commands such as :botright vsplit a:file
. For that purpose, Vim gives us the :execute
command, from :help :execute
:
:exe[cute] {expr1} .. Executes the string that results from the
evaluation of {expr1} as an Ex command. Multiple
arguments are concatenated, with a space in
between. To avoid the extra space use the "."
operator to concatenate strings into one
argument.
In that way, you can take advantage of the :execute
command to get the intended result, as follows:
function DiffWith(file)
execute "botright vsplit" a:file
windo diffthis
endfunction
command -nargs=1 -complete=file Diffwith call DiffWith(<f-args>)
and then you can call it by typing in:
:Diffwith foo.rb
Bonus
As Peter Rincker pointed out, Vim includes a similar functionality, see below:
:botright vertical diffsplit foo.rb
and you can rewrite your command in this way:
:command! -nargs=1 -complete=file Diffwith botright vertical diffsplit <args>
:botright vertical diffpsplit foo.rb
? – Peter Rincker Aug 8 '17 at 19:23