# How can I conditionally include a syntax file from another syntax file?

I have a custom syntax plugin for a file format that can contain embedded HLSL or GLSL code. At the moment, I've manually included a bunch of syntax keyword and syntax match commands in my syntax file to cover the basics of HLSL or GLSL source. I'd prefer to simply reference an existing HLSL syntax plugin via syntax include, but there is no built-in HLSL or GLSL syntax support in vim, so I cannot expect that a syntax include will succeed.

I'd like to attempt to execute syntax include, and if it fails (or would fail), fall back to my half-hearted custom version. How can I accomplish this?

I've looked at try/endtry, but they didn't seem to allow me to avoid an error if the desired syntax file wasn't present, and in any case only work on vim 7.0 or greater, and if possible I'd like to use a version-agnostic solution.

When 'verbose' is one or higher, there is a message when no file could be found.

This uses :echomsg to print the error, which you can capture like:

redir => error
verbose silent runtime syntax/cx.vim
redir END


I've found that using :redir in startup scripts is sometimes problematic though, sometimes Vim mixes up which redir belongs to which variable, so alternatively you can just use a loop to scan each entry in the runtimepath:

let found = 0
for path in split(&runtimepath, ',')
execute 'source ' . path . '/fname.vim'
let found = 1
break
endif
endfor

• +1 for introducing me to redir. :D – Josh Jul 30 '15 at 18:24

Since try/endtry did not seem to work for me after a cursory attempt, I resorted to relying on the behavior of syntax include which states that a relative path is searched for in the runtime path, and put this in my syntax file:

let b:has_hlsl_support = 0
for directory in split(&runtimepath, ",")

Then I can check b:has_hlsl_support and branch accordingly. This works, but I find myself wondering if there's a superior method.