[Tex/LaTex] XeLaTeX, fontspec and printing the name of the current font

fontsfontspecxetex

Is it possible, using XeLaTeX and fontspec.sty, to write a macro, say, \printcurrentfont, such that it would print the name of the font currently in use? I have looked through the fontspec documentation, but so far have not found an answer.

Best Answer

You can access the internal and the external names of the current font respectively with \the\font and \fontname\font. The former must be stringified in order to print it.

Further massaging of the external font name can be added.

\documentclass{article}

\usepackage{fontspec}

\setmainfont{Libertinus Serif}
\setsansfont{TeX Gyre Adventor}[Scale=MatchUppercase]
\newfontfamily{\junicode}{Junicode}

\DeclareTextFontCommand{\textttup}{\normalfont\ttfamily}

\newcommand{\printinternalcurrentfont}{%
  \expandafter\textttup\expandafter{\expandafter\string\the\font}%
}
\newcommand{\printexternalcurrentfont}{%
  \expandafter\textttup\expandafter{\fontname\font}%
}

\begin{document}

\printinternalcurrentfont

\printexternalcurrentfont

\bigskip

{\itshape\printinternalcurrentfont\par\printexternalcurrentfont}

\bigskip

\sffamily

\printinternalcurrentfont

\printexternalcurrentfont

\bigskip

\junicode

\printinternalcurrentfont

\printexternalcurrentfont

\end{document}

Output with XeLaTeX

enter image description here

Output with LuaLaTeX

enter image description here

If you're not interested in the finer details, but just in the main font name part, change the definition of \printexternalcurrentfont into

\makeatletter
\newcommand{\printexternalcurrentfont}{%
  \expandafter\format@externalcurrentfont\fontname\font:\@nil
}
\def\format@externalcurrentfont#1:#2\@nil{%
  \textttup{\@ifnextchar"{\@gobble}{}#1}%
}
\makeatother

The output would become

enter image description here