How can you check if fontspec (with LuaLaTeX) can load a font?

I want to check if fontspec (with LuaLaTeX) can load a certain font and if not try to load another one. For pdflatex I did by checking if the package file exists; but I don't find an easy way to do it with fontspec.

The patch originally described here is not needed (and may not work in recent releases).

As documented in the fontspec manual, fontspec now has an

\IfFontExistsTF{font name}{yes code}{no code}

command that allows you to test if a font exists.

You can trap the error and make it a warning, just setting a flag, then test for that and load something else, see the code below. Note this is poking into internal interfaces so if it breaks at a fontspec update, don't complain:-)

\documentclass{article}

\usepackage{fontspec}

\newif\ifgoodfont
\makeatletter
\ExplSyntaxOn
{
\__fontspec_font_set:Nnn    \l_fontspec_font
{ \__fontspec_fullname:n {\l_fontspec_fontname_up_tl} } {\f@size pt}
\__fontspec_font_if_null:NT \l_fontspec_font {
\global\goodfontfalse
\__fontspec_warning:nx {font-not-found} {\l_fontspec_fontname_up_tl} }
\__fontspec_set_font_type:
\__fontspec_font_gset:Nnn   \l_fontspec_font
{ \__fontspec_fullname:n {\l_fontspec_fontname_up_tl} } {\f@size pt}
\l_fontspec_font % this is necessary for LuaLaTeX to check the scripts properly
}

{
\prop_get:NVNF \g__fontspec_fontopts_prop \l_fontspec_fontname_tl \l__fontspec_fontopts_clist
{ \clist_clear:N \l__fontspec_fontopts_clist }
\__fontspec_font_set:Nnn \l_fontspec_font {\__fontspec_fullname:n {\l_fontspec_fontname_tl}} {\f@size pt}
\__fontspec_font_if_null:NT \l_fontspec_font {
\global\goodfontfalse
\__fontspec_warning:nx {font-not-found} {#1} }
}

\ExplSyntaxOff
\makeatother

{\scrollmode\global\goodfonttrue
\setmainfont{zzzz}
}

\ifgoodfont
\typeout{(zzzz found (strange:-)}
\else
\typeout{zzzz not found, trying TeX Gyre Bonum}
\global\goodfonttrue
\setmainfont{TeX Gyre Bonum}
\ifgoodfont
\typeout{OK}
\else
\stop
\fi
\fi

\begin{document}
zzz
\end{document}

• One day, the private scope will mean something :-) Jun 15 '15 at 12:19
• @SeanAllred there's no privacy in a macro expansion language, only gentleman's agreements not to peek (not followed here:-) Jun 15 '15 at 12:33
• I can't compile your code : ./test_font.tex:38: Undefined control sequence. \__fontspec_load_font: ->\__fontspec_font_set:Nnn Mar 18 '20 at 8:30
• @AlainMatthes as Sean hinted that was a patch to an undocumented internal interface, and it may have broken in the years since I posted this, but since then Will took the patch idea and made a documented interface see section 2.4 of the fontspec manual \IfFontExistsTF I will update the answer above with a pointer to this function. Mar 18 '20 at 9:22
• Thanks for your comment ! Mar 18 '20 at 9:26