[Tex/LaTex] Use stylistic set variations only for certain glyphs

fontsfontspecxetex

Some fonts include stylistic variations of certain glyphs. But it seems like there is only a global switch for these alternates, as in this example from the fontspec manual:

\fontspec{Linux Libertine}
\textsc{a} \& h \\
\addfontfeature{Alternate=0}
\textsc{a} \& h

Is it possible to use stylistic alternates only for individual glyphs, e.g. only for the '&'-glyph?

Best Answer

For the specific example you have in mind, the simplest solution is simply to redefine \& as the alternate version. This is especially true of \&, since it's already a macro. For the occasional other character, this route might also be best, i.e. simply define a macro to introduce the alternate.

There is a more complicated version using \XeTeXintercharclass that might be useful for choosing alternates for more characters. The basic technique is explained in the XeTeX documentation (texdoc xetex). Note that this solution will not work for LuaLaTeX, which does not support these interchar classes.

I've worked both methods in the following sample document:

% !TEX TS-program = XeLaTeX

\documentclass{article}
\usepackage{fontspec}
\setmainfont[]{Linux Libertine O}
\begin{document}

This is an \& not alternate 

% First the simple version
\let\oldand\&
\renewcommand{\&}{\begingroup\addfontfeature{Alternate=0}\oldand\endgroup}

This is the alternate \& after redefinition.

\renewcommand\&{\oldand}

This is back to the old \&

% Now the more complicated version:
\XeTeXinterchartokenstate=1 % enable character classes
\newXeTeXintercharclass\myalt % create a new class
\XeTeXcharclass `\& \myalt % add & to the class
% between any character of class 0 and \myalt add the alternate feature
\XeTeXinterchartoks 0 \myalt = {\begingroup\addfontfeature{Alternate=0}}
% between \myalt and any character end the group
\XeTeXinterchartoks  \myalt 0 = {\endgroup}
% between a word boundary and \myalt add the alternate feature
\XeTeXinterchartoks 255 \myalt = {\begingroup\addfontfeature{Alternate=0}}
% between \myalt and the word boundary end the group
\XeTeXinterchartoks  \myalt 255 = {\endgroup}
This is an \&  alternate. And one in the middle of a word: A\&B.
\end{document}

output of code