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.


Updated answer

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.

Original answer

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:-)



\cs_set:Nn \__fontspec_load_font:
  \__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 { 
\__fontspec_warning:nx {font-not-found} {\l_fontspec_fontname_up_tl} }
  \__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

\cs_set:Nn \__fontspec_load_fontname:n
    \__fontspec_load_external_fontoptions:Nn \l_fontspec_fontname_tl {#1}
    \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 { 
\__fontspec_warning:nx {font-not-found} {#1} }



\typeout{(zzzz found (strange:-)}
\typeout{zzzz not found, trying TeX Gyre Bonum}
\setmainfont{TeX Gyre Bonum}
\typeout{not found that either, stopping}

  • 3
    One day, the private scope will mean something :-) Jun 15 '15 at 12:19
  • 5
    @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
  • 1
    @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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.