In a .vimrc
, is it possible to load a color scheme only if it exists?
Using :colorscheme
in a try-catch as Randy has done may be enough if you just want to load it if it exists and do something else otherwise. If you are not interested in the else part, a simple :silent! colorscheme
is enough.
Otherwise, globpath()
is the way to go. You may, then, check each path returned with filereadable()
if you really wish to.
" {rtp}/autoload/has.vim
function! has#colorscheme(name) abort
let pat = 'colors/'.a:name.'.vim'
return !empty(globpath(&rtp, pat))
endfunction
" .vimrc
if has#colorscheme('desert')
...
EDIT: filereadable($HOME.'/.vim/colors/'.name.'.vim')
may seem simple and it's definitively attractive, but this is not enough if the colorscheme we're looking for is elsewhere. Typically if it has been installed in another directory thanks to a plugin manager. In that case the only reliable way is to check in the vim 'runtimepath'
(a.k.a. 'rtp'
). Hence globpath()
. Note that :colorscheme name
command searches in {rtp}/colors/{name}.vim
.