Vimscript: Run Command in Terminal

~ 2 minute read.

A more re­cent vim fea­ture is :term, the abil­i­ty to have a ter­mi­nal in­side vim. This su­per use­ful fea­ture now al­lows you to switch be­tween your code and asyn­chro­neous­ly run com­pile com­mands very eas­i­ly.

Since I use Vis­ual C++ on Win­dows, I need to run vcvarsall.bat in my con­sole to al­low CMake to prop­er­ly find the com­pil­er. To do so I now set up a vim com­mand :Vcvarsall which does this for me so that I don’t have to re­mem­ber the path. Us­ing term_sendkeys(buf, keys), you can eas­i­ly send text in­to the ter­mi­nal from a vim com­mand:

let $VCVARSALL = 'C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/vcvarsall.bat'
command! Vcvarsall call term_sendkeys(bufnr("%"), "\"%VCVARSALL%\" x64\<CR>")

The first line is the “easy way”, just an en­vi­ron­ment vari­able con­tain­ing the path. Since that still re­quires a bit of awk­ward % typ­ing, I de­fined the com­mand to do it for me. bufnr("%") is just a way to get the cur­rent buf­fer. Hence this com­mand on­ly works through C-W : in a ter­mi­nal buf­fer.

Writ­ten in 5 min­utes