Search code examples
vimvim-plugin

How to execute a Plug in .vimrc conditionally on Vim version?


I have this .vimrc config file

$ cat ~/.vimrc
call plug#begin('~/.vim/plugged')
  Plug 'alvan/vim-closetag'

  " below only work with vim9
  Plug 'yegappan/lsp'
call plug#end()
$

This .vimrc is used by users with Vim 8 others with Vim 9.

How could I execute the line

Plug 'yegappan/lspl

only in case the Vim which loads it is Vim 9?


Solution

  • In general, check for a feature, not for a version. The fact that a certain feature was added in a specific version renders the version a secondary property.

    Let's apply this rule of thumb to the case at hand. Quoting from yegappan/lsp's README (emphasis mine):

    This plugin is written using only the Vim9 script.

    Comparing with :help +feature-list, we see that the +vim9script feature is what we're looking for.

    You can wrap the Plug command in a conditional like this:

    call plug#begin('~/.vim/plugged')
        Plug 'alvan/vim-closetag'
    
        if has('vim9script')
            Plug 'yegappan/lsp'
        endif
    call plug#end()
    

    See :help has() for more information on how to check for features.

    To answer your literal question, the version number is found in the pre-defined variable v:version (see :help v:version) as a three digit integer. So you could also do:

    if version >= 900
        Plug 'yegappan/lsp'
    endif
    

    But really, it's the feature we're interested in.

    On a side note: some features (not vim9script, though) can be activated or deactivated at compile time. There may be a newer version of Vim not supporting a feature because it was not compiled in.