vimtricks.wiki Concise Vim tricks, one at a time.

How do I set a colorscheme with a fallback in case it is not installed?

Answer

try | colorscheme gruvbox | catch | colorscheme default | endtry

Explanation

How it works

When you share your vimrc across multiple machines, a colorscheme you have installed on one system may not exist on another. Using try/catch in your vimrc gracefully handles this by attempting your preferred colorscheme and falling back to a safe default if it is not found.

The try/catch/endtry block in Vimscript works like exception handling in other languages:

try
    colorscheme gruvbox
catch
    colorscheme default
endtry

If colorscheme gruvbox fails (because the scheme is not installed), Vim catches the error and runs colorscheme default instead, which is always available.

Alternative approaches:

  • silent!: silent! colorscheme gruvbox suppresses the error but does not set a fallback
  • Multiple fallbacks: You can nest try blocks or chain checks
  • Check existence: if filereadable(expand('~/.vim/colors/gruvbox.vim')) before loading

For true colors support in modern terminals, also add:

if has('termguicolors')
    set termguicolors
endif

Example

A robust colorscheme section for your ~/.vimrc:

set background=dark

if has('termguicolors')
    set termguicolors
endif

try
    colorscheme gruvbox
catch
    try
        colorscheme desert
    catch
        colorscheme default
    endtry
endtry

This tries gruvbox first, falls back to desert (a built-in scheme), and finally falls back to default. Your vimrc will work on any machine without errors, whether or not your preferred colorscheme is installed.

Next

How do you yank a single word into a named register?