Search code examples
vimftplugin

Set "compiler" option from .vimrc


I am using Vim 8.2 on Windows 10.

I have a custom compiler plugin called msbuild which I use to build a single C++ file. Each time I work on a new file, I must type:

:compiler msbuild

to make sure my msbuild compiler plugin is loaded, otherwise make fails. It's very annoying. I can type:

:compiler! msbuild

to set it globally, but then it is set for all files, even non C++ ones. I'd like my msbuild compiler plugin to be automatically loaded when I start working a new C++ file (extension :.cpp). I have tried using autocmd with FileType with no success:

autocmd FileType cpp compiler msbuild

I did not find a working example using Google. How can I achieve this?


Solution

  • Your autocommand probably fails because you didn't enable filetype detection and/or filetype plugins. Adding the following line to your vimrc should get you out of trouble:

    filetype plugin on
    

    If you also want filetype-specific indenting (you probably should) you can use this line instead:

    filetype plugin indent on
    

    If, somehow, you don't want to enable filetype detection, you can condition your autocommand on the file extension:

    autocmd BufNewFile,BufRead *.cpp compiler msbuild
    

    That said, the most canonical way to deal with the problem at hand, which is what @phd hinted at, is to…

    1. Enable filetype detection, plugins, and indenting in your vimrc with:

      filetype plugin indent on
      
    2. Create a custom ftplugin:

      %userprofile%\vimruntime\after\ftplugin\cpp.vim
      
    3. With the following content:

      compiler msbuild