# [XeTeX] how to test whether a font exists?

Will Robertson wspr81 at gmail.com
Thu Dec 4 00:17:03 CET 2008

On 04/12/2008, at 3:25 AM, Grzegorz Murzynowski wrote:

> I know it's basic but I don't find in The XeTeX Companion a primitive
> for testing existence of a font.
>
> It would be nice to write something like
>
> \iffontexists "Garamond Premier Pro" \setmainfont{Garamond Premier
> Pro}
> \else \typeout{@@@@ no Garamond Premier Pro, leaving the default
> font}\fi
>
> Any suggestions?

The reason this primitive doesn't exist is for performance reasons; it
can be very slow to check for the non-existence of a font.

Jonathan has a sample file floating around called
"testfontavailability" which I've reproduced below; it should be a
good starting point :)

Hope this helps,
Will

% Macros to try and find available fonts for XeTeX sample docs
%
% Usage:
%
% \testFontIsAvailable{font-name}
% sets \ifFontIsAvailable according to whether or not it could be found
%
% \FindAnInstalledFont{font-name/alternative/another/yet-another}{\cs}
% searches for an available font from among the names given,
% and \def's the control sequence \cs to the first one found
% or to <No suitable font found> if none (which will subsequently
% cause an error when used in a \font command).
\newif\ifFontIsAvailable
\def\testFontAvailability#1{
\count255=\interactionmode
\batchmode
\else \FontIsAvailabletrue \fi
\interactionmode=\count255
}
\def\FindAnInstalledFont#1#2{
\expandafter\getFirstFontName#1/\end
\let\next\gobbleTwo
\ifx\trialFontName\empty
\def#2{<No suitable font found>}%
\else
\testFontAvailability{\trialFontName}
\ifFontIsAvailable
\edef#2{\trialFontName}%
\else
\let\next\FindAnInstalledFont
\fi
\fi
\expandafter\next\expandafter{\remainingNames}{#2}
}
\def\getFirstFontName#1/#2\end{\def\trialFontName{#1}\def
\remainingNames{#2}}
\def\gobbleTwo#1#2{}