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.
Asked
Active
Viewed 1,135 times
18
TeXtnik
- 5,853
1 Answers
19
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:-)
\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}
David Carlisle
- 757,742
./test_font.tex:38: Undefined control sequence. \__fontspec_load_font: ->\__fontspec_font_set:Nnn– Alain Matthes Mar 18 '20 at 08:30\IfFontExistsTFI will update the answer above with a pointer to this function. – David Carlisle Mar 18 '20 at 09:22