15

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.

15

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
\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 { 
\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
 }

\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 { 
\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
\typeout{not found that either, stopping}
\stop
\fi
\fi


\begin{document}
zzz
\end{document}
  • 2
    One day, the private scope will mean something :-) – Sean Allred 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:-) – David Carlisle Jun 15 '15 at 12:33

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.