
\ifdefined \XeTeXOTcountscripts \else
  \makeatletter
  \@latex@error{^^J*** The fontspec documentation can only be typeset with XeTeX at present! ***\@gobble}\@ehc
\fi

\documentclass[a4paper]{ltxdoc}

\makeatletter

\usepackage{booktabs,calc,caption,color,enumitem,fancyvrb,hologo,graphicx,ifthen,url,varioref,varwidth,microtype,tocloft,framed}

% ToC formatting:
\setlength\cftsubsecnumwidth{1.4\cftsubsecnumwidth}
%\def\@cfttocstart{\small\begin{multicols}{2}}
%\def\@cfttocfinish{\end{multicols}}

\fvset{gobble=0}

\captionsetup[table]{position=above}
\captionsetup[figure]{position=above}

\usepackage{tgpagella,eulervm}
\usepackage{inconsolata}
\usepackage[
  bookmarks=true,
  colorlinks=true,
  linkcolor=niceblue,
  urlcolor=niceblue,
  citecolor=niceblue,
  pdftitle={The fontspec package},
  pdfsubject={Advanced font selection for XeLaTeX/LuaLaTeX},
  pdfauthor={Will Robertson},
  pdfkeywords={xetex, xelatex, luatex, lualatex, unicode, opentype, aat}
  ]{hyperref}

%% ToC
\def\@dotsep{1000}
\setcounter{tocdepth}{2}
\setlength\columnseprule{0.4pt}
\renewcommand\tableofcontents{\relax
  \begin{multicols}{2}[\section*{\contentsname}]\relax
    \@starttoc{toc}\relax
  \end{multicols}}

%% Index
\setcounter{IndexColumns}{2}
\renewenvironment{theglossary}
  {\small\list{}{}
     \item\relax
     \glossary@prologue\GlossaryParms
     \let\item\@idxitem \ignorespaces
     \def\pfill{\hspace*{\fill}}}
  {\endlist}

