[Tex/LaTex] How to check if a font exists in XeLaTeX

programmingxetex

Is there a way to check if a font exists in XeLaTeX? I am aware of Check for missing fonts/characters in XeLaTeX?, but sadly the one answer only refers to the log. I am interested for a test via code.

Background:

I am trying to define a command that checks a series of fonts and uses the first one that it finds (similar to the CSS properties)

 p{font-family:"Times New Roman",Georgia,Serif;}

I intend to use pgf keys and here is a MWE example.

 \documentclass{article}
 \usepackage{ifxetex}
 % Generic defaults
 \ifxetex
   \usepackage{fontspec}
   \defaultfontfeatures{Mapping=tex-text}
   \setmainfont{Times New Roman}
   \setsansfont{Minion Pro}
\else
   \usepackage{mathpazo}
   \usepackage[T1]{fontenc}
\fi
\usepackage{pgfkeys}
\usepackage{lipsum}
\makeatletter
% keys
\pgfkeys{/fonts/.is family}
\def\cxset{\pgfqkeys{/fonts}} 
\cxset{%
  serif/.code=\rmfamily,
  Serif/.code=\rmfamily,
  font-name/.store in =\fontname@cx,
}
\cxset{
   serif,
   font-name=Times New Roman,
}

\ifxetex
  \defaultfontfeatures{Mapping=tex-text}
  % code to be added here for iterating through list etc..
  \setmainfont{\fontname@cx}
  \setsansfont{Minion Pro}
\fi
\makeatother
\begin{document}
\lipsum[1]
\end{document}

Ultimately the key

font-family={Times New Roman, Some Other Font, Another Font, serif}

should iterate via all the font names. if none is found the serif value will trigger the default \rmfamily. I can code the iteration etc, but I am stuck on the test.

Best Answer

Does this help (take from XeTeX mailing list):

\documentclass{article}
\begin{document}
 \def\myfont{"Persian Modern"}% first preferred font
  \def\myfallback{"XB Zar"} % if first font not avaliable
  \count255=\interactionmode
  \batchmode
  \font\bodyfont=\myfont\space at 10pt
  \ifx\bodyfont\nullfont
    \font\bodyfont = \myfallback\space at 10pt
    \ifx\bodyfont\nullfont
      \errorstopmode
      \errmessage{no suitable font found}
    \else
      \let\myfont=\myfallback
    \fi
  \fi
  \interactionmode=\count255
  \bodyfont
This is a test.
\end{document}
Related Question