Changing the font based on availability to fontspec

I would like to distribute a class that uses a professional font loaded via fontspec, and falls back to one of the default fonts in TeX Live if this is not available. I know that one can detect fonts packaged with TeX Live:

\documentclass{article}
\usepackage{fontspec}
\IfFileExists{tgpagella.sty}{\setmainfont{TeX Gyre Pagella}}{}

\begin{document}

\fontname\font\ at \the\fontdimen6\font

\end{document}


This doesn't work, however, if one instead tries to detect a font file in the same directory:

\documentclass{article}
\usepackage{fontspec}
\IfFileExists{texgyrepagella-regular.otf}{\setmainfont{TeX Gyre Pagella}}{}

\begin{document}

\fontname\font\ at \the\fontdimen6\font

\end{document}


Is there a mechanism somewhere to include .otf files in what \IfFileExists is able to detect?

• fontspec has a fallback mechanism these days older answer but Will added a proper interface to that if I recall correctly – David Carlisle Jan 21 '19 at 16:38
• \fontspec_font_if_exist:nTF and similar commands look to be the right thing.... – David Carlisle Jan 21 '19 at 16:43
• @DavidCarlisle the documentation suggests \IfFontExistsTF. – Ulrike Fischer Jan 21 '19 at 16:44
• @UlrikeFischer but it looks much more impressive with _ and : – David Carlisle Jan 21 '19 at 16:45
• @DavidCarlisle Only for people not really used to _ and : ;-). – Ulrike Fischer Jan 21 '19 at 16:47

Recent fontspec releases allow you to test for a font being loadable with \IfFontExistsTF or its internal expl3 version \fontspec_font_if_exist:nTF:
\documentclass{article}