%% varioref definitions:
\labelformat{table}{Table~#1}
\labelformat{section}{Section~#1}
\labelformat{subsection}{Section~#1}

\definecolor{niceblue}{rgb}{0.1,0.2,0.8}

\newsavebox\X
\newsavebox\Y

\newcounter{example}

\newcommand\exref[1]{Example~\ref{ex:#1}}
\newcommand\Exref[1]{Example~\ref{ex:#1}}

\newenvironment{Xexample}[3][]
  {\VerbatimEnvironment\begin{Fexample}[#1]{#2}{#3}{X}}
  {\end{Fexample}}

\newenvironment{Lexample}[3][]
  {\VerbatimEnvironment\begin{Fexample}[#1]{#2}{#3}{L}}
  {\end{Fexample}}



\newenvironment{Fexample}[4][]
  {%
    \def\options{#1}%
    \def\filename{#2}%
    \def\captiontext{#3}%
    \def\prefix{#4}
    \refstepcounter{example}%
    \label{ex:\filename}%
    \IfFileExists{zzz-\theexample-\prefix-\filename.tex}{}{%
      \immediate\write18{rm -f zzz-\theexample-* ;}%
    }%
    \VerbatimEnvironment
    \begin{VerbatimOut}{zzz-\theexample-\prefix-\filename.tex}}
% text in the environment
  {\end{VerbatimOut}
    \begin{figure}
      \setlength\parindent{0pt}%
      \edef\@tempa{[gobble=0,fontsize=\noexpand\small,\options]}%
      \savebox\X{%
                  \expandafter\BVerbatimInput
                  \@tempa{zzz-\theexample-\prefix-\filename.tex}%
                }%
      \IfFileExists{zzz-\theexample-\prefix-\filename.pdf}{}
         {%
           \edef\1{%
             \csname prog@\prefix\endcsname
             "%
             \unexpanded{%
               \documentclass{article}%
               \usepackage{booktabs,ifthen,graphicx,xcolor,varwidth}
               \usepackage[active,tightpage]{preview}%
               \usepackage{fontspec}%
               \defaultfontfeatures{Ligatures=TeX} \begin{document}\begin{preview}\begin{varwidth}{0.7\linewidth}\input} zzz-\theexample-\prefix-\filename.tex
             \unexpanded{\end{varwidth}\end{preview}\end{document}}
             "
           }%
           \immediate\write18{\unexpanded\expandafter{\1}}%
         }%
      \savebox\Y{%
      \IfFileExists{zzz-\theexample-\prefix-\filename.pdf}
          {\includegraphics{zzz-\theexample-\prefix-\filename.pdf}}
          {\color{red}\itshape ---Graphic not generated---}%
      }
      % TYPESETTING
      \rule[0.5\baselineskip]{\columnwidth}{1pt}%
      \vspace{-1.2ex}%
      \def\@tempa{\small\textsf{Example~\theexample:~}}%
      \settowidth\@tempdima{\@tempa\captiontext}%
      \par
      \ifdim\@tempdima>\linewidth
        \settowidth\@tempdima{\@tempa}%
        \@tempa\parbox[t]{\linewidth-\@tempdima}{\small\captiontext}%
        \vspace{0.4\baselineskip}%
      \else
        \parbox{\linewidth}{\centering\@tempa~\captiontext}%
      \fi
      \par\rule[0.4\baselineskip]{\columnwidth}{0.4pt}\par
      \ifdim\dimexpr\wd\X+\wd\Y>\linewidth\relax
        \null\hfill\makebox[0pt][r]{\usebox\Y}\usebox\X
      \else
        \hfill\usebox\Y\hfill\usebox\X
      \fi
      \par\rule[0.5\baselineskip]{\columnwidth}{1pt}
    \end{figure}
}

\def\prog@X{xelatex
               -jobname=zzz-\theexample-X-\filename\space}

\def\prog@L{lualatex
               -jobname=zzz-\theexample-L-\filename\space}

%%%%%%%%%%%%%%%%%%%%%%

\newcommand*\setexsize[1]{\let\examplesize#1}
\newcommand*\setverbwidth[1]{\def\auxwidth{#1}}

%% Various labelling commands:
\newcommand*\name[1]{{#1}}
\newcommand*\pkg[1]{\textsf{#1}}
\newcommand*\opt[1]{\texttt{#1}}
\newcommand*\feat[1]{\texttt{#1}}

\let\latin\textit
\def\eg{\latin{e.g.}}
\def\ie{\latin{i.e.}}
\def\Eg{\latin{E.g.}}
\def\Ie{\latin{I.e.}}
\def\etc{\@ifnextchar.{\latin{etc}}{\latin{etc.}\@}}

\newcommand\note[1]{\unskip\footnote{#1}}

\def\MacOSX{Mac~OS~X}
\def\AAT{\textsc{aat}}
\def\ATSUI{\textsc{atsui}}

\newcommand\NFSS{\textsc{nfss}}
\newcommand\XeTeX{\hologo{XeTeX}}
\newcommand\XeLaTeX{\hologo{XeLaTeX}}
\newcommand\LuaTeX{\hologo{LuaTeX}}
\newcommand\LuaLaTeX{\hologo{LuaLaTeX}}


%% (La)TeX font-related declarations:
\linespread{1.05}      % Pagella needs more space between lines
\frenchspacing         % Remove ugly extra space after punctuation

\newcounter{argument}
\g@addto@macro\endmacro{\setcounter{argument}{0}}
\newcommand*\darg[1]{%
  \stepcounter{argument}%
  \noindent{\ttfamily\char`\#\theargument~:~}#1\par}
\newcommand*\doarg[1]{%
  \stepcounter{argument}%
  \noindent{\ttfamily\makebox[0pt][r]{[}\char`\#\theargument]:~}#1\par}

\newcommand\unichar[2]{\textsc{\MakeLowercase{u+#1: #2}}}

\newcommand\cmdbox[1]{%
  \smallskip\par\noindent
  \fbox{\begin{varwidth}{\linewidth}
    #1%
  \end{varwidth}}%
  \smallskip
}
\def\CMD#1{\texttt{\null#1\unskip}}

\usepackage{xparse}
\NewDocumentCommand \otf {somm} {%
  \IfBooleanTF #1
  {%
    \gdef\NOTE{\par\smallskip {$\ast$ \footnotesize This feature is activated by default.}}%
    \IfNoValueTF {#2} {\gdef\offname{No#3}}{\gdef\offname{#2}}%
    \featname&#3&$\ast$&\texttt{#4}\\
    \featname&\offname&&\texttt{#4}~~{\footnotesize(\textit{deactivate})}\\
  }
  {\featname&#3&&\texttt{#4}\\}%
}
\newenvironment{features}[1]{%
  \def\NOTE{}
  \def\thisfeatname{#1}%
  \def\featname{\thisfeatname~~\texttt=~~\null\gdef\featname{}}%
  \begin{table}
    \caption{Options for the OpenType font feature `\thisfeatname'.}
    \edef\@tempa{\noexpand\label{feat:\thisfeatname}}\@tempa
    \centering
    \begin{tabular}{@{}l@{}l@{\hspace{0.5\tabcolsep}}l@{\hspace{0.5\tabcolsep}}l@{}}
    \toprule
    Feature & Option && Tag \\
    \midrule
}{
    \bottomrule
    \end{tabular}
    \NOTE
  \end{table}
}

%%%%%%%%%%%

\def \MakePrivateLetters {%
  \catcode `\@ = 11
  \catcode `\_ = 11
  \catcode `\: = 11
}

%% for LaTeX3 csnames
\catcode `\_= 11

\renewcommand\partname{Part}

\makeatother


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\EnableCrossrefs
\CodelineIndex
\RecordChanges
%\OnlyDescription
\begin{document}

\GetFileInfo{fontspec.dtx}
\errorcontextlines=999                ^^A% Show up all my mistakes

\title{The \textsf{fontspec} package\\Font selection for \XeLaTeX\ and \LuaLaTeX}
\author{
   \textsc{Will Robertson} and \textsc{Khaled Hosny}\\
   \texttt{will.robertson@latex-project.org}
}
\date{\filedate \qquad \fileversion}

\maketitle

\tableofcontents

\newpage

\part{Getting started}

\section{History}

This package began life as a \LaTeX\ interface to select system-installed
\MacOSX\ fonts in \name{Jonathan Kew}'s \XeTeX, the first widely-used
Unicode extension to \TeX. Over time, \XeTeX\ was extended to support OpenType
fonts and then was ported into a cross-platform program to run also on Windows
and Linux.

More recently, \LuaTeX\ is fast becoming the \TeX\ engine of the day; it
supports Unicode encodings and OpenType fonts and opens up the internals of
\TeX\ via the Lua programming language. Hans Hagen's Con\TeX t Mk.\,IV is a
re-write of his powerful typesetting system, taking full advantage of
\LuaTeX's features including font support; a kernel of his work in this area
has been extracted to be useful for other \TeX\ macro systems as well, and
this has enabled \pkg{fontspec} to be adapted for \LaTeX\ when run with the
\LuaTeX\ engine.

\section{Introduction}

The \pkg{fontspec} package allows users of either \XeTeX\ or \LuaTeX\ to
load OpenType fonts in a \LaTeX\ document. No font installation is necessary,
and font features can be selected and used as desired throughout the document.

Without \pkg{fontspec}, it is necessary to write cumbersome font definition
files for \LaTeX, since \LaTeX's font selection scheme (known as the
`\textsc{nfss}') has a lot going on behind the scenes to allow easy
commands like \cmd\emph\ or \cmd\bfseries. With an uncountable number of
fonts now available for use, however, it becomes less desirable to have to
write these font definition (|.fd|) files for every font one wishes to use.

Because \pkg{fontspec} is designed to work in a variety of modes, this
user documentation is split into separate sections that are designed to be
relatively independent. Nonetheless, the basic functionality all behaves in
the same way, so previous users of \pkg{fontspec} under \XeTeX\ should have
little or no difficulty switching over to \LuaTeX.

This manual can get rather in-depth, as there are a lot of details
to cover. See the documents \path{fontspec-example.tex} for a complete minimal example
to get started quickly.


\subsection{Acknowledgements}

This package could not have been possible without the early and continued support
the author of \XeTeX, Jonathan Kew. When I started this package, he steered
me many times in the right direction.

I've had great
feedback over the years on feature requests, documentation queries, bug reports, font suggestions, and so on from lots of people all around the world.
Many thanks to you all.

Thanks to David Perry and Markus B\"ohning for numerous documentation
improvements and David Perry again for contributing the text for one of the
sections of this manual.

Special thanks to Khaled Hosny, who was the driving force behind the support for \LuaLaTeX, ultimately leading to version 2.0 of the package.

\section{Package loading and options}

For basic use, no package options are required:
\begin{Verbatim}
  \usepackage{fontspec}
\end{Verbatim}
Package options will be introduced below; some preliminary details are discussed first.

\paragraph{Font encodings}
\null\marginpar{\null\hfill\fbox{\color{red}\textsc{update}!}}%
The 2016 release of \pkg{fontspec} initiates some changes for font encodings and the loading of \pkg{xunicode}.

A new package option, \texttt{tuenc}, which is selected by default, switches the \textsc{nfss} font encoding to \texttt{TU}.
\texttt{TU} is a new Unicode font encoding, intended for both \XeTeX\ and \LuaTeX\ engines, and automatically contains support for symbols covered by \LaTeX's traditional \texttt{T1} and \texttt{TS1} font encodings (for example, |\%|, |\textbullet|, |\"u|, and so on).
As a result, with this package option, Ross Moore's \pkg{xunicode} package is \textbf{not} loaded.

The old behaviour can be achieved by loading the \texttt{euenc} package option. This selects the \texttt{EU1} or \texttt{EU2} encoding (\XeTeX/\LuaTeX, resp.) and loads the \pkg{xunicode} package.
Package authors and users who have referred explicitly to the encoding names \texttt{EU1} or \texttt{EU2} should update their code or documents.
(See internal variable names described in \vref{sec:api} for how to do this properly.)

\emph{While \pkg{fontspec} is providing the \texttt{TU} encoding, its interface should be considered \textsc{experimental}; feedback welcome. Once \texttt{TU} is incorporated into the \LaTeXe\ kernel directly (later in 2016), it will be considered stable.}


\paragraph{\LuaTeX\ users only}
In order to load fonts by their name rather than by their filename (\eg,
`Latin Modern Roman' instead of `ec-lmr10'), you may need to run the script
\texttt{luaotfload-tool}, which is distributed with the \pkg{luaotfload}
package. Note that if you do not execute this script beforehand, the first
time you attempt to typeset the process will pause for (up to) several
minutes. (But only the first time.)
Please see the \pkg{luaotfload} documentation for more information.


\paragraph{\pkg{babel}}
\emph{The \pkg{babel} package is only supported for certain languages.}
Especially Vietnamese, Greek, and Hebrew at least might not work correctly, as far as I can tell.
There's a better chance with Cyrillic and Latin-based languages, however---\pkg{fontspec} ensures at least that fonts should load correctly.
The \pkg{polyglossia} package is recommended instead as a modern replacement for \pkg{babel}.



\subsection{Maths fonts adjustments}
By default, \pkg{fontspec} adjusts \LaTeX's default maths setup in order to maintain the correct Computer Modern symbols when the roman font changes.
However, it will attempt to avoid doing this if another maths font package is loaded (such as \pkg{mathpazo} or the \pkg{unicode-math} package).

If you find that \pkg{fontspec} is incorrectly changing the maths font when it shouldn't be, apply the |no-math| package option to manually suppress its selection of the maths fonts.

\subsection{Configuration}
\label{sec:config}

If you wish to customise any part of the
\pkg{fontspec} interface, this should be done by creating your own
\texttt{fontspec.cfg} file,
which will be automatically loaded if it is found by \XeTeX\ or \LuaTeX.
A |fontspec.cfg| file is distributed with \pkg{fontspec} with a small number of defaults set up within it.

To customise \pkg{fontspec} to your liking, use the standard |.cfg| file as a starting point or write your own from scratch, then either place it in the same folder as the main document for isolated cases, or in a location
that \XeTeX\ or \LuaTeX\ searches by default; \eg\ in Mac\TeX: \path{~/Library/texmf/tex/latex/}.

The package option |no-config| will suppress the loading of the |fontspec.cfg| file under all circumstances.

\subsection{Warnings}
\label{sec:quiet-warnings}

This package can give some warnings that can be harmless if you know what
you're doing. Use the |quiet| package option to write these warnings to the
transcript (\texttt{.log}) file instead.

Use the |silent| package option to completely suppress these warnings if you
don't even want the |.log| file cluttered up.





\part{General font selection}

This section concerns the variety of commands that can be used to select
fonts.

\cmdbox{%
  \CMD{\string\fontspec}\marg{font name}\oarg{font features}\\
  \CMD{\string\setmainfont}\marg{font name}\oarg{font features}\\
  \CMD{\string\setsansfont}\marg{font name}\oarg{font features}\\
  \CMD{\string\setmonofont}\marg{font name}\oarg{font features}\\
  \CMD{\string\newfontfamily}\meta{cmd}\marg{font name}\oarg{font features}
}

These are the main font-selecting commands of this package.
The \cs{fontspec} command selects a font for one-time use; all
others should be used to define the standard fonts used in a document, as shown in \exref{fontload}.
Here, the scales of the fonts have been chosen to equalise their
lowercase letter heights. The \feat{Scale} font feature will be discussed
further in \vref{sec:font-ind-features}, including methods for automatic
scaling.

\begin{Lexample}{fontload}{Loading the default, sans serif, and monospaced fonts.}
  \setmainfont{texgyrebonum-regular.otf}
  \setsansfont{lmsans10-regular.otf}[Scale=MatchLowercase]
  \setmonofont{Inconsolata.otf}[Scale=MatchLowercase]

  \rmfamily Pack my box with five dozen liquor jugs\par
  \sffamily Pack my box with five dozen liquor jugs\par
  \ttfamily Pack my box with five dozen liquor jugs
\end{Lexample}

The font features argument accepts comma separated
\meta{font feature}=\meta{option} lists; these are described in later:
\begin{itemize}
\item For general font features, see \vref{sec:font-ind-features}
\item For OpenType fonts, see Part~\vref{sec:opentype-features}
\item For \XeTeX-only general font features, see Part~\vref{sec:xetex-features}
\item For \LuaTeX-only general font features, see Part~\vref{sec:luatex-features}
\item For features for \AAT\ fonts in \XeTeX, see \vref{sec:aat-features}
\end{itemize}

\section{Font selection}

In both \LuaTeX\ and \XeTeX, fonts can be selected either by `font name' or
by `file name', but there are some differences in how each engine finds and selects fonts --- don't be too surprised if a font invocation in one engine needs correction to work in the other.

\subsection{By font name}

Fonts known to \LuaTeX\ or \XeTeX\ may be loaded by their standard names as
you'd speak them out loud, such as \emph{Times New Roman} or
\emph{Adobe Garamond}.
`Known to' in this case generally means `exists in a standard fonts location'
such as |~/Library/Fonts| on \MacOSX, or |C:\Windows\Fonts| on Windows.
In \LuaTeX, fonts found in the \textsc{texmf} tree can also be loaded by name.

The simplest example might be something like
\begin{Verbatim}
  \setmainfont{Cambria}[ ... ]
\end{Verbatim}
in which the bold and italic fonts will be found automatically
(if they exist) and are immediately accessible with the usual
\cs{textit} and \cs{textbf} commands.

The `font name' can be found in various ways, such as by looking in the name listed in a application like \emph{Font Book} on Mac~OS~X.
Alternatively, \TeX{}Live contains the \texttt{otfinfo} command line program, which can query this information; for example:
\begin{Verbatim}
    otfinfo -a `kpsewhich lmroman10-regular.otf`
\end{Verbatim}
results in `\texttt{LM Roman 10}'.

\subsection{By file name}
\label{sec:by-file-name}

\XeTeX\ and \LuaTeX\ also allow fonts to be loaded by file name instead of font name.
When you have a very large collection of fonts, you will sometimes not
wish to have them all installed in your system's font directories.
In this case, it is more convenient to load them from a different location on your disk.
This technique is also necessary in \XeTeX\ when loading OpenType fonts that are present within your \TeX\ distribution, such as \path{/usr/local/texlive/2013/texmf-dist/fonts/opentype/public}.
Fonts in such locations are visible to \XeTeX\ but cannot be loaded by font name, only file name; \LuaTeX\ does not have this restriction.

When selecting fonts by file name, any font that can be found in the default
search paths may be used directly (including in the current directory)
without having to explicitly define the location of the font file on disk.

Fonts selected by filename must include bold and italic variants explicitly.
\begin{Verbatim}
  \setmainfont{texgyrepagella-regular.otf}[
       BoldFont       = texgyrepagella-bold.otf ,
       ItalicFont     = texgyrepagella-italic.otf ,
       BoldItalicFont = texgyrepagella-bolditalic.otf ]
\end{Verbatim}
\pkg{fontspec} knows that the font is to be selected by file name by the
presence of the `|.otf|' extension.
An alternative is to specify the extension separately, as shown following:
\begin{Verbatim}
  \setmainfont{texgyrepagella-regular}[
       Extension      = .otf ,
       BoldFont       = texgyrepagella-bold ,
       ... ]
\end{Verbatim}
If desired, an abbreviation can be applied to the font names based on the
mandatory `font name' argument:
\begin{Verbatim}
  \setmainfont{texgyrepagella}[
       Extension      = .otf ,
       UprightFont    = *-regular ,
       BoldFont       = *-bold ,
       ... ]
\end{Verbatim}
In this case `texgyrepagella' is no longer the name of an actual font,
but is used to construct the font names for each shape;
the |*| is replaced by `texgyrepagella'.
Note in this case that |UprightFont| is required for constructing the font
name of the normal font to use.

To load a font that is not in one of the default search paths, its location
in the filesystem must be specified with the |Path| feature:
\begin{Verbatim}
  \setmainfont{texgyrepagella}[
       Path           = /Users/will/Fonts/ ,
       UprightFont    = *-regular ,
       BoldFont       = *-bold ,
       ... ]
\end{Verbatim}
Note that \XeTeX\ and \LuaTeX\ are able to load the font without giving an
extension, but \pkg{fontspec} must know to search for the file; this can can
be indicated by using the |Path| option without an argument:
\begin{Verbatim}
  \setmainfont{texgyrepagella-regular}[
       Path, BoldFont = texgyrepagella-bold,
       ... ]
\end{Verbatim}
In previous versions of the package, the alias |ExternalLocation| was documented for this purpose, but this is now deprecated and may be removed in the future.






\section{Commands to select font families}

\cmdbox{
  \CMD{\string\newfontfamily}\cs{\meta{font-switch}}\marg{font name}\oarg{font features} \\
  \CMD{\string\newfontface}\cs{\meta{font-switch}}\marg{font name}\oarg{font features}
}

\noindent For cases when a specific font with a specific
feature set is going to be re-used many times in a document, it is inefficient
to keep calling \cs{fontspec} for every use. While the \cs{fontspec} command does not define
a new font instance after the first call, the feature options must still be
parsed and processed.

\DescribeMacro{\newfontfamily}
For this reason, new commands can be created for loading a particular font
family with the \cmd\newfontfamily\ command, demonstrated in \exref{nff}.
This macro should be used to create commands that would be used in
the same way as \cmd\rmfamily, for example.
If you would like to create a command that only changes the font
inside its argument (i.e., the same behaviour as \cs{emph}) define it using regular \LaTeX\
commands:
\begin{Verbatim}
  \newcommand\textnote[1]{{\notefont #1}}
  \textnote{This is a note.}
\end{Verbatim}
Note that the double braces are intentional; the inner pair are used to
to delimit the scope of the font change.

\begin{Lexample}{nff}{Defining new font families.}
  \newfontfamily\notefont{Kurier}
  \notefont This is a \emph{note}.
\end{Lexample}

\DescribeMacro{\newfontface}
Sometimes only a specific font face is desired, without accompanying italic or bold variants
being automatically selected.
This is common when selecting a fancy italic font, say, that has swash features unavailable
in the upright forms. \cmd\newfontface\ is used for this purpose, shown
in \exref{nfface}, which is repeated in \vref{sec:contextuals}.

\begin{Xexample}{nfface}{Defining a single font face.}
  \newfontface\fancy{Hoefler Text Italic}%
      [Contextuals={WordInitial,WordFinal}]
  \fancy where is all the vegemite
  % \emph, \textbf, etc., all don't work
\end{Xexample}

Comment for advanced users:
The commands defined by \cs{newfontface} and \cs{newfontfamily} include
their encoding information, so even if the document is set to use a
legacy \TeX\ encoding, such commands will still work correctly. For example,
\begin{Verbatim}
\documentclass{article}
\usepackage{fontspec}
\newfontfamily\unicodefont{Lucida Grande}
\usepackage{mathpazo}
\usepackage[T1]{fontenc}
\begin{document}
A legacy \TeX\ font. {\unicodefont A unicode font.}
\end{document}
\end{Verbatim}

\subsection{More control over font shape selection}
\label{sec:bfitfonts}

\cmdbox{
 \feat{BoldFont} = \meta{font name} \\
 \feat{ItalicFont} = \meta{font name} \\
 \feat{~BoldItalicFont} = \meta{font name} \\
 \feat{SlantedFont} = \meta{font name} \\
 \feat{BoldSlantedFont} = \meta{font name} \\
 \feat{SmallCapsFont} = \meta{font name}
}

The automatic bold, italic, and bold italic font selections will not be
adequate for the needs of every font: while some fonts mayn't even
have bold or italic shapes, in which case a skilled (or lucky)
designer may be able to chose well-matching accompanying shapes from
a different font altogether, others can have a range of bold and
italic fonts to chose among.  The \feat{BoldFont} and
\feat{ItalicFont} features are provided for these situations. If only
one of these is used, the bold italic font is requested as the
default from the \emph{new} font. See \exref{bff}.

\begin{Xexample}{bff}{Explicit selection of the bold font.}
  \fontspec{Helvetica Neue UltraLight}%
           [BoldFont={Helvetica Neue}]
                Helvetica Neue UltraLight         \\
  {\itshape     Helvetica Neue UltraLight Italic} \\
  {\bfseries               Helvetica Neue       } \\
  {\bfseries\itshape       Helvetica Neue Italic} \\
\end{Xexample}

If a bold italic shape is not defined, or you want to specify
\emph{both} custom bold and italic shapes, the \feat{BoldItalicFont}
feature is provided.



\subsubsection{Small caps and slanted font shapes}

When a font family has both slanted \emph{and} italic shapes, these may be specified separately using the analogous features \feat{SlantedFont} and \feat{BoldSlantedFont}.
Without these, however, the \LaTeX\ font switches for slanted (\cs{textsl}, \cs{slshape}) will default to the italic shape.

Pre-OpenType, it was common for font families to be distributed with small caps glyphs in separate fonts, due to the limitations on the number of glyphs allowed in the PostScript Type~1 format.
Such fonts may be used by declaring the \feat{SmallCapsFont} of the family you are specifying:
\begin{Verbatim}
  \setmainfont{Minion MM Roman}[
    SmallCapsFont={Minion MM Small Caps & Oldstyle Figures}
  ]
  Roman 123 \\ \textsc{Small caps 456}
\end{Verbatim}
In fact, you should specify the small caps font for each individual bold and
italic shape as in
\begin{Verbatim}
  \setmainfont{ <upright> }[
    UprightFeatures    = { SmallCapsFont={ <sc> } } ,
    BoldFeatures       = { SmallCapsFont={ <bf sc> } } ,
    ItalicFeatures     = { SmallCapsFont={ <it sc> } } ,
    BoldItalicFeatures = { SmallCapsFont={ <bf it sc> } } ,
  ]
  Roman 123 \\ \textsc{Small caps 456}
\end{Verbatim}
For most modern fonts that have small caps as a font feature, this level of
control isn't generally necessary.

All of the bold, italic, and small caps fonts can be loaded with different
font features from the main font. See \ref{sec:bfit-feat} for details.
When an OpenType font is selected for |SmallCapsFont|, the small caps
font feature is \emph{not} automatically enabled. In this case, users
should write instead, if necessary,
\begin{Verbatim}
  \setmainfont{...}[
    SmallCapsFont={...},
    SmallCapsFeatures={Letters=SmallCaps},
  ]
\end{Verbatim}

\subsection{Specifically choosing the \NFSS\ family}

In \LaTeX's \NFSS, font families are defined with names such as `\texttt{ppl}' (Palatino), `\texttt{lmr}' (Latin Modern Roman), and so on, which are selected with the \cs{fontfamily} command:
\begin{Verbatim}
  \fontfamily{ppl}\selectfont
\end{Verbatim}
In \pkg{fontspec}, the family names are auto-generated based on the fontname of the font; for example, writing |\fontspec{Times New Roman}| for the first time would generate an internal font family name of `\texttt{TimesNewRoman(1)}'.
Please note that should not rely on the name that is generated.

In certain cases it is desirable to be able to choose this internal font family name so it can be re-used elsewhere for interacting with other packages that use the \LaTeX's font selection interface; an example might be
\begin{Verbatim}
  \usepackage{fancyvrb}
  \fvset{fontfamily=myverbatimfont}
\end{Verbatim}
To select a font for use in this way in \pkg{fontspec} use the \feat{NFSSFamily} feature:\footnote{Thanks to Luca Fascione for the example and motivation for finally implementing this feature.}
\begin{Verbatim}
  \newfontfamily\verbatimfont[NFSSFamily=myverbatimfont]{Inconsolata}
\end{Verbatim}
It is then possible to write commands such as:
\begin{Verbatim}
  \fontfamily{myverbatimfont}\selectfont
\end{Verbatim}
which is essentially the same as writing |\verbatimfont|, or to go back to the orginal example:
\begin{Verbatim}
  \fvset{fontfamily=myverbatimfont}
\end{Verbatim}
Only use this feature when necessary; the in-built font switching commands that \pkg{fontspec} generates (such as |\verbatimfont| in the example above) are recommended in all other cases.

If you don't wish to explicitly set the \NFSS\ family but you would like to know what it is, an alternative mechanism for package writers is introduced as part of the \pkg{fontspec} programming interface; see the function \cs{fontspec_set_family:Nnn} for details (\vref*{sec:api}).

\subsection{Choosing additional \NFSS\ font faces}

\LaTeX's font selection scheme (\NFSS) is more flexible than the \pkg{fontspec} interface discussed up until this point.
It assigns to each font face a \emph{family} (discussed above), a \emph{series} such as bold or light or condensed, and a \emph{shape} such as italic or slanted or small caps.
The \pkg{fontspec} features such as \feat{BoldFont} and so on all assign faces for the default series and shapes of the \NFSS, but it's not uncommon to have font families that have multiple weights and shapes and so on.

If you set up a regular font family with the `standard four' (upright, bold, italic, and bold italic) shapes and then want to use, say, a light font for a certain document element, many users will be perfectly happy to use \cs{newfontface}\cs{\meta{switch}} and use the resulting font \cs{\meta{switch}}.
In other cases, however, it is more convenient or even necessary to load additional fonts using additional \NFSS\ specifiers.

\cmdbox{
  \texttt{FontFace = }\marg{series}\marg{shape}
     \texttt{\char`\{} \texttt{Font = }\meta{font name} \texttt, \meta{features} \texttt{\char`\}} \\
  \texttt{FontFace = }\marg{series}\marg{shape}\marg{font name}
}

The font thus specified will inherit the font features of the main font, with optional additional \meta{features} as requested.
(Note that the optional \marg{features} argument is still surrounded with curly braces.)
Multiple \feat{FontFace} commands may be used in a single declaration to specify multiple fonts.
As an example:
\begin{Verbatim}
  \setmainfont{font1.otf}[
     FontFace = {c}{\updefault}{ font2.otf } ,
     FontFace = {c}{m}{ Font = font3.otf , Color = red }
    ]
\end{Verbatim}
Writing |\fontseries{c}\selectfont| will result in |font2| being selected, which then followed by |\fontshape{m}\selectfont| will result in |font3| being selected (in red).
A font face that is defined in terms of a different series but an upright shape (|\updefault|, as shown above) will attempt to find a matching small caps feature and define that face as well.
Conversely, a font face defined in terms of a non-standard font shape will not.

There are some standards for choosing shape and series codes; the \LaTeXe\ font selection guide\footnote{\texttt{texdoc fntguide}} lists series |m| for medium, |b| for bold, |bx| for bold extended, |sb| for semi-bold, and |c| for condensed.
A far more comprehensive listing is included in Appendix~A of Philipp Lehman's `The Font Installation Guide'\footnote{\texttt{texdoc fontinstallationguide}} covering 14 separate weights and 12 separate widths.

The \feat{FontFace} command also interacts properly with the \feat{SizeFeatures} command as follows: (nonsense set of font selection choices)
\begin{Verbatim}
  FontFace = {c}{n}{
    Font = Times ,
    SizeFeatures = {
      { Size =   -10 , Font = Georgia } ,
      { Size = 10-15}                 , % default "Font = Times"
      { Size = 15-   , Font = Cochin  } ,
    },
  },
\end{Verbatim}
Note that if the first \feat{Font} feature is omitted then each size needs its own inner \feat{Font} declaration.

\subsection{Math(s) fonts}

When \cmd\setmainfont, \cmd\setsansfont\ and \cmd\setmonofont\ are used in the
preamble, they also define the fonts to be used in maths mode inside the
\cmd\mathrm-type commands. This only occurs in the preamble because \LaTeX\
freezes the maths fonts after this stage of the processing. The \pkg{fontspec}
package must also be loaded after any maths font packages (\eg, \pkg{euler})
to be successful. (Actually, it is \emph{only} \pkg{euler} that is the
problem.\note{Speaking of \pkg{euler}, if you want to use its
\texttt{[mathbf]} option, it won't work, and you'll need to put this after
\pkg{fontspec} is loaded instead:
\ttfamily\cmd\AtBeginDocument\char`\{\cmd\DeclareMathAlphabet\cmd\mathbf\char`\{U\char`\}\char`\{eur\char`\}\char`\{b\char`\}\char`\{n\char`\}})

Note that \pkg{fontspec} will not change the font for general mathematics;
only the upright and bold shapes will be affected.
To change the font used for the mathematical symbols, see either the
\pkg{mathspec} package or the \pkg{unicode-math} package.

Note that you may find that loading some maths packages won't be as smooth as
you expect since \pkg{fontspec} (and \XeTeX\ in general) breaks many of the
assumptions of \TeX\ as to where maths characters and accents can be found.
Contact me if you have troubles, but I can't guarantee to be able to fix any
incompatibilities. The Lucida and Euler maths fonts should be fine; for all
others keep an eye out for problems.

\cmdbox{
  \cmd{\setmathrm}\marg{font name}\oarg{font features} \\
  \cmd{\setmathsf}\marg{font name}\oarg{font features} \\
  \cmd{\setmathtt}\marg{font name}\oarg{font features} \\
  \cmd{\setboldmathrm}\marg{font name}\oarg{font features}
}

However, the default text fonts may not necessarily be the ones you
wish to use when typesetting maths (especially with the use of fancy
ligatures and so on). For this reason, you may optionally use the
commands above (in the same way as our other
\cmd\fontspec-like commands) to explicitly state which fonts to use
inside such commands as \cmd\mathrm. Additionally, the
\cmd\setboldmathrm\ command allows you define the font used for
\cmd\mathrm\ when in bold maths mode (which is activated with, among
others, \cmd\boldmath).

For example, if you were using Optima with the Euler maths font, you
might have this in your preamble:
\begin{Verbatim}
  \usepackage{mathpazo}
  \usepackage{fontspec}
  \setmainfont{Optima}
  \setmathrm{Optima}
  \setboldmathrm[BoldFont={Optima ExtraBlack}]{Optima Bold}
\end{Verbatim}
These commands are compatible with the \pkg{unicode-math} package.
Having said that, \pkg{unicode-math} also defines a more general way of defining fonts to use in maths mode, so you can ignore this subsection if you're already using that package.


\section{Miscellaneous font selecting details}

\paragraph{The optional argument --- from v2.4}
For the first decade of \pkg{fontspec}'s life, optional font features were selected with a bracketed argument before the font name, as in:
\begin{Verbatim}
  \setmainfont[
    lots and lots ,
    and more and more ,
    an excessive number really ,
    of font features could go here
  ]{myfont.otf}
\end{Verbatim}
This always looked like ugly syntax to me, because the most important detail --- the name of the font --- was tucked away at the end.
The order of these arguments has now been reversed:
\begin{Verbatim}
  \setmainfont{myfont.otf}[
    lots and lots ,
    and more and more ,
    an excessive number really ,
    of font features could go here
  ]
\end{Verbatim}
I hope this doesn't cause any problems.
\begin{enumerate}
 \item Backwards compatibility has been preserved, so either input method works. (In fact, in the next version of \pkg{fontspec} you will be able to write
 \begin{Verbatim}
  \fontspec[Ligatures=Rare]{myfont.otf}[Color=red]
 \end{Verbatim}
 if you really felt like it and both sets of features would be applied.)

 \item
 Following standard \pkg{xparse} behaviour, there must be no space before the opening bracket; writing
 \begin{Verbatim*}
\fontspec{myfont.otf} [Color=red]
 \end{Verbatim*}
 will result in |[Color=red]| not being recognised an argument and therefore it will be typeset as text. When breaking over lines, write either of:
 \begin{Verbatim}
   \fontspec{myfont.otf}%        \fontspec{myfont.otf}[
     [Color=red]                    Color=Red]
 \end{Verbatim}

\end{enumerate}

\paragraph{Spaces}
\cmd\fontspec\ and \cmd\addfontfeatures\ ignore trailing spaces as
if it were a `naked' control sequence; \eg, `|M. \fontspec{...} N|' and
`|M. \fontspec{...}N|' are the same.

\paragraph{Italic small caps}
Note that this package redefines the \cs{itshape}, \cs{slshape}, and \cs{scshape} commands in order to allow them to select italic small caps in conjunction.
With these changes, writing |\itshape\scshape| will lead to italic small caps, and |\upshape| subsequently then moves back to small caps only. |\upshape| again returns from small caps to upright regular.
(And similarly for for |\slshape|. In addition, once italic small caps are selected then |\slshape| will switch to slanted small caps, and vice versa.)

\paragraph{Emphasis and nested emphasis}
\LaTeXe\ allows you to specify the behaviour of \cs{emph} nested within \cs{emph} by setting the \cs{eminnershape} command.
For example, |\renewcommand\eminnershape{\upshape\scshape}| will produce small caps within |\emph{\emph{...}}|.

The \pkg{fontspec} package takes this idea one step further to allow arbitrary font changes (e.g., boldness) and arbitrary levels of nesting within emphasis.
This is performed using the |\emfontdeclare| command, which takes a comma-separated list of font switches corresponding to increasing levels of emphasis.
Two examples:
\begin{enumerate}
\item |\emfontdeclare{\itshape,\upshape\scshape,\itshape}| will lead to `italics', `small caps', then `italic small caps' as the level of emphasis increases, as long as italic small caps are defined for the font.
  Note that |\upshape| is required because the font changes are cascading.
\item |\emfontdeclare{\bfseries,\fontseries{h}\selectfont,\fontseries{x}\selectfont}| could lead to (if fonts are set up correctly) `bold', `heavy', and `extra bold'.
\end{enumerate}




\section{Selecting font features}
\label{sec:selectingfeature}

The commands discussed so far such as \cs{fontspec} each take an optional argument for
accessing the font features of the requested font.
Commands are provided to set default features to be applied for all fonts, and even to change the features that a font is presently loaded with.
Different font shapes can be loaded with separate features, and different features can even be selected for different sizes that the font appears in.
This section discusses these options.

\subsection{Default settings} \label{sec:defaults}

\cmdbox{\cmd\defaultfontfeatures\marg{font features}}

It is sometimes useful to define
font features that are applied to every subsequent font selection command.
This may be defined with the
\cmd{\defaultfontfeatures} command, shown in \exref{dff}.
New calls of \cs{defaultfontfeatures} overwrite previous ones, and defaults can be reset by calling the command with an empty argument.

\begin{Xexample}{dff}{A demonstration of the \cs{defaultfontfeatures} command.}
  \fontspec{texgyreadventor-regular.otf}
  Some default text 0123456789 \\
  \defaultfontfeatures{
     Numbers=OldStyle, Color=888888
  }
  \fontspec{texgyreadventor-regular.otf}
  Now grey, with old-style figures:
  0123456789
\end{Xexample}

\cmdbox{\cmd\defaultfontfeatures\oarg{font name}\marg{font features}}

Default font features can be specified on a per-font and per-face basis
by using the optional argument to \cs{defaultfontfeatures} as shown.\footnote{Internally, \meta{font name} has all spaces removed and is converted to lowercase.}
\begin{Verbatim}
  \defaultfontfeatures[texgyreadventor-regular.otf]{Color=blue}
  \setmainfont{texgyreadventor-regular.otf}% will be blue
\end{Verbatim}
Multiple fonts may be affected by using a comma separated list of font names.

\cmdbox{\cmd\defaultfontfeatures\oarg{\cs{font-switch}}\marg{font features}}

\textbf{New in v2.4}.
Defaults can also be applied to symbolic families such as those created with the |\newfontfamily| command and for |\rmfamily|, |\sffamily|, and |\ttfamily|:
\begin{Verbatim}
  \defaultfontfeatures[\rmfamily,\sffamily]{Ligatures=TeX}
  \setmainfont{texgyreadventor-regular.otf}% will use standard TeX ligatures
\end{Verbatim}
The line above to set \TeX-like ligatures is now activated by \emph{default} in \texttt{fontspec.cfg}.
To reset default font features, simply call the command with an empty argument:
\begin{Verbatim}
  \defaultfontfeatures[\rmfamily,\sffamily]{}
  \setmainfont{texgyreadventor-regular.otf}% will no longer use standard TeX ligatures
\end{Verbatim}

\cmdbox{\cmd\defaultfontfeatures\texttt{+}\marg{font features}\\
        \cmd\defaultfontfeatures\texttt{+}\oarg{font name}\marg{font features}}

\textbf{New in v2.4}.
Using the |+| form of the command appends the \meta{font features} to any already-selected defaults.


\subsection{Default settings from a file}

In addition to the defaults that may be specified in the document as described above, when a font is first loaded, a configuration file is searched
for with the name `\meta{fontname}\texttt{.fontspec}'.\footnote{Located in the current folder or within a standard \texttt{texmf} location.}

The contents of this file can be used to specify default font features without
having to have this information present within each document.
\meta{fontname} is stripped of spaces and file extensions are omitted; for
example, the line above for \TeX\ Gyre Adventor could be placed in a file
called \texttt{TeXGyreAdventor.fontspec}, or for specifying options for
\texttt{texgyreadventor-regular.otf} (when loading by filename), the configuration
file would be \texttt{texgyreadventor-regular.fontspec}.
(N.B. the lettercase of the names should match.)

This mechanism can be used to define custom names or aliases for your font collections.
If you create a file \texttt{MyCharis.fontspec} containing, say,
\begin{Verbatim}
  \defaultfontfeatures[My Charis]
   {
    Extension = .ttf ,
    UprightFont = CharisSILR,
    BoldFont = CharisSILB,
    ItalicFont = CharisSILI,
    BoldItalicFont = CharisSILBI,
    % <any other desired options>
   }
\end{Verbatim}
you can load that custom family with \verb|\fontspec{My Charis}| and similar.
The optional argument to \cs{defaultfontfeatures} must match that requested by the font loading command (\verb|\fontspec|, etc.), else the options won't take effect.

Finally, note that options for font faces can also be defined in this way.
To continue the example above, here we colour the different faces:
\begin{Verbatim}
  \defaultfontfeatures[CharisSILR]{Color=blue}
  \defaultfontfeatures[CharisSILB]{Color=red}
\end{Verbatim}
And such configuration lines can be stored either inline inside \texttt{My Charis.fontspec} or within their own \texttt{.fontspec} files; in this way, \pkg{fontspec} is designed to handle `nested' configuration options as well.

\subsection{Changing the currently selected features}
\label{sec:addfontfeatures}

\cmdbox{\cmd\addfontfeatures\marg{font features}}

This command allows font features to
be changed without knowing what features are currently selected or even what
font is being used. A good example of this could be to add a hook to all
tabular material to use monospaced numbers, as shown in \exref{aff}.
Note however that the behaviour in this regard will be unreliable (subject to the font itself) if you attempt to \emph{change} an already selected feature.
\Eg, this sort of thing can cause troubles:
\begin{Verbatim}
\addfontfeature{Numbers=OldStyle}...
\addfontfeature{Numbers=Lining}...
123
\end{Verbatim}
With both features active, how will the font render `123'? Depends on the font.
In the distant future this functionality will be re-written to avoid this issue (giving `\verb|Numbers=OldStyle|' the smarts to know to explicitly de-activate any previous instances of `\verb|Numbers=Lining|', and vice-versa, but as I hope you can imagine this requires a fair degree of elbow grease which I haven't had available for some time now.

\begin{Lexample}{aff}{A demonstration of the \cs{addfontfeatures} command. Note the caveat listed in the text regarding such usage.}
  \fontspec{texgyreadventor-regular.otf}%
           [Numbers={Proportional,OldStyle}]
  `In 1842, 999 people sailed 97 miles in
   13 boats. In 1923, 111 people sailed 54
   miles in 56 boats.'            \bigskip

  {\addfontfeatures{Numbers={Monospaced,Lining}}
  \begin{tabular}{@{} cccc @{}}
            Year & People & Miles & Boats \\
    \hline  1842 &  999   &  75   &  13   \\
            1923 &  111   &  54   &  56
  \end{tabular}}
\end{Lexample}

\DescribeMacro{\addfontfeature}
This command may also be executed under the alias \cmd{\addfontfeature}.

\subsection{Priority of feature selection}
Features defined with \cs{addfontfeatures} override features
specified by \cs{fontspec}, which in turn override features
specified by \cs{defaultfontfeatures}.  If in doubt, whenever a
new font is chosen for the first time, an entry is made in the
transcript (\texttt{.log}) file displaying the font name and the
features requested.

\subsection{Different features for different font shapes}
\label{sec:bfit-feat}

\cmdbox{
 \feat{BoldFeatures}\texttt=\marg{features} \\
 \feat{ItalicFeatures}\texttt=\marg{features} \\
 \feat{BoldItalicFeatures}\texttt=\marg{features} \\
 \feat{SlantedFeatures}\texttt=\marg{features} \\
 \feat{BoldSlantedFeatures}\texttt=\marg{features} \\
 \feat{SmallCapsFeatures}\texttt=\marg{features}
}

It is entirely possible that separate fonts in a family will require
separate options; \eg, Hoefler Text Italic contains various swash
feature options that are completely unavailable in the upright shapes.

The font features defined at the top level of the optional \cmd\fontspec\
argument are applied to \emph{all} shapes of the family.
Using \feat{Upright-}, \feat{SmallCaps-}, \feat{Bold-},
\feat{Italic-}, and \feat{BoldItalicFeatures},
separate font features may be defined to their respective shapes
\emph{in addition} to, and with precedence over, the `global' font features.
See \exref{itfeat}.

\begin{Xexample}{itfeat}{Features for, say, just italics.}
\fontspec{EBGaramond12-Regular.otf}%
  [ItalicFont=EBGaramond12-Italic.otf]
\itshape Don’t Ask Victoria! \\
\addfontfeature{ItalicFeatures={Style=Swash}}
Don’t Ask Victoria! \\
\end{Xexample}

Note that because most fonts include their small caps glyphs
within the main font, features specified with \feat{SmallCapsFeatures} are applied \emph{in addition} to
any other shape-specific features as defined above, and hence \feat{SmallCapsFeatures}
can be nested within \feat{ItalicFeatures} and friends. Every combination
of upright, italic, bold and small caps can thus be assigned individual
features, as shown in the somewhat ludicrous \exref{scfeat}.

\begin{Xexample}{scfeat}{An example of setting the \feat{SmallCapsFeatures}
separately for each font shape.}
  \fontspec{texgyretermes}[
      Extension = {.otf},
      UprightFont = {*-regular}, ItalicFont = {*-italic},
      BoldFont = {*-bold}, BoldItalicFont = {*-bolditalic},
      UprightFeatures={Color = 220022,
           SmallCapsFeatures = {Color=115511}},
       ItalicFeatures={Color = 2244FF,
           SmallCapsFeatures = {Color=112299}},
         BoldFeatures={Color = FF4422,
           SmallCapsFeatures = {Color=992211}},
   BoldItalicFeatures={Color = 888844,
           SmallCapsFeatures = {Color=444422}},
           ]
  Upright {\scshape Small Caps}\\
  \itshape Italic {\scshape Italic Small Caps}\\
  \upshape\bfseries Bold {\scshape Bold Small Caps}\\
  \itshape Bold Italic {\scshape Bold Italic Small Caps}
\end{Xexample}

\subsection{Different features for different font sizes}
\label{sec:sizefeature}

\cmdbox{
\ttfamily SizeFeatures = \char`\{\\
\null\quad...\\
\null\quad\char`\{~Size =
\rmfamily\meta{size range}\ttfamily
,
\rmfamily \meta{font features}\ttfamily
~\char`\} , \\
\null\quad\char`\{~Size =
\rmfamily\meta{size range}\ttfamily
, Font =
\rmfamily\meta{font name}\texttt, \meta{font features}\ttfamily
~\char`\} , \\
\null\quad... \\
\char`\}}

The \feat{SizeFeature} feature is a little more complicated
than the previous features discussed. It allows different fonts
and different font features to be selected for a given font
family as the point size varies.

It takes a comma separated list of braced, comma separated lists of features for each size range.
Each sub-list must contain the \opt{Size} option
to declare the size range, and optionally \opt{Font} to change the
font based on size. Other (regular) fontspec features that are added
are used on top of the font features that would be used anyway.
A demonstration to clarify these details is shown in \exref{sizefeat}.
A less trivial example is shown in the context of optical font sizes
in \vref{sec:opticalsize}.

\begin{Xexample}{sizefeat}{An example of specifying different font features for different sizes of font with \feat{SizeFeatures}.}
  \fontspec{texgyrechorus-mediumitalic.otf}[
    SizeFeatures={
      {Size={-8}, Font=texgyrebonum-italic.otf, Color=AA0000},
      {Size={8-14}, Color=00AA00},
      {Size={14-}, Color=0000AA}} ]

  {\scriptsize Small\par} Normal size\par {\Large Large\par}
\end{Xexample}

To be precise, the \opt{Size} sub-feature accepts arguments in the form shown in \vref{tab:sizing}.
Braces around the size range are optional. For an exact font size (|Size=X|)
font sizes chosen near that size will `snap'. For example, for size definitions
at exactly 11pt and 14pt, if a 12pt font is requested \emph{actually} the
11pt font will be selected. This is a remnant of the past when fonts were designed
in metal (at obviously rigid sizes) and later when bitmap fonts were similarly
designed for fixed sizes.

If additional features are only required for a single size, the other sizes
must still be specified.  As in:
\begin{Verbatim}
  SizeFeatures={
     {Size=-10,Numbers=Uppercase},
     {Size=10-}}
\end{Verbatim}
Otherwise, the font sizes greater than 10 won't be defined at all!

\begin{table}
\caption{Syntax for specifying the size to apply custom font features.}\label{tab:sizing}
\centering
\begin{tabular}{@{}ll@{}}
\toprule
Input & Font size, $s$ \\
\midrule
 |Size = X-| & $s \geq \texttt{X}$ \\
 |Size = -Y| & $s < \texttt{Y}$ \\
 |Size = X-Y| & $\texttt{X} \leq s < \texttt{Y}$ \\
 |Size = X| & $s = \texttt{X}$ \\
\bottomrule
\end{tabular}
\end{table}

\paragraph{Interaction with other features}
For \feat{SizeFeatures} to work with \feat{ItalicFeatures}, \feat{BoldFeatures}, etc., and \feat{SmallCapsFeatures}, a strict heirarchy is required:
\begin{Verbatim}
 UprightFeatures =
  {
   SizeFeatures =
    {
     {
      Size = -10,
      Font = ..., % if necessary
      SmallCapsFeatures = {...},
      ... % other features for this size range
     },
     ... % other size ranges
    }
  }
\end{Verbatim}
Suggestions on simplifying this interface welcome.


\section{Font independent options} \label{sec:font-ind-features}

Features introduced in this section may be used with any font.

\subsection{Colour}

\feat{Color} (or \feat{Colour}), also shown in \vref{sec:defaults}
and elsewhere, uses font specifications to set the colour of
the text. The colour is defined as a triplet of two-digit Hex RGB
values, with optionally another value for the transparency (where
|00| is completely transparent and |FF| is opaque.)
\begin{Lexample}{color}{Selecting colour with transparency. N.B. due to a conflict betweeen \pkg{fontspec} and the \pkg{preview} package, this example currently does not show any transparency!}
  \fontsize{48}{48}
  \fontspec{texgyrebonum-bold.otf}
  {\addfontfeature{Color=FF000099}W}\kern-0.5ex
  {\addfontfeature{Color=0000FF99}S}\kern-0.4ex
  {\addfontfeature{Color=DDBB2299}P}\kern-0.4ex
  {\addfontfeature{Color=00BB3399}R}
\end{Lexample}
Transparency is supported by \LuaLaTeX; \XeLaTeX\ with the \texttt{xdvipdfmx} driver
does not support this feature.

If you load the \pkg{xcolor} package, you may use any named colour instead
of writing the colours in hexadecimal.
\begin{Verbatim}
 \usepackage{xcolor}
 ...
 \fontspec[Color=red]{Verdana} ...
 \definecolor{Foo}{rgb}{0.3,0.4,0.5}
 \fontspec[Color=Foo]{Verdana} ...
\end{Verbatim}
The \pkg{color} package is \emph{not} supported; use \pkg{xcolor} instead.

You may specify the transparency with a named colour using the \feat{Opacity}
feature which takes an decimal from zero to one corresponding to
transparent to opaque respectively:
\begin{Verbatim}
 \fontspec[Color=red,Opacity=0.7]{Verdana} ...
\end{Verbatim}
It is still possible to specify a colour in six-char hexadecimal form
while defining opacity in this way, if you like.

\subsection{Scale}

\cmdbox{
 \feat{Scale} = \meta{number} \\
 \feat{Scale} = \opt{MatchLowercase} \\
 \feat{Scale} = \opt{MatchUppercase}
}

In its explicit form, \feat{Scale} takes a single
numeric argument for linearly scaling the font, as demonstrated
in \exref{fontload}.
It is now possible to
measure the correct dimensions of the fonts loaded and
calculate values to scale them automatically.

As well as a numerical argument, the \feat{Scale} feature
also accepts options \opt{MatchLowercase}
and \opt{MatchUppercase}, which will scale the font being selected to match
the current default roman font to either the height of the lowercase or
uppercase letters, respectively; these features are shown in \exref{scale}.

\begin{Xexample}{scale}{Automatically calculated scale values.}
  \setmainfont{Georgia}
  \newfontfamily\lc[Scale=MatchLowercase]{Verdana}
   The perfect match {\lc is hard to find.}\\
  \newfontfamily\uc[Scale=MatchUppercase]{Arial}
   L O G O \uc F O N T
\end{Xexample}

The amount of scaling used in each instance is reported in the \texttt{.log} file.
Since there is some subjectivity about the exact scaling to be used, these values
should be used to fine-tune the results.

Note that when |Scale=MatchLowercase| is used with |\setmainfont|, the new `main' font of the document will be scaled to match the old default.
This may be undesirable in some cases, so to achieve `natural' scaling for the main font but automatically scale all other fonts selected, you may write
\begin{Verbatim}
  \defaultfontfeatures{ Scale = MatchLowercase }
  \defaultfontfeatures[\rmfamily]{ Scale = 1}
\end{Verbatim}
One or both of these lines may be placed into a local |fontspec.cfg| file (see \vref{sec:config}) for this behaviour to be effected in your own documents automatically.
(Also see \vref{sec:defaults} for more information on setting font defaults.)



\subsection{Interword space}

While the space between words can be varied on an individual
basis with the \TeX\ primitive \cmd\spaceskip\ command, it is
more convenient to specify this information when the font is
first defined.

The space in between words in a paragraph will be chosen automatically,
and generally will not need to be adjusted. For those
times when the precise details are important, the \feat{WordSpace}
feature is
provided, which takes either a single scaling factor to scale the
default value, or a triplet of comma-separated
values to scale the nominal value, the stretch, and the shrink of the
interword space by, respectively. (|WordSpace={|$x$|}| is the same as
|WordSpace={|$x$|,|$x$|,|$x$|}|.)

\begingroup
\let\centering\relax
\begin{Xexample}{wordspace}{Scaling the default interword space. An exaggerated value has been chosen to emphasise the effects here.}
  \fontspec{texgyretermes-regular.otf}
  Some text for our example to take
  up some space, and to demonstrate
  the default interword space.
  \bigskip

  \fontspec{texgyretermes-regular.otf}%
    [WordSpace = 0.3]
  Some text for our example to take
  up some space, and to demonstrate
  the default interword space.
\end{Xexample}
\endgroup

\subsection{Post-punctuation space}

If \cmd\frenchspacing\ is \emph{not} in effect, \TeX\ will allow extra
space after some punctuation in its goal of justifying the lines of text.
Generally, this is considered old-fashioned, but occasionally in small amounts the
effect can be justified, pardon the pun.

The \feat{PunctuationSpace} feature takes a scaling factor by which to
adjust the nominal value chosen for the font; this is demonstrated in
\exref{punctspace}.
Note that |PunctuationSpace=0|
is \emph{not} equivalent to \cmd\frenchspacing, although the difference
will only be apparent when a line of text is under-full.

\begin{Lexample}{punctspace}{Scaling the default post-punctuation space.}
  \nonfrenchspacing
  \fontspec{texgyreschola-regular.otf}
   Letters, Words. Sentences.          \par
  \fontspec{texgyreschola-regular.otf}[PunctuationSpace=2]
   Letters, Words. Sentences.          \par
  \fontspec{texgyreschola-regular.otf}[PunctuationSpace=0]
   Letters, Words. Sentences.
\end{Lexample}




\subsection{The hyphenation character}

The letter used for hyphenation may be chosen with the \feat{HyphenChar}
feature. It takes three types of input, which are chosen according to some
simple rules. If the input is the string \opt{None}, then hyphenation is
suppressed for this font.
If the input is a single character, then this
character is used. Finally, if the input is longer than a single character
it must be the UTF-8 slot number of the hyphen character you desire.

This package redefines \LaTeX's \cmd\-\ macro such that it adjusts along with the above changes.

\begin{Xexample}{hyphchar}{Explicitly choosing the hyphenation character.}
 \def\text{\fbox{\parbox{1.55cm}{%
   EXAMPLE HYPHENATION%
 }}\qquad\qquad\null\par\bigskip}

 \fontspec{Linux Libertine O}[HyphenChar=None]
 \text
 \fontspec{Linux Libertine O}[HyphenChar={+}]
 \text
\end{Xexample}

Note that \TeX's optimisations in how it loads fonts means that you cannot
use this feature in \cs{addfontfeatures}.

\subsection{Optical font sizes} \label{sec:opticalsize}

Optically scaled fonts thicken out as the font size decreases
in order to make the glyph shapes more robust (less prone to losing
detail), which improves legibility. Conversely, at large optical
sizes the serifs and other small details may be more delicately
rendered.

OpenType fonts with optical scaling will exist in
several discrete sizes, and these will be selected by \XeTeX\
and Lua\TeX\
\emph{automatically} determined by the current font size as in
\exref{optsize}, in which we've scaled down some large text in order to be
able to compare the difference for equivalent font sizes.

The
\opt{OpticalSize} option may be used to specify a different optical
size.
With \opt{OpticalSize} set
to zero, no optical size font substitution is performed, as shown in
\exref{optsize0}.

\begin{Xexample}{optsize}{A demonstration of automatic optical size selection.}
  \fontspec{Latin Modern Roman}
   Automatic optical size                  \\
  \scalebox{0.4}{\Huge
   Automatic optical size}
\end{Xexample}

\begin{Xexample}{optsize0}{Optical size substitution is suppressed when set to zero.}
  \fontspec{Latin Modern Roman 5 Regular}[OpticalSize=0]
   Latin Modern optical sizes                \\
  \fontspec{Latin Modern Roman 8 Regular}[OpticalSize=0]
   Latin Modern optical sizes                \\
  \fontspec{Latin Modern Roman 12 Regular}[OpticalSize=0]
   Latin Modern optical sizes                \\
  \fontspec{Latin Modern Roman 17 Regular}[OpticalSize=0]
   Latin Modern optical sizes
\end{Xexample}

The \feat{SizeFeatures} feature (\vref*{sec:sizefeature}) can be
used to specify exactly which optical sizes will be used for ranges
of font size. For example, something like:
\begin{Verbatim}
  \fontspec{Latin Modern Roman}[
    UprightFeatures = { SizeFeatures = {
      {Size=-10,     OpticalSize=8 },
      {Size= 10-14,  OpticalSize=10},
      {Size= 14-18,  OpticalSize=14},
      {Size=    18-, OpticalSize=18}}}
           ]
\end{Verbatim}

\part{OpenType}
\label{sec:opentype-features}

\section{Introduction}
\label{sec:opentype-features-intro}

OpenType fonts (and other `smart' font technologies such as AAT and Graphite) can change the appearance of text in many different ways.
These changes are referred to as font features.
When the user applies a feature~--- for example, small capitals~--- to a run of text, the code inside the font makes appropriate substitutions and small capitals appear in place of lowercase letters.
However, the use of such features does not affect the underlying text.
In our small caps example, the lowercase letters are still stored in the document; only the appearance has been changed by the OpenType feature.
This makes it possible to search and copy text without difficulty.
If the user selected a different font that does not support small caps, the `plain' lowercase letters would appear instead.

Some OpenType features are required to support particular scripts, and these features are often applied automatically.
The Indic scripts, for example, often require that characters be reshaped and reordered after they are typed by the user, in order to display them in the traditional ways that readers expect.
Other features can be applied to support a particular language.
The Junicode font for medievalists uses by default the Old English shape of the letter thorn, while in modern Icelandic thorn has a more rounded shape.
If a user tags some text as being in Icelandic, Junicode will automatically change to the Icelandic shape through an OpenType feature that localises the shapes of letters.

There are a large group of OpenType features, designed to support high quality typography a multitude of languages and writing scripts.
Examples of some font features have already been shown in previous sections; the complete set of OpenType font features supported by \pkg{fontspec} is described below in \ref{sec:ot-feat}.

The OpenType specification provides four-letter codes (e.g., \texttt{smcp} for small capitals) for each feature.  The four-letter codes are given below along with the \pkg{fontspec} names for various features, for the benefit of people who are already familiar with OpenType.  You can ignore the codes if they don't mean anything to you.


\subsection{How to select font features}

Font features are selected by a series of \meta{feature}=\meta{option}
selections. Features are (usually) grouped logically; for example, all
font features relating to ligatures are accessed by writing \verb|Ligatures={...}| with the appropriate argument(s), which could be \texttt{TeX}, \texttt{Rare}, etc., as shown below in \ref{sec:ot-feat-liga}.

Multiple options may be given to
any feature that accepts non-numerical input, although doing so will
not always work. Some options will override others in generally
obvious ways; \Verb|Numbers={OldStyle,Lining}| doesn't make much
sense because the two options are mutually exclusive, and \XeTeX\
will simply use the last option that is specified (in this case
using \opt{Lining} over \opt{OldStyle}).

If a feature or an option is requested that the font does not have,
a warning is given in the console output. As mentioned in \vref{sec:quiet-warnings}
these warnings can be suppressed by selecting the \texttt{[quiet]} package option.

\subsection{How do I know what font features are supported by my fonts?}

Although I've long desired to have a feature within \pkg{fontspec} to display the OpenType features within a font, it's never been high on my priority list.
One reason for that is the existence of the document |opentype-info.tex|, which is available on \textsc{ctan} or typing |kpsewhich opentype-info.tex| in a Terminal window.
Make a copy of this file and place it somewhere convenient.
Then open it in your regular \TeX\ editor and change the font name to the font you'd like to query; after running through plain \XeTeX, the output \textsc{pdf} will look something like this:

\begin{framed}
\def\myfontname{[Asana-Math.otf]}
%
%%% OpenType-info.tex %%%

\font\testfont="\myfontname/ICU" at 12pt

\rightskip=0pt plus 1fil

\font\titlefont=ec-lmssbx10 at 12pt
\font\tenrm=ec-lmss10 at 9pt \tenrm
\font\tentt=ec-lmtt10 at 9pt

\def\fourcharcode#1{\begingroup
 \count0=#1\count1=\count0
 \ifnum\count0=0
  $\langle$default$\rangle$%
 \else
  \tentt
  '%
  \divide\count0 by "1000000
  \char\count0
  \multiply\count0 by "1000000
  \advance\count1 by -\count0
  \count0=\count1
  \divide\count0 by "10000
  \char\count0
  \multiply\count0 by "10000
  \advance\count1 by -\count0
  \count0=\count1
  \divide\count0 by "100
  \char\count0
  \multiply\count0 by "100
  \advance\count1 by -\count0
  \ifnum\count1=32 \ \else \char\count1 \fi
  '%
 \fi
 \endgroup
}

\newcount\scriptcount
\newcount\scriptindex
\newcount\scripttag
\newcount\langcount
\newcount\langindex
\newcount\langtag
\newcount\featurecount
\newcount\featureindex
\newcount\featuretag

\leftline{\titlefont OpenType Layout features found in `\myfontname'}
\nobreak

\scriptcount=\XeTeXOTcountscripts\testfont
\ifnum\scriptcount=0 \noindent None\par\fi

\loop
 \ifnum\scriptindex<\scriptcount
  \smallskip
  \scripttag=\XeTeXOTscripttag\testfont\scriptindex
  \noindent script = \fourcharcode{\scripttag}\endgraf\nobreak
  \langcount=\XeTeXOTcountlanguages\testfont\scripttag
  \advance\langcount by 1 % one extra to get the default language system
  {\loop
    \langtag=\XeTeXOTlanguagetag\testfont\scripttag\langindex
    \indent language = \fourcharcode{\langtag}\endgraf\nobreak
    \featurecount=\XeTeXOTcountfeatures\testfont\scripttag\langtag
    {\indent\indent \hangindent=3\parindent \hangafter=1 features = \loop
      \featuretag=\XeTeXOTfeaturetag\testfont\scripttag\langtag\featureindex
      \fourcharcode{\featuretag}
      \advance\featureindex by 1
      \ifnum\featureindex<\featurecount \repeat\endgraf}
    \advance\langindex by 1
  \ifnum\langindex<\langcount \medskip \repeat}
  \advance\scriptindex by 1
\repeat
\end{framed}

\noindent I intentionally picked a font that by design needs few font features; `regular' text fonts such as Latin Modern Roman contain many more, and I didn't want to clutter up the document too much.
You'll then need to cross-check the OpenType feature tags with the `logical' names used by \pkg{fontspec}.

\paragraph{otfinfo}
Alternatively, and more simply, you can use the command line tool |otfinfo|, which is distributed with \TeX{}Live.
Simply type in a Terminal window, say:
\begin{Verbatim}
  otfinfo -f `kpsewhich lmromandunh10-oblique.otf`
\end{Verbatim}
which results in:
\begin{Verbatim}[frame=single]
aalt	Access All Alternates
cpsp	Capital Spacing
dlig	Discretionary Ligatures
frac	Fractions
kern	Kerning
liga	Standard Ligatures
lnum	Lining Figures
onum	Oldstyle Figures
pnum	Proportional Figures
size	Optical Size
tnum	Tabular Figures
zero	Slashed Zero
\end{Verbatim}

\section{Complete listing of OpenType font features}
\label{sec:ot-feat}

\subsection{Ligatures}
\label{sec:ot-feat-liga}

\feat{Ligatures} refer to the replacement of two separate characters
with a specially drawn glyph for functional or \ae sthetic reasons.
The list of options, of which multiple may be selected at one time,
is shown in \ref{feat:Ligatures}.
A demonstration with the Linux Libertine fonts\note{\url{http://www.linuxlibertine.org/}} is shown in \exref{lig}.

Note the additional features accessed with \verb|Ligatures=TeX|. These are
not actually real OpenType features, but additions provided by \pkg{luaotfload} (i.e., \LuaTeX\ only) to emulate \TeX's behaviour for \textsc{ascii} input of curly quotes and punctuation. In \XeTeX\ this is achieved with the \feat{Mapping} feature (see \vref{sec:mapping}) but for consistency \verb|Ligatures=TeX| will perform the same function as \verb|Mapping=tex-text|.

\subsection{Letters} \label{sec:letters}
The \opt{Letters} feature specifies how the letters in the current font
will look. OpenType fonts may contain the following options:
\opt{Uppercase}, \opt{SmallCaps}, \opt{PetiteCaps},
\opt{UppercaseSmallCaps}, \opt{UppercasePetiteCaps}, and
\opt{Unicase}.


\begin{features}{Ligatures}
\otf*{Required}{rlig}
\otf*{Common}{liga}
\otf*{Contextual}{clig}
\otf{Rare/Discretionary}{dlig}
\otf{Historic}{hlig}
\otf{TeX}{tlig/trep}
\end{features}

\begin{Lexample}[firstline=2]{lig}{An example of the \feat{Ligatures} feature.}
   \Huge\centering
   \def\test#1#2{%
     #2 $\to$ {\addfontfeature{#1} #2}\\}
   \fontspec{Linux Libertine O}
   \test{Ligatures=Historic}{strict}
   \test{Ligatures=Rare}{wurtzite}
   \test{Ligatures=NoCommon}{firefly}
\end{Lexample}

\begin{features}{Letters}
\otf{Uppercase}{case}
\otf{SmallCaps}{smcp}
\otf{PetiteCaps}{pcap}
\otf{UppercaseSmallCaps}{c2sc}
\otf{UppercasePetiteCaps}{c2pc}
\otf{Unicase}{unic}
\end{features}

Petite caps are smaller than small caps.
\opt{SmallCaps} and \opt{PetiteCaps}
turn lowercase letters into the smaller caps letters,
whereas the \opt{Uppercase...} options turn the \emph{capital} letters into
the smaller
caps (good, \eg, for applying to already uppercase acronyms like
`NASA').
This difference is shown in \exref{caps}.
`Unicase' is a weird hybrid of upper and lower case letters.

\begin{Lexample}{caps}{Small caps from lowercase or uppercase letters.}
  \fontspec{texgyreadventor-regular.otf}[Letters=SmallCaps]
   THIS SENTENCE no verb                \\
  \fontspec{texgyreadventor-regular.otf}[Letters=UppercaseSmallCaps]
   THIS SENTENCE no verb
\end{Lexample}

Note that the \opt{Uppercase} option will (probably)
not actually map letters to uppercase.
 \note{If you want automatic uppercase letters, look to \LaTeX's
      \cmd\MakeUppercase\ command.}
It is designed to select various
uppercase forms for glyphs such as accents and dashes, such as shown
in \exref{letters-uppercase}; note the raised position of the hyphen
to better match the surrounding letters.

\begin{Lexample}{letters-uppercase}{An example of the \opt{Uppercase} option of the \feat{Letters} feature.}
  \fontspec{Linux Libertine O}
   UPPER-CASE example \\
  \addfontfeature{Letters=Uppercase}
   UPPER-CASE example
\end{Lexample}

The \feat{Kerning} feature also contains an \opt{Uppercase} option,
which adds a small amount of spacing in between letters (see \vref{sec:kerning}).

\subsection{Numbers}

The \feat{Numbers} feature defines how numbers will look in the
selected font, accepting options shown in \ref{feat:Numbers}.

\begin{features}{Numbers}
\otf{Uppercase/Lining}{lnum}
\otf{Lowercase/OldStyle}{onum}
\otf{Proportional}{pnum}
\otf{Monospaced}{tnum}
\otf{SlashedZero}{zero}
\otf{Arabic}{anum}
\end{features}

The synonyms
\opt{Uppercase} and \opt{Lowercase} are equivalent to \opt{Lining} and
\opt{OldStyle}, respectively.
The differences have been shown previously
in \vref{sec:addfontfeatures}.
The \opt{Monospaced} option is useful for tabular material when digits need
to be vertically aligned.

The \opt{SlashedZero} option
replaces the default zero with a slashed version to prevent
confusion with an uppercase `O', shown in \exref{slashzero}.

\begin{Lexample}{slashzero}{The effect of the \opt{SlashedZero} option.}
  \fontspec[Numbers=Lining]{texgyrebonum-regular.otf}
   0123456789
  \fontspec[Numbers=SlashedZero]{texgyrebonum-regular.otf}
   0123456789
\end{Lexample}

The \opt{Arabic} option (with tag \verb|anum|) maps regular numerals to their Arabic script or Persian equivalents
based on the current \opt{Language} setting (see \vref{sec:ot}).
This option is based on a \LuaTeX\ feature of the \pkg{luaotfload} package,
not an OpenType feature. (Thus, this feature is unavailable in \XeTeX.)

\subsection{Contextuals}
This feature refers to substitutions of glyphs that vary `contextually' by their relative position in a word or string of characters;
features such as contextual swashes are accessed via the options shown in \ref{feat:Contextuals}.

\begin{features}{Contextuals}
\otf{Swash}{cswh}
\otf{Alternate}{calt}
\otf{WordInitial}{init}
\otf{WordFinal}{fina}
\otf{LineFinal}{falt}
\otf{Inner}{medi}
\end{features}

Historic forms are accessed in OpenType
fonts via the feature \feat{Style=Historic}; this is generally \emph{not}
contextual in OpenType, which is why it is not included in this feature.

\subsection{Vertical Position}

\begin{features}{VerticalPosition}
\otf{Superior}{sups}
\otf{Inferior}{subs}
\otf{Numerator}{numr}
\otf{Denominator}{dnom}
\otf{ScientificInferior}{sinf}
\otf{Ordinal}{ordn}
\end{features}

The \feat{VerticalPosition} feature is used to access things like
subscript (\opt{Inferior}) and superscript (\opt{Superior}) numbers and
letters (and a small amount of punctuation, sometimes).
The \opt{Ordinal} option will only raise characters that are used
in some languages directly after a number.
The \opt{ScientificInferior} feature will move glyphs
further below the baseline than the \opt{Inferior} feature.
These are shown in \exref{vertpos}

\opt{Numerator} and \opt{Denominator} should only be used for creating
arbitrary fractions (see next section).

\begin{Lexample}{vertpos}{The \feat{VerticalPosition} feature.}
  \fontspec{LibreCaslonText-Regular.otf}[VerticalPosition=Superior]
   Superior: 1234567890                                   \\
  \fontspec{LibreCaslonText-Regular.otf}[VerticalPosition=Numerator]
   Numerator: 12345                                       \\
  \fontspec{LibreCaslonText-Regular.otf}[VerticalPosition=Denominator]
   Denominator: 12345                                     \\
  \fontspec{LibreCaslonText-Regular.otf}[VerticalPosition=ScientificInferior]
   Scientific Inferior: 12345
\end{Lexample}

The \pkg{realscripts} package
(which is also loaded by \pkg{xltxtra} for \XeTeX)
redefines the \cmd\textsubscript\ and
\cmd\textsuperscript\ commands to use the above font features automatically,
including for use in footnote labels.
If this is the only feature of \pkg{xltxtra} you wish to use, consider
loading \pkg{realscripts} on its own instead.


\subsection{Fractions}

\begin{features}{Fractions}
\otf{On}{frac}
\otf{Alternate}{afrc}
\end{features}

For OpenType fonts use a regular text slash to create fractions, but
the \feat{Fraction} feature must be explicitly activated.
Some (Asian fonts predominantly) also provide for the
\opt{Alternate} feature. These are both shown in \exref{ot-frac}.

\begin{Xexample}{ot-frac}{The \feat{Fractions} feature.}
  \fontspec{Hiragino Maru Gothic Pro W4}
   1/2 \quad 1/4 \quad 5/6 \quad 13579/24680 \\
  \addfontfeature{Fractions=On}
   1/2 \quad 1/4 \quad 5/6 \quad 13579/24680 \\
  \addfontfeature{Fractions=Alternate}
   1/2 \quad 1/4 \quad 5/6 \quad 13579/24680 \\
\end{Xexample}


\subsection{Stylistic Set variations}

This feature selects a `Stylistic Set' variation,
which usually corresponds to an alternate glyph style for a range of
characters (usually an alphabet or subset thereof).
This feature is specified numerically. These correspond to OpenType
features |ss01|, |ss02|, etc.

Two demonstrations from the Junicode
font\note{\url{http://junicode.sf.net}}
are shown in \exref{ss} and \exref{ss2}; thanks to Adam
Buchbinder for the suggestion.

\begin{Lexample}{ss}{Insular letterforms, as used in medieval Northern Europe, for the Junicode font accessed with the \feat{StylisticSet} feature.}
  \fontspec{Junicode}
   Insular forms. \\
  \addfontfeature{StylisticSet=2}
   Insular forms. \\
\end{Lexample}

\begin{Lexample}{ss2}{Enlarged minuscules (capital letters remain unchanged) for the Junicode font, accessed with the \feat{StylisticSet} feature.}
  \fontspec{Junicode}
   ENLARGED Minuscules. \\
  \addfontfeature{StylisticSet=6}
   ENLARGED Minuscules. \\
\end{Lexample}

Multiple stylistic sets may be selected simultaneously by writing, e.g.,
|StylisticSet={1,2,3}|.

The |StylisticSet| feature is a synonym of the \feat{Variant} feature for \AAT\ fonts.
See \vref{sec:newfeatures} for a way to assign names to stylistic sets, which should be done on a per-font basis.

\subsection{Character Variants}

Similar to the `Stylistic Sets' above, `Character Variations' are selected
numerically to adjust the output of (usually) a single character for the
particular font. These correspond to the OpenType features |cv01| to |cv99|.

For each character that can be varied, it is possible to select among
possible options for that particular glyph.
For example, in \exref{cv} a variety of glyphs for the character `v' are
selected, in which |5| corresponds to the character `v' for this font feature,
and the trailing |:|\meta{n} corresponds to which variety to choose.
Georg Duffner's open source Garamond revival font\footnote{\url{http://www.georgduffner.at/ebgaramond/}} is used in this example.
Character variants are specifically designed not to conflict with each
other, so you can enable them individually per character as shown in
\exref{cv2}. (Unlike stylistic alternates, say.)

Note that the indexing starts from zero.

\begin{Lexample}[firstline=2]{cv}{The \feat{CharacterVariant} feature showing off Georg Duffner's open source Garamond revival font.}
  \huge
  \fontspec{EB Garamond 12 Italic}                       very \\
  \fontspec{EB Garamond 12 Italic}[CharacterVariant=5]   very \\
  \fontspec{EB Garamond 12 Italic}[CharacterVariant=5:0] very \\
  \fontspec{EB Garamond 12 Italic}[CharacterVariant=5:1] very \\
  \fontspec{EB Garamond 12 Italic}[CharacterVariant=5:2] very \\
  \fontspec{EB Garamond 12 Italic}[CharacterVariant=5:3] very
\end{Lexample}

\begin{Lexample}[firstline=2]{cv2}{The \feat{CharacterVariant} feature selecting multiple variants simultaneously.}
  \huge
  \fontspec{EB Garamond 12 Italic}                           \& violet \\
  \fontspec{EB Garamond 12 Italic}[CharacterVariant={4}]     \& violet \\
  \fontspec{EB Garamond 12 Italic}[CharacterVariant={5:2}]   \& violet \\
  \fontspec{EB Garamond 12 Italic}[CharacterVariant={4,5:2}] \& violet
\end{Lexample}

\subsection{Alternates}

The \feat{Alternate} feature (for the raw OpenType feature |salt|) is used to access alternate font glyphs when variations exist in the font, such as in \exref{salt}.
It uses a numerical selection, starting from zero, that will be different for each font.
Note that the \texttt{Style=Alternate} option is equivalent
to \texttt{Alternate=0} to access the default case.

\begin{Xexample}[firstline=2]{salt}{The \feat{Alternate} feature.}
  \huge
  \fontspec{Linux Libertine O}
  \textsc{a} \& h \\
  \addfontfeature{Alternate=0}
  \textsc{a} \& h
\end{Xexample}

Note that the indexing starts from zero.

See \vref{sec:newfeatures} for a way to assign names to alternates,
which must be done on a per-font basis.

\subsection{Style}
\label{sec:ot-feat-style}

\begin{features}{Style}
\otf{Alternate}{salt}
\otf{Italic}{ital}
\otf{Ruby}{ruby}
\otf{Swash}{swsh}
\otf{Historic}{hist}
\otf{TitlingCaps}{titl}
\otf{HorizontalKana}{hkna}
\otf{VerticalKana}{vkna}
\end{features}

`Ruby' refers to a small optical size, used in
Japanese typography for annotations.
For fonts with multiple |salt| OpenType features,
use the fontspec \feat{Alternate} feature instead.

\Exref{style-alt} and \exref{style-hist} both contain glyph
substitutions with similar characteristics.
Note the occasional inconsistency with which font features are labelled; a long-tailed `Q' could turn up anywhere!

 \begin{Xexample}[firstline=2]{style-alt}{Example of the \opt{Alternate} option of the \feat{Style} feature.}
  \Large
  \fontspec{Quattrocento Roman}
   M Q W                      \\
  \addfontfeature{Style=Alternate}
   M Q W
\end{Xexample}

\begin{Xexample}[firstline=2]{style-hist}{Example of the \opt{Historic} option of the \feat{Style} feature.}
  \Large
  \fontspec{Adobe Jenson Pro}
   M Q Z                      \\
  \addfontfeature{Style=Historic}
   M Q Z
\end{Xexample}

In other features, larger breadths of changes can be seen, covering
the style of an entire alphabet. See \exref{style-titl} and \exref{style-itrub}; in the latter, the \opt{Italic} option affects the Latin text and the \opt{Ruby} option the Japanese.

\begin{Xexample}[firstline=2]{style-titl}{Example of the \opt{TitlingCaps} option of the \feat{Style} feature.}
  \Large
  \fontspec{Adobe Garamond Pro}
   TITLING CAPS                       \\
  \addfontfeature{Style=TitlingCaps}
   TITLING CAPS
\end{Xexample}

\begin{Xexample}[firstline=2]{style-itrub}{Example of the \opt{Italic} and \opt{Ruby} options of the \feat{Style} feature.}
  \Large \def\kana{ようこそ ワカヨタレソ}
  \fontspec{Hiragino Mincho Pro}
   Latin \kana        \\
  \addfontfeature{Style={Italic, Ruby}}
   Latin \kana
\end{Xexample}

Note the difference here between the default and the horizontal style kana
in \exref{style-hvkana}: the horizontal style is slightly wider.

\begin{Xexample}[firstline=2]{style-hvkana}{Example of the \opt{HorizontalKana} and \opt{VerticalKana} options of the \feat{Style} feature.}
  \Large \def\kana{ようこそ ワカヨタレソ}
   \fontspec{Hiragino Mincho Pro}
    \kana   \\
  {\addfontfeature{Style=HorizontalKana}
    \kana } \\
  {\addfontfeature{Style=VerticalKana}
    \kana }
\end{Xexample}

\subsection{Diacritics}
Specifies how combining diacritics should be placed.
These will usually be controlled automatically
according to the Script setting.

\begin{features}{Diacritics}
\otf*{MarkToBase}{mark}
\otf*{MarkToMark}{mkmk}
\otf*{AboveBase}{abvm}
\otf*{BelowBase}{blwm}
\end{features}

\subsection{Kerning}\label{sec:kerning}
Specifies how inter-glyph spacing should behave.
Well-made fonts include information for how differing
amounts of space should be inserted between separate character pairs.
This kerning space is inserted automatically but in rare
circumstances you may wish to turn it off.

\begin{features}{Kerning}
\otf{Uppercase}{cpsp}
\otf*[Off]{On}{kern}
\end{features}

As briefly mentioned previously at the end of \vref{sec:letters},
the \opt{Uppercase} option will add a small amount of tracking between
uppercase letters, seen in \exref{kernup}, which uses the Romande
fonts\note{\url{http://arkandis.tuxfamily.org/adffonts.html}}
(thanks to Clea F. Rees for the suggestion).
The \opt{Uppercase} option acts separately to the regular kerning
controlled by the \opt{On}/\opt{Off} options.

\begin{Xexample}[firstline=2]{kernup}{Adding extra kerning for uppercase letters. (The difference is usually very small.)}
  \large
  \fontspec{Romande ADF Std Bold}
   UPPERCASE EXAMPLE \\
  \addfontfeature{Kerning=Uppercase}
   UPPERCASE EXAMPLE
\end{Xexample}


\subsection{Font transformations}

In rare situations users may want to mechanically distort the shapes of the glyphs in the current font such as shown in \exref{fake}. Please don't overuse these features; they are \emph{not} a good alternative to having the real shapes.

\begin{Xexample}{fake}{Articifial font transformations.}
  \fontspec{Charis SIL} \emph{ABCxyz} \quad
  \fontspec{Charis SIL}[FakeSlant=0.2] ABCxyz

  \fontspec{Charis SIL}  ABCxyz \quad
  \fontspec{Charis SIL}[FakeStretch=1.2] ABCxyz

  \fontspec{Charis SIL} \textbf{ABCxyz} \quad
  \fontspec{Charis SIL}[FakeBold=1.5] ABCxyz
\end{Xexample}

If values are omitted, their defaults are as shown above.

If you want the bold shape to be faked automatically, or the italic shape
to be slanted automatically, use the \feat{AutoFakeBold} and
\feat{AutoFakeSlant} features. For example, the following two invocations
are equivalent:
\begin{Verbatim}
  \fontspec[AutoFakeBold=1.5]{Charis SIL}
  \fontspec[BoldFeatures={FakeBold=1.5}]{Charis SIL}
\end{Verbatim}
If both of the \feat{AutoFake...} features are used, then the bold italic
font will also be faked.

The \feat{FakeBold} and \feat{AutoFakeBold} features are only available with the \XeTeX\ engine and will be ignored in \LuaTeX.

\subsection{Annotation}
Some fonts are equipped with an extensive range of
numbers and numerals in different forms. These are accessed with the
\feat{Annotation} feature (OpenType feature |nalt|), selected numerically as shown in
\exref{ot-annot}.

\begin{Xexample}{ot-annot}{Annotation forms for OpenType fonts.}
  \fontspec{Hiragino Maru Gothic Pro}
   1 2 3 4 5 6 7 8 9
  \def\x#1{\\{\addfontfeature{Annotation=#1}
            1 2 3 4 5 6 7 8 9 }}
  \x0\x1\x2\x3\x4\x5\x6\x7\x7\x8\x9
\end{Xexample}

Note that the indexing starts from zero.

\subsection{CJK shape}

\begin{features}{CJKShape}
\otf{Traditional}{trad}
\otf{Simplified} {smpl}
\otf{JIS1978}    {jp78}
\otf{JIS1983}    {jp83}
\otf{JIS1990}    {jp90}
\otf{Expert}     {expt}
\otf{NLC}        {nlck}
\end{features}

There have been many standards for how CJK ideographic
glyphs are `supposed' to look. Some fonts will contain many alternate
glyphs available in order to be able to display these gylphs
correctly in whichever form is appropriate. Both \AAT\ and OpenType
fonts support the following \feat{CJKShape} options:
\opt{Traditional}, \opt{Simplified}, \opt{JIS1978}, \opt{JIS1983},
\opt{JIS1990}, and \opt{Expert}. OpenType also supports the \opt{NLC} option.

\begin{Xexample}[firstline=2]{ot-cjk-shape}{Different standards for CJK ideograph presentation.}
  \LARGE\def\text{ 唖噛躯 妍并訝}
  \fontspec{Hiragino Mincho Pro}
  {\addfontfeature{CJKShape=Traditional}
  \text }                          \\
  {\addfontfeature{CJKShape=NLC}
  \text }                          \\
  {\addfontfeature{CJKShape=Expert}
  \text }
\end{Xexample}

\subsection{Character width}\label{sec:CharacterWidth}
Many Asian fonts are equipped with variously spaced characters for
shoe-horning into their generally monospaced text.
These are
accessed through the \feat{CharacterWidth} feature.

\begin{features}{CharacterWidth}
\otf{Proportional}{pwid}
\otf{Full}        {fwid}
\otf{Half}        {hwid}
\otf{Third}       {twid}
\otf{Quarter}     {qwid}
\otf{AlternateProportional}{palt}
\otf{AlternateHalf}{halt}
\end{features}

Japanese alphabetic glyphs (in Hiragana or Katakana) may be typeset
proportionally, to better fit horizontal measures, or monospaced, to
fit into the rigid grid imposed by ideographic typesetting. In this
latter case, there are also half-width forms for squeezing more kana
glyphs (which are less complex than the kanji they are amongst) into
a given block of space. The same features are given to roman letters
in Japanese fonts, for typesetting foreign words in the same style
as the surrounding text.

\begin{Xexample}[firstline=2]{charwdprop}{Proportional or fixed width forms.}
  \def\texta{ようこそ}\def\textb{ワカヨタレソ}
  \def\test{\makebox[2cm][l]{\texta}%
            \makebox[2.5cm][l]{\textb}%
            \makebox[2.5cm][l]{abcdef}}
  \fontspec{Hiragino Mincho Pro}
  {\addfontfeature{CharacterWidth=Proportional}\test}\\
  {\addfontfeature{CharacterWidth=Full}\test}\\
  {\addfontfeature{CharacterWidth=Half}\test}
\end{Xexample}

The same situation occurs with numbers, which are provided in
increasingly illegible compressed forms seen in \exref{charwd}.

\begin{Xexample}[firstline=2]{charwd}{Numbers can be compressed significantly.}
  \centering
  \fontspec[Renderer=AAT]{Hiragino Mincho Pro}
  {\addfontfeature{CharacterWidth=Full}
   ---12321---}\\
  {\addfontfeature{CharacterWidth=Half}
   ---1234554321---}\\
  {\addfontfeature{CharacterWidth=Third}
   ---123456787654321---}\\
  {\addfontfeature{CharacterWidth=Quarter}
   ---12345678900987654321---}
\end{Xexample}

\subsection{Vertical typesetting}

TODO!


\subsection{OpenType scripts and languages}\label{sec:ot}

Fonts that include glyphs for various scripts and languages may contain different font features for the different character sets and languages they support, and different font features may behave differently depending on the script or language chosen.
When multilingual fonts are used, it is important to select which language
they are being used for, and more importantly what script is being used.

The `script' refers to the alphabet in use; for example, both English
and French use the Latin script. Similarly, the Arabic script can be used
to write in both the Arabic and Persian languages.

The
\feat{Script} and \feat{Language} features are used to designate this information. The possible options are
tabulated in \vref{tab:ot-scpt} and \vref{tab:ot-lang},
respectively. When a script or language is requested that is not
supported by the current font, a warning is printed in the console output.

Because these font features can
change which features are able to be selected for the font, they are automatically selected
by \pkg{fontspec} before all others and, if \XeTeX\ is being used, will
specifically select the \opt{OpenType}
renderer for this font, as described in \vref{sec:renderer}.


\subsubsection{\feat{Script} and \feat{Language} examples}

In the examples shown in \exref{script-lang},
the Code2000 font\note{\url{http://www.code2000.net/}}
is used to typeset various input texts with and without the OpenType Script
applied for various alphabets.
The text is only rendered correctly in the second case;
many examples of incorrect diacritic spacing as
well as a lack of contextual ligatures and rearrangement can be
seen.
Thanks to \name{Jonathan Kew}, \name{Yves Codet} and
\name{Gildas Hamel} for their contributions towards these examples.

\begin{Xexample}[firstline=14,lastline=23]{script-lang}{An example of various Scripts and Languages.}
\def\testfeature#1#2{%^^A
  \fontspec{\examplefont}#2 & \fontspec[#1]{\examplefont}#2\\[1ex]}
\def \examplefont{Code2000}
\def \arabictext{العربي}
\def \devanagaritext{हिन्दी}
\def \bengalitext{লেখ}
\def \gujaratitext{મર્યાદા-સૂચક નિવેદન}
\def \malayalamtext{നമ്മുടെ പാരബര്യ}
\def \gurmukhitext{ਆਦਿ ਸਚੁ ਜੁਗਾਦਿ ਸਚੁ}
\def \tamiltext{தமிழ் தேடி}
\def \hebrewtext{רִדְתָּֽהּ}
\def \vietnamesetext{cấp số mỗi}
\begin{tabular}{r@{\quad}l}
  \testfeature{Script=Arabic}{\arabictext}
  \testfeature{Script=Devanagari}{\devanagaritext}
  \testfeature{Script=Bengali}{\bengalitext}
  \testfeature{Script=Gujarati}{\gujaratitext}
  \testfeature{Script=Malayalam}{\malayalamtext}
  \testfeature{Script=Gurmukhi}{\gurmukhitext}
  \testfeature{Script=Tamil}{\tamiltext}
  \testfeature{Script=Hebrew}{\hebrewtext}
  \def\examplefont{Doulos SIL}
  \testfeature{Language=Vietnamese}{\vietnamesetext}
\end{tabular}
\end{Xexample}



\subsubsection{Defining new scripts and languages}

\DescribeMacro{\newfontscript}
\DescribeMacro{\newfontlanguage}
While the scripts and languages listed in \ref{tab:ot-scpt} and \ref{tab:ot-lang}
are intended to be comprehensive, there may be some missing; alternatively,
you might wish to use different names to access scripts/languages that are
already listed.
Adding scripts and languages can be performed with the \cmd\newfontscript\
and \cmd\newfontlanguage\ commands. For example,
\begin{Verbatim}
  \newfontscript{Arabic}{arab}
  \newfontlanguage{Zulu}{ZUL}
\end{Verbatim}
The first argument is the \pkg{fontspec} name, the second the OpenType
tag. The advantage to using these commands rather than \cmd\newfontfeature\
(see \vref{sec:newfeatures}) is the error-checking that is performed when
the script or language is requested.

\begin{table}[!hbp]
  \caption{Defined \opt{Script}s for OpenType fonts. Aliased names are shown in adjacent positions marked with red pilcrows ({\sffamily\textcolor{red}{\P}}).}
  \label{tab:ot-scpt}
\def\dup{\makebox[0pt][r]{\textcolor{red}{\P}}}
\setlength\columnseprule{0pt}
  \hrule
  \begin{multicols}{4}\setlength\parindent{0pt}
    \sffamily\scriptsize
    Arabic \par Armenian \par Balinese \par Bengali \par Bopomofo \par Braille \par Buginese \par Buhid \par Byzantine Music \par Canadian Syllabics \par Cherokee \par \dup CJK \par \dup CJK Ideographic \par Coptic \par Cypriot Syllabary \par Cyrillic \par Default \par Deseret \par Devanagari \par Ethiopic \par Georgian \par Glagolitic \par Gothic \par Greek \par Gujarati \par Gurmukhi \par Hangul Jamo \par Hangul \par Hanunoo \par Hebrew \par \dup Hiragana and Katakana \par \dup Kana \par Javanese \par Kannada \par Kharosthi \par Khmer \par Lao \par Latin \par Limbu \par Linear B \par Malayalam \par \dup Math \par \dup Maths \par Mongolian \par Musical Symbols \par Myanmar \par N'ko \par Ogham \par Old Italic \par Old Persian Cuneiform \par Oriya \par Osmanya \par Phags-pa \par Phoenician \par Runic \par Shavian \par Sinhala \par Sumero-Akkadian Cuneiform \par Syloti Nagri \par Syriac \par Tagalog \par Tagbanwa \par Tai Le \par Tai Lu \par Tamil \par Telugu \par Thaana \par Thai \par Tibetan \par Tifinagh \par Ugaritic Cuneiform \par Yi
  \end{multicols}
  \hrule
\end{table}

\begin{table}[p]
  \vspace*{-3cm}
  \hspace{-3cm}
  \def\dup{\makebox[0pt][r]{\textcolor{red}{\P}}}
  \begin{minipage}{\linewidth+4cm}
  \caption{Defined \opt{Language}s for OpenType fonts. Aliased names are shown in adjacent positions marked with red pilcrows ({\sffamily\textcolor{red}{\P}}).}
  \label{tab:ot-lang}
  \setlength\columnseprule{0pt}
  \hrule
  \begin{multicols}{6}
    \everypar{\setlength\parindent{0pt}\setlength\hangindent{2em}}
    \sffamily\footnotesize\raggedright
    Abaza \par Abkhazian \par Adyghe \par Afrikaans \par Afar \par Agaw \par Altai \par Amharic \par Arabic \par Aari \par Arakanese \par Assamese \par Athapaskan \par Avar \par Awadhi \par Aymara \par Azeri \par Badaga \par Baghelkhandi \par Balkar \par Baule \par Berber \par Bench \par Bible Cree \par Belarussian \par Bemba \par Bengali \par Bulgarian \par Bhili \par Bhojpuri \par Bikol \par Bilen \par Blackfoot \par Balochi \par Balante \par Balti \par Bambara \par Bamileke \par Breton \par Brahui \par Braj Bhasha \par Burmese \par Bashkir \par Beti \par Catalan \par Cebuano \par Chechen \par Chaha Gurage \par Chattisgarhi \par Chichewa \par Chukchi \par Chipewyan \par Cherokee \par Chuvash \par Comorian \par Coptic \par Cree \par Carrier \par Crimean Tatar \par Church Slavonic \par Czech \par Danish \par Dargwa \par Woods Cree \par German \par Default \par Dogri \par Divehi \par Djerma \par Dangme \par Dinka \par Dungan \par Dzongkha \par Ebira \par Eastern Cree \par Edo \par Efik \par Greek \par English \par Erzya \par Spanish \par Estonian \par Basque \par Evenki \par Even \par Ewe \par French Antillean \par \dup Farsi \par \dup Parsi \par \dup Persian \par Finnish \par Fijian \par Flemish \par Forest Nenets \par Fon \par Faroese \par French \par Frisian \par Friulian \par Futa \par Fulani \par Ga \par Gaelic \par Gagauz \par Galician \par Garshuni \par Garhwali \par Ge'ez \par Gilyak \par Gumuz \par Gondi \par Greenlandic \par Garo \par Guarani \par Gujarati \par Haitian \par Halam \par Harauti \par Hausa \par Hawaiin \par Hammer-Banna \par Hiligaynon \par Hindi \par High Mari \par Hindko \par Ho \par Harari \par Croatian \par Hungarian \par Armenian \par Igbo \par Ijo \par Ilokano \par Indonesian \par Ingush \par Inuktitut \par Irish \par Irish Traditional \par Icelandic \par Inari Sami \par Italian \par Hebrew \par Javanese \par Yiddish \par Japanese \par Judezmo \par Jula \par Kabardian \par Kachchi \par Kalenjin \par Kannada \par Karachay \par Georgian \par Kazakh \par Kebena \par Khutsuri Georgian \par Khakass \par Khanty-Kazim \par Khmer \par Khanty-Shurishkar \par Khanty-Vakhi \par Khowar \par Kikuyu \par Kirghiz \par Kisii \par Kokni \par Kalmyk \par Kamba \par Kumaoni \par Komo \par Komso \par Kanuri \par Kodagu \par Korean Old Hangul \par Konkani \par Kikongo \par Komi-Permyak \par Korean \par Komi-Zyrian \par Kpelle \par Krio \par Karakalpak \par Karelian \par Karaim \par Karen \par Koorete \par Kashmiri \par Khasi \par Kildin Sami \par Kui \par Kulvi \par Kumyk \par Kurdish \par Kurukh \par Kuy \par Koryak \par Ladin \par Lahuli \par Lak \par Lambani \par Lao \par Latin \par Laz \par L-Cree \par Ladakhi \par Lezgi \par Lingala \par Low Mari \par Limbu \par Lomwe \par Lower Sorbian \par Lule Sami \par Lithuanian \par Luba \par Luganda \par Luhya \par Luo \par Latvian \par Majang \par Makua \par Malayalam Traditional \par Mansi \par Marathi \par Marwari \par Mbundu \par Manchu \par Moose Cree \par Mende \par Me'en \par Mizo \par Macedonian \par Male \par Malagasy \par Malinke \par Malayalam Reformed \par Malay \par Mandinka \par Mongolian \par Manipuri \par Maninka \par Manx Gaelic \par Moksha \par Moldavian \par Mon \par Moroccan \par Maori \par Maithili \par Maltese \par Mundari \par Naga-Assamese \par Nanai \par Naskapi \par N-Cree \par Ndebele \par Ndonga \par Nepali \par Newari \par Nagari \par Norway House Cree \par Nisi \par Niuean \par Nkole \par N'ko \par Dutch \par Nogai \par Norwegian \par Northern Sami \par Northern Tai \par Esperanto \par Nynorsk \par Oji-Cree \par Ojibway \par Oriya \par Oromo \par Ossetian \par Palestinian Aramaic \par Pali \par Punjabi \par Palpa \par Pashto \par Polytonic Greek \par Pilipino \par Palaung \par Polish \par Provencal \par Portuguese \par Chin \par Rajasthani \par R-Cree \par Russian Buriat \par Riang \par Rhaeto-Romanic \par Romanian \par Romany \par Rusyn \par Ruanda \par Russian \par Sadri \par Sanskrit \par Santali \par Sayisi \par Sekota \par Selkup \par Sango \par Shan \par Sibe \par Sidamo \par Silte Gurage \par Skolt Sami \par Slovak \par Slavey \par Slovenian \par Somali \par Samoan \par Sena \par Sindhi \par Sinhalese \par Soninke \par Sodo Gurage \par Sotho \par Albanian \par Serbian \par Saraiki \par Serer \par South Slavey \par Southern Sami \par Suri \par Svan \par Swedish \par Swadaya Aramaic \par Swahili \par Swazi \par Sutu \par Syriac \par Tabasaran \par Tajiki \par Tamil \par Tatar \par TH-Cree \par Telugu \par Tongan \par Tigre \par Tigrinya \par Thai \par Tahitian \par Tibetan \par Turkmen \par Temne \par Tswana \par Tundra Nenets \par Tonga \par Todo \par Turkish \par Tsonga \par Turoyo Aramaic \par Tulu \par Tuvin \par Twi \par Udmurt \par Ukrainian \par Urdu \par Upper Sorbian \par Uyghur \par Uzbek \par Venda \par Vietnamese \par Wa \par Wagdi \par West-Cree \par Welsh \par Wolof \par Tai Lue \par Xhosa \par Yakut \par Yoruba \par Y-Cree \par Yi Classic \par Yi Modern \par Chinese Hong Kong \par Chinese Phonetic \par Chinese Simplified \par Chinese Traditional \par Zande \par Zulu
  \end{multicols}
  \hspace{4pt}
  \hrule
 \end{minipage}
\end{table}



\part{\LuaTeX-only font features}
\label{sec:luatex-features}

\section{OpenType font feature files}

An OpenType font feature file is a plain text file describing OpenType layout
feature of a font in a human-readable format. The syntax of OpenType feature
files is defined by Adobe\note{\url{http://www.adobe.com/devnet/opentype/afdko/topic_feature_file_syntax.html}}.

Feature files can be used to add or customize OpenType features of a font on
the fly without editing the font file itself.

Adding a new OpenType feature is as creating a plain text file defining
the new feature and then loading it by passing its name or path to
\feat{FeatureFile}, then OpenType features defined in the file can be
activated as usual.

For example, when adding one of the default features like \texttt{kern}
or \texttt{liga}, no special activation is needed. On the other hand,
an optional feature like \texttt{onum} or \texttt{smcp} will be
activated when old style numbers or small capitals are activated,
respectively. However, OpenType feature in the feature file can have any
and that can be used to selectively activate the feature; for example
defining a ligature feature called \texttt{mlig} and then activating it
using \feat{RawFeature} option without activating other ligatures in the
font.

Figure~\ref{fig:featurefile} shows an example feature file. The first two
lines set the script and language under which the defined features will be
available, which the default language in both default and Latin scripts,
respectively.

Then it defines a \texttt{liga} feature, which is a glyph substitution
feature. The names starting with backslash are glyph names that is to be
substituted and while the leading backslash is optional, it is used to
escape glyph names when they interfere with preserved keywords. It should
also be noted that glyph names are font specific and the same glyph can be
named differently in different fonts.

Glyph positioning features like kerning can be defined in a similar way,
but instead of the keyword \texttt{sub(stitute)} the keyword
\texttt{pos(ition)} is used instead. Figure~\ref{fig:featurefile} shows
an example of adding kerning between \texttt{AY} and \texttt{ay}\note{
The kerning is expressed in font design units which are fractions of em
depending on the \emph{units per em} value of the font, usually 1000 for
PostScript fonts and 2048 for TrueType fonts.}.

Lines starting with \verb|#| are comments and will be ignored.

An OpenType feature file can have any number of features and can have a
mix of substitution and positioning features, please refer to the full
feature file specification for further documentation.

\begin{figure}
\caption{An example font feature file.}
\label{fig:featurefile}
\hrule
\begin{Verbatim}
languagesystem DFLT dflt;
languagesystem latn dflt;

# Ligatures
feature liga {
  sub \f \i by \fi;
  sub \f \l by \fl;
} liga;

# Kerning
feature kern {
 pos \A \Y -200;
 pos \a \y -80;
} kern;
\end{Verbatim}
\hrule
\end{figure}

\part{Fonts and features with \XeTeX}
\label{sec:xetex-features}




\section{\XeTeX-only font features}

The features described here are available for any font
selected by \pkg{fontspec}.

\subsection{Mapping}
\label{sec:mapping}

\feat{Mapping} enables a \XeTeX\ text-mapping scheme, shown in \exref{mapping}.

\begin{Xexample}{mapping}{\XeTeX's \feat{Mapping} feature.}
  \fontspec{Cochin}[Mapping=tex-text]
  ``!`A small amount of---text!''
\end{Xexample}

Using the |tex-text| mapping is also equivalent to writing |Ligatures=TeX|.
The use of the latter syntax is recommended for better compatibility with
\LuaTeX\ documents.


\subsection{Letter spacing}
Letter spacing, or tracking, is the term given to adding (or subtracting) a small amount of horizontal space in between adjacent characters. It is specified with the \feat{LetterSpace}, which takes a numeric argument,
shown in \exref{tracking}.

The letter spacing parameter is a normalised additive factor (not a scaling factor); it is defined as a percentage of the font size. That is, for a 10\,pt font, a letter spacing parameter of `|1.0|' will add 0.1\,pt between each letter.

\begin{Xexample}{tracking}{The \feat{LetterSpace} feature.}
  \fontspec{Didot}
  \addfontfeature{LetterSpace=0.0}
  USE TRACKING FOR DISPLAY CAPS TEXT \\
  \addfontfeature{LetterSpace=2.0}
  USE TRACKING FOR DISPLAY CAPS TEXT
\end{Xexample}

This functionality \emph{should not be used for lowercase text}, which is spacing correctly to begin with, but it can be very useful, in small amounts, when setting small caps or all caps titles.
Also see the OpenType \opt{Uppercase}
option of the \feat{Letters} feature (\vref*{sec:letters}).

\subsection{Different font technologies: \AAT\ and OpenType}\label{sec:renderer}

\XeTeX\ supports two rendering technologies for typesetting, selected with
the \feat{Renderer} font feature. The first, \opt{AAT}, is
that provided (only) by \MacOSX\ itself. The second, \opt{OpenType},
is an open source OpenType interpreter.
\note{v2.4: This was called `\texttt{ICU}' in previous versions of \XeTeX\ and \pkg{fontspec}.
Backwards compatibility is preserved.}
It provides greater support for
OpenType features, notably contextual arrangement, over \opt{AAT}.

In general, this feature will not need to be explicitly called: for OpenType
fonts, the \opt{OpenType} renderer is used automatically, and for \AAT\ fonts,
\opt{AAT} is chosen by default. Some fonts, however, will contain font tables
for \emph{both} rendering technologies, such as the Hiragino Japanese fonts
distributed with \MacOSX, and in these cases the choice may be required.

Among some other font features only available through a specific renderer,
\opt{OpenType} provides for the \feat{Script} and \feat{Language} features, which allow
different font behaviour for different alphabets and languages; see \vref{sec:ot}
for the description of these features. {\em Because these font features can
change which features are able to be selected for the font instance, they are selected
by \pkg{fontspec} before all others and will automatically and without warning
select the \opt{OpenType} renderer.}


\subsection{Optical font sizes} \label{sec:aat-opticalsize}

Multiple Master fonts are parameterised over
orthogonal font axes, allowing continuous selection along such
features as weight, width, and optical size~(see \vref{sec:mm} for
further details). Whereas an OpenType font will have only a few separate
optical sizes, a Multiple Master font's optical size can be
specified over a continuous range. Unfortunately, this flexibility makes
it harder to create an automatic interface through \LaTeX, and the
optical size for a Multiple Master font must always be specified
explicitly.
\begin{Verbatim}
  \fontspec{Minion MM Roman}[OpticalSize=11]
   MM optical size test                    \\
  \fontspec{Minion MM Roman}[OpticalSize=47]
   MM optical size test                    \\
  \fontspec{Minion MM Roman}[OpticalSize=71]
   MM optical size test                    \\
\end{Verbatim}




\section{\MacOSX's \AAT\ fonts}
\label{sec:aat-features}

\begin{quote}\itshape
\textbf{Warning!}
\XeTeX's implementation on \MacOSX\ is currently in a state of flux and the information contained below may well be wrong from 2013 onwards.
There is a good chance that the features described in this section will not be available any more as \XeTeX's completes its transition to a cross-platform--only application.
\end{quote}

\MacOSX's font technology began life before the ubiquitous-OpenType era
and revolved around the Apple-invented `\AAT' font format. This format
had some advantages (and other disadvantages) but it never became widely
popular in the font world.

Nonetheless, this is the font format that was first supported by \XeTeX\
(due to its pedigree on \MacOSX\ in the first place) and was the first
font format supported by \pkg{fontspec}. A number of fonts distributed with
\MacOSX\ are still in the \AAT\ format, such as `Skia'.

\subsection{Ligatures}

\feat{Ligatures} refer to the replacement of two separate characters
with a specially drawn glyph for functional or \ae sthetic reasons.
For \AAT\ fonts, you may choose from any combination of \opt{Required},
\opt{Common}, \opt{Rare} (or \opt{Discretionary}), \opt{Logos}, \opt{Rebus},
\opt{Diphthong}, \opt{Squared}, \opt{AbbrevSquared}, and \opt{Icelandic}.

Some other Apple \AAT\ fonts have those `Rare' ligatures contained in
the \opt{Icelandic} feature. Notice also that the old \TeX\ trick of
splitting up a ligature with an empty brace pair does not work in
\XeTeX; you must use a 0\,pt kern or \cs{hbox} (\eg, \cs{null}) to
split the characters up if you do not want a ligature to be performed (the usual examples for when this might be desired are words like `shelf\null full').

\subsection{Letters} \label{sec:aat-letters}
The \opt{Letters} feature specifies how the letters in the current font
will look. For \AAT\ fonts, you may choose from \opt{Normal},
\opt{Uppercase}, \opt{Lowercase}, \opt{SmallCaps}, and
\opt{InitialCaps}.


\subsection{Numbers}
The \feat{Numbers} feature defines how numbers will look in the
selected font. For \AAT\ fonts, they may be a
combination of \opt{Lining} or \opt{OldStyle} and \opt{Proportional} or
\opt{Monospaced} (the latter is good for tabular material). The synonyms
\opt{Uppercase} and \opt{Lowercase} are equivalent to \opt{Lining} and
\opt{OldStyle}, respectively. The differences have been shown previously
in \vref{sec:addfontfeatures}.

\subsection{Contextuals} \label{sec:contextuals}
This feature refers to glyph substitution that vary by their position;
things like contextual swashes are implemented here.
The options for \AAT\ fonts are
\opt{WordInitial}, \opt{WordFinal} (\exref{wordcx}), \opt{LineInitial},
\opt{LineFinal}, and \opt{Inner} (\exref{longsaat}, also called `non-final' sometimes). As
non-exclusive selectors, like the ligatures, you can turn them off
by prefixing their name with \opt{No}.

\begin{Xexample}{wordcx}{Contextual glyph for the beginnings and ends of words.}
  \newfontface\fancy{Hoefler Text Italic}
      [Contextuals={WordInitial,WordFinal}]
  \fancy where is all the vegemite
\end{Xexample}

\begin{Xexample}{longsaat}{A contextual feature for the `long s' can be convenient as the character does not need to be marked up explicitly.}
  \fontspec{Hoefler Text}[Contextuals=Inner]
  `Inner' swashes can \emph{sometimes}    \\
   contain the archaic long~s.
\end{Xexample}



\subsection{Vertical position}
The \feat{VerticalPosition} feature is used to access things like
subscript (\opt{Inferior}) and superscript (\opt{Superior}) numbers and
letters (and a small amount of punctuation, sometimes).
The \opt{Ordinal} option is (supposed to be)
contextually sensitive to only raise characters that appear directly
after a number.
These are shown in \exref{aat-supp}.

\begin{Xexample}{aat-supp}{Vertical position for AAT fonts.}
  \fontspec{Skia}
   Normal
  \fontspec{Skia}[VerticalPosition=Superior]
   Superior
  \fontspec{Skia}[VerticalPosition=Inferior]
   Inferior                \\
  \fontspec{Skia}[VerticalPosition=Ordinal]
   1st 2nd 3rd 4th 0th 8abcde
\end{Xexample}

The \pkg{realscripts} package
(also loaded by \pkg{xltxtra})
redefines the \cmd\textsubscript\ and
\cmd\textsuperscript\ commands to use the above font features,
including for use in footnote labels.

\subsection{Fractions}
Many fonts come with the capability to typeset various forms of
fractional material. This is accessed in \pkg{fontspec} with the
\feat{Fractions} feature, which may be turned \opt{On} or \opt{Off}
in both \AAT\ and OpenType fonts.

In \AAT\ fonts, the `fraction slash' or solidus character, is
to be used to create fractions. When \feat{Fractions} are turned
\opt{On}, then only pre-drawn fractions will be used.
See \exref{aat-frac}.

Using the \opt{Diagonal} option (\AAT\ only), the font will attempt
to create the fraction from superscript and subscript
characters.

\edef\caretcc{\the\catcode`\^}
\catcode`\^=12\relax
\begin{Xexample}{aat-frac}{Fractions in AAT fonts. The \texttt{\relax^^^^2044} glyph is the `fraction slash' that may be typed in \MacOSX\ with \textsc{opt+shift+1}; not shown literally here due to font contraints.}
  \fontspec[Fractions=On]{Skia}
   1{^^^^2044}2 \quad 5{^^^^2044}6 \\ % fraction slash
   1/2 \quad 5/6    % regular  slash

  \fontspec[Fractions=Diagonal]{Skia}
         13579{^^^^2044}24680 \\ % fraction slash
   \quad 13579/24680    % regular  slash
\end{Xexample}
\catcode`\^=\caretcc\relax

Some (Asian fonts predominantly) also provide for the
\opt{Alternate} feature shown in \exref{frac-alt}.

\begin{Xexample}{frac-alt}{Alternate design of pre-composed fractions.}
  \fontspec{Hiragino Maru Gothic Pro}
   1/2 \quad 1/4 \quad 5/6 \quad 13579/24680 \\
  \addfontfeature{Fractions=Alternate}
   1/2 \quad 1/4 \quad 5/6 \quad 13579/24680
\end{Xexample}


\subsection{Variants}
The \feat{Variant} feature takes a single numerical input for
choosing different alphabetic shapes. Don't mind my fancy \exref{aat-var}
\texttt{:)} I'm just looping through the nine~(\,!\,) variants of
Zapfino.

\begin{Xexample}[firstline=2,lastline=9]{aat-var}{Nine variants of Zapfino.}
  \Huge \rule{0pt}{2cm}
  \newcounter{var}
  \whiledo{\value{var}<9}{%
    \edef\1{%
    \noexpand\fontspec[Variant=\thevar,
      Color=0099\thevar\thevar]{Zapfino}}\1%
    \makebox[0.75\width]{d}%
    \stepcounter{var}}
  \hspace*{2cm}
\end{Xexample}

See \vref{sec:newfeatures} for a way to assign names to variants,
which should be done on a per-font basis.

\subsection{Alternates}

Selection of \feat{Alternate}s \emph{again}
must be done numerically; see \exref{aat-alt}.
See \vref{sec:newfeatures} for a way to assign names to alternates,
which should be done on a per-font basis.

\begin{Xexample}{aat-alt}{Alternate shape selection must be numerical.}
  \fontspec{Hoefler Text Italic}[Alternate=0]
   Sphinx Of Black Quartz, {\scshape Judge My Vow} \\
  \fontspec{Hoefler Text Italic}[Alternate=1]
   Sphinx Of Black Quartz, {\scshape Judge My Vow}
\end{Xexample}


\subsection{Style}

The options of the \feat{Style} feature
are defined in \AAT\ as one of the following: \opt{Display},
\opt{Engraved}, \opt{IlluminatedCaps}, \opt{Italic},
\opt{Ruby},\footnotemark\ \opt{TallCaps}, or \opt{TitlingCaps}.
\footnotetext{`Ruby' refers to a small optical size, used in
Japanese typography for annotations.}

Typical examples for these features are shown in \ref{sec:ot-feat-style}.






\subsection{CJK shape}
There have been many standards for how CJK ideographic
glyphs are `supposed' to look. Some fonts will contain many alternate
glyphs in order to be able to display these gylphs
correctly in whichever form is appropriate. Both \AAT\ and OpenType
fonts support the following \feat{CJKShape} options:
\opt{Traditional}, \opt{Simplified}, \opt{JIS1978}, \opt{JIS1983},
\opt{JIS1990}, and \opt{Expert}. OpenType also supports the \opt{NLC} option.

\subsection{Character width}
See \vref{sec:CharacterWidth} for relevant examples; the features are
the same between OpenType and \AAT\ fonts.
\AAT\ also allows \feat{CharacterWidth}|=|\opt{Default} to return to
the original font settings.







\subsection{Vertical typesetting}

TODO: improve!

\XeTeX\ provides for vertical typesetting simply with the ability to rotate
the individual glyphs as a font is used for typesetting, as shown in
\exref{vert}.

\begin{Xexample}[firstline=2]{vert}{Vertical typesetting.}
  \def\verttext{共産主義者は}
  \fontspec{Hiragino Mincho Pro}
  \verttext

  \fontspec{Hiragino Mincho Pro}[Renderer=AAT,Vertical=RotatedGlyphs]
  \rotatebox{-90}{\verttext}% requires the graphicx package
\end{Xexample}

No actual provision is made for typesetting top-to-bottom
languages; for an example of how to do this, see the vertical Chinese
example provided in the \XeTeX\ documentation.




\subsection{Diacritics}
Diacritics are marks, such as the acute accent or the tilde, applied to letters; they usually indicate a change in pronunciation.
In Arabic scripts, diacritics are used to indicate vowels.
You may either choose
to \opt{Show}, \opt{Hide} or \opt{Decompose} them in \AAT\ fonts.
The \opt{Hide} option is for scripts such as Arabic which may be
displayed either with or without vowel markings. E.g.,
\verb|\fontspec[Diacritics=Hide]{...}|

Some older fonts distributed with \MacOSX\ included `|O/|' \etc\ as shorthand for writing `\O' under the label of the \feat{Diacritics} feature. If you come across such fonts, you'll
want to turn this feature off (imagine typing |hello/goodbye| and
getting `hell\o goodbye' instead!) by decomposing the two characters
in the diacritic into the ones you actually
want. I recommend using
the proper \LaTeX\ input conventions for obtaining such characters
instead.



\subsection{Annotation}
Various Asian fonts are equipped with a more extensive range of
numbers and numerals in different forms. These are accessed through
the \feat{Annotation} feature with the following
options: \opt{Off},
\opt{Box}, \opt{RoundedBox}, \opt{Circle}, \opt{BlackCircle},
\opt{Parenthesis}, \opt{Period}, \opt{RomanNumerals}, \opt{Diamond},
\opt{BlackSquare}, \opt{BlackRoundSquare}, and \opt{DoubleCircle}.



\part{Programming interface}

This is the beginning of some work to provide some hooks that use
\pkg{fontspec} for various macro programming purposes.


\section{Defining new features} \label{sec:newfeatures}
This package cannot hope to contain every possible font
feature. Three commands are provided for selecting font features
that are not provided for out of the box. If you are using
them a lot, chances are I've left something out, so please let me
know.

\DescribeMacro{\newAATfeature}
New \AAT\ features may be created with this command:\par
{\centering\cmd\newAATfeature\marg{feature}\marg{option}\marg{feature code}\marg{selector code}\par}\noindent
Use the \XeTeX\ file \path{AAT-info.tex} to obtain the code numbers.
See \exref{newAATfeat}.

\begin{Xexample}{newAATfeat}{Assigning new \AAT\ features.}
  \newAATfeature{Alternate}{HoeflerSwash}{17}{1}
  \fontspec{Hoefler Text Italic}[Alternate=HoeflerSwash]
   This is XeTeX by Jonathan Kew.
\end{Xexample}


\DescribeMacro{\newopentypefeature}
New OpenType features may be created with this command:\par
{\centering\cmd\newopentypefeature\marg{feature}\marg{option}\marg{feature tag}\par}
The synonym \cs{newICUfeature} is deprecated.

Here's what it would look like in practise:
\begin{Verbatim}
\newopentypefeature{Style}{NoLocalForms}{-locl}
\end{Verbatim}

\DescribeMacro{\newfontfeature}
In case the above commands do not accommodate the desired font feature
(perhaps a new \XeTeX\ feature that \pkg{fontspec} hasn't been updated
to support), a command is provided to pass arbitrary input into the
font selection string:\par
{\centering\cmd{\newfontfeature}\marg{name}\marg{input string}\par}

For example, Zapfino
contains the feature `Avoid d-collisions'. To access it
with this package, you could do some like that shown in \exref{avoidd}.
(For some reason this feature doesn't appear to be working although \pkg{fontspec} is doing the right thing. To be investigated.)

\begin{Xexample}{avoidd}{Assigning new arbitary features.}
  \newfontfeature{AvoidD}{Special=Avoid d-collisions}
  \newfontfeature{NoAvoidD}{Special=!Avoid d-collisions}
  \fontspec{Zapfino}[AvoidD,Variant=1]
   sockdolager rubdown               \\
  \fontspec{Zapfino}[NoAvoidD,Variant=1]
   sockdolager rubdown
\end{Xexample}

The advantage to using the \cmd\newAATfeature\ and \cmd\newopentypefeature\
commands instead of \cs{newfontfeature} is that they check if the selected font actually contains the desired font
feature at load time. By contrast, \cmd\newfontfeature\ will not give a warning
for improper input.

\section{Going behind \pkg{fontspec}'s back}
Expert users may wish not to use \pkg{fontspec}'s feature handling at all,
while still taking advantage of its \LaTeX\ font selection conveniences. The
\feat{RawFeature} font feature allows literal \XeTeX\ font feature selection
when you happen to have the OpenType feature tag memorised.

\begin{Xexample}{raw}{Using raw font features directly.}
  \fontspec{texgyrepagella-regular.otf}[RawFeature=+smcp]
  Pagella small caps
\end{Xexample}

Multiple features can either be included in a single declaration:\par
{\centering|[RawFeature=+smcp;+onum]|\par}
\noindent or with multiple declarations:\par
{\centering|[RawFeature=+smcp, RawFeature=+onum]|\par}

\section{Renaming existing features \& options}
\label{sec:aliasfontfeature}

\DescribeMacro{\aliasfontfeature}
If you don't like the name of a particular font feature,
it may be aliased to another with the
\cs{aliasfontfeature}\marg{existing name}\marg{new name} command,
such as shown in \exref{alias}.

\begin{Xexample}{alias}{Renaming font features.}
  \aliasfontfeature{ItalicFeatures}{IF}
  \fontspec{Hoefler Text}[IF = {Alternate=1}]
  Roman Letters \itshape And Swash
\end{Xexample}

Spaces in feature (and option names, see below) \emph{are} allowed. (You may have
noticed this already in the lists of OpenType scripts and languages).

\DescribeMacro{\aliasfontfeatureoption}
If you wish to change the name of a font feature option,
it can be aliased to another with the command
\cs{aliasfontfeatureoption}\marg{font feature}\marg{existing name}\marg{new name}, such as shown in \exref{aliasopt}.

\begin{Lexample}{aliasopt}{Renaming font feature options.}
  \aliasfontfeature{VerticalPosition}{Vert Pos}
  \aliasfontfeatureoption{VerticalPosition}{ScientificInferior}{Sci Inf}
  \fontspec{LinLibertine_R.otf}[Vert Pos=Sci Inf]
   Scientific Inferior: 12345
\end{Lexample}

This example demonstrates an important point: when aliasing the feature
options, the \emph{original} feature name must be used when declaring
to which feature the option belongs.

Only feature options that exist as sets of fixed strings may be altered in
this way. That is, \opt{Proportional} can be aliased to \opt{Prop} in the
\feat{Letters} feature, but \opt{550099BB} cannot be substituted for \opt{Purple}
in a \feat{Color} specification. For this type of thing, the \cmd\newfontfeature\
command should be used to declare a new, \eg, \feat{PurpleColor} feature:
\begin{Verbatim}
  \newfontfeature{PurpleColor}{color=550099BB}
\end{Verbatim}
Except that this example was written before support for named colours was
implemented. But you get the idea.

\section{Programming details}
\label{sec:api}

\subsection{Variables}

\DescribeMacro{\l_fontspec_family_tl}
\DescribeMacro{\l_fontspec_font}
In some cases, it is useful to know what the \LaTeX\ font family
of a specific \pkg{fontspec} font is. After a \cmd\fontspec-like
command, this is stored inside the \cmd\l_fontspec_family_tl\ macro.
Otherwise, \LaTeX's own \cmd\f@family\ macro can be useful here,
too.
The raw \TeX\ font that is defined from the `base' font in the family is stored in \cmd{\l_fontspec_font}.

\DescribeMacro{\g_fontspec_encoding_tl}
Package authors who need to load fonts with legacy \LaTeX\ \NFSS\ commands may also need to know what the default font encoding is.
Since this has changed from \texttt{EU1}/\texttt{EU2} to \texttt{TU}, it is best to use the variables \cs{g_fontspec_encoding_tl} or \cs{UTFencname} instead.

\subsection{Functions for loading new fonts and families}

\begin{macro}{\fontspec_set_family:Nnn}
\darg{\LaTeX\ family}
\darg{fontspec features}
\darg{font name}
Defines a new \NFSS\ family from given \meta{features} and \meta{font},
and stores the family name in the variable \meta{family}.
This font family can then be selected with standard \LaTeX\ commands
\cs{fontfamily}\marg{family}\cs{selectfont}.
See the standard \pkg{fontspec} user commands for applications of this
function.
\end{macro}

\begin{macro}{\fontspec_set_fontface:NNnn}
\darg{primitive font}
\darg{\LaTeX\ family}
\darg{fontspec features}
\darg{font name}
Variant of the above in which the primitive \TeX\ font command is stored in
the variable \meta{primitive font}.
If a family is loaded (with bold and italic shapes) the primitive font
command will only select the regular face.
This feature is designed for \LaTeX\ programmers who need to
perform subsequent font-related tests on the \meta{primitive font}.
\end{macro}


\subsection{Functions for querying font families}

The following functions in \pkg{expl3} syntax may be used
for writing code that interfaces with \pkg{fontspec}-loaded fonts.
All of the following conditionals also exist with |T| and |F|
as well as |TF| suffixes.

\begin{macro}{\fontspec_if_fontspec_font:TF}
Test whether the currently selected font has been loaded by fontspec.
\end{macro}


\begin{macro}{\fontspec_if_aat_feature:nnTF}
Test whether the currently selected font contains the \AAT\
feature (|#1|,|#2|).
\end{macro}


\begin{macro}{\fontspec_if_opentype:TF}
Test whether the currently selected font is an OpenType font.
Always true for \LuaTeX{} fonts.
\end{macro}

\begin{macro}{\fontspec_if_feature:nTF}
Test whether the currently selected font contains the raw OpenType
feature |#1|. E.g.: |\fontspec_if_feature:nTF {pnum} {True} {False}|.
Returns false if the font is not loaded by fontspec or is not an OpenType
font.
\end{macro}

\begin{macro}{\fontspec_if_feature:nnnTF}
Test whether the currently selected font with raw OpenType script tag |#1| and raw OpenType language tag |#2| contains the raw OpenType feature tag |#3|. E.g.: |\fontspec_if_feature:nTF {latn} {ROM} {pnum} {True} {False}|.
Returns false if the font is not loaded by fontspec or is not an OpenType
font.
\end{macro}

\begin{macro}{\fontspec_if_script:nTF}
Test whether the currently selected font contains the raw OpenType
script |#1|. E.g.: |\fontspec_if_script:nTF {latn} {True} {False}|.
Returns false if the font is not loaded by fontspec or is not an OpenType
font.
\end{macro}

\begin{macro}{\fontspec_if_language:nTF}
Test whether the currently selected font contains the raw OpenType language
tag |#1|. E.g.: |\fontspec_if_language:nTF {ROM} {True} {False}|.
Returns false if the font is not loaded by fontspec or is not an OpenType
font.
\end{macro}

\begin{macro}{\fontspec_if_language:nnTF}
Test whether the currently selected font contains the raw OpenType language
tag |#2| in script |#1|. E.g.: |\fontspec_if_language:nnTF {cyrl} {SRB} {True} {False}|.
Returns false if the font is not loaded by fontspec or is not an OpenType
font.
\end{macro}


\begin{macro}{\fontspec_if_current_script:nTF}
Test whether the currently loaded font is using the specified raw
OpenType script tag |#1|.
\end{macro}

\begin{macro}{\fontspec_if_current_language:nTF}
Test whether the currently loaded font is using the specified raw
OpenType language tag |#1|.
\end{macro}


 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\part{The `improvement' of \LaTeXe\ and other packages}
\label{sec:patching}

This part of the package code contains patches to various
\LaTeX\ components and third-party packages to improve the default
behaviour.

\section{Verbatim}
\label{sec:verb}

Many verbatim mechanisms assume the existence of a `visible space' character that exists in the \textsc{ascii} space slot of the typewriter font. This character is known in Unicode as \unichar{2423}{box open}, which looks like this: `\verb*| |'.

When a Unicode typewriter font is used, \LaTeX\ no longer prints visible spaces for the |verbatim*| environment and |\verb*| command. This problem is fixed by using the correct Unicode glyph, and the following packages are patched to do the same:
\pkg{listings}, \pkg{fancyvrb}, \pkg{moreverb}, and \pkg{verbatim}.

In the case that the typewriter font does not contain `\verb*| |', the Latin Modern Mono font is used as a fallback.

\section{Discretionary hyphenation: \cmd\-}
\label{sec:hyphen}

\LaTeX\ defines the macro \cmd\-\ to insert discretionary hyphenation points.
However, it is hard-coded in \LaTeX\ to use the hyphen |-| character. Since \pkg{fontspec}
makes it easy to change the hyphenation character on a per font basis, it would
be nice if \cmd\-\ adjusted automatically --- and now it does.

\section{Commands for old-style and lining numbers}

\DescribeMacro{\oldstylenums}
\DescribeMacro{\liningnums}
\LaTeX's definition of \cs{oldstylenums} relies on strange font encodings.
We provide a \pkg{fontspec}-compatible alternative and while we're at it
also throw in the reverse option as well. Use \cs{oldstylenums}\marg{text}
to explicitly use old-style (or lowercase) numbers in \meta{text}, and
the reverse for \cs{liningnums}\marg{text}.

\providecommand\ENDDOCUMENT{\end{document}}
\ENDDOCUMENT
