In my .vimrc, how can I check for the existence of a color scheme?
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
.
An alternative to @eckes answer would be to try to load the colorscheme and deal with the error if it doesn't exist:
try
colorscheme mayormaynotexist
catch /^Vim\%((\a\+)\)\=:E185/
" deal with it
endtry
You could use the filereadable
function to check if a color scheme (e.g. schemename
) exists: check once under ~/vimfiles/colors
(Win32, for Unix use ~/.vim/colors/
) and once under $VIMRUNTIME/colors/
:
if filereadable("/path/to/schemename.vim")
colo schemename
endif
My method is similar,
if filereadable( expand("$HOME/.vim/colors/railscast.vim") )
colorscheme railscast
endif
This is a little more robust than hardcoding the entire path.