[Tex/LaTex] Font selection in XeTeX for specific characters

fontsxetex

I just ran into another issue, I like to use gill sans very much but the number 1, lower case L and upper case I are almost indistinguisable. On the other hand I like Helvetica numbers. Is there a way to use Gill Sans for all non-numeric characters and Helvetica only for numbers [0 9] ?

Best Answer

Yes, you can. But I only know a tricky method --- to use \XeTeXinterchartoks and related commands. There have been some packages, for example xeCJK and ucharclasses, that use this mechanism for multilingual support. (I wrote a few code for xeCJK.) For more information, you can read XeTeX's reference.

Set \XeTeXinterchartokenstate=1 to enable the mechanism.

There are already some predefined char classes. 0 for normal westen alphabets and symbols, 1 for CJK ideographs, 4095 for boundary (255 in older versions of XeTeX), etc. And you can use \newXeTeXintercharclass to allocate a new class.

Use \XeTeXcharclass to set the numbers to the new character class, and use \XeTeXinterchartoks to do the trick.

Full example:

result

\documentclass{article}
\usepackage{fontspec}
\XeTeXinterchartokenstate=1
\chardef\CharNormal=0
\makeatletter
% Test for old and new versions of the latex kernel
\ifx\e@alloc@intercharclass@top\@undefined
    \chardef\CharBound=255
\else
    \chardef\CharBound=\e@alloc@intercharclass@top
\fi
\makeatother
\newXeTeXintercharclass\CharNumbers
\XeTeXcharclass`0=\CharNumbers
\XeTeXcharclass`1=\CharNumbers
\XeTeXcharclass`2=\CharNumbers
\XeTeXcharclass`3=\CharNumbers
\XeTeXcharclass`4=\CharNumbers
\XeTeXcharclass`5=\CharNumbers
\XeTeXcharclass`6=\CharNumbers
\XeTeXcharclass`7=\CharNumbers
\XeTeXcharclass`8=\CharNumbers
\XeTeXcharclass`9=\CharNumbers
\newtoks\TokSetfont
\TokSetfont={\begingroup\fontspec{Latin Modern Mono}}
\XeTeXinterchartoks\CharNormal\CharNumbers=\TokSetfont
\XeTeXinterchartoks\CharBound\CharNumbers=\TokSetfont
\XeTeXinterchartoks\CharNumbers\CharNormal={\endgroup}
\XeTeXinterchartoks\CharNumbers\CharBound={\endgroup}
\begin{document}
0123

abc123

123abc

abc123def

123abc456
\end{document}

BTW, this does not affect math fonts.

Note Code has been updated to reflect changes in XeTeX (but not actually reflected in the documentation.) If this code fails, remove the test for XeTeX version and just use \chardef\CharBound=4095. (There was one version of the kernel that did not have \e@alloc@intercharclass@top defined, but the class was still 4095.)

Related Question