% \iffalse meta-comment
%
% Copyright 2012-2013 Javier Bezos and Johannes L. Braams.
% Copyright 1989-2012 Johannes L. Braams and any individual authors
% listed elsewhere in this file. 
% All rights reserved.
% 
% This file is part of the Babel system.
% --------------------------------------
% 
% It may be distributed and/or modified under the
% conditions of the LaTeX Project Public License, either version 1.3
% of this license or (at your option) any later version.
% The latest version of this license is in
%   http://www.latex-project.org/lppl.txt
% and version 1.3 or later is part of all distributions of LaTeX
% version 2003/12/01 or later.
% 
% This work has the LPPL maintenance status "maintained".
% 
% The Current Maintainer of this work is Javier Bezos.
% 
% The list of all files belonging to the Babel system is
% given in the file `manifest.bbl. See also `legal.bbl' for additional
% information.
% 
% The list of derived (unpacked) files belonging to the distribution
% and covered by LPPL is defined by the unpacking scripts (with
% extension .ins) which are part of the distribution.
% \fi
% \CheckSum{5011}
%
% \def\filename{babel.dtx}
% \let\thisfilename\filename
%
%\iffalse
% \changes{babel~3.5g}{1996/10/10}{We need at least \LaTeX\ from
%    December 1994}
% \changes{babel~3.6k}{1999/03/18}{We need at least \LaTeX\ from
%    June 1998}
%    \begin{macrocode}
%<package>\NeedsTeXFormat{LaTeX2e}[2005/12/01]
%    \end{macrocode}
%
%% File 'babel.dtx'
%\fi
%%\ProvidesFile{babel.dtx}[2013/05/16 v3.9f The Babel package]
%\iffalse
%
% Babel DOCUMENT-STYLE option for LaTeX version 2.09 or plain TeX;
%% Babel package for LaTeX2e.
%
%% Copyright (C) 1989 -- 2008 by Johannes Braams,
%%                            TeXniek
%%                            all rights reserved.
%% Copyright (C) 2013         by Johannes Braams
%%                            TeXniek
%%                            by Javier Bezos
%%                            all rights reserved.
%
%<*filedriver>
\documentclass{ltxdoc}
\raggedright
\addtolength{\textwidth}{25pt}
\font\manual=logo10 % font used for the METAFONT logo, etc.
\newcommand*\MF{{\manual META}\-{\manual FONT}}
\newcommand*\babel{\textsf{babel}}
\newcommand*\Babel{\textsf{Babel}}
\newcommand*\xetex{\textsf{xetex}}
\newcommand*\luatex{\textsf{luatex}}
\newcommand*\nb[1]{}
\newcommand*\m[1]{\mbox{$\langle$\normalfont\itshape#1\/$\rangle$}}
\newcommand*\langlist{%
  \meta{language}\texttt{,}\meta{language}\texttt{,}...}
\newcommand*\langvar{\m{lang}}
\newcommand*\note[1]{}
\newcommand*\bsl{\protect\bslash}
\newcommand*\Lopt[1]{\textsf{#1}}
\newcommand*\Lenv[1]{\textsf{#1}}
\newcommand*\menv[1]{\char`\{#1\char`\}}
\newcommand*\Eenv[1]{%
  \quad\ldots\quad   
  \texttt{\color{thered}\string\end\menv{#1}}}
\newcommand*\file[1]{\texttt{#1}}
\newcommand*\cls[1]{\texttt{#1}}
\newcommand*\pkg[1]{\texttt{#1}}
\addtolength{\oddsidemargin}{1em}
% Stolen and adapted from microtype:
\usepackage{color}
\definecolor{thered}  {rgb}{0.65,0.04,0.07}
\definecolor{thegreen}{rgb}{0.06,0.44,0.08}
\definecolor{thegrey} {gray}{0.8}
\definecolor{theshade}{rgb}{1,1,0.97}
\definecolor{theframe}{gray}{0.6}
\definecolor{lightgray}{gray}{0.95}
\IfFileExists{listings.sty}{
  \usepackage{listings}
  \lstset{
    % gobble=1,
    columns=flexible,
    keepspaces,
    basicstyle=\MacroFont,
    keywords=[0]{\selectlanguage,\foreignlanguage,\defineshorthand,
     \babelhyphen,\babelhyphenation,\spanishhyphenmins,\addto,
     \StartBabelCommands,\SetString,\EndBabelCommands,\shorthandoff,
     \languageshorthands,\useshorthands,\AddBabelHook,\SetStringLoop,
     \SetCase,\AfterBabelLanguage},
    keywordstyle=[0]\color{thered},
    keywords=[1]{ngerman,italian,dutch,english,main,esperanto,
     frenchb,shorthands,extrasfrench,extrasrussian,extrasenglish,
     stringprocess,afterextras,latin,medieval,spanish,notilde,
     lcroman,danish},
    keywordstyle=[1]\color{thegreen},
    comment=[l]\%,
    commentstyle=\color{thegrey}\itshape,
    alsoother={0123456789_},
    frame=single,
    backgroundcolor=\color{theshade},
    rulecolor=\color{theframe},
    framerule=\fboxrule,
  }
  \let\verbatim\relax
  \lstnewenvironment{verbatim}[1][]{\lstset{##1}}{}
}{}
\def\PrintDescribeMacro#1{%
  \strut\MacroFont\color{thered}\normalsize\string#1}
\def\Describe#1{%
  \par\penalty-500\vskip3ex\noindent
  \DescribeMacro{#1}\args}
\def\DescribeOther{\vskip-4ex\Describe}
\makeatletter
\def\args#1{%
  \def\bbl@tempa{#1}%
  \ifx\bbl@tempa\@empty\else#1\vskip1ex\fi\ignorespaces}
\makeatother
\begin{document}
\title{Babel, a multilingual package for use with \LaTeX's standard
   document classes\thanks{During the development ideas from Nico
   Poppelier, Piet van Oostrum and many others have been used.
   Bernd Raichle has provided many helpful suggestions.}}
\author{Johannes Braams\\
        Kersengaarde 33\\
        2723 BP Zoetermeer\\
        The Netherlands\\
        \normalsize For version 3.9, Javier Bezos\\
        \normalsize \texttt{www.tex-tipografia.com}}

\date{Typeset \today}

\maketitle

\begin{abstract}
  The standard distribution of \LaTeX\ contains a number of document
  classes that are meant to be used, but also serve as examples for
  other users to create their own document classes.  These document
  classes have become very popular among \LaTeX\ users. But it should
  be kept in mind that they were designed for American tastes and
  typography. At one time they even contained a number of hard-wired
  texts.

  This report describes \babel{}, a package that makes use of the
  capabilities of \TeX\ version 3 and, to some extent, \xetex{} and
  \luatex, to provide an environment in which documents can be typeset
  in a language other than US English, or in more than one language.
  However, no attempt has been done to take full advantage of the
  features provided by the latter, which would require a completely
  new core (as for example \file{polyglossia} or as part of \LaTeX3).
\end{abstract}

\tableofcontents

\section{The user interface}\label{U-I}

The user interface of this package is quite simple. It consists of a
set of commands that switch from one language to another, and a set of
commands that deal with shorthands. It is also possible to find out
what the current language is.

In \LaTeX2e\ the preamble of the document:
\begin{verbatim}
\documentclass{article}
\usepackage[dutch,english]{babel}
\end{verbatim}
would tell \LaTeX\ that the document would be written in two
languages, Dutch and English, and that English would be the first
language in use, and the main one. You can also set the main language
explicitly:
\begin{verbatim}
\documentclass{article}
\usepackage[main=english,dutch]{babel}
\end{verbatim}
Another approach is making \Lopt{dutch} and \Lopt{english} global
options in order to let other packages detect and use them:

\begin{verbatim}
\documentclass[dutch,english]{article}
\usepackage{babel}
\usepackage{varioref}
\end{verbatim}

In this last example, the package \texttt{varioref} will also see
the options and will be able to use them.

Languages may be set as global and as package option at the same
time, but in such a case you should set explicitly the main language
with the package option |main|:
\begin{verbatim}
\documentclass[italian]{babel}
\usepackage[ngerman,main=italian]{babel}
\end{verbatim}

\fbox{New 3.9c} The basic behaviour of some languages can be modified
when loading \babel. Modifiers are set after the language name, and
are prefixed with a dot (only when the language is set as package
option -- neither global options nor the |main| key accept them). An
example is (spaces are not significant and it can be written closed,
too):
\begin{verbatim}
\usepackage[latin .medieval, spanish .notilde .lcroman, danish]{babel}
\end{verbatim}

Attributes (described below) are considered modifiers, ie, you can
set an attribute by including it in the modifiers list. However,
modifiers is a more general mechanism.

Currently \babel{} provides no standard interface for
scripts. Languages sharing the same non-Latin script may define macros
to switch them (eg, |\textcyrillic|), but be aware they may also set
the language to a certain default. (Future versions might add such an
interface.)

Because of the way \babel{} has evolved, ``language'' can refer to (1)
a set of hyphenation patters as preloaded into the format, (2) a
package option, (3) an |ldf| file, and (4) a name used in the document
to select a language or dialect. So, a package option refers to a
language in a generic way -- sometimes it is the actual language name
used to select it, sometimes it is a file name loading a language with
a different name, sometimes it is a file name loading several
languages. Please, read the documentation for specific languages for
further info.

Loading directly |sty| files in \LaTeX{} (ie,
|\usepackage|\marg{language}) is deprected and you will get the error
``You have used an old interface to call babel''.

In Plain, load languages styles with |\input| and then use
|\begindocument| (the latter is defined by \babel):
\begin{verbatim}
\input estonian.sty
\begindocument
\end{verbatim}
Note not all languages provide a |sty| file and some of them are
not compatible with Plain.

\subsection{Selecting languages}

The main language is selected automatically when the |document|
environment begins.

\Describe\selectlanguage{\marg{language}}
When a user wants to switch from one language to another he can
do so using the macro |\selectlanguage|. This macro takes the
language, defined previously by a language definition file, as
its argument. It calls several macros that should be defined in
the language definition files to activate the special definitions
for the language chosen.

If used inside braces there might be some non-local changes, as this
would be  roughly equivalent to:
\begin{verbatim}
{\selectlanguage{<inner-language>} ...}\selectlanguage{<outer-language>}
\end{verbatim}
If you want a change which is really local, you must enclose this
code with an additional grouping, like braces |{}|.

This command can be used as environment, too.

\Describe{\begin\menv{otherlanguage}}{\marg{language}\Eenv{otherlanguage}}

The environment \Lenv{otherlanguage} does basically the same as
|\selectlanguage|, except the language change is (mostly) local to the
environment. This environment is required for intermixing
left-to-right typesetting with right-to-left typesetting.
The language to switch to is specified as an
argument to |\begin{otherlanguage}|.

Actually, there might be some non-local changes, as this environment
is roughly equivalent to:
\begin{verbatim}
\begingroup
\selectlanguage{<inner-language>}
...
\endgroup
\selectlanguage{<outer-language>}
\end{verbatim}
If you want a change which is really local, you must enclose this
environment with and additional grouping, like braces |{}|.

Spaces after the environment are ignored.

\Describe\foreignlanguage{\oarg{language}\marg{text}}
The command |\foreignlanguage| takes two arguments; the second
argument is a phrase to be typeset according to the rules of the
language named in its first argument. This command (1) only
switches the extra definitions and the hyphenation rules for the
language, \emph{not} the names and dates, (2) does not send
information about the language to auxiliary files (i.e., the
surrounding language is still in force), and (3) it works even if
the language has not been set as package option (but in such a
case it only sets the hyphenation patterns).

\Describe{\begin\menv{otherlanguage*}}%
{\marg{language}\Eenv{otherlanguage*}}

Same as |\foreignlanguage| but as environment. Spaces after the
environment are \textit{not} ignored.

\Describe\languagename{}
The control sequence |\languagename| contains the name of the
current language. However, due to some internal inconsistencies in
catcodes it should \textit{not} be used to test its value (use
\textsf{iflang}, by Heiko Oberdiek).

\Describe\iflanguage{\marg{language}\marg{true}\marg{false}}

If more than one language is used, it might be necessary to know which
language is active at a specific time. This can be checked by a call
to |\iflanguage|, but note here ``language'' is used in the \TeX\
sense, as a set of hyphenation patterns, and \textit{not} as its
\textsf{babel} name. This macro takes three arguments.  The first
argument is the name of a language; the second and third arguments are
the actions to take if the result of the test is true or false
respectively. The advice about |\languagename| also applies here --
use \textsf{iflang} instead of |\iflanguage| if possible.

\Describe{\begin\menv{hyphenrules}}{\marg{language}\Eenv{hyphenrules}}

The environment \Lenv{hyphenrules} can be used to select \emph{only}
the hyphenation rules to be used (it can be used as command,
too). This can for instance be used to select `nohyphenation',
provided that in \file{language.dat} the `language'
\textsf{nohyphenation} is defined by loading \file{zerohyph.tex}. It
deactivates language shorthands, too (but not user shorthands).

Except for these simple uses, |hyphenrules| is discouraged and
|otherlanguage*| (the starred version) is preferred, as the former
does not take into account possible changes in encodings or characters
like, say, |'| done by some languages (eg, \textsf{italian},
\textsf{frenchb}, \textsf{ukraineb}). To set hyphenation exceptions,
use |\babelhyphenation| (see below).

\subsection{Shorthands}

A \textit{shorthand} is a sequence of one or two characters that
expands to arbitrary \TeX{} code.

Shorthands can be used for different kinds of things, as for example:
(1) in some languages shorthands such as |"a| are defined to be able
to hyphenate the word if the encoding is OT1; (2) in some languages
shorthands such as |!| are used to insert the right amount of white
space; (3) several kinds of discretionaries and breaks can be inserted
easily with |"-|, |"=|, etc.

The package \textsf{inputenc} as well as \xetex{} an \luatex{} have
alleviated entering non-ASCII characters, but minority languages and
some texts can still require characters not directly available in the
keyboards (and sometimes not even as separated or precomposed Unicode
characters). As to the point 2, now \textsf{pdfTeX} provides
|\knbccode|. Tools of point 3 can be still very useful in general.

There are three levels of shorthands: \textit{user},
\textit{language}, and \textit{system} (by order of
precedence). Version 3.9 introduces the \textit{language user}
level on top of the user level, as described below. In most
cases, you will use only shorthands provided by languages.

Please, note the following:
\begin{enumerate}
\item Activated chars used for two-char shorthands cannot be
  followed by a closing brace |}| and the spaces following are
  gobbled. With one-char shorthands (eg, |:|), they are preserved.
\item If on a certain level (system, language, user) there is a
  one-char shorthand, two-char ones starting with that 
  char and on the same level are ignored.
\end{enumerate}

\Describe{\shorthandon}{\marg{shorthands-list}}
\DescribeOther{\shorthandoff}{%
\colorbox{thegrey}{\ttfamily\hskip-.2em*\hskip-.2em}%
\marg{shorthands-list}}
It is sometimes necessary to switch a shorthand
character off temporarily, because it must be used in an
entirely different way. For this purpose, the user commands
|\shorthandoff| and |\shorthandon| are provided. They each take a
list of characters as their arguments.

The command |\shorthandoff| sets the |\catcode| for each of the
characters in its argument to other (12); the command |\shorthandon|
sets the |\catcode| to active (13). Both commands only work on `known'
shorthand characters. If a character is not known to be a shorthand
character its category code will be left unchanged.

\fbox{New 3.9} Note however, |\shorthandoff| does not behave as
you would expect with characters like |~| or |^|, because they
usually are not ``other''. For them |\shorthandoff*| is provided,
so that with
\begin{verbatim}
\shorthandoff*{~^}
\end{verbatim}
|~| is still active, very likely with the meaning of a non-breaking
space, and |^| is the superscript character. The catcodes used are
those when the shorthands are defined, usually when language files are
loaded.

\Describe{\useshorthands}{%
\colorbox{thegrey}{\ttfamily\hskip-.2em*\hskip-.2em}%
\marg{char}}

The command |\useshorthands| initiates the definition of user-defined
shorthand sequences. It has one argument, the character that starts
these personal shorthands.

\fbox{New 3.9} However, user shorthands are not always alive, as they
may be deactivated by languages (for example, if you use |"| for your
user shorthands and switch from \textsf{german} to \textsf{french},
they stop working). Therefore, a starred version
|\useshorthands*|\marg{char} is provided, which makes sure shorthands
are always activated.

Currently, if the option |shorthands| is used, you must include any
character to be activated with |\useshorthands|. This restriction will
be lifted in a future release.

\Describe\defineshorthand{\texttt{[}\langlist\texttt{]}%^^A
     \marg{shorthand}\marg{code}}

The command |\defineshorthand| takes two arguments: the first is
a one- or two-character shorthand sequence, and the second is the
code the shorthand should expand to.

\fbox{New 3.9} An optional argument allows to (re)define language
and system shorthands (some languages do not activate shorthands,
so you may want to add |\languageshorthands|\marg{lang} to the
corresponding |\extras|\m{lang}). By default, user shorthands are
(re)defined.

User shorthands override language ones, which in turn override
system shorthands. Language-dependent user shorthands (new in
3.9) take precedence over ``normal'' user shorthands.

As an example of their applications, let's assume you want a
unified set of shorthand for discretionaries (languages do not
define shorthands consistently, and |"-|, |\-|, |"=| have
different meanings).  You could start with, say:
\begin{verbatim}
\useshorthands*{"}
\defineshorthand{"*}{\babelhyphen{soft}}
\defineshorthand{"-}{\babelhyphen{hard}}
\end{verbatim}
However, behaviour of hyphens is language dependent. For example, in
languages like Polish and Portugese, a hard hyphen inside compound
words are repeated at the beginning of the next line. You could set:
\begin{verbatim}
\defineshorthand[*polish,*portugese]{"-}{\babelhyphen{repeat}}
\end{verbatim}
Here, options with |*| set a language-dependent user shorthand, which
means the generic one above only applies for the rest of languages;
without |*| they would (re)define the language shorthands instead,
which are overriden by user ones.

Now, you have a single unified shorthand (|"-|), with a content-based
meaning (`compound word hyphen') whose visual behavior is that
expected in each context.

\Describe\aliasshorthand{\marg{original}\marg{alias}}

The command |\aliasshorthand| can be used to let another
character perform the same functions as the default shorthand
character. If one prefers for example to use the character |/|
over |"| in typing Polish texts, this can be achieved by entering
|\aliasshorthand{"}{/}|. \emph{Please note} the substitute
character must \textit{not} have been declared before as
shorthand (in such case, |\aliashorthands| is ignored).

The following example shows how to replace a shorthand by another
\begin{verbatim}
\aliasshorthand{~}{^}
\AtBeginDocument{\shorthandoff*{~}}
\end{verbatim}
However, shorthands remember somehow the original character, and the
fallback value is that of the latter. So, in this example, if no
shorthand if found, |^| expands to a non-breaking space, because this
is the value of |~| (internally, |^| calls |\active@char~| or
|\normal@char~|). Furthermore, if you change the |system| value of |^|
with |\defineshorthand| nothing happens.

\Describe\languageshorthands{\marg{language}} The command
|\languageshorthands| can be used to switch the shorthands on the
language level. It takes one argument, the name of a language or
|none| (the latter does what its name suggests).\footnote{Actually,
any name not corresponding to a language group does the same as
\texttt{none}. However, follow this convention because it might be
enforced in future releases of \babel{} to catch possible errors.}
Note that for this to work the language should have been specified as
an option when loading the \babel\ package.  For example, you can use
in \textsf{english} the shorthands defined by \textsf{ngerman} with
\begin{verbatim}
\addto\extrasenglish{\languageshorthands{ngerman}}
\end{verbatim}

Very often, this is a more convenient way to deactivate shorthands
than |\shorthandoff|, as for example if you want to define a macro
to easy typing phonetic characters with \textsf{tipa}:
\begin{verbatim}
\newcommand{\myipa}[1]{{\languageshorthands{none}\tipaencoding#1}}
\end{verbatim}

\Describe\babelshorthand{\marg{shorthand}}
With this command you can use shorthands even if (1) not activated in
\texttt{shorthands} (in this case only shorthands for the current
language are taken into account, ie, not user shorthands), (2) turned
off with |\shorthandoff| or (3) deactivated with |\bbl@deactivate|;
for example, \verb|\babelshorthand{"u}| or \verb|\babelshorthand{:}|.
(You can conveniently define your own macros, or even you own user
shorthands provided they do not ovelap.)

For your records, here is a list of shorthands, but you must check
them, as they may change:\footnote{Thanks to Enrico Gregorio}

\begin{description}
\itemsep=-\parskip
\item[Languages with no shorthands] Croatian, English (any variety),
  Indonesian, Hebrew, Interlingua, Irish, Lower Sorbian, Malaysian,
  North Sami, Romanian, Scottish, Welsh
\item[Languages with only \texttt{"} as defined shorthand character]
  Albanian, Bulgarian, Danish, Dutch, Finnish, German (old and new
  orthography, also Austrian), Icelandic, Italian, Norwegian, Polish,
  Portuguese (also Brazilian), Russian, Serbian (with Latin script),
  Slovene, Swedish, Ukrainian, Upper Sorbian
\item[Basque] |" ' ~|
\item[Breton] |: ; ? !|
\item[Catalan] |" ' `|
\item[Czech] |" -|
\item[Esperanto] |^|
\item[Estonian] |" ~|
\item[French] (all varieties) |: ; ? !|
\item[Galician] |" . ' ~ < >|
\item[Greek] |~|
\item[Hungarian] |`|
\item[Kurmanji] |^|
\item[Latin] |" ^ =|
\item[Slovak] |" ^ ' -|
\item[Spanish] |" . < > '|
\item[Turkish] |: ! =|
\end{description}
In addition, the \babel{} core declares |~| as a one-char shorthand
which is let, like the standard |~|, to a non breaking
space.\footnote{This declaration serves to nothing, but it is
preserved for backward compatibility.}


\subsection{Package options}

\fbox{New 3.9}
These package options are processed before language options, so
that they are taken into account irrespective of its order.

\Describe{shorthands=}{\meta{char}\meta{char}...
$\string|$ \texttt{off}}
The only language shorthands activated
are those given, like, eg:
\begin{verbatim}
\usepackage[esperanto,frenchb,shorthands=:;!?]{babel}
\end{verbatim} 
If \verb|'| is included, \texttt{activeacute} is set; if \verb|`|
is included, \texttt{activegrave} is set.  Active characters (like
\verb|~|) should be preceded by \verb|\string| (otherwise they
will be expanded by \LaTeX{} before they are passed to the package
and therefore they will not be recognized); however, |t| is provided
for the common case of |~| (as well as |c| for the comma).

With |shorthands=off| no language shorthands are defined,
As some languages use this mechanism for tools not available
otherwise, a macro \verb|\babelshorthand| is defined, which allows
using them; see above.

\Describe{safe=}{\texttt{none} $\string|$ \texttt{ref}
$\string|$ \texttt{bib}}
Some \LaTeX{} macros are redefined so that using
shorthands is safe. With \texttt{safe=bib} only |\nocite|, |\bibcite| and
|\bibitem| are  redefined. With |safe=ref| only |\newlabel|,  |\ref|
and |\pageref| are  redefined (as well as a few macros from
\textsf{varioref} and \textsf{ifthen}). With |safe=none| no macro is
redefined. Of course, in such a case you cannot use shorthands in
these macros.

\Describe{math=}{\texttt{active} $\string|$ \texttt{normal}}
Shorthands are mainly intended for text, not for math. By setting this
option with the value |normal| they are deactivated in math mode
(default is |active|) and things like |${a'}$| (a closing brace after
a shorthand) are not a source of trouble any more.

\Describe{config=}{\meta{file}} Instead of loading |bblopts.cfg|,
the file \meta{file}\texttt{.cfg} is loaded.

\Describe{main=}{\meta{language}} Sets the main language, as
explained above, ie, this language is always the last loaded. The
language may be also given as package or global option or not.

\Describe{headfoot=}{\meta{language}} By default, headlines and footlines are
not touched (only marks), and if they contain language dependent
macros (which is not usual) there may be unexpected results. With
this option you may set the language in heads and foots.

\Describe{noconfigs}{} Global and
language default config files are not loaded, so you can make sure
your document is not spoilt by an unexpected \texttt{.cfg}
file. The key |config| still works.

\Describe{showlanguages}{} Prints to the log the list of languages
loaded when the format was created: number (remember dialects can
share it), name, hyphenation file and exceptions file. 

\Describe{strings=}{\texttt{generic} $\string|$ \texttt{unicode}
$\string|$ \texttt{encoded} $\string|$ \meta{label} $\string|$ \meta{font encoding}}
Selects the encoding
of strings in languages supporting this feature. Predefined labels
are |generic| (for traditional \TeX), |unicode| (for engines like
\xetex{} and \luatex) and |encoded| (for special cases requiring mixed
encodings). Other allowed values are font encoding codes (|T1|, |T2A|,
|LGR|, |L7X|...), but only in languages supporting them. 

\vspace{3ex}
(The following three options have been available in previous versions
of \babel.)

\Describe{KeepShorthandsActive}{}
Tells babel not to deactivate shorthands after loading a language
file, so that they are also availabe in the preamble.

\Describe{activeacute}{} For some languages \babel\ supports this
options to set |'| as a shorthand in case it is not done by default.

\Describe{activegrave}{}
Same for |`|.

\subsection{The \texttt{base} option}

With this package option \babel{} just loads some basic macros (those
in |switch.def|), defines |\AfterBabelLanguage| and exits. It also
selects the hyphenations patterns for the last language passed as
option (by its name in |language.dat|). There are two main uses:
classes and packages, and as a last resort in case there are, for some
reason, incompatible languages. It can be used if you just want to
select the hyphenations patterns of a single language.

\Describe\AfterBabelLanguage{\marg{option-name}\marg{code}}

This command is currently the only provided by |base|. Executes
\meta{code} when the file loaded by the corresponding package option
is finished (at |\ldf@finish|). The setting is global. So
\begin{verbatim}
\AfterBabelLanguage{frenchb}{...}
\end{verbatim}
does ... at the end of |frenchb.ldf|. It can be used in |ldf| files,
too, but in such a case the code is executed only if
\meta{option-name} is the same as |\CurrentOption| (which could not
be the same as the option name as set in |\usepackage|!). 

For example, consider two languages \textsf{foo} and \textsf{bar}
defining the same |\macro| with |\newcommand|. An error is raised if
you attempt to load both. Here is a way to overcome this problem:
\begin{verbatim}
\usepackage[base]{babel}
\AfterBabelLanguage{foo}{%
  \let\macroFoo\macro
  \let\macro\relax}
\usepackage[foo,bar]{babel}
\end{verbatim}

\subsection{Hooks}

\fbox{New 3.9} A hook is code to be executed at certain events. Some
hooks are predefined when \luatex{} and \xetex{} are used.

\Describe\AddBabelHook{\marg{name}\marg{event}\marg{code}}

The same name can be applied to several events.  Hooks may be enabled
and disabled for all defined events with
|\EnableBabelHook|\marg{name}, |\DisableBabelHook|\marg{name}

Current events are: |adddialect|, |write|, |beforeextras|,
|afterextras|, |patterns|, |hyphenation|, |defaultcommands|, |encodedcommands|,
|stopcommands| and |stringprocess|. Four events are used in
\file{hyphen.cfg}, which are handled in a quite different way for
efficiency reasons -- these are |everylanguage|, |loadkernel|,
|loadpatterns| and |loadexceptions|, which, unlike the precedent ones,
only have a single hook and replace a default definition. (Names
containing the string |babel| are reserved; they are used, for
example, by |\useshortands*| to add a hook for the event
|afterextras|.)

In some of them you can use one or two \TeX{} parameters (|#1|, |#2|),
with the meaning given below:
\begin{description}
\renewcommand\makelabel[1]{%
  \hspace\labelsep\normalfont\ttfamily\color{thered}#1}
\itemsep=-\parskip
\item[everylanguage] (language) Executed before patterns are loaded.
\item[loadkernel] (file) By default loads |switch.def|. It can be used
  to load a different version of this files or to load nothing.
\item[loadpatterns] (patterns file) Loads the patterns file. Used by
  \file{luababel.def}.
\item[loadexceptions] (exceptions file) Loads the exceptions
  file. Used by \file{luababel.def}.
\item[adddialect] (language name, dialect name) Used by
  \file{luababel.def} to load the patterns if not preloaded.
\item[patterns] (language name, language with encoding) Executed just
  after the |\language| has been set. The second argument has the
  patterns name actually selected (in the form of either |lang:ENC| or
  |lang|).
\item[hyphenation] (language name, language with encoding) Executed
  locally just before exceptions given in |\babelhyphenation| are
  actually set.
\item[defaultcommands] Used (locally) in |\StartBabelCommands|.
\item[encodedcommands] (input, font encodings) Used (locally) in
  |\StartBabelCommands|. Both \xetex{} and \luatex{} make sure the
  encoded text is read correctly.
\item[stopcommands] Used to reset the the above, if necessary.
\item[write] This event comes just after the switching commands are
  written to the |aux| file.
\item[beforeextras] Just before executing |\extras|\m{language}. This
  event and the next one should not contain language-dependent code
  (for that, add it to |\extras|\m{language}).
\item[afterextras] Just after executing |\extras|\m{language}. For
  example, the following deactivates shorthands in all languages:
\begin{verbatim}
\AddBabelHook{noshort}{afterextras}{\languageshorthands{none}}
\end{verbatim}
\item[stringprocess] Intead of a parameter, you can manipulate the
  macro |\BabelString| containing the string to be defined with
  |\SetString|. For example, to use an expanded version of the string
  in the definition, write:
\begin{verbatim}
\AddBabelHook{myhook}{stringprocess}{%
  \protected@edef\BabelString{\BabelString}}
\end{verbatim}
\end{description}

\subsection{Hyphen tools}

\Describe\babelhyphen{%
  \colorbox{thegrey}{\ttfamily\hskip-.2em*\hskip-.2em}\marg{type}}
\DescribeOther\babelhyphen{%
  \colorbox{thegrey}{\ttfamily\hskip-.2em*\hskip-.2em}\marg{text}}

\fbox{New 3.9} It is customary to classify hyphens in two types: (1)
\textit{explicit} or \textit{hard hyphens}, which in \TeX\ are
entered as \verb|-|, and (2) \textit{optional} or \textit{soft
hyphens}, which are entered as \verb|\-|. Strictly, a \textit{soft
hyphen} is not a hyphen, but just a breaking oportunity or, in
\TeX\ terms, a ``discretionary''; a \textit{hard hyphen} is a hyphen
with a breaking oportunity after it. A further type is a
\textit{non-breaking hyphen}, a hyphen without a breaking
oportunity.

In \TeX, \verb|-| and \verb|\-| forbid further breaking oportunities
in the word. This is the desired behaviour very often, but not
always, and therefore many languages provide shorthands for these
cases. Unfortunately, this has not been done consistently: for
example, in Dutch, Portugese, Catalan or Danish, \verb|"-| is a hard
hyphen, while in German, Spanish, Norwegian, Slovak or Russian, it
is a soft hyphen. Furthermore, some of them even redefine |\-|, so
that you cannot insert a soft hyphen without breaking oportunities
in the rest of the word.

Therefore, some macros are provide with a set of basic ``hyphens''
which can be used by themselves, to define a user shorthand, or even
in language files.
\begin{itemize}
\item |\babelhyphen{soft}| and |\babelhyphen{hard}| are self
  explanatory.
\item |\babelhyphen{repeat}| inserts a hard hyphen which is repeated
  at the beginning of the next line, as done in languages like
  Polish, Portugese and Spanish.
\item |\babelhyphen{nobreak}| inserts a hard hyphen without a break
  after it (even if a space follows).
\item |\babelhyphen{empty}| inserts a break oportunity without
  a hyphen at all.
\item |\babelhyphen|\marg{text} is a hard ``hyphen'' using \m{text}
  instead. A typical case is |\babelhyphen{/}|.
\end{itemize}
With all of them hyphenation in the rest of the word is enabled. If
you don't want enabling it, there is a starred counterpart:
|\babelhyphen*{soft}| (which in most cases is equivalent to the
original |\-|), |\babelhyphen*{hard}|, etc.

Note |hard| is also good for isolated prefixes (eg, \textit{anti-})
and |nobreak| for isolated suffixes (eg, \textit{-ism}), but in both
cases |\babelhyphen*{nobreak}| is usually better. 

There are also some differences with \LaTeX: (1) the character used is
that set for the current font, while in \LaTeX{} it is hardwired to
|-| (a typical value); (2) the hyphen to be used in fonts with a
negative |\hyphenchar| is  |-|, like in \LaTeX, but it can be changed to
another value by redefining |\babelnullhyphen|; (3) a break after the
hyphen is forbidden if preceded by a glue ${>}0$~pt (at the beginning
of a word, provided it is not immediately preceded by, say, a
parenthesis).

\Describe\babelhyphenation{\texttt{[}\langlist\texttt{]}%^^A
   \marg{exceptions}}

\fbox{New 3.9} Sets hyphenation exceptions for the languages given
or, without the optional argument, for \textit{all} languages (eg,
proper nouns or common loan words, and of course monolingual
documents). Language exceptions take precedence over global ones.

It can be used only in the preamble, and exceptions are set when the
language is first selected, thus taking into account changes of
|\lccodes|'s done in |\extras|\m{lang} as well as the script specific
encoding (not set in the preamble by default). Multiple
|\babelhyphenation|'s are allowed. For example:
\begin{verbatim}
\babelhyphenation{Wal-hal-la Dar-bhan-ga}
\end{verbatim}

Listed words are saved expanded and therefore it relies on the
LICR. Of course, it also works without the LICR if the input and the
font encondings are the same, like in Unicode based engines.

\subsection{Language attributes}

\DescribeMacro{\languageattribute}
This is a user-level command, to be used in the preamble of a
document (after |\usepackage[...]{babel}|), that declares which
attributes are to be used for a given language. It takes two
arguments: the first is the name of the language; the second,
a (list of) attribute(s) to be used. Attributes must be set in the
preamble and only once -- they cannot be turned on and off.
The command checks whether the language is known in this document
and whether the attribute(s) are known for this language.

Several language definition files use their own methods to set
options. For example, \textsf{frenchb} uses |\frenchbsetup|,
\textsf{magyar} (1.5) uses |\magyarOptions| and \textsf{spanish}
a set of package options (eg, |es-nolayout|). Macros settting
options are also used (eg, |\ProsodicMarksOn| in \textsf{latin}).

\subsection{Languages supported by \babel}

In the following table most of the languages supported by \babel\ are
listed, together with the names of the options  which you can load
\babel\ with for each language. Note this list is open and the
current options may be different. 

\begin{description}
\itemsep=-\parskip
\sffamily
\item[Afrikaans] afrikaans
\item[Bahasa] bahasa, indonesian, indon, bahasai,
    bahasam, malay, meyalu
\item[Basque] basque
\item[Breton] breton
\item[Bulgarian] bulgarian
\item[Catalan] catalan
\item[Croatian] croatian
\item[Czech] czech
\item[Danish] danish
\item[Dutch] dutch
\item[English] english, USenglish, american, UKenglish,
     british, canadian, australian, newzealand
\item[Esperanto] esperanto
\item[Estonian] estonian
\item[Finnish] finnish
\item[French] french, francais, canadien, acadian
\item[Galician] galician
\item[German] austrian, german, germanb, ngerman, naustrian
\item[Greek] greek, polutonikogreek
\item[Hebrew] hebrew
\item[Icelandic] icelandic
\item[Interlingua] interlingua
\item[Irish Gaelic] irish
\item[Italian] italian
\item[Latin] latin
\item[Lower Sorbian] lowersorbian
\item[North Sami] samin
\item[Norwegian] norsk, nynorsk
\item[Polish] polish
\item[Portuguese] portuges, portuguese, brazilian, brazil
\item[Romanian] romanian 
\item[Russian] russian
\item[Scottish Gaelic] scottish
\item[Spanish]  spanish
\item[Slovakian] slovak
\item[Slovenian]  slovene
\item[Swedish] swedish
\item[Serbian] serbian
\item[Turkish] turkish
\item[Ukrainian] ukrainian
\item[Upper Sorbian] uppersorbian
\item[Welsh] welsh
\end{description}

There are more languages not listed above, including \textsf{hindi,
thai, thaicjk, latvian, turkmen, magyar, mongolian, romansh,
lithuanian, spanglish, vietnamese, japanese, pinyin, arabic, farsi,
ibygreek, bgreek, serbianc, frenchle, ethiop} and \textsf{friulan}.

Most of them work out of the box, but some may require extra fonts,
encoding files, a preprocessor or even a complete framework (like
CJK).  For example, if your have the \textsf{velthuis/devnag} package,
you can create a file with extension |.dn|:
\begin{verbatim}
\documentclass{article}
\usepackage[hindi]{babel}
\begin{document}
{\dn devaanaa.m priya.h}
\end{document}
\end{verbatim}
Then you preprocess it with |devnag| \m{file}, which creates
\m{file}|.tex|; you can then typeset the latter with \LaTeX.

\subsection{Tips, workarounds and know issues}

\begin{itemize}
\item If you use the document class \cls{book} \emph{and} you use
  |\ref| inside the argument of |\chapter| (or just use |\ref| inside
  |\MakeUppercase|), \LaTeX\ will keep complaining about an undefined
  label.  To prevent such problems, you could revert to using
  uppercase labels, you can use |\lowercase{\ref{foo}}| inside the
  argument of |\chapter|, or, if you will not use shorthands in
  labels, set the |safe| option to |none| or |bib|.

\item\catcode`\|=12\relax Both \textsf{ltxdoc} and \textsf{babel} use
  \verb|\AtBeginDocument| to change some catcodes, and babel reloads
  \textsf{hhline} to make sure \verb|:| has the right one, so if you
  want to change the catcode of \verb/|/ it has to be done using the
  same method at the proper place, with
\begin{verbatim}
\AtBeginDocument{\DeleteShortVerb{\|}}
\end{verbatim}
  \textit{before} loading babel. This way, when the document begins
  the sequence is (1) make \verb/|/ active (\textsf{ltxdoc}); (2) make
  it unactive (your settings); (3) make babel shorthands active
  (\textsf{babel)}; (4) reload \textsf{hhline} (\textsf{babel}, now
  with the correct catcodes for \verb/|/ and
  \verb|:|).\catcode`\|=\active

\item Documents with several input encodings are not frequent, but
  sometimes are useful. You can set different encodings for different
  languages as the following example shows:
\begin{verbatim}
\addto\extrasfrench{\inputencoding{latin1}}
\addto\extrasrussian{\inputencoding{koi8-r}}
\end{verbatim}
   (A recent version of \textsf{inputenc} is required.)
 \item For the hyphenation to work correctly, lccodes cannot change,
   because \TeX{} only takes into account the values when the
   paragraph is hyphenated, i.e., when it has been
   finished.\footnote{This explains why \LaTeX{} assumes the lowercase
   mapping of T1 and does not provide a tool for multiple
   mappings. Unfortunately, \cs{savinghyphcodes} is not a solution
   either, because lccodes for hyphenation are frozen in the format
   and cannot be changed.} So, if you write a chunk of French text
   with |\foreinglanguage|, the apostrophes might not be taken into
   account. This is a limitation of \TeX, not of
   \babel. Alternatively, you may use |\useshorthands| to activate |'|
   and |\defineshorthand|, or redefine |\textquoteright| (the latter
   is called by the non-ASCII right quote).
\item \verb|\bibitem| is out of sync with \verb|\selectlanguage| in
  the \file{.aux} file. The reason is \verb|\bibitem| uses
  \verb|\immediate| (and others, in fact), while
  \verb|\selectlanguage| doesn't. There is no known workaround.
\item Babel does not take into account |\normalsfcodes| and
  (non-)French spacing is not always properly (un)set by
  languages. However, problems are unlikely to happen and therefore
  this part remains untouched in version 3.9 (but it is in the `to
  do' list). 
\item Using a character mathematically active (ie, with math code
  |"8000|) as a shorthand can make \TeX{} enter in an infinite
  loop. (Another issue in the `to do' list, although there is a
  partial solution.)
\item Also in the `to do' list is a common interface to switch
  scripts, to avoid the current problem of languages trying to define
  |\text|\m{script} in different ways.
\end{itemize}

\section{Preloading languages with \file{language.dat}}

\TeX{} and most engines based on it (pdf\TeX, \xetex, $\epsilon$-\TeX,
the main exception being \luatex) require hyphenation patterns to be
loaded when a format is created (eg, \LaTeX, Xe\LaTeX,
pdf\LaTeX). \babel{} provides a tool which has become standand in many
distributions and based on a ``configuration file'' named
\file{language.dat}. The exact way this file is used depends on the
distribution, so please, read the documentation for the latter (note
also some distributions generate the file with some tool).

In that file the person who maintains a \TeX\ environment has to record
for which languages he has hyphenation patterns \emph{and} in which
files these are stored\footnote{This is because different operating
systems sometimes use \emph{very} different file-naming
conventions.}. When hyphenation exceptions are stored in a separate
file this can be indicated by naming that file \emph{after} the file
with the hyphenation patterns.

The file can contain empty lines and comments, as well as lines which
start with an equals (\texttt{=}) sign. Such a line will instruct
\LaTeX\ that the hyphenation patterns just processed have to be known
under an alternative name. Here is an example:
\begin{verbatim}
% File    : language.dat
% Purpose : tell iniTeX what files with patterns to load.
english    english.hyphenations
=british

dutch      hyphen.dutch exceptions.dutch % Nederlands
german hyphen.ger
\end{verbatim}

You may also set the font encoding the patterns are
intended for by following the language name by a colon and the encoding
code.\footnote{This in not a new feature, but in former
versions it didn't work correctly.} For example:
\begin{verbatim}
german:T1 hyphenT1.ger
german hyphen.ger
\end{verbatim}
With the previous settings, if the enconding when the language is
selected is |T1| then the patterns in \file{hyphenT1.ger} are
used, but otherwise use those in \file{hyphen.ger} (note the encoding
could be set in |\extras|\m{lang}).

A typical error when using \babel{} is the following:
\begin{verbatim}
No hyphenation patterns were preloaded for
the language `<lang>' into the format.
Please, configure your TeX system to add them and
rebuild the format. Now I will use the patterns
preloaded for english instead}}
\end{verbatim}
It simply means you must reconfigure \file{language.dat}, either by 
hand or with the tools provided by your distribution.

\section{The interface between the core of \babel{} and the language
definition files}

The \textit{language definition files} (ldf) must conform to a
number of conventions, because these files have to fill in the gaps
left by the common code in \file{babel.def}, i.\,e., the
definitions of the macros that produce texts.  Also the
language-switching possibility which has been built into the
\babel{} system has its implications.

The following assumptions are made:
\begin{itemize}
\item Some of the language-specific definitions might be used by plain
  \TeX\ users, so the files have to be coded so that they can be read
  by both \LaTeX\ and plain \TeX. The current format can be checked by
  looking at the value of the macro |\fmtname|.
\item The common part of the \babel{} system redefines a number of
  macros and environments (defined previously in the document style)
  to put in the names of macros that replace the previously hard-wired
  texts.  These macros have to be defined in the language definition
  files.
\item The language definition files must define five macros, used to
  activate and deactivate the language-specific definitions.  These
  macros are |\|\langvar|hyphenmins|, |\captions|\langvar,
  |\date|\langvar, |\extras|\langvar\ and |\noextras|\langvar (the
  last two may be left empty); where \langvar\ is either the name of
  the language definition file or the name of the \LaTeX\ option that
  is to be used. These macros and their functions are discussed
  below. You must define all or none for a language (or a dialect);
  defining, say, |\date|\langvar\ but not |\captions|\langvar\ does
  not raise an error but can lead to unexpected results.
\item When a language definition file is loaded, it can define
  |\l@|\langvar\ to be a dialect of |\language0| when |\l@|\langvar\
  is undefined.
\item Language names must be all lowercase. If an unknow language is
  selected, \babel{} will attempt setting it after lowercasing its name.
\end{itemize}

Some recommendations:
\begin{itemize}
\item The preferred shorthand is |"|, which is not used in \LaTeX{}
  (quotes are entered as |``| and |''|). Other good choices are
  characters which are not used in a certain context (eg, |=| in an
  ancient language). Note however |=|, |<|, |>|, |:| and the like
  can be dangerous, because they may be used as part of the syntax
  of some elements (numeric expressions, key/value pairs, etc.).
\item Captions should not contain shorthands or encoding dependent
  commands (the latter is not always possible, but should be clearly
  documented). They should be defined using the LICR. You may
  also use the new tools for encoded strings, described below.
\item Avoid adding things to |\noextras|\m{lang} except for umlauthigh
  and friends, |\bbl@deactivate|, |\bbl@(non)frenchspacing|, and
  language specific macros. Use always, if possible, |\bbl@save| and
  |\bbl@savevariable| (except if you still want to have access to the
  previous value).
\end{itemize}

There are no special requirements for documenting your language
files. Now they are not included in the base \babel{} manual, so
provide a standalone document suited for your needs (and the
corresponding PDF, if you like), as well as other files you think can
be useful (eg, samples, readme).

\subsection{Basic macros}

In the core of the \babel{} system, several macros are defined for use
in language definition files. Their purpose is to make a new language
known. The first two are related to hyphenation patterns.

\DescribeMacro{\addlanguage}
The macro |\addlanguage| is a non-outer version of the macro
|\newlanguage|, defined in \file{plain.tex} version~3.x. For older
versions of \file{plain.tex} and \file{lplain.tex} a substitute
definition is used. Here ``language'' is used in the \TeX{} sense of
set of hyphenation patterns.

\DescribeMacro{\adddialect}
The macro |\adddialect| can be used when two languages can (or
must) use the same hyphenation patterns. This can also be useful
for languages for which no patterns are preloaded in the
format. In such cases the default behaviour of the \babel{}
system is to define this language as a `dialect' of the language
for which the patterns were loaded as |\language0|.  Here
``language'' is used in the \TeX{} sense of set of hyphenation
patterns.

\DescribeMacro{\<lang>hyphenmins}
The macro |\|\langvar|hyphenmins| is used to store the values of
the |\lefthyphenmin| and |\righthyphenmin|. Redefine this macro
to set your own values, with two numbers corresponding to these
two parameters. For example:
\begin{verbatim}
\renewcommand\spanishhyphenmins{34}
\end{verbatim}
(Assigning |\lefthyphenmin| and |\righthyphenmin| directly in
|\extras<lang>| has no effect.)

\DescribeMacro{\providehyphenmins}
The macro |\providehyphenmins| should be used in the language
definition files to set |\lefthyphenmin| and
|\righthyphenmin|. This macro will check whether these parameters
were provided by the hyphenation file before it takes any action.
If these values have been already set, this command is ignored
(currenty, default pattern files do \textit{not} set them).

\DescribeMacro{\captions<lang>}
The macro |\captions|\langvar\ defines the macros that
hold the texts to replace the original hard-wired texts.

\DescribeMacro{\date<lang>}
The macro |\date|\langvar\ defines |\today|.

\DescribeMacro{\extras<lang>}
The macro |\extras|\langvar\ contains all the extra definitions needed
for a specific language. This macro, like the following, is a hook --
you can add thing to it, but it must not be used directly.

\DescribeMacro{\noextras<lang>}
Because we want to let the user switch
between languages, but we do not know what state \TeX\ might be in
after the execution of |\extras|\langvar, a macro that brings
\TeX\ into a predefined state is needed. It will be no surprise
that the name of this macro is |\noextras|\langvar.

\DescribeMacro{\bbl@declare@ttribute}
This is a command to be used in the language definition files for
declaring a language attribute. It takes three arguments: the
name of the language, the attribute to be defined, and the code
to be executed when the attribute is to be used.

\DescribeMacro{\main@language}
To postpone the activation of the definitions needed for a
language until the beginning of a document, all language
definition files should use |\main@language| instead of
|\selectlanguage|. This will just store the name of the language,
and the proper language will be activated at the start of the
document.

\DescribeMacro{\ProvidesLanguage}
The macro |\ProvidesLanguage| should be used to identify the
language definition files. Its syntax is similar to the syntax
of the \LaTeX\ command |\ProvidesPackage|.

\DescribeMacro{\LdfInit}
The macro |\LdfInit| performs a couple of standard checks that
must be made at the beginning of a language definition file,
such as checking the category code of the @-sign, preventing
the \file{.ldf} file from being processed twice, etc.

\DescribeMacro{\ldf@quit}
The macro |\ldf@quit| does work needed
if a \file{.ldf} file was processed
earlier. This includes resetting the category code
of the @-sign, preparing the language to be activated at
|\begin{document}| time, and ending the input stream.

\DescribeMacro{\ldf@finish}
The macro |\ldf@finish| does work needed
at the end of each \file{.ldf} file. This
includes resetting the category code of the @-sign,
loading a local configuration file, and preparing the language
to be activated at |\begin{document}| time.

\DescribeMacro{\loadlocalcfg}
After processing a language definition file,
\LaTeX\ can be instructed to load a local configuration
file. This file can, for instance, be used to add strings to
|\captions|\langvar\ to support local document
classes. The user will be informed that this
configuration file has been loaded. This macro is called by
|\ldf@finish|.

\DescribeMacro{\substitutefontfamily}
(Deprecated.) This command takes three arguments, a font encoding and
two font family names. It creates a font description file for the
first font in the given encoding. This \file{.fd} file will instruct
\LaTeX\ to use a font from the second family when a font from the
first family in the given encoding seems to be needed.

\subsection{Skeleton}

Here is the basic structure of an |ldf| file, with a language, a
dialect and an attribute.

\begin{verbatim}
\ProvidesLanguage{<language>}
     [2013/05/16 v0.0 <Language> support from the babel system]
\LdfInit{<language>}{captions<language>}

\ifx\undefined\l@<language>
  \@nopatterns{<Language>}
  \adddialect\l@<language>0
\fi

\adddialect\l@<dialect>\l@<language>

\bbl@declare@ttribute{<language>}{<attrib>}{%
  \expandafter\addto\expandafter\extras<language>
  \expandafter{\extras<attrib><language>}%
  \let\captions<language>\captions<attrib><language>}

\providehyphenmins{<language>}{\tw@\thr@@}

\def\captions<language>{}
\let\captions<dialect>\captions<language>

\def\date<language>{}
\def\date<dialect>{}

\addto\extras<language>{}
\addto\noextras<language>{}
\let\extras<dialect>\extras<language>
\let\noextras<dialect>\noextras<language>

\ldf@finish{<language>}
\end{verbatim}

\subsection{Support for active characters}

In quite a number of language definition files, active characters are
introduced. To facilitate this, some support macros are provided.

\DescribeMacro{\initiate@active@char}
The internal macro |\initiate@active@char| is used in language
definition files to instruct \LaTeX\ to give a character the category
code `active'. When a character has been made active it will remain
that way until the end of the document. Its definition may vary.

\DescribeMacro{\bbl@activate}
\DescribeMacro{\bbl@deactivate}
The command |\bbl@activate| is used to change the way an active
character expands. |\bbl@activate| `switches on' the active behaviour
of the character. |\bbl@deactivate| lets the active character expand
to its former (mostly) non-active self.

\DescribeMacro{\declare@shorthand}
The macro |\declare@shorthand| is used to define the various
shorthands. It takes three arguments: the name for the collection of
shorthands this definition belongs to; the character (sequence) that
makes up the shorthand, i.e.\ |~| or |"a|; and the code to be executed
when the shorthand is encountered. (It does \textit{not} raise an
error if the shorthand character has not been ``initiated''.)

\DescribeMacro{\bbl@add@special}
\DescribeMacro{\bbl@remove@special}
The \TeX book states: ``Plain \TeX\ includes a macro called
|\dospecials| that is essentially a set macro, representing the set of
all characters that have a special category code.'' \cite[p.~380]{DEK}
It is used to set text `verbatim'.  To make this work if more
characters get a special category code, you have to add this character
to the macro |\dospecial|.  \LaTeX\ adds another macro called
|\@sanitize| representing the same character set, but without the
curly braces.  The macros |\bbl@add@special|\meta{char} and
|\bbl@remove@special|\meta{char} add and remove the character
\meta{char} to these two sets.

\subsection{Support for saving macro definitions}

Language definition files may want to \emph{re}define macros that
already exist. Therefor a mechanism for saving (and restoring) the
original definition of those macros is provided. We provide two macros
for this\footnote{This mechanism was introduced by Bernd Raichle.}.

\DescribeMacro{\babel@save}
To save the current meaning of any control sequence, the macro
|\babel@save| is provided. It takes one argument, \meta{csname}, the
control sequence for which the meaning has to be saved.

\DescribeMacro{\babel@savevariable}
A second macro is provided to save the current value of a variable.
In this context, anything that is allowed after the |\the| primitive
is considered to be a variable. The macro takes one argument, the
\meta{variable}.

The effect of the preceding macros is to append a piece of code to
the current definition of |\originalTeX|. When |\originalTeX| is
expanded, this code restores the previous definition of the control
sequence or the previous value of the variable.

\subsection{Support for extending macros}

\DescribeMacro{\addto}
The macro |\addto{|\meta{control sequence}|}{|\meta{\TeX\ code}|}| can
be used to extend the definition of a macro. The macro need not be
defined (ie, it can be undefined or |\relax|). This macro can, for
instance, be used in adding instructions to a macro like
|\extrasenglish|.

Be careful when using this macro, because depending on the case the
assignment could be either global (usually) or local (sometimes). That
does not seems very consistent, but this behaviour is preserved for
backward compatibility. If you are using \pkg{etoolbox}, by Philipp
Lehman, consider using the tools provided by this package instead of
|\addto|.

\subsection{Macros common to a number of languages}

\DescribeMacro{\bbl@allowhyphens}
In several languages compound words are used. This means that when
\TeX\ has to hyphenate such a compound word, it only does so at the
`\texttt{-}' that is used in such words. To allow hyphenation in the
rest of such a compound word, the macro |\bbl@allowhyphens| can be
used.

\DescribeMacro{\allowhyphens}
Same as |\bbl@allowhyphens|, but does nothing if the encoding is
|T1|. It is intended mainly for characters provided as real glyphs by
this encoding but constructed with |\accent| in |OT1|.

Note the previous command (|\bbl@allowhyphens|) has different
applications (hyphens and discretionaries) than this one (composite
chars). Note also prior to version 3.7, |\allowhyphens| had the
behaviour of |\bbl@allowhyphens|.

\DescribeMacro{\set@low@box}
For some languages, quotes need to be lowered to the baseline. For
this purpose the macro |\set@low@box| is available. It takes one
argument and puts that argument in an |\hbox|, at the baseline. The
result is available in |\box0| for further processing.

\DescribeMacro{\save@sf@q}
Sometimes it is necessary to preserve the |\spacefactor|.  For this
purpose the macro |\save@sf@q| is available. It takes one argument,
saves the current spacefactor, executes the argument, and restores the
spacefactor.

\DescribeMacro{\bbl@frenchspacing}
\DescribeMacro{\bbl@nonfrenchspacing}
The commands |\bbl@frenchspacing| and |\bbl@nonfrenchspacing| can be
used to properly switch French spacing on and off.

\subsection{Encoding-dependent strings}

\fbox{New 3.9} Babel 3.9 provides a way of defining strings in several
encodings, intended mainly for \luatex{} and \xetex. This is the only new
feature requiring changes in language files if you want to make use of
it.

Furthermore, it must be activated explicitly, with the package option
|strings|. If there is no |strings|, these blocks are ignored, except
|\SetCase|s (and except if forced with |\UseStrings|, see
below). In other words, the old way of defining/switching strings still
works and it's used by default.

It consist is a series of blocks started with
|\StartBabelCommands|. The last block is closed with
|\EndBabelCommands|. Each block is a single group (ie, local
declarations apply until the next |\StartBabelCommands| or
|\EndBabelCommands|). An |ldf| may contain several series of this
kind.

Thanks to this new feature, string values and string language
switching are not mixed any more. No need of |\addto|. If the language
is german, just redefine |\germanchaptername|.

\Describe\StartBabelCommands
  {\marg{language-list}\marg{category}\oarg{selector}}

The \m{language-list} specifies which languages the block is intended
for. A block is taken into account only if the |\CurrentOption| is
listed here. 

A ``selector'' is a name to be used as value in package option
|strings|, optionally followed by extra info about the encodings to be
used. The name |unicode| must be used for \xetex{} and \luatex{} (the
key |strings| has also other two special values: |generic| and
|encoded|).

If a string is set several times (because several blocks are read),
the first one take precedence (ie, it works much like
|\providecommand|).

Encoding info is |charset=| followed by a charset, which if given sets
how the strings should be traslated to the internal representation
used by the engine, typically |utf8|, which is the only value
supported currently (default is no traslations).

A list of font encodings which the strings are expected to work with
can be given after |fontenc=| (separated with spaces, if two or more) --
recommended, but not mandatory, although blocks without this key are
not taken into account if you have requested |strings=encoded|.

Blocks without a selector are read always if the key |strings| has
been used.  They provide fallback values, and therefore must be the
last blocks; they should be provided always if possible and all
strings should be defined somehow inside it; they can be the only
blocks (mainly LGC scripts using the LICR). Blocks without a selector
can be activated explicitly with |strings=generic| (no block is taken
into account except those). With |strings=encoded|, strings in those
blocks are set as default (internally, |?|).  If there is no key
|strings|, string definitions are ignored, but |\SetCase|s are still
honoured (an a |encoded| way).

The \m{category} is either |captions|, |date| or |extras|. You must
stick to these three categories, even if no error is raised when using
other name.\footnote{In future releases further categories may be
added.\nb{like `monetary', `time', `address', `name', `case' or
`numeric'}} It may be empty, too, but in such a case using
|\SetString| is an error (but not |\SetCase|).

\begin{verbatim}
\StartBabelCommands\CurrentOption{captions}
  [unicode, fontenc=EU1 EU2, charset=utf8]
\SetString{\chaptername}{utf8-string}

\StartBabelCommands\CurrentOption{captions}
\SetString{\chaptername}{ascii-maybe-LICR-string}

\EndBabelCommands
\end{verbatim}

A real example is:
\begin{verbatim}[escapechar=\&]
\StartBabelCommands{austrian}{date}
  [unicode, fontenc=EU1 EU2, charset=utf8]
  \SetString\monthiname{J&\"a&nner}

\StartBabelCommands{german,austrian}{date}
  [unicode, fontenc=EU1 EU2, charset=utf8]
  \SetString\monthiiiname{M&\"a&rz}

\StartBabelCommands{austrian}{date}
  \SetString\monthiname{J\"{a}nner}

\StartBabelCommands{german}{date}
  \SetString\monthiname{Januar}

\StartBabelCommands{german,austrian}{date}
  \SetString\monthiiname{Februar}
  \SetString\monthiiiname{M\"{a}rz}
  \SetString\monthivname{April}
  \SetString\monthvname{Mai}
  \SetString\monthviname{Juni}
  \SetString\monthviiname{Juli}
  \SetString\monthviiiname{August}
  \SetString\monthixname{September}
  \SetString\monthxname{Oktober}
  \SetString\monthxiname{November}
  \SetString\monthxiiname{Dezenber}
  \SetString\today{\number\day.~%
    \csname month\romannumeral\month name\endcsname\space
    \number\year}

\StartBabelCommands{german,austrian}{captions}
  \SetString\prefacename{Vorwort}
  [etc.]

\EndBabelCommands
\end{verbatim}

When used in |ldf| files, previous values of |\|\m{category}\m{language}
are overriden, which means the old way to define strings still works
and used by default (to be precise, is first set to undefined and then
strings are added). However, when used in the preamble or in a
package, new settings are added to the previous ones, if the language
exists (in the \babel{} sense, ie, if |\date|\m{language} exists).

\Describe\EndBabelCommands{}
Marks the end of the series of blocks.

\Describe\UseStrings{}
You may also want to omit the old way of defining define strings
altogether. Just add |\UseStrings| after the first
|\StartBabelCommands| and the generic branchs will be taken into
account even if there is no |strings| key. This directive applies to
all subsequent blocks, until |\EndBabelCommands|.

\Describe\SetString{\marg{macro-name}\marg{string}}
Adds \meta{macro-name} to the current category, and defines globally
\meta{lang-macro-name} to \meta{code} (after applying the
transformation corresponding to the current charset or defined with
the hook |stringprocess|).

Use this command to define strings, without including any ``logic'' if
possible, which should be a separated macro. See the example above for
the date.

\Describe\SetStringLoop{\marg{macro-name}\marg{string-list}}
A convenient way to define several ordered names at once. For example,
to define |\abmoniname|, |\abmoniiname|, etc. (and similarly with
|abday|):
\begin{verbatim}
\SetStringLoop{abmon#1name}{en,fb,mr,ab,my,jn,jl,ag,sp,oc,nv,dc}
\SetStringLoop{abday#1name}{lu,ma,mi,ju,vi,sa,do}
\end{verbatim}
|#1| is replaced by the roman numeral.

\Describe\SetCase{\oarg{map-list}\marg{toupper-code}\marg{tolower-code}}
Sets globally code to be executed at |\MakeUppercase| and
|\MakeLowercase|. The code would be typically things like |\let\BB\bb|
and |\uccode| or |\lccode| (although for the reasons explained above,
changes in lc/uc codes may not work). A \meta{map-list} is a series of
macros using the internal format of |\@uclclist| (eg,
|\bb\BB\cc\CC|). The mandatory arguments take precedence over the
optional one. This command, unlike |\SetString|, is executed always
(even without |strings|), and it is intented for minor readjustments
only.

For example, as |T1| is the default case mapping in \LaTeX, we could
set for Turkish:
\begin{verbatim}[escapechar=\&]
\StartBabelCommands{turkish}{}[ot1enc, fontenc=OT1]
\SetCase
  {\uccode"10=`I\relax}
  {\lccode`I="10\relax}

\StartBabelCommands{turkish}{}[unicode, fontenc=EU1 EU2, charset=utf8]
\SetCase
  {\uccode`i=`&\rmfamily\.{\ttfamily I}&\relax
   \uccode`&\i&=`I\relax}
  {\lccode`&\rmfamily\.{\ttfamily I}&=`i\relax
   \lccode`I=`&\i&\relax}

\StartBabelCommands{turkish}{}
\SetCase
  {\uccode`i="9D\relax
   \uccode"19=`I\relax}
  {\lccode"9D=`i\relax
   \lccode`I="19\relax}

\EndBabelCommands
\end{verbatim}
(Note the mapping for |OT1| is not complete.)

\section{Compatibility and changes}

\subsection{Compatibility with \file{german.sty}}\label{l-h}

The file \file{german.sty} has been one of the sources of inspiration
for the \babel{} system. Because of this I wanted to include
\file{german.sty} in the \babel{} system.  To be able to do that I had
to allow for one incompatibility: in the definition of the macro
|\selectlanguage| in \file{german.sty} the argument is used as the
{$\langle \it number \rangle$} for an |\ifcase|. So in this case a
call to |\selectlanguage| might look like |\selectlanguage{\german}|.

In the definition of the macro |\selectlanguage| in \file{babel.def}
the argument is used as a part of other macronames, so a call to
|\selectlanguage| now looks like |\selectlanguage{german}|.  Notice
the absence of the escape character.  As of version~3.1a of \babel{}
both syntaxes are allowed.

All other features of the original \file{german.sty} have been copied
into a new file, called \file{germanb.sty}\footnote{The `b' is added
to the name to distinguish the file from Partls' file.}.

Although the \babel{} system was developed to be used with \LaTeX,
some of the features implemented in the language definition files
might be needed by plain \TeX\ users. Care has been taken that all
files in the system can be processed by plain \TeX.

\subsection{Compatibility with \file{ngerman.sty}}

When used with the options \Lopt{ngerman} or \Lopt{naustrian},
\babel{} will provide all features of the package \pkg{ngerman}.
There is however one exception: The commands for special hyphenation
of double consonants (|"ff| etc.) and ck (|"ck|), which are no longer
required with the new German orthography, are undefined. With the
\pkg{ngerman} package, however, these commands will generate
appropriate warning messages only.

\subsection{Compatibility with the \pkg{french} package}

It has been reported to me that the package \pkg{french} by Bernard
Gaulle (\texttt{gaulle@idris.fr}) works together with \babel. On the
other hand, it seems \emph{not} to work well together with a lot of
other packages. Therefore I have decided to no longer load
\file{french.ldf} by default. Instead, when you want to use the
package by Bernard Gaulle, you will have to request it specifically,
by passing either \Lopt{frenchle} or \Lopt{frenchpro} as an option to
\babel.

\subsection{Changes in \babel\ version 3.9}

Most of changes in version 3.9 are related to bugs, either to fix them
(there were lots), or to provide some alternatives. Even new features
like |\babelhyphen| are intended to solve a certain problem (in this
case, the lacking of a uniform syntax and behaviour for shorthands
across languages). These changes are described in this manual in the
correspondin place.

\subsection{Changes in \babel\ version 3.7}

In \babel\ version 3.7 a number of bugs that were found in
version~3.6 are fixed. Also a number of changes and additions
have occurred:
\begin{itemize}
\item Shorthands are expandable again. The disadvantage is that
  one has to type |'{}a| when the acute accent is used as a
  shorthand character. The advantage is that a number of other
  problems (such as the breaking of ligatures, etc.) have
  vanished.
\item Two new commands, |\shorthandon| and |\shorthandoff| have
  been introduced to enable to temporarily switch off one or more
  shorthands.
\item Support for typesetting Greek has been enhanced. Code from
  the \pkg{kdgreek} package (suggested by the author) was added
  and |\greeknumeral| has been added.
\item Support for typesetting Basque is now available thanks to
  Juan Aguirregabiria.
\item Support for typesetting Serbian with Latin script is now
  available thanks to Dejan Muhamedagi\'{c} and Jankovic
  Slobodan.
\item Support for typesetting Hebrew (and potential support for
  typesetting other right-to-left written languages) is now
  available thanks to Rama Porrat and Boris Lavva.
\item Support for typesetting Bulgarian is now available thanks to
  Georgi Boshnakov.
\item Support for typesetting Latin is now available, thanks to
  Claudio Beccari and Krzysztof Konrad \.Zelechowski.
\item Support for typesetting North Sami is now available, thanks
  to Regnor Jernsletten.
\item The options \Lopt{canadian}, \Lopt{canadien} and
  \Lopt{acadien} have been added for Canadian English and French
  use.
\item A language attribute has been added to the |\mark...|
  commands in order to make sure that a Greek header line comes
  out right on the last page before a language switch.
\item Hyphenation pattern files are now read \emph{inside a
  group}; therefore any changes a pattern file needs to make to
  lowercase codes, uppercase codes, and category codes are kept
  local to that group. If they are needed for the language, these
  changes will need to be repeated and stored in |\extras...|
\item The concept of language attributes is introduced. It is
  intended to give the user some control over the
  features a language-definition file provides. Its
  first use is for the Greek language, where the user can choose
  the  $\pi o\lambda\upsilon\tau o\nu\kappa\acute{o}$
  (``Polutoniko'' or multi-accented) Greek way of typesetting
  texts. These attributes will possibly find wider use in future
  releases.
\item The environment \Lenv{hyphenrules} is introduced.
\item The syntax of the file \file{language.dat} has been
  extended to allow (optionally) specifying the font
  encoding to be used while processing the patterns file.
\item The command |\providehyphenmins| should now be used in
  language definition files in order to be able to keep any
  settings provided by the pattern file.
\end{itemize}

\subsection{Changes in \babel\ version 3.6}

In \babel\ version 3.6 a number of bugs that were found in
version~3.5 are fixed. Also a number of changes and additions
have occurred:
\begin{itemize}
\item A new environment \Lenv{otherlanguage*} is introduced. it
  only switches the `specials', but leaves the `captions'
  untouched.
\item The shorthands are no longer fully expandable. Some
  problems could only be solved by peeking at the token following
  an active character. The advantage is that |'{}a| works as
  expected for languages that have the |'| active.
\item Support for typesetting french texts is much enhanced; the
  file \file{francais.ldf} is now replaced by \file{frenchb.ldf}
  which is maintained by Daniel Flipo.
\item Support for typesetting the russian language is again
  available. The language definition file was originally
  developed by Olga Lapko from CyrTUG. The fonts needed to
  typeset the russian language are now part of the \babel\
  distribution. The support is not yet up to the level which is
  needed according to Olga, but this is a start.
\item Support for typesetting greek texts is now also
  available. What is offered in this release is a first attempt;
  it will be enhanced later on by Yannis Haralambous.
\item in \babel\ 3.6j some hooks have been added for the
  development of support for Hebrew typesetting.
\item Support for typesetting texts in Afrikaans (a variant of
  Dutch, spoken in South Africa) has been added to
  \file{dutch.ldf}.
\item Support for typesetting Welsh texts is now available.
\item A new command |\aliasshorthand| is introduced. It seems
  that in Poland various conventions are used to type the
  necessary Polish letters. It is now possible to use the
  character~|/| as a shorthand character instead of the
  character~|"|, by issuing the command |\aliasshorthand{"}{/}|.
\item The shorthand mechanism now deals correctly with characters
  that are already active.
\item Shorthand characters are made active at |\begin{document}|,
  not earlier. This is to prevent problems with other packages.
\item A \emph{preambleonly} command |\substitutefontfamily| has
  been added to create \file{.fd} files on the fly when the font
  families of the Latin text differ from the families used for
  the Cyrillic or Greek parts of the text.
\item Three new commands |\LdfInit|, |\ldf@quit| and
  |\ldf@finish| are introduced that perform a number of standard
  tasks.
\item In babel 3.6k the language Ukrainian has been added and the
  support for Russian typesetting has been adapted to the package
  'cyrillic' to be released with the December 1998 release of
  \LaTeXe.
\end{itemize}

\subsection{Changes in \babel\ version 3.5}

In \babel\ version 3.5 a lot of changes have been made when compared
with the previous release. Here is a list of the most important ones:
\begin{itemize}
\item the selection of the language is delayed until
  |\begin{document}|, which means you must add appropriate
    |\selectlanguage| commands if you include |\hyphenation| lists in
    the preamble of your document.
\item \babel\ now has a \Lenv{language} environment and a new
  command |\foreignlanguage|;
\item the way active characters are dealt with is completely
  changed. They are called `shorthands'; one can have three
  levels of shorthands: on the user level, the language level,
  and on `system level'. A consequence of the new way of handling
  active characters is that they are now written to auxiliary
  files `verbatim';
\item A language change now also writes information in the
  \file{.aux} file, as the change might also affect typesetting
  the table of contents. The consequence is that an \file{.aux} file
  generated by a LaTeX format with babel preloaded gives errors
  when read with a LaTeX format without babel; but I think this
  probably doesn't occur;
\item \babel\ is now compatible with the \pkg{inputenc} and
  \pkg{fontenc} packages;
\item the language definition files now have a new extension,
  \file{ldf};
\item the syntax of the file \file{language.dat} is extended to
  be compatible with the \pkg{french} package by Bernard Gaulle;
\item each language definition file looks for a configuration
  file which has the same name, but the extension \file{.cfg}. It
can contain any valid \LaTeX\ code.
\end{itemize}

\DocInput{babel.dtx}
\DocInput{bbplain.dtx}
\DocInput{bbunicode.dtx}

\section{Conclusion}

A system of document options has been presented that enable the user
of \LaTeX\ to adapt the standard document classes of \LaTeX\ to the
language he or she prefers to use. These options offer the possibility
of switching between languages in one document. The basic interface
consists of using one option, which is the same for \emph{all}
standard document classes.

In some cases the language definition files provide macros that can be
useful to plain \TeX\ users as well as to \LaTeX\ users.  The \babel{}
system has been implemented so that it can be used by both groups of
users.

\section{Acknowledgements}

I would like to thank all who volunteered as $\beta$-testers for their
time. I would like to mention Julio Sanchez who supplied the option
file for the Spanish language and Maurizio Codogno who supplied the
option file for the Italian language. Michel Goossens supplied
contributions for most of the other languages.  Nico Poppelier helped
polish the text of the documentation and supplied parts of the macros
for the Dutch language.  Paul Wackers and Werenfried Spit helped find
and repair bugs.

During the further development of the babel system I received much
help from Bernd Raichle, for which I am grateful.

\begin{thebibliography}{9}
 \bibitem{DEK} Donald E. Knuth,
   \emph{The \TeX book}, Addison-Wesley, 1986.
 \bibitem{LLbook} Leslie Lamport,
    \emph{\LaTeX, A document preparation System}, Addison-Wesley,
    1986.
 \bibitem{treebus} K.F. Treebus.
    \emph{Tekstwijzer, een gids voor het grafisch verwerken van
    tekst.}
    SDU Uitgeverij ('s-Gravenhage, 1988). A Dutch book on layout
    design and typography.
 \bibitem{HP} Hubert Partl,
   \emph{German \TeX}, \emph{TUGboat} 9 (1988) \#1, p.~70--72.
  \bibitem{LLth} Leslie Lamport,
    in: \TeX hax Digest, Volume 89, \#13, 17 February 1989.
 \bibitem{BEP} Johannes Braams, Victor Eijkhout and Nico Poppelier,
   \emph{The development of national \LaTeX\ styles},
   \emph{TUGboat} 10 (1989) \#3, p.~401--406.
 \bibitem{ilatex} Joachim Schrod,
   \emph{International \LaTeX\ is ready to use},
   \emph{TUGboat} 11 (1990) \#1, p.~87--90.
\end{thebibliography}
\end{document}
%</filedriver>
%\fi
% \changes{babel~3.7a}{1997/04/16}{Make multiple loading of
%    \file{babel.def} impossible} 
% \changes{babel~3.9a}{2012/05/16}{Now using \cs{ldf@quit} for the test} 
%    \begin{macrocode}
%<*core>
\ifx\ldf@quit\@undefined
\else
  \expandafter\endinput
\fi
%</core>
%    \end{macrocode}
%<*dtx>
\ProvidesFile{babel.dtx}
%</dtx>
%\fi
%
% \GetFileInfo{babel.dtx}
%
% \changes{babel~2.0a}{1990/04/02}{Added text about \file{german.sty}}
% \changes{babel~2.0b}{1990/04/18}{Changed order of code to prevent
%    plain \TeX from seeing all of it}
% \changes{babel~2.1}{1990/04/24}{Modified user interface,
%    \cs{langTeX} no longer necessary}
% \changes{babel~2.1a}{1990/05/01}{Incorporated Nico's comments}
% \changes{babel~2.1b}{1990/05/01}{rename \cs{language} to
%    \cs{current@language}}
% \changes{babel~2.1c}{1990/05/22}{abstract for report fixed, missing
%    \texttt{\}}, found by Nicolas Brouard}
% \changes{babel~2.1d}{1990/07/04}{Missing right brace in definition of
%    abstract environment, found by Werenfried Spit}
% \changes{babel~2.1e}{1990/07/16}{Incorporated more comments from
%    Nico}
% \changes{babel~2.2}{1990/07/17}{Renamed \cs{newlanguage} to
%    \cs{addlanguage}}
% \changes{babel~2.2a}{1990/08/27}{Modified the documentation
%    somewhat}
% \changes{babel~3.0}{1991/04/23}{Moved part of the code to hyphen.doc
%    in preparation for \TeX~3.0}
% \changes{babel~3.0a}{1991/05/21}{Updated comments in various places}
% \changes{babel~3.0b}{1991/05/25}{Removed some problems in change log}
% \changes{babel~3.0c}{1991/07/15}{Renamed \file{babel.sty} and
%    \file{latexhax.sty} to \file{.com}}
% \changes{babel~3.1}{1991/10/31}{Added the support for active
%    characters and for extending a macro}
% \changes{babel~3.1}{1991/11/05}{Removed the need for
%    \file{latexhax}}
% \changes{babel~3.2}{1991/11/10}{Some Changes by br}
% \changes{babel~3.2a}{1992/02/15}{Fixups of the code and
%    documentation}
% \changes{babel~3.3}{1993/07/06}{Included driver file, and prepared
%    for distribution}
% \changes{babel~3.4}{1994/01/30}{Updated for \LaTeXe}
% \changes{babel~3.4}{1994/02/28}{Added language definition file for
%    bahasa}
% \changes{babel~3.4b}{1994/05/18}{Added a small driver to be able to
%    process just this file}
% \changes{babel~3.5a}{1995/02/03}{Provided common code to handle the
%    active double quote}
% \changes{babel~3.5c}{1995/06/14}{corrected a few typos (PR1652)}
% \changes{babel~3.5d}{1995/07/02}{Merged glyphs.dtx into this file}
% \changes{babel~3.5f}{1995/07/13}{repaired a typo}
% \changes{babel~3.5f}{1996/01/09}{replaced \cs{tmp}, \cs{bbl@tmp} and
%    \cs{bbl@temp} with \cs{bbl@tempa}}
% \changes{babel~3.5g}{1996/07/09}{replaced \cs{undefined} with
%    \cs{@undefined} to be consistent with \LaTeX}
% \changes{babel~3.7d}{1999/05/05}{Fixed a few typos in \cs{changes}
%    entries which made typesetting the code impossible}
% \changes{babel~3.7h}{2001/03/01}{Added a number of missing comment
%    characters which caused spurious white space}
% \changes{babel~3.8e}{2005/03/24}{Many enhancements to the text by
%    Andrew Young} 
% \changes{babel~3.9c}{2013/04/04}{Added the ``modifiers'' mechanism}
%
% \section{Identification and loading of required files}
%
%    \textit{Code documentation is still under revision.}
%
%    The file \file{babel.sty}\footnote{The file described in this
%    section is called \texttt{\filename}, has version
%    number~\fileversion\ and was last revised on~\filedate.} is meant
%    for \LaTeXe, therefor we make sure that the format file used is
%    the right one.
%
%  \begin{macro}{\ProvidesLanguage}
% \changes{babel~3.7a}{1997/03/18}{Added macro to prevent problems
%    with unexpected \cs{ProvidesFile} in plain formats because of
%    \babel.}
%    The identification code for each file is something that was
%    introduced in \LaTeXe. When the command |\ProvidesFile| does not
%    exist, a dummy definition is provided temporarily. For use in the
%    language definition file the command |\ProvidesLanguage| is
%    defined by \babel.
% \changes{babel~3.4e}{1994/06/24}{Redid the identification code,
%    provided dummy definition of \cs{ProvidesFile} for plain \TeX}
% \changes{babel~3.5f}{1995/07/26}{Store version in \cs{fileversion}}
% \changes{babel~3.5f}{1995/12/18}{Need to temporarily change the
%    definition of \cs{ProvidesFile} for December 1995 release}
% \changes{babel~3.5g}{1996/07/09}{Save a few csnames; use
%    \cs{bbl@tempa} instead of \cs{\@ProvidesFile} and store message
%    in \cs{toks8}}
% \changes{babel~3.9a}{2012/12/09}{Save info about the babel version
%    in the format (switch.def) so that it can be checked later if
%    necessary}
%    \begin{macrocode}
%<*kernel>
\def\bbl@version{3.9f}
\def\bbl@date{2013/05/16}
%</kernel>
%<*patterns>
\xdef\bbl@format{\jobname}
%</patterns>
%<*core|kernel|patterns>
\ifx\ProvidesFile\@undefined
  \def\ProvidesFile#1[#2 #3 #4]{%
    \wlog{File: #1 #4 #3 <#2>}%
    \let\ProvidesFile\@undefined
    }
%</core|kernel|patterns>
%    \end{macrocode}
%    As an alternative for |\ProvidesFile| we define
%    |\ProvidesLanguage| here to be used in the language definition
%    files.
%    \begin{macrocode}
%<*kernel>
  \def\ProvidesLanguage#1[#2 #3 #4]{%
    \wlog{Language: #1 #4 #3 <#2>}%
    }
\else
%    \end{macrocode}
%    When |\ProvidesFile| is defined we give |\ProvidesLanguage| a
%    similar definition.
%    \begin{macrocode}
  \def\ProvidesLanguage#1{%
    \begingroup
      \catcode`\ 10 %
      \@makeother\/%
      \@ifnextchar[%]
        {\@provideslanguage{#1}}{\@provideslanguage{#1}[]}}
  \def\@provideslanguage#1[#2]{%
    \wlog{Language: #1 #2}%
    \expandafter\xdef\csname ver@#1.ldf\endcsname{#2}%
    \endgroup}
%</kernel>
%<*core|kernel|patterns>
\fi
%</core|kernel|patterns>
%    \end{macrocode}
%  \end{macro}
%
%    Identify each file that is produced from this source file.
% \changes{babel~3.4c}{1995/04/28}{lhyphen.cfg has become
%    lthyphen.cfg}
% \changes{babel~3.5b}{1995/01/25}{lthyphen.cfg has become hyphen.cfg}
%    \begin{macrocode}
%<package>\ProvidesPackage{babel}
%<core>\ProvidesFile{babel.def}
%<patterns>\ProvidesFile{hyphen.cfg}
%<kernel>\ProvidesFile{switch.def}
%<nil>\ProvidesLanguage{nil}
%<driver&!user>\ProvidesFile{babel.drv}
%<driver&user>\ProvidesFile{user.drv}
    [2013/05/16 v3.9f %
%<package>     The Babel package]
%<core>     Babel common definitions]
%<kernel|patterns>     Babel language switching mechanism]
%<nil>    Nil language]
%<driver>]
%    \end{macrocode}
%
%    Now we make sure all required files are loaded.  When the command
%    |\AtBeginDocument| doesn't exist we assume that we are dealing
%    with a plain-based format or \LaTeX2.09. In that case the file
%    \file{plain.def} is needed (which also defines
%    |\AtBeginDocument|, and therefore it is not loaded twice). We
%    need the first part when the format is created, and |\orig@dump|
%    is used as a flag. Otherwise, we need to use the second part, so
%    |\orig@dump| is not defined (\file{plain.def} undefines it).
%
% \changes{babel~3.9a}{2012/12/21}{Use \cs{orig@dump} as flag instead
%    of \cs{adddialect}}
%\begingroup
%  \catcode`&=\active
%  \gdef\MakePrivateLetters{\catcode`@=11\relax\catcode`&=\active}%
%  \gdef&#1&{\quad\colorbox{thegrey}{\textsf{#1}}}
%\endgroup
%    \begin{macrocode}
%<*core|kernel|patterns>
\ifx\AtBeginDocument\@undefined
%</core|kernel|patterns>
%<*patterns>
  \let\orig@dump\dump
%</patterns>
%<*core|kernel|patterns>
  \input plain.def\relax
\fi
%</core|kernel|patterns>
%    \end{macrocode}
%
%    Check if the current version of \file{switch.def} has been
%    previously loaded (mainly, \file{hyphen.cfg}). If not, load it
%    now. We cannot load |babel.def| here because we first need to
%    declare and process the package options.
% \changes{babel~3.0d}{1991/10/29}{Removed use of \cs{@ifundefined}}
% \changes{babel~3.9a}{2012/08/11}{Now switch.def is loaded always, so
%    that there is no need to rebuild formats just to update babel}
% \changes{babel~3.9a}{2012/12/13}{But switch.def is loaded only if
%    loaded in a different version (or not loaded)}
% \changes{babel~3.9a}{2013/01/14}{Added the debug option}
% \changes{babel~3.9a}{2013/02/05}{Added \cs{bbl@add}}
%    \begin{macrocode}
%<*package>
\@ifpackagewith{babel}{debug}
  {\let\bbl@tempa\relax}
  {\def\bbl@tempa{3.9f}}%
%</package>
%<*core>
\def\bbl@tempa{3.9f}
%</core>
%<*core|package>
\ifx\bbl@version\bbl@tempa\else
  \input switch.def\relax
\fi
%    \end{macrocode}
%    The following macros just make the code cleaner.  |\bbl@add| is
%    now used internally instead of |\addto| because of the
%    unpredictable behaviour of the latter. (There are some
%    duplications, but, you know, I [JBL] never rememer where the code
%    ends up when intermingled with docstrip.)
%    \begin{macrocode}
\def\bbl@for#1#2#3{\@for#1:=#2\do{\ifx#1\@empty\else#3\fi}}
\def\bbl@add#1#2{%
  \@ifundefined{\expandafter\@gobble\string#1}%
    {\def#1{#2}}%
    {\expandafter\def\expandafter#1\expandafter{#1#2}}}
\def\bbl@csarg#1#2{\expandafter#1\csname bbl@#2\endcsname}%
\long\def\bbl@afterelse#1\else#2\fi{\fi#1}
\long\def\bbl@afterfi#1\fi{\fi#1}
%</core|package>
%    \end{macrocode}
% \changes{babel~3.6a}{1996/11/02}{Removed \cs{babel@core@loaded}, no
%    longer needed with the advent of \cs{LdfInit}}
%
%    \section{The Package File}
%
%    In order to make use of the features of \LaTeXe, the \babel\
%    system contains a package file, \file{babel.sty}. This file is
%    loaded by the |\usepackage| command and defines all the language
%    options whose name is different from that of the |.ldf| file
%    (like variant spellings). It also takes care of a number of
%    compatibility issues with other packages an defines a few
%    aditional package options.
%
%
%    Apart from all the language options below we also have a few options
%    that influence the behaviour of language definition files.
%
%    Many of the following options don't do anything themselves, they
%    are just defined in order to make it possible for babel and
%    language definition files to check if one of them was specified
%    by the user.
%
%   \subsection{\texttt{base}}
%
%    The first option to be processed is |base|, which set the
%    hyphenation patterns then resets |ver@babel.sty| so that
%    LaTeX forgets about the first loading. After |switch.def| has
%    been loaded (above) and |\AfterBabelLanguage| defined, exits.
%
% \changes{babel~3.5d}{1995/07/04}{Added options to influence
%    behaviour of active acute and grave accents}
% \changes{babel~3.9a}{2012/10/05}{preset option started,
%    party stolen from fontenc}
% \changes{babel~3.9a}{2012/10/17}{Hooks started}
% \changes{babel~3.9a}{2013/02/07}{Rejected preset, and replaced by
%   base}
%    \begin{macrocode}
%<*package>
\def\AfterBabelLanguage#1{%
  \global\expandafter\bbl@add\csname#1.ldf-h@@k\endcsname}%
\@ifpackagewith{babel}{base}{%
  \DeclareOption*{\bbl@patterns{\CurrentOption}}%
  \DeclareOption{base}{}%
  \ProcessOptions
  \global\expandafter\let\csname opt@babel.sty\endcsname\relax
  \global\expandafter\let\csname ver@babel.sty\endcsname\relax
  \global\let\@ifl@ter@@\@ifl@ter
  \def\@ifl@ter#1#2#3#4#5{\global\let\@ifl@ter\@ifl@ter@@}%
  \endinput}{}%
%    \end{macrocode}
%
%    \subsection{\texttt{key=value} options and other general option}
%
%    The following macros extract language modifiers, and only real
%    package options are kept in the option list. Modifiers are saved
%    and assigned to |\BabelModifiers| at |\bbl@load@language|; when
%    no modifiers have been given, the former is |\relax|. How
%    modifiers are handled are left to language styles; they can use
%    |\in@|, loop them with |\@for| o load |keyval|).
% \changes{babel~3.9e}{2013/04/15}{Bug fixed - a dot was added in
%    key=value pairs}
%
%    \begin{macrocode}
\bbl@csarg\let{tempa\expandafter}\csname opt@babel.sty\endcsname
\def\bbl@tempb#1.#2{%
   #1\ifx\@empty#2\else,\bbl@afterfi\bbl@tempb#2\fi}%
\def\bbl@tempd#1.#2\@nnil{%
  \ifx\@empty#2%
    \edef\bbl@tempc{\ifx\bbl@tempc\@empty\else\bbl@tempc,\fi#1}%
  \else
    \in@{=}{#1}\ifin@
      \edef\bbl@tempc{\ifx\bbl@tempc\@empty\else\bbl@tempc,\fi#1.#2}%
    \else
      \edef\bbl@tempc{\ifx\bbl@tempc\@empty\else\bbl@tempc,\fi#1}%
      \bbl@csarg\edef{mod@#1}{\bbl@tempb#2}%
    \fi
  \fi}
\let\bbl@tempc\@empty
\bbl@for\bbl@tempa\bbl@tempa{%
  \expandafter\bbl@tempd\bbl@tempa.\@empty\@nnil}
\expandafter\let\csname opt@babel.sty\endcsname\bbl@tempc
%    \end{macrocode}
%
%    \begin{macrocode}
\DeclareOption{activeacute}{}
\DeclareOption{activegrave}{}
%    \end{macrocode}
%    The next option tells \babel\ to leave shorthand characters
%    active at the end of processing the package. This is \emph{not}
%    the default as it can cause problems with other packages, but for
%    those who want to use the shorthand characters in the preamble of
%    their documents this can help.
% \changes{babel~3.6f}{1997/01/14}{Added option
%    \Lopt{KeepShorthandsActive}}
% \changes{babel~3.7a}{1997/03/21}{No longer define the control
%    sequence \cs{KeepShorthandsActive}}
%    \begin{macrocode}
\DeclareOption{KeepShorthandsActive}{}
%    \end{macrocode}
% \changes{babel~3.9a}{2012/08/14}{Implemented the \texttt{noconfigs}
%    option}
% \changes{babel~3.9a}{2012/09/26}{Implemented the
%    \texttt{showlanguages} option}
%    \begin{macrocode}
\DeclareOption{debug}{}
\DeclareOption{noconfigs}{}
\DeclareOption{showlanguages}{}
\DeclareOption{shorthands=off}{\bbl@tempa shorthands=\bbl@tempa}
\DeclareOption{strings}{\def\bbl@opt@strings{\BabelStringsDefault}}
\DeclareOption{strings=encoded}{\let\bbl@opt@strings\relax}
\DeclareOption{safe=none}{\let\bbl@opt@safe\@empty}
\DeclareOption{safe=bib}{\def\bbl@opt@safe{B}}
\DeclareOption{safe=ref}{\def\bbl@opt@safe{R}}
\DeclareOption{math=active}{}
\DeclareOption{math=normal}{\def\bbl@mathnormal{\noexpand\textormath}}
\def\BabelStringsDefault{generic}
%    \end{macrocode}
%
%    Handling of package options is done in three passes. (I [JBL] am not
%    very happy with the idea, anyway.) The first one processes
%    options which has been declared above or follow the syntax
%    |<key>=<value>|, the second one 
%    loads the requested languages, except the main one if set with
%    the key |main|, and the third one loads the latter. First, we
%    ``flag'' valid keys with a nil value.
% \changes{babel~3.9a}{2012/08/10}{Added the `safe' key, including code
%    below for selecting the redefined macros}
%    \begin{macrocode}
\let\bbl@opt@shorthands\@nnil
\let\bbl@opt@config\@nnil
\let\bbl@opt@main\@nnil
\let\bbl@opt@strings\@nnil
\let\bbl@opt@headfoot\@nnil
%    \end{macrocode}
%    The following tool is defined temporarily to store the values of
%    options.
%    \begin{macrocode}
\def\bbl@tempa#1=#2\bbl@tempa{%
  \expandafter\ifx\csname bbl@opt@#1\endcsname\@nnil
    \expandafter\edef\csname bbl@opt@#1\endcsname{#2}%
  \else
    \bbl@error{%
      Bad option `#1=#2'. Either you have misspelled the\\%
      key or there is a previous setting of `#1'}{%
      Valid keys are `shorthands', `config', `strings', `main',\\%
      `headfoot', `safe', `math'}
  \fi}
%    \end{macrocode}
%    Now the option list is processed, taking into account only
%    currently declared options (including those declared with a |=|),
%    and |<key>=<value>| options (the former take precedence). 
%    Unrecognized options are saved in |\bbl@language@opts|, because
%    they are language options. 
%    \begin{macrocode}
\let\bbl@language@opts\@empty
\DeclareOption*{%
  \@expandtwoargs\in@{\string=}{\CurrentOption}%
  \ifin@
    \expandafter\bbl@tempa\CurrentOption\bbl@tempa
  \else
    \edef\bbl@language@opts{%
      \ifx\bbl@language@opts\@empty\else\bbl@language@opts,\fi
      \CurrentOption}%
  \fi}
%    \end{macrocode}
%    Now we finish the first pass (and start over).
%    \begin{macrocode}
\ProcessOptions*
%    \end{macrocode}
%
%    \subsection{Conditional loading of shorthands}
%
%    If there is no |shorthands=<chars>|, the original \textsf{babel}
%    macros are left untouched, but if there is, these macros are
%    wrapped (in |babel.def|) to define only those given.
%
%    A bit of optimization: if there is no |shorthands=|, then
%    |\bbl@ifshorthands| is always true, and it is always false if
%    |shorthands| is empty. Also, some code makes sense only with
%    |shorthands=...|.  
% \changes{babel~3.9c}{2013/04/07}{Added t and c for tilde and comma}
%    \begin{macrocode}
\def\bbl@sh@string#1{%
  \ifx#1\@empty\else
    \ifx#1t\string~%
    \else\ifx#1c\string,%
    \else\string#1%
    \fi\fi
    \expandafter\bbl@sh@string
  \fi}
\ifx\bbl@opt@shorthands\@nnil
  \def\bbl@ifshorthand#1#2#3{#2}%
\else\ifx\bbl@opt@shorthands\@empty
  \def\bbl@ifshorthand#1#2#3{#3}%
\else
%    \end{macrocode}
%    The following macro tests if a shortand is one of the allowed
%    ones.
%    \begin{macrocode}
  \def\bbl@ifshorthand#1{%
    \@expandtwoargs\in@{\string#1}{\bbl@opt@shorthands}%
    \ifin@
      \expandafter\@firstoftwo
    \else
      \expandafter\@secondoftwo
    \fi}
%    \end{macrocode}
%    We make sure all chars in the string are `other', with the help
%    of an auxiliary macro defined above (which also zaps spaces).
%    \begin{macrocode}
  \edef\bbl@opt@shorthands{%
    \expandafter\bbl@sh@string\bbl@opt@shorthands\@empty}%
%    \end{macrocode}

%    The following is ignored with |shorthands=off|, since it is
%    intended to take some aditional actions for certain chars.
%    \begin{macrocode}
  \bbl@ifshorthand{'}%
    {\PassOptionsToPackage{activeacute}{babel}}{}
  \bbl@ifshorthand{`}%
    {\PassOptionsToPackage{activegrave}{babel}}{}
\fi\fi
%    \end{macrocode}
% \changes{babel~3.9a}{2012/07/30}{Code setting language in
%    head/foots.  Related to babel/3796}
%    With |headfoot=lang| we can set the language used in heads/foots.         
%    For example, in babel/3796 just adds |headfoot=english|.  It
%    misuses \cs{@resetactivechars} but seems to work.
%    \begin{macrocode}
\ifx\bbl@opt@headfoot\@nnil\else
  \g@addto@macro\@resetactivechars{%
    \set@typeset@protect                  
    \expandafter\select@language@x\expandafter{\bbl@opt@headfoot}%
    \let\protect\noexpand}
\fi
%    \end{macrocode}
%    For the option safe we use a different approach --
%    |\bbl@opt@safe| says which macros are redefined (B for bibs and R
%    for refs). By default, both are set. 
%    \begin{macrocode}
\@ifundefined{bbl@opt@safe}{\def\bbl@opt@safe{BR}}{}
\ifx\bbl@opt@main\@nnil\else
  \edef\bbl@language@opts{%
    \ifx\bbl@language@opts\@empty\else\bbl@language@opts,\fi
      \bbl@opt@main}
\fi
%    \end{macrocode}
%    If the format created a list of loaded languages (in
%    |\bbl@languages|), get the name of the 0-th to show the actual
%    language used.
%    \begin{macrocode}
\ifx\bbl@languages\@undefined\else
  \begingroup
    \catcode`\^^I=12
    \@ifpackagewith{babel}{showlanguages}{%
      \begingroup
        \def\bbl@elt#1#2#3#4{\wlog{#2^^I#1^^I#3^^I#4}}%
        \wlog{<*languages>}%
        \bbl@languages
        \wlog{</languages>}%
      \endgroup}{}
  \endgroup
  \def\bbl@elt#1#2#3#4{%
    \ifnum#2=\z@
      \gdef\bbl@nulllanguage{#1}%
      \def\bbl@elt##1##2##3##4{}%
    \fi}%
  \bbl@languages
\fi
%    \end{macrocode}
%
%  \subsection{Language options}
%
% \changes{babel~3.6c}{1997/01/05}{When \cs{LdfInit} is undefined we
%    need to load \file{babel.def} from \file{babel.sty}}
% \changes{babel~3.6l}{1999/04/03}{Don't load \file{babel.def} now,
%    but rather define \cs{LdfInit} temporarily in order to load
%    \file{babel.def} at the right time, preventing problems with the
%    temporary definition of \cs{bbl@redefine}}
% \changes{babel~3.6r}{1999/04/12}{We \textbf{do} need to load
%    \file{babel.def} right now as \cs{ProvidesLanguage} needs to be
%    defined before the \file{.ldf} files are read and the reason for
%    for 3.6l has been removed}
% \changes{babel~3.9a}{2012/06/15}{Rewritten the loading mechanism, so
%    that languages not declared are also correctly recognized, even
%    if given as global options} 
% \changes{babel~3.9a}{2012/08/12}{Revised the loading mechanism}
% \changes{babel~3.5a}{1995/03/14}{Changed extension of language
%    definition files to \texttt{ldf}}
% \changes{babel~3.5d}{1995/07/02}{Load language definition files
%    \emph{after} the check for the hyphenation patterns}
% \changes{babel~3.5g}{1996/10/04}{Added option \Lopt{afrikaans}}
% \changes{babel~3.7g}{2001/02/09}{Added option \Lopt{acadian}}
% \changes{babel~3.8c}{2004/06/12}{Added option \Lopt{australian}}
% \changes{babel~3.8h}{2005/11/23}{Added option \Lopt{albanian}}
% \changes{babel~3.6i}{1997/02/20}{Added the \Lopt{Basque} option}
% \changes{babel~3.8h}{2005/11/23}{added synonyms \Lopt{indonesian},
%    \Lopt{indon} and \Lopt{bahasai} for the original bahasa
%    (indonesia) support}
% \changes{babel~3.8h}{2005/11/23}{added \Lopt{malay}, \Lopt{meyaluy}
%    and \Lopt{bahasam} for the Bahasa Malaysia support}
% \changes{babel~3.5b}{1995/05/25}{Added \Lopt{brazilian} as
%    alternative for \Lopt{brazil}}
% \changes{babel~3.5d}{1995/07/02}{Added \Lopt{british} as an
%    alternative for \Lopt{english} with a preference for british
%    hyphenation}
% \changes{babel~3.7f}{2000/09/21}{Added the \Lopt{bulgarian} option}
% \changes{babel~3.7g}{2001/02/07}{Added option \Lopt{canadian}}
% \changes{babel~3.7g}{2001/02/09}{Added option \Lopt{canadien}}
% \changes{babel~3.5b}{1995/06/06}{Added the \Lopt{estonian} option}
% \changes{babel~3.5f}{1996/01/10}{Now use the file \file{frenchb.ldf}
%    from Daniel Flipo for french support}
% \changes{babel~3.6e}{1997/01/08}{Added option \Lopt{frenchb} an
%    alias for \Lopt{francais}}
% \changes{babel~3.5d}{1995/07/02}{Load \file{french.ldf} when it is
%    found instead of \file{frenchb.ldf}}
% \changes{babel~3.7j}{2003/06/07}{\emph{only} load
%    \file{frenchb.ldf}}
% \changes{babel~3.5f}{1996/05/31}{Added the \Lopt{greek} option}
% \changes{babel~3.7a}{1997/11/13}{Added the \Lopt{polutonikogreek}
%    option}
% \changes{babel~3.7c}{1999/04/22}{set the correct language attribute
%    for polutoniko greek}
% \changes{babel~3.7a}{1998/03/27}{Added the \Lopt{hebrew} option}
% \changes{babel~3.7b}{1998/06/25}{Added the \Lopt{latin} option}
% \changes{babel~3.7m}{2003/11/13}{Added the \Lopt{interlingua}
%    option}
% \changes{babel~3.6p}{1999/04/10}{Added the \Lopt{ngerman} and
%    \Lopt{naustrian} options}
% \changes{babel~3.7f}{2000/09/26}{Added the \Lopt{samin} option}
% \changes{babel~3.8c}{2004/06/12}{Added the \Lopt{newzealand} option}
% \changes{babel~3.6e}{1997/01/08}{Added options \Lopt{UKenglish} and
%    \Lopt{USenglish}}
%
%    Languages are loaded when processing the corresponding option
%    \textit{except} if a |main| language has been set. In such a
%    case, it is not loaded until all options has been processed.
%    The following macro inputs the ldf file and does some additional
%    checks (|\input| works, too, but possible errors are not catched).
%    \begin{macrocode}
\let\bbl@afterlang\relax
\let\BabelModifiers\relax
\let\bbl@loaded\@empty
\def\bbl@load@language#1{%
  \InputIfFileExists{#1.ldf}%
    {\edef\bbl@loaded{\CurrentOption
       \ifx\bbl@loaded\@empty\else,\bbl@loaded\fi}%
     \expandafter\let\expandafter\bbl@afterlang
        \csname\CurrentOption.ldf-h@@k\endcsname
     \expandafter\let\expandafter\BabelModifiers
        \csname bbl@mod@\CurrentOption\endcsname}%
    {\bbl@error{%
       Unknow option `\CurrentOption'. Either you misspelled it\\%
       or the language definition file \CurrentOption.ldf was not found}{%
       Valid options are: shorthands=..., KeepShorthandsActive,\\%
       activeacute, activegrave, noconfigs, safe=, main=, math=\\%
       headfoot=, strings=, config=, or a language name.}}}
%    \end{macrocode}
%    Now, we set language options whose names are different from |ldf| files.
%    \begin{macrocode}
\DeclareOption{acadian}{\bbl@load@language{frenchb}}
\DeclareOption{afrikaans}{\bbl@load@language{dutch}}
\DeclareOption{american}{\bbl@load@language{english}}
\DeclareOption{australian}{\bbl@load@language{english}}
\DeclareOption{austrian}{\bbl@load@language{germanb}}
\DeclareOption{bahasa}{\bbl@load@language{bahasai}}
\DeclareOption{bahasai}{\bbl@load@language{bahasai}}
\DeclareOption{bahasam}{\bbl@load@language{bahasam}}
\DeclareOption{brazil}{\bbl@load@language{portuges}}
\DeclareOption{brazilian}{\bbl@load@language{portuges}}
\DeclareOption{british}{\bbl@load@language{english}}
\DeclareOption{canadian}{\bbl@load@language{english}}
\DeclareOption{canadien}{\bbl@load@language{frenchb}}
\DeclareOption{francais}{\bbl@load@language{frenchb}}
\DeclareOption{french}{\bbl@load@language{frenchb}}%
\DeclareOption{german}{\bbl@load@language{germanb}}
\DeclareOption{hebrew}{%
  \input{rlbabel.def}%
  \bbl@load@language{hebrew}}
\DeclareOption{hungarian}{\bbl@load@language{magyar}}
\DeclareOption{indon}{\bbl@load@language{bahasai}}
\DeclareOption{indonesian}{\bbl@load@language{bahasai}}
\DeclareOption{lowersorbian}{\bbl@load@language{lsorbian}}
\DeclareOption{malay}{\bbl@load@language{bahasam}}
\DeclareOption{meyalu}{\bbl@load@language{bahasam}}
\DeclareOption{naustrian}{\bbl@load@language{ngermanb}}
\DeclareOption{newzealand}{\bbl@load@language{english}}
\DeclareOption{ngerman}{\bbl@load@language{ngermanb}}
\DeclareOption{nynorsk}{\bbl@load@language{norsk}}
\DeclareOption{polutonikogreek}{%
  \bbl@load@language{greek}%
  \languageattribute{greek}{polutoniko}}
\DeclareOption{portuguese}{\bbl@load@language{portuges}}
\DeclareOption{russian}{\bbl@load@language{russianb}}
\DeclareOption{UKenglish}{\bbl@load@language{english}}
\DeclareOption{ukrainian}{\bbl@load@language{ukraineb}}
\DeclareOption{uppersorbian}{\bbl@load@language{usorbian}}
\DeclareOption{USenglish}{\bbl@load@language{english}}
%    \end{macrocode}
%
%    Another way to extend the list of `known' options for \babel\ is
%    to create the file \file{bblopts.cfg} in which one can add option
%    declarations. However, this mechanism is deprecated -- if you
%    want an alternative name for a language, just create a new |.ldf|
%    file loading the actual one. You can also set the name
%    of the file with the package option |config=<name>|, which will
%    load |<name>.cfg| instead. 
% \changes{babel~3.6i}{1997/03/15}{Added the possibility to have a
%    \file{bblopts.cfg} file with option declarations.}
% \changes{babel~3.9a}{2012/06/28}{Added the \cs{AfterBabelLanguage}
%    mechanism, to be used mainly with the local cfg file.}
% \changes{babel~3.9a}{2012/06/31}{Now you can set the name of the
%    local cfg file.}
%    \begin{macrocode}
\ifx\bbl@opt@config\@nnil
  \@ifpackagewith{babel}{noconfigs}{}%
    {\InputIfFileExists{bblopts.cfg}%
      {\typeout{*************************************^^J%
               * Local config file bblopts.cfg used^^J%
               *}}%
      {}}%
\else
  \InputIfFileExists{\bbl@opt@config.cfg}%
    {\typeout{*************************************^^J%
             * Local config file \bbl@opt@config.cfg used^^J%
             *}}%
    {\bbl@error{%
       Local config file `\bbl@opt@config.cfg' not found}{%
       Perhaps you misspelled it.}}%
\fi
%    \end{macrocode}
%
%    Recognizing global options in packages not having a closed set of
%    them is not trivial, as for them to be processed they must be
%    defined explicitly. So, package options not yet taken into
%    account and stored in |bbl@language@opts| are assumed to be
%    languages (note this list also contains the language given with
%    |main|). If not declared above, the name of the option and the
%    file are the same.
%    \begin{macrocode}
\bbl@for\bbl@tempa\bbl@language@opts{%
  \@ifundefined{ds@\bbl@tempa}%
    {\edef\bbl@tempb{%
       \noexpand\DeclareOption
         {\bbl@tempa}%
         {\noexpand\bbl@load@language{\bbl@tempa}}}%
     \bbl@tempb}%
     \@empty}
%    \end{macrocode}
%    Now, we make sure an option is explicitly declared for any
%    language set as global option, by checking if an |ldf|
%    exists. The previous step was, in fact, somewhat redundant, but
%    that way we minimize accesing the file system just to see if the
%    option could be a language.
%    \begin{macrocode}
\bbl@for\bbl@tempa\@classoptionslist{%
  \@ifundefined{ds@\bbl@tempa}%
    {\IfFileExists{\bbl@tempa.ldf}%
      {\edef\bbl@tempb{%
         \noexpand\DeclareOption
           {\bbl@tempa}%
           {\noexpand\bbl@load@language{\bbl@tempa}}}%
       \bbl@tempb}%
      \@empty}%
    \@empty}
%    \end{macrocode}
%    If a main language has been set, store it for the third pass.
%    \begin{macrocode}
\ifx\bbl@opt@main\@nnil\else
  \expandafter
  \let\expandafter\bbl@loadmain\csname ds@\bbl@opt@main\endcsname
  \DeclareOption{\bbl@opt@main}{}
\fi
%    \end{macrocode}
%    And we are done, because all options for this pass has been
%    declared. Those already processed in the first pass are just ignored.
% \changes{babel~3.6i}{1997/03/12}{Added default option}
% \changes{babel~3.9a}{2012/12/22}{Default option does nothing}
%
%    The options have to be processed in the order in which the user
%    specified them (except, of course, global options, which \LaTeX{}
%    processes before):
%    \begin{macrocode}
\def\AfterBabelLanguage#1{%
  \bbl@ifsamestring\CurrentOption{#1}{\global\bbl@add\bbl@afterlang}{}}
\DeclareOption*{}
\ProcessOptions*
%    \end{macrocode}
%    This finished the second pass. Now the third one begins, which
%    loads the main language set with the key |main|. A warning is
%    raised if the main language is not the same as the last named
%    one, or if the value of the key |main| is not a language. Then
%    execute directly the option (because it could be used only in
%    |main|). After loading all languages, we deactivate
%    |\AfterBabelLanguage|.
%    \begin{macrocode}
\ifx\bbl@opt@main\@nnil
  \edef\bbl@tempa{\@classoptionslist,\bbl@language@opts}
  \let\bbl@tempc\@empty
  \bbl@for\bbl@tempb\bbl@tempa{%
    \@expandtwoargs\in@{,\bbl@tempb,}{,\bbl@loaded,}%
    \ifin@\edef\bbl@tempc{\bbl@tempb}\fi}
  \def\bbl@tempa#1,#2\@nnil{\def\bbl@tempb{#1}}
  \expandafter\bbl@tempa\bbl@loaded,\@nnil
  \ifx\bbl@tempb\bbl@tempc\else
    \bbl@warning{%
      Last declared language option is `\bbl@tempc,\\%
      but the last processed one was `\bbl@tempb'.\\%
      The main language cannot be set as both a global\\%
      and a package option. Use `main=\bbl@tempc' as\\%
      option. Reported}%
  \fi
\else
  \DeclareOption{\bbl@opt@main}{\bbl@loadmain}
  \ExecuteOptions{\bbl@opt@main}
  \DeclareOption*{}
  \ProcessOptions*
\fi
\def\AfterBabelLanguage{%
  \bbl@error
    {Too late for \string\AfterBabelLanguage}%
    {Languages have been loaded, so I can do nothing}}
%    \end{macrocode}
% \changes{babel~3.7c}{1999/03/13}{Added an error message for when no
%    language option was specified}
%    In order to catch the case where the user forgot to specify a
%    language we check whether |\bbl@main@language|, has become
%    defined. If not, no language has been loaded and an error
%    message is displayed.
% \changes{babel~3.7c}{1999/04/09}{No longer us a redefinition of an
%    internal macro, just check \cs{bbl@main@language} and load
%    \file{babel.def}}
% \changes{babel~3.9a}{2012/06/24}{Now babel is not loaded to prevent
%    the document from raising errors after fixing it}
%    \begin{macrocode}
\ifx\bbl@main@language\@undefined
  \bbl@error{%
    You haven't specified a language option}{%
    You need to specify a language, either as a global option\\%
    or as an optional argument to the \string\usepackage\space
    command;\\%
    You shouldn't try to proceed from here, type x to quit.}
\fi
%</package>
%    \end{macrocode}
%
%    \section{The Kernel of Babel}
%
%    The kernel of the \babel\ system is stored in either
%    \file{hyphen.cfg} or \file{switch.def} and \file{babel.def}.  The
%    file \file{babel.def} contains most of the code, while
%    \file{switch.def} defines the language switching commands; both
%    can be read at run time. The file \file{hyphen.cfg} is a file
%    that can be loaded into the format, which is necessary when you
%    want to be able to switch hyphenation patterns (by default, it
%    also inputs \file{switch.def}, for ``historical reasons'', but it
%    is not necessary). When \file{babel.def} is loaded it checks if
%    the current version of \file{switch.def} is in the format; if not
%    it is loaded. A further file, \file{babel.sty}, contains
%    \LaTeX-specific stuff.
%
%    Because plain \TeX\ users might want to use some of the features
%    of the \babel{} system too, care has to be taken that plain \TeX\
%    can process the files. For this reason the current format will
%    have to be checked in a number of places. Some of the code below
%    is common to plain \TeX\ and \LaTeX, some of it is for the
%    \LaTeX\ case only.
% \changes{babel~3.9a}{2013/01/11}{Added \cs{bbl@for} for loops
%    ignoring empties}
% \changes{babel~3.9c}{2013/04/06}{Normalize \cs{bbl@afterlang} to relax}
%
%    \subsection{Tools}
%
%    \begin{macrocode}
%<*core>
\ifx\bbl@opt@strings\@undefined
  \def\bbl@opt@safe{BR}
  \let\bbl@opt@strings\@nnil
  \let\bbl@opt@shorthands\@nnil
\fi
\ifx\BabelModifiers\@undefined\let\BabelModifiers\relax\fi
\ifx\bbl@afterlang\@undefined\let\bbl@afterlang\relax\fi
\providecommand\AfterBabelLanguage[2]{}
\def\bbl@csarg#1#2{\expandafter#1\csname bbl@#2\endcsname}%
%    \end{macrocode}
%
%  \begin{macro}{\bbl@afterelse}
%  \begin{macro}{\bbl@afterfi}
%    Because the code that is used in the handling of active
%    characters may need to look ahead, we take extra care to `throw'
%    it over the |\else| and |\fi| parts of an
%    |\if|-statement\footnote{This code is based on code presented in
%    TUGboat vol. 12, no2, June 1991 in ``An expansion Power Lemma''
%    by Sonja Maus.}. These macros will break if another |\if...\fi|
%    statement appears in one of the arguments and it is not enclosed
%    in braces.
% \changes{babel~3.6i}{1997/02/20}{Made \cs{bbl@afterelse} and
%    \cs{bbl@afterfi} \cs{long}}
%    \begin{macrocode}
\long\def\bbl@afterelse#1\else#2\fi{\fi#1}
\long\def\bbl@afterfi#1\fi{\fi#1}
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
% \changes{babel~3.9a}{2012/08/10}{Removed the \cs{peek@token} and
%    \textsc{test@token} stuff}
%    The macro |\initiate@active@char| takes all the necessary actions
%    to make its argument a shorthand character. The real work is
%    performed once for each character.
% \changes{babel~3.7c}{1999/04/30}{Only execute
%    \cs{initiate@active@char} once for each character}
% \changes{babel~3.9a}{1999/04/30}{Added \cs{bbl@withactive}}
%    \begin{macrocode}
\def\bbl@withactive#1#2{%
  \begingroup
    \lccode`~=`#2\relax
    \lowercase{\endgroup#1~}}
%    \end{macrocode}
%
%
%  \begin{macro}{\bbl@redefine}
% \changes{babel~3.5f}{1995/11/15}{Macro added}
%    To redefine a command, we save the old meaning of the macro.
%    Then we redefine it to call the original macro with the
%    `sanitized' argument.  The reason why we do it this way is that
%    we don't want to redefine the \LaTeX\ macros completely in case
%    their definitions change (they have changed in the past).
%
%    Because we need to redefine a number of commands we define the
%    command |\bbl@redefine| which takes care of this. It creates a
%    new control sequence, |\org@...|
%    \begin{macrocode}
\def\bbl@redefine#1{%
  \edef\bbl@tempa{\expandafter\@gobble\string#1}%
  \expandafter\let\csname org@\bbl@tempa\endcsname#1%
  \expandafter\def\csname\bbl@tempa\endcsname}
%    \end{macrocode}
%
%    This command should only be used in the preamble of the document.
%    \begin{macrocode}
\@onlypreamble\bbl@redefine
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\bbl@redefine@long}
% \changes{babel~3.6f}{1997/01/14}{Macro added}
%    This version of |\babel@redefine| can be used to redefine |\long|
%    commands such as |\ifthenelse|.
%    \begin{macrocode}
\def\bbl@redefine@long#1{%
  \edef\bbl@tempa{\expandafter\@gobble\string#1}%
  \expandafter\let\csname org@\bbl@tempa\endcsname#1%
  \expandafter\long\expandafter\def\csname\bbl@tempa\endcsname}
\@onlypreamble\bbl@redefine@long
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\bbl@redefinerobust}
% \changes{babel~3.5f}{1995/11/15}{Macro added}
% \changes{babel~3.5f}{1996/04/09}{Define \cs*{foo } instead of
%    \cs{foo}}
%    For commands that are redefined, but which \textit{might} be
%    robust we need a slightly more intelligent macro. A robust
%    command |foo| is defined to expand to |\protect|\verb*|\foo |. So
%    it is necessary to check whether \verb*|\foo | exists. The result
%    is that the command that is being redefined is always robust
%    afterwards.  Therefor all we need to do now is define \verb*|\foo |.
%    \begin{macrocode}
\def\bbl@redefinerobust#1{%
  \edef\bbl@tempa{\expandafter\@gobble\string#1}%
  \expandafter\ifx\csname\bbl@tempa\space\endcsname\relax
    \expandafter\let\csname org@\bbl@tempa\endcsname#1%
    \expandafter\edef\csname\bbl@tempa\endcsname{\noexpand\protect
      \expandafter\noexpand\csname\bbl@tempa\space\endcsname}%
  \else
    \expandafter\let\csname org@\bbl@tempa\expandafter\endcsname
                    \csname\bbl@tempa\space\endcsname
  \fi
  \expandafter\def\csname\bbl@tempa\space\endcsname}
%    \end{macrocode}
%
%    This command should only be used in the preamble of the document.
%    \begin{macrocode}
\@onlypreamble\bbl@redefinerobust
%    \end{macrocode}
%  \end{macro}
%
%  \subsection{Encoding issues}
%
%    The first thing we need to do is to determine, at
%    |\begin{document}|, which latin fontencoding to use.
%
%  \begin{macro}{\latinencoding}
% \changes{babel~3.6i}{1997/03/15}{Macro added, moved from
%    \file{.ldf} files}
%    When text is being typeset in an encoding other than `latin'
%    (\texttt{OT1} or \texttt{T1}), it would be nice to still have
%    Roman numerals come out in the Latin encoding.
%    So we first assume that the current encoding at the end
%    of processing the package is the Latin encoding.
%    \begin{macrocode}
\AtEndOfPackage{\edef\latinencoding{\cf@encoding}}
%    \end{macrocode}
%    But this might be overruled with a later loading of the package
%    \pkg{fontenc}. Therefor we check at the execution of
%    |\begin{document}| whether it was loaded with the \Lopt{T1}
%    option. The normal way to do this (using |\@ifpackageloaded|) is
%    disabled for this package. Now we have to revert to parsing the
%    internal macro |\@filelist| which contains all the filenames
%    loaded.
% \changes{babel~3.6k}{1999/03/15}{Use T1 encoding when it is a known
%    encoding}
% \changes{babel~3.6m}{1999/04/06}{Can't use \cs{@ifpackageloaded}
%    need to parse \cs{@filelist}}
% \changes{babel~3.6n}{1999/04/07}{moved checking for fontenc right to
%    the top of \file{babel.sty}}
% \changes{babel~3.6n}{1999/04/07}{Added a check for `manual' selection
%    of \texttt{T1} encoding, without loading \pkg{fontenc}}
% \changes{babel~3.6q}{1999/04/12}{Better solution then parsing
%    \cs{@filelist}, use \cs{@ifl@aded}}
% \changes{babel~3.6u}{1999/04/20}{Moved this code to
%    \file{babel.def}}
%    \begin{macrocode}
\AtBeginDocument{%
  \gdef\latinencoding{OT1}%
  \ifx\cf@encoding\bbl@t@one
    \xdef\latinencoding{\bbl@t@one}%
  \else
    \@ifl@aded{def}{t1enc}{\xdef\latinencoding{\bbl@t@one}}{}%
  \fi
  }
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\latintext}
% \changes{babel~3.6i}{1997/03/15}{Macro added, moved from
%    \file{.ldf} files}
%    Then we can define the command |\latintext| which is a
%    declarative switch to a latin font-encoding.
%    \begin{macrocode}
\DeclareRobustCommand{\latintext}{%
  \fontencoding{\latinencoding}\selectfont
  \def\encodingdefault{\latinencoding}}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\textlatin}
% \changes{babel~3.6i}{1997/03/15}{Macro added, moved from
%    \file{.ldf} files}
% \changes{babel~3.7j}{2003/03/19}{added \cs{leavevmode} to prevent a
%    paragraph starting \emph{inside} the group}
% \changes{babel~3.7k}{2003/10/12}{Use \cs{DeclareTextFontComand}}
%    This command takes an argument which is then typeset using the
%    requested font encoding. In order to avoid many encoding switches
%    it operates in a local scope.
%    \begin{macrocode}
\ifx\@undefined\DeclareTextFontCommand
  \DeclareRobustCommand{\textlatin}[1]{\leavevmode{\latintext #1}}
\else
  \DeclareTextFontCommand{\textlatin}{\latintext}
\fi
%    \end{macrocode}
%
%    The second version of this macro takes two arguments. The first
%    argument is the name of the language that will be defined in the
%    language definition file; the second argument is either a control
%    sequence or a string from which a control sequence should be
%    constructed. The existence of the control sequence indicates that
%    the file has been processed before.
%
%    At the start of processing a language definition file we always
%    check the category code of the at-sign. We make sure that it is
%    a `letter' during the processing of the file. We also save its
%    name as the last called option, even if not loaded.
%
%    Another character that needs to have the correct category code
%    during processing of language definition files is the equals sign,
%    `=', because it is sometimes used in constructions with the
%    |\let| primitive. Therefor we store its current catcode and
%    restore it later on.
% \changes{babel~3.7o}{2003/11/26}{make sure the equals sign has its
%    default category code}
%
%    Now we check whether we should perhaps stop the processing of
%    this file. To do this we first need to check whether the second
%    argument that is passed to |\LdfInit| is a control sequence. We
%    do that by looking at the first token after passing |#2| through
%    |string|. When it is equal to |\@backslashchar| we are dealing
%    with a control sequence which we can compare with |\@undefined|.
%
% \changes{babel~3.9a}{2012/08/11}{\cs{ldf@quit} is not delayed any
%   more after \cs{fi} , since \cs{endinput} is not executed immediately}
%   If so, we call |\ldf@quit| to set the main language, restore the
%   category code of the @-sign and call |\endinput|
%
%    When |#2| was \emph{not} a control sequence we construct one and
%    compare it with |\relax|.
%
%    Finally we check |\originalTeX|.
%    \begin{macrocode}
\def\LdfInit#1#2{%
  \chardef\atcatcode=\catcode`\@
  \catcode`\@=11\relax
  \chardef\eqcatcode=\catcode`\=
  \catcode`\==12\relax
  \expandafter\if\expandafter\@backslashchar
                 \expandafter\@car\string#2\@nil
    \ifx#2\@undefined\else
      \ldf@quit{#1}%
    \fi
  \else
    \expandafter\ifx\csname#2\endcsname\relax\else
      \ldf@quit{#1}%
    \fi
  \fi
  \let\bbl@screset\@empty
  \ifx\originalTeX\@undefined
    \let\originalTeX\@empty
  \else
    \originalTeX
  \fi}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\ldf@quit}
% \changes{babel~3.6a}{1996/10/29}{Macro added}
%    This macro interrupts the processing of a language definition file.
% \changes{babel~3.7o}{2003/11/26}{Also restore the category code of
%    the equals sign}
%    \begin{macrocode}
\def\ldf@quit#1{%
  \expandafter\main@language\expandafter{#1}%
  \catcode`\@=\atcatcode \let\atcatcode\relax
  \catcode`\==\eqcatcode \let\eqcatcode\relax
  \endinput}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\ldf@finish}
% \changes{babel~3.6a}{1996/10/16}{Macro added}
%    This macro takes one argument. It is the name of the language
%    that was defined in the language definition file.
%
%    We load the local configuration file if one is present, we set
%    the main language (taking into account that the argument might be
%    a control sequence that needs to be expanded) and reset the
%    category code of the @-sign.
% \changes{babel~3.7o}{2003/11/26}{Also restore the category code of
%    the equals sign}
% \changes{babel~3.9a}{2012/10/01}{Added \cs{bbl@afterlang} which
%    executes the code delayed with \cs{AfterBabelLanguage}}
%    \begin{macrocode}
\def\ldf@finish#1{%
  \loadlocalcfg{#1}%
  \bbl@afterlang
  \let\bbl@afterlang\relax
  \let\BabelModifiers\relax
  \let\bbl@screset\relax
  \expandafter\main@language\expandafter{#1}%
  \catcode`\@=\atcatcode \let\atcatcode\relax
  \catcode`\==\eqcatcode \let\eqcatcode\relax}
%    \end{macrocode}
%  \end{macro}
%
%    After the preamble of the document the commands |\LdfInit|,
%    |\ldf@quit| and |\ldf@finish| are no longer needed. Therefor
%    they are turned into warning messages in \LaTeX.
%    \begin{macrocode}
\@onlypreamble\LdfInit
\@onlypreamble\ldf@quit
\@onlypreamble\ldf@finish
%    \end{macrocode}
%
%  \begin{macro}{\main@language}
% \changes{babel~3.5a}{1995/02/17}{Macro added}
% \changes{babel~3.6a}{1996/10/16}{\cs{main@language} now also sets
%    \cs{languagename} and \cs{l@languagename} for use by other
%    packages in the preamble of a document}
%  \begin{macro}{\bbl@main@language}
% \changes{babel~3.5a}{1995/02/17}{Macro added}
%    This command should be used in the various language definition
%    files. It stores its argument in |\bbl@main@language|; to be used
%    to switch to the correct language at the beginning of the
%    document.
% \changes{babel~3.8l}{2008/07/06}{Use \cs{bbl@patterns}}
%    \begin{macrocode}
\def\main@language#1{%
  \def\bbl@main@language{#1}%
  \let\languagename\bbl@main@language
  \bbl@patterns{\languagename}}
%    \end{macrocode}
%
%    We also have to make sure that some code gets executed at the
%    beginning of the document.
%    \begin{macrocode}
\AtBeginDocument{%
  \expandafter\selectlanguage\expandafter{\bbl@main@language}}
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%
% \subsection{Support for active characters}
%
%  \begin{macro}{\bbl@add@special}
% \changes{babel~3.2}{1991/11/10}{Added macro}
%    The macro |\bbl@add@special| is used to add a new character (or
%    single character control sequence) to the macro |\dospecials|
%    (and |\@sanitize| if \LaTeX\ is used).
%
%    To keep all changes local, we begin a new group.  Then we
%    redefine the macros |\do| and |\@makeother| to add themselves and
%    the given character without expansion.
%
%    To add the character to the macros, we expand the original macros
%    with the additional character inside the redefinition of the
%    macros.  Because |\@sanitize| can be undefined, we put the
%    definition inside a conditional.
%    \begin{macrocode}
\def\bbl@add@special#1{%
  \begingroup
    \def\do{\noexpand\do\noexpand}%
    \def\@makeother{\noexpand\@makeother\noexpand}%
  \edef\x{\endgroup
    \def\noexpand\dospecials{\dospecials\do#1}%
    \expandafter\ifx\csname @sanitize\endcsname\relax \else
      \def\noexpand\@sanitize{\@sanitize\@makeother#1}%
    \fi}%
  \x}
%    \end{macrocode}
%    The macro |\x| contains at this moment the following:\\
%    |\endgroup\def\dospecials{|\textit{old contents}%
%    |\do|\meta{char}|}|.\\
%    If |\@sanitize| is defined, it contains an additional definition
%    of this macro.  The last thing we have to do, is the expansion of
%    |\x|.  Then |\endgroup| is executed, which restores the old
%    meaning of |\x|, |\do| and |\@makeother|.  After the group is
%    closed, the new definition of |\dospecials| (and |\@sanitize|) is
%    assigned.
%
%  \end{macro}
%
%  \begin{macro}{\bbl@remove@special}
% \changes{babel~3.2}{1991/11/10}{Added macro}
%    The companion of the former macro is |\bbl@remove@special|.  It
%    is used to remove a character from the set macros |\dospecials|
%    and |\@sanitize|.
%
%    To keep all changes local, we begin a new group.  Then we define
%    a help macro |\x|, which expands to empty if the characters
%    match, otherwise it expands to its nonexpandable input.  Because
%    \TeX\ inserts a |\relax|, if the corresponding |\else| or |\fi|
%    is scanned before the comparison is evaluated, we provide a `stop
%    sign' which should expand to nothing.
%
%    With the help of this macro we define |\do| and |\make@other|.
%
%    The rest of the work is similar to |\bbl@add@special|.
%    \begin{macrocode}
\def\bbl@remove@special#1{%
  \begingroup
    \def\x##1##2{\ifnum`#1=`##2\noexpand\@empty
                 \else\noexpand##1\noexpand##2\fi}%
    \def\do{\x\do}%
    \def\@makeother{\x\@makeother}%
  \edef\x{\endgroup
    \def\noexpand\dospecials{\dospecials}%
    \expandafter\ifx\csname @sanitize\endcsname\relax \else
      \def\noexpand\@sanitize{\@sanitize}%
    \fi}%
  \x}
%    \end{macrocode}
%  \end{macro}
%
%  \subsection{Shorthands}
%
%  \begin{macro}{\initiate@active@char}
% \changes{babel~3.5a}{1995/02/11}{Added macro}
% \changes{babel~3.5b}{1995/03/03}{Renamed macro}
%    A language definition file can call this macro to make a
%    character active. This macro takes one argument, the character
%    that is to be made active. When the character was already active
%    this macro does nothing. Otherwise, this macro defines the
%    control sequence |\normal@char|\m{char} to expand to the
%    character in its `normal state' and it defines the active
%    character to expand to |\normal@char|\m{char} by default
%    (\m{char} being the character to be made active). Later its
%    definition can be changed to expand to |\active@char|\m{char}
%    by calling |\bbl@activate{|\m{char}|}|.
%
%    For example, to make the double quote character active one could
%    have |\initiate@active@char{"}| in a language definition file.
%    This defines |"| as |\active@prefix "\active@char"| (where the
%    first |"| is the character with its original catcode, when the
%    shorthand is created, and |\active@char"| is a single token). In
%    protected contexts, it expands to |\protect "| or |\noexpand "|
%    (ie, with the original |"|); otherwise |\active@char"| is
%    executed. This macro in turn expands to |\normal@char"| in
%    ``safe'' contexts (eg, |\label|), but |\user@active"| in normal
%    ``unsafe'' ones. The latter search a definition in the user,
%    language and system levels, in this order, but if none is found,
%    |\normal@char"| is used.  However, a deactivated shorthand (with
%    |\bbl@deactivate| is defined as |\active@prefix "\normal@char"|.
%
%    The following macro is used to define shorthands in the three
%    levels. It takes 4 arguments: the (string'ed) character,
%    |\<level>@group|, |<level>@active| and |<next-level>@active|
%    (except in |system|). 
% \changes{babel~3.9a}{2012/08/18}{New macro, with code from
%    \cs{@initiate@active@char}}
%    \begin{macrocode}
\def\bbl@active@def#1#2#3#4{%
  \@namedef{#3#1}{%
    \expandafter\ifx\csname#2@sh@#1@\endcsname\relax
      \bbl@afterelse\bbl@sh@select#2#1{#3@arg#1}{#4#1}%
    \else
      \bbl@afterfi\csname#2@sh@#1@\endcsname
    \fi}%
%    \end{macrocode}
%    When there is also no current-level shorthand with an argument we
%    will check whether there is a next-level  defined shorthand for
%    this active character. 
% \changes{babel~3.7e}{1999/09/24}{pass the argument on with braces in
%    order to prevent it from breaking up}
% \changes{babel~3.7f}{2000/02/18}{remove the braces again}
%    \begin{macrocode}
  \long\@namedef{#3@arg#1}##1{%
    \expandafter\ifx\csname#2@sh@#1@\string##1@\endcsname\relax
      \bbl@afterelse\csname#4#1\endcsname##1%
    \else
      \bbl@afterfi\csname#2@sh@#1@\string##1@\endcsname
    \fi}}%
%    \end{macrocode}
% \changes{babel~3.9a}{2012/08/18}{Removed an extra hash. Now calls
%    \cs{@initiate@active@char} with 3 arguments.}
%    |\initiate@active@char| calls |\@initiate@active@char| with 3
%    arguments. All of them are the same character with different
%    catcodes: active, other (string'ed) and the original one.
%    \begin{macrocode}
\def\initiate@active@char#1{%
  \expandafter\ifx\csname active@char\string#1\endcsname\relax
    \bbl@withactive
      {\expandafter\@initiate@active@char\expandafter}#1\string#1#1%
  \fi}
%    \end{macrocode}
% \changes{babel~3.9e}{2012/08/18}{Introduced the 3-argument
%   \cs{@initiate@active@char}, with different catcodes: active,
%   string'ed, and original. Reorganized}
% \changes{babel~3.9a}{2012/08/19}{The catcode is saved}
% \changes{babel~3.9a}{2012/09/09}{The original definition is saved,
% too}
% \changes{babel~3.9a}{2012/12/27}{Take into account mathematically
%   active chars, to avoid infinite loops}
%   The very first thing to do is saving the original catcode and the
%   original definition, even if not active, which is possible
%   (undefined characters require a special treatement to avoid
%   making them |\relax|).  
%    \begin{macrocode}
\def\@initiate@active@char#1#2#3{%
  \expandafter\edef\csname bbl@oricat@#2\endcsname{%
    \catcode`#2=\the\catcode`#2\relax}%
  \ifx#1\@undefined
    \expandafter\edef\csname bbl@oridef@#2\endcsname{%
      \let\noexpand#1\noexpand\@undefined}%
  \else
    \expandafter\let\csname bbl@oridef@@#2\endcsname#1%
    \expandafter\edef\csname bbl@oridef@#2\endcsname{%
      \let\noexpand#1%
      \expandafter\noexpand\csname bbl@oridef@@#2\endcsname}%
  \fi
%    \end{macrocode}
%    If the character is already active we provide the default
%    expansion under this shorthand mechanism. Otherwise we write a
%    message in the transcript file, and define |\normal@char|\m{char}
%    to expand to the character in its default state. If the character
%    is mathematically active when \babel{} is loaded (for example
%    |'|) the normal expansion is somewhat different to avoid an
%    infinite loop (but it does not prevent the loop if the mathcode
%    is set to |"8000| \textit{a posteriori}).
%    \begin{macrocode}
  \ifx#1#3\relax
    \expandafter\let\csname normal@char#2\endcsname#3%
  \else
    \bbl@info{Making #2 an active character}%
    \ifnum\mathcode`#2="8000
      \@namedef{normal@char#2}{%
        \textormath{#3}{\csname bbl@oridef@@#2\endcsname}}%
    \else
      \@namedef{normal@char#2}{#3}%
    \fi
%    \end{macrocode}
%    To prevent problems with the loading of other packages after
%    \babel\ we reset the catcode of the character to the original one
%    at the end of the package and of each language file (except with
%    \textsf{KeepShorthandsActive}). It is re-activate again at
%    |\begin{document}|.  We also need to make sure that the
%    shorthands are active during the processing of the \file{.aux}
%    file. Otherwise some citations may give unexpected results in
%    the printout when a shorthand was used in the optional argument
%    of |\bibitem| for example.
% \changes{babel~3.6i}{1997/03/01}{Make shorthands active during
%    \file{.aux} file processing}. Then we
%    make it active (not strictly necessary, but done for backward
%    compatibility).
% \changes{babel~3.5f}{1995/12/01}{Restore the category code of a
%    shorthand char at end of package}
% \changes{babel~3.6f}{1997/01/14}{Made restoring of the category code
%    of shorthand characters optional}
% \changes{babel~3.7a}{1997/03/21}{Use \cs{@ifpackagewith} to
%    determine whether shorthand characters need to remain active}
%    \begin{macrocode}
    \bbl@restoreactive{#2}%
    \AtBeginDocument{%
      \catcode`#2\active
      \if@filesw
        \immediate\write\@mainaux{\catcode`\string#2\active}%
      \fi}%
    \expandafter\bbl@add@special\csname#2\endcsname
    \catcode`#2\active
  \fi
%    \end{macrocode}
%    Now we have set |\normal@char|\m{char}, we must define
%    |\active@char|\m{char}, to be executed when the character is
%    activated.  We define the first level expansion of
%    |\active@char|\m{char} to check the status of the |@safe@actives|
%    flag. If it is set to true we expand to the `normal' version of
%    this character, otherwise we call |\user@active|\m{char} to start
%    the search of a definition in the user, language and system
%    levels (or eventually |normal@char|\m{char}).
% \changes{babel~3.9a}{2012/12/27}{Added code for option math=normal}
%    \begin{macrocode}
  \let\bbl@tempa\@firstoftwo
  \if\string^#2%
    \def\bbl@tempa{\noexpand\textormath}%
  \else
    \ifx\bbl@mathnormal\@undefined\else
      \let\bbl@tempa\bbl@mathnormal
    \fi
  \fi
  \expandafter\edef\csname active@char#2\endcsname{%
    \bbl@tempa
      {\noexpand\if@safe@actives
         \noexpand\expandafter
         \expandafter\noexpand\csname normal@char#2\endcsname
       \noexpand\else
         \noexpand\expandafter
         \expandafter\noexpand\csname user@active#2\endcsname
       \noexpand\fi}%
     {\expandafter\noexpand\csname normal@char#2\endcsname}}%
%    \end{macrocode}
%
% \changes{babel~3.9a}{2012/12/27}{Shorthands are not defined
%    directly, but with a couple of intermediate macros}
% 
%    We now define the default values which the shorthand is set to
%    when activated or deactivated. It is set to the deactivated form
%    (globally), so that the character expands to
%    \begin{center}
%    |\active@prefix| \m{char} |\normal@char|\m{char}
%    \end{center}
%    (where |\active@char|\m{char} is \emph{one} control sequence!).
%
%    \begin{macrocode}
  \bbl@csarg\edef{active@#2}{%
    \noexpand\active@prefix\noexpand#1%
    \expandafter\noexpand\csname active@char#2\endcsname}%
  \bbl@csarg\edef{normal@#2}{%
    \noexpand\active@prefix\noexpand#1%
    \expandafter\noexpand\csname normal@char#2\endcsname}%
  \expandafter\let\expandafter#1\csname bbl@normal@#2\endcsname
%    \end{macrocode}
%    The next level of the code checks whether a user has defined a
%    shorthand for himself with this character. First we check for a
%    single character shorthand. If that doesn't exist we check for a
%    shorthand with an argument.
% \changes{babel~3.5d}{1995/07/02}{Skip the user-level active char
%    with argument if no shorthands with arguments were defined}
% \changes{babel~3.8b}{2004/04/19}{Now use \cs{bbl@sh@select}}
% \changes{babel~3.9a}{2012/08/18}{Instead of the ``copy-paste pattern''
%    a new macro is used}
%    \begin{macrocode}
  \bbl@active@def#2\user@group{user@active}{language@active}%
  \bbl@active@def#2\language@group{language@active}{system@active}%
  \bbl@active@def#2\system@group{system@active}{normal@char}%
%    \end{macrocode}
%    In order to do the right thing when a shorthand with an argument
%    is used by itself at the end of the line we provide a definition
%    for the case of an empty argument. For that case we let the
%    shorthand character expand to its non-active self. Also, When a
%    shorthand combination such as |''| ends up in a heading \TeX\
%    would see |\protect'\protect'|. To prevent this from happening a
%    couple of shorthand needs to be defined at user level.
% \changes{babel~3.7f}{1999/12/09}{Added an extra shorthand
%    combination on user level to catch an interfering \cs{protect}}
% \changes{babel~3.9a}{2012/8/18}{Use \cs{user@group}, as above,
%    instead of the hardwired \texttt{user}}
%    \begin{macrocode}
  \expandafter\edef\csname\user@group @sh@#2@@\endcsname
    {\expandafter\noexpand\csname normal@char#2\endcsname}%
  \expandafter\edef\csname\user@group @sh@#2@\string\protect@\endcsname
    {\expandafter\noexpand\csname user@active#2\endcsname}%
%    \end{macrocode}
%    Finally, a couple of special cases are taken care of.  (1) If we
%    are making the right quote (|'|) active we need to change |\pr@m@s| as
%    well.  Also, make sure that a single |'| in math mode `does the
%    right thing'.  (2) If we are using the caret (|^|) as a shorthand
%    character special care should be taken to make sure math still
%    works. Therefor an extra level of expansion is introduced with a
%    check for math mode on the upper level.
%
% \changes{babel~3.7f}{1999/12/18}{Insert a check for math mode in
%    the definition of \cs{normal@char'}}
% \changes{babel~3.7g}{2000/10/02}{use \cs{textormath} to get rid
%    of the \cs{fi} (PR 3266)}
% \changes{babel~3.7f}{1999/12/18}{The redefinition needs to take
%    place one level higher, \cs{prim@s} needs to be redefined.}
% \changes{babel~3.7f}{1999/12/18}{Introduced an extra
%    level of expansion in the definition of an active caret}
% \changes{babel~3.7f}{2000/09/25}{Make an exception for the active
%    caret which needs an extra level of expansion}
% \changes{babel~3.9a}{2012/09/11}{The output routine resets the quote
%   to \cs{active@math@prime}, so we redefine the latter with the new
%  ``normal'' value}
% \changes{babel~3.9a}{2012/06/20}{Added a couple of missing
%    comment characters (PR 4146)}
% \changes{babel~3.9a}{2012/07/29}{Use \cs{textormath} instead of
%    \cs{ifmath}}
% \changes{babel~3.9a}{2012/11/26}{Compare the char, irrespective of
%    its catcode.}
% \changes{babel~3.9a}{2012/12/27}{Removed the redeclaration of
%   \cs{normal@char'} because it is handled in a generic way above}
% \changes{babel~3.9a}{2012/12/29}{Removed the intermediate step of
%   \cs{bbl@act@caret} and moved above} 
%    \begin{macrocode}
  \if\string'#2%
    \let\prim@s\bbl@prim@s
    \let\active@math@prime#1%
  \fi}
%    \end{macrocode}
%
%    Initiating a shorthand makes active the char. That is not
%    strictly necessary but it is still done for backward
%    compatibility. So we need to restore the original catcode at the
%    end of package \textit{and} and the end of the |ldf|.
%
% \changes{babel~3.9a}{2012/07/04}{Catcodes are also restored after
%    each language, to prevent incompatibilities. Use \cs{string} instead
%    of \cs{noexpand} and add \cs{relax}}
% \changes{babel~3.9a}{2012/10/18}{Catcodes are deactivated in a separate
%    macro, which is made no-op when babel exits}
%
%    \begin{macrocode}
\@ifpackagewith{babel}{KeepShorthandsActive}%
  {\let\bbl@restoreactive\@gobble}%
  {\def\bbl@restoreactive#1{%
     \edef\bbl@tempa{%
       \noexpand\AfterBabelLanguage\noexpand\CurrentOption
         {\catcode`#1=\the\catcode`#1\relax}%
       \noexpand\AtEndOfPackage{\catcode`#1=\the\catcode`#1\relax}}%
     \bbl@tempa}%
   \AtEndOfPackage{\let\bbl@restoreactive\@gobble}}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\bbl@sh@select}
%    This command helps the shorthand supporting macros to select how
%    to proceed. Note that this macro needs to be expandable as do all
%    the shorthand macros in order for them to work in expansion-only
%    environments such as the argument of |\hyphenation|.
%
%    This macro expects the name of a group of shorthands in its first
%    argument and a shorthand character in its second argument. It
%    will expand to either |\bbl@firstcs| or |\bbl@scndcs|. Hence two
%    more arguments need to follow it.
% \changes{babel~3.8b}{2004/04/19}{Added command}
% \changes{babel~3.9a}{2012/08/18}{Removed \cs{string}s, because the
%   char are already string'ed}
%    \begin{macrocode}
\def\bbl@sh@select#1#2{%
  \expandafter\ifx\csname#1@sh@#2@sel\endcsname\relax
    \bbl@afterelse\bbl@scndcs
  \else
    \bbl@afterfi\csname#1@sh@#2@sel\endcsname
  \fi}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\active@prefix}
%    The command |\active@prefix| which is used in the expansion of
%    active characters has a function similar to |\OT1-cmd| in that it
%    |\protect|s the active character whenever |\protect| is
%    \emph{not} |\@typeset@protect|.
% \changes{babel~3.5d}{1995/07/02}{\cs{@protected@cmd} has vanished
%    from \file{ltoutenc.dtx}}
% \changes{babel~3.7o}{2003/11/17}{Added handling of the situation
%    where \cs{protect} is set to \cs{@unexpandable@protect}}
%    \begin{macrocode}
\def\active@prefix#1{%
  \ifx\protect\@typeset@protect
  \else
%    \end{macrocode}
%    When |\protect| is set to |\@unexpandable@protect| we make sure
%    that the active character is als \emph{not} expanded by inserting
%    |\noexpand| in front of it. The |\@gobble| is needed to remove
%    a token such as |\activechar:| (when the double colon was the
%    active character to be dealt with).
%    \begin{macrocode}
    \ifx\protect\@unexpandable@protect
      \noexpand#1%
    \else
      \protect#1%
    \fi
    \expandafter\@gobble
  \fi}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\if@safe@actives}
%    In some circumstances it is necessary to be able to change the
%    expansion of an active character on the fly. For this purpose the
%    switch |@safe@actives| is available. The setting of this switch
%    should be checked in the first level expansion of
%    |\active@char|\m{char}.
%    \begin{macrocode}
\newif\if@safe@actives
\@safe@activesfalse
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\bbl@restore@actives}
% \changes{babel~3.7m}{2003/11/15}{New macro added}
%    When the output routine kicks in while the
%    active characters were made ``safe'' this must be undone in
%    the headers to prevent unexpected typeset results. For this
%    situation we define a command to make them ``unsafe'' again.
%    \begin{macrocode}
\def\bbl@restore@actives{\if@safe@actives\@safe@activesfalse\fi}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\bbl@activate}
%  \begin{macro}{\bbl@deactivate}
%  \changes{babel~3.5a}{1995/02/11}{Added macro}
%  \changes{babel~3.9a}{2013/01/11}{\cs{bbl@withactive} makes sure the
%    catcode is active} 
%    Both macros take one argument, like |\initiate@active@char|. The
%    macro is used to change the definition of an active character to
%    expand to |\active@char|\m{char} in the case of |\bbl@activate|,
%    or |\normal@char|\m{char} in the case of
%    |\bbl@deactivate|.
%    \begin{macrocode}
\def\bbl@activate#1{%
  \bbl@withactive{\expandafter\let\expandafter}#1%
    \csname bbl@active@\string#1\endcsname}
\def\bbl@deactivate#1{%
  \bbl@withactive{\expandafter\let\expandafter}#1%
    \csname bbl@normal@\string#1\endcsname}
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%
%  \begin{macro}{\bbl@firstcs}
%  \begin{macro}{\bbl@scndcs}
%    These macros have two arguments. They use one of their arguments
%    to build a control sequence from.
%    \begin{macrocode}
\def\bbl@firstcs#1#2{\csname#1\endcsname}
\def\bbl@scndcs#1#2{\csname#2\endcsname}
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%
%  \begin{macro}{\declare@shorthand}
%    The command |\declare@shorthand| is used to declare a shorthand
%    on a certain level. It takes three arguments:
%    \begin{enumerate}
%    \item a name for the collection of shorthands, i.e. `system', or
%      `dutch';
%    \item the character (sequence) that makes up the shorthand,
%      i.e. |~| or |"a|;
%    \item the code to be executed when the shorthand is encountered.
%    \end{enumerate}
% \changes{babel~3.5d}{1995/07/02}{Make a `note' when a shorthand with
%    an argument is defined.}
% \changes{babel~3.6i}{1997/02/23}{Make it possible to distinguish the
%    constructed control sequences for the case with argument}
% \changes{babel~3.8b}{2004/04/19}{We need to support shorthands with
%    and without argument in different groups; added the name of the
%    group to the storage macro}
% \changes{babel~3.9a}{2012/07/03}{Check if shorthands are redefined}
%    \begin{macrocode}
\def\declare@shorthand#1#2{\@decl@short{#1}#2\@nil}
\def\@decl@short#1#2#3\@nil#4{%
  \def\bbl@tempa{#3}%
  \ifx\bbl@tempa\@empty
    \expandafter\let\csname #1@sh@\string#2@sel\endcsname\bbl@scndcs
    \@ifundefined{#1@sh@\string#2@}{}%
      {\def\bbl@tempa{#4}%
       \expandafter\ifx\csname#1@sh@\string#2@\endcsname\bbl@tempa
       \else
         \bbl@info
           {Redefining #1 shorthand \string#2\\%
            in language \CurrentOption}%
       \fi}%
    \@namedef{#1@sh@\string#2@}{#4}%
  \else
    \expandafter\let\csname #1@sh@\string#2@sel\endcsname\bbl@firstcs
    \@ifundefined{#1@sh@\string#2@\string#3@}{}%
      {\def\bbl@tempa{#4}%
       \expandafter\ifx\csname#1@sh@\string#2@\string#3@\endcsname\bbl@tempa
       \else
         \bbl@info
           {Redefining #1 shorthand \string#2\string#3\\%
            in language \CurrentOption}%
       \fi}%
    \@namedef{#1@sh@\string#2@\string#3@}{#4}%
  \fi}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\textormath}
%    Some of the shorthands that will be declared by the language
%    definition files have to be usable in both text and mathmode. To
%    achieve this the helper macro |\textormath| is provided.
% \changes{babel~3.9a}{2012/12/29}{Failed if an argument had a
%    condicional. Use the more robust mechanism of  \cs{XXXoftwo}} 
%    \begin{macrocode}
\def\textormath{%
  \ifmmode
    \expandafter\@secondoftwo
  \else
    \expandafter\@firstoftwo
  \fi}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\user@group}
%  \begin{macro}{\language@group}
%  \begin{macro}{\system@group}
%    The current concept of `shorthands' supports three levels or
%    groups of shorthands. For each level the name of the level or
%    group is stored in a macro. The default is to have a user group;
%    use language group `english' and have a system group called
%    `system'.
% \changes{babel~3.6i}{1997/02/24}{Have a user group called `user' by
%    default}
%    \begin{macrocode}
\def\user@group{user}
\def\language@group{english}
\def\system@group{system}
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%  \end{macro}
%
%  \begin{macro}{\useshorthands}
%    This is the user level command to tell \LaTeX\ that user level
%    shorthands will be used in the document. It takes one argument,
%    the character that starts a shorthand. First note that this is
%    user level, and then initialize and activate the character for
%    use as a shorthand character (ie, it's active in the
%    preamble). Languages can deactivate shorthands, so a starred
%    version is also provided which activates them always after the
%    language has been switched.
%
% \changes{babel~3.7j}{2001/11/11}{When \TeX\ has seen a character
%    its category code is fixed; need to use a `stand-in' for the
%    call of \cs{bbl@activate}} 
% \changes{babel~3.7j}{2003/09/11}{The change from 11/112001 was
%    incomplete}
% \changes{babel~3.9a}{2012/08/05}{Now \cs{bbl@activate} makes sure
%    the catcode is active, so this part is simplified}
% \changes{babel~3.9a}{2012/08/12}{User shorhands can be
%   defined even with shorthands=off}
%    \begin{macrocode}
\def\useshorthands{%
  \@ifstar\bbl@usesh@s{\bbl@usesh@x{}}}
\def\bbl@usesh@s#1{%
  \bbl@usesh@x
    {\AddBabelHook{babel-sh-\string#1}{afterextras}{\bbl@activate{#1}}}%
    {#1}}
\def\bbl@usesh@x#1#2{%
  \bbl@ifshorthand{#2}%
    {\def\user@group{user}%
     \initiate@active@char{#2}%
     #1%
     \bbl@activate{#2}}%
    {\bbl@error
       {Cannot declare a shorthand turned off (\string#2)}
       {Sorry, but you cannot use shorthands which have been\\%
        turned off in the package options}}}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\defineshorthand}
% \changes{babel~3.9a}{2012/08/05}{Added optional argument, to provide
%    a way to (re)define language shorthands} 
% \changes{babel~3.9a}{2012/08/25}{Extended for language-dependent
%    user macros, with two new auxiliary macros}
%    Currently we only support two groups of user level shorthands,
%    named internally |user| and |user@<lang>| (language-dependent
%    user shorthands). By default, only the first one is taken into
%    account, but if the former is also used (in the optional argument
%    of |\defineshorthand|) a new level is inserted for it
%    (|user@generic|, done by |\bbl@set@user@generic|); we make also
%    sure |{}| and |\protect| are taken into account in this new top
%    level.
%    \begin{macrocode}
\def\user@language@group{user@\language@group}
\def\bbl@set@user@generic#1#2{%
  \@ifundefined{user@generic@active#1}%
    {\bbl@active@def#1\user@language@group{user@active}{user@generic@active}%
     \bbl@active@def#1\user@group{user@generic@active}{language@active}%
     \expandafter\edef\csname#2@sh@#1@@\endcsname{%
       \expandafter\noexpand\csname normal@char#1\endcsname}%
     \expandafter\edef\csname#2@sh@#1@\string\protect@\endcsname{%
       \expandafter\noexpand\csname user@active#1\endcsname}}%
  \@empty}
\newcommand\defineshorthand[3][user]{%
  \edef\bbl@tempa{\zap@space#1 \@empty}%
  \bbl@for\bbl@tempb\bbl@tempa{%
    \if*\expandafter\@car\bbl@tempb\@nil
      \edef\bbl@tempb{user@\expandafter\@gobble\bbl@tempb}%
      \@expandtwoargs
        \bbl@set@user@generic{\expandafter\string\@car#2\@nil}\bbl@tempb
    \fi
    \declare@shorthand{\bbl@tempb}{#2}{#3}}}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\languageshorthands}
%    A user level command to change the language from which shorthands
%    are used. Unfortunately, \babel{} currently does not keep track
%    of defined groups, and therefore there is no way to catch a
%    possible change in casing.
%    \begin{macrocode}
\def\languageshorthands#1{\def\language@group{#1}}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\aliasshorthand}
% \changes{babel~3.5f}{1996/01/25}{New command}
%    First the new shorthand needs to be initialized,
%    \begin{macrocode}
\def\aliasshorthand#1#2{%
  \bbl@ifshorthand{#2}%
    {\expandafter\ifx\csname active@char\string#2\endcsname\relax
       \ifx\document\@notprerr
         \@notshorthand{#2}%
       \else
         \initiate@active@char{#2}%
%    \end{macrocode}
% \changes{babel~3.9a}{2012/08/06}{Instead of letting the new shorthand to
%    the original char, which very often didn't work, we define it
%    directly}
% \changes{babel~3.9a}{2012/08/20}{Make sure both characters (old an
%    new) are active}
%    Then, we define the new shorthand in terms of the original
%    one, but note with |\aliasshorthands{"}{/}| is
%    |\active@prefix /\active@char/|, so we still need to let the
%    lattest to |\active@char"|.
%    \begin{macrocode}
         \expandafter\let\csname active@char\string#2\expandafter\endcsname
           \csname active@char\string#1\endcsname
         \expandafter\let\csname normal@char\string#2\expandafter\endcsname
           \csname normal@char\string#1\endcsname
         \bbl@activate{#2}%
       \fi
     \fi}%
    {\bbl@error
       {Cannot declare a shorthand turned off (\string#2)}
       {Sorry, but you cannot use shorthands which have been\\%
        turned off in the package options}}}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\@notshorthand}
% \changes{v3.8d}{2004/11/20}{Error message added}
%    
%    \begin{macrocode}
\def\@notshorthand#1{%
  \bbl@error{%
    The character `\string #1' should be made a shorthand character;\\%
    add the command \string\useshorthands\string{#1\string} to
    the preamble.\\%
    I will ignore your instruction}{}}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\shorthandon}
% \changes{babel~3.7a}{1998/06/07}{Added command}
%  \begin{macro}{\shorthandoff}
% \changes{babel~3.7a}{1998/06/07}{Added command}
% \changes{babel~3.9a}{2012/09/08}{Added code fo the starred variant
%    of \cs{shorthandoff}} 
%    The first level definition of these macros just passes the
%    argument on to |\bbl@switch@sh|, adding |\@nil| at the end to
%    denote the end of the list of characters.
%    \begin{macrocode}
\newcommand*\shorthandon[1]{\bbl@switch@sh\@ne#1\@nnil}
\DeclareRobustCommand*\shorthandoff{%
  \@ifstar{\bbl@shorthandoff\tw@}{\bbl@shorthandoff\z@}}
\def\bbl@shorthandoff#1#2{\bbl@switch@sh#1#2\@nnil}
%    \end{macrocode}
%
%  \begin{macro}{\bbl@switch@sh}
% \changes{babel~3.7a}{1998/06/07}{Added command}
% \changes{babel~3.9a}{2013/02/21}{Code revised}
%    The macro |\bbl@switch@sh| takes the list of characters apart one
%    by  one and subsequently switches the category code of the
%    shorthand character according to the first argument of
%    |\bbl@switch@sh|.
%
%    But before any of this switching takes place we make sure that
%    the character we are dealing with is known as a shorthand
%    character. If it is, a macro such as |\active@char"| should
%    exist.
%
%    Switching off and on is easy -- we just set the category
%    code to `other' (12) and |\active|. With the starred version, the
%    original catcode and the original definition, saved
%    in |@initiate@active@char|, are restored. 
%
%    \begin{macrocode}
\def\bbl@switch@sh#1#2{%
  \ifx#2\@nnil\else
    \@ifundefined{bbl@active@\string#2}%
      {\bbl@error
         {I cannot switch `\string#2' on or off--not a shorthand}%
         {This character is not a shorthand. Maybe you made\\%
          a typing mistake? I will ignore your instruction}}%
      {\ifcase#1%
         \catcode`#212\relax
       \or
         \catcode`#2\active
       \or
         \csname bbl@oricat@\string#2\endcsname
         \csname bbl@oridef@\string#2\endcsname
       \fi}%
    \bbl@afterfi\bbl@switch@sh#1%
  \fi}
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%  \end{macro}
%
% \subsection{Conditional loading of shorthands}
%
% \changes{babel~3.9a}{2012/06/16}{Added code}
%
% Note the value is that at the expansion time, eg, in the preample
% shorhands are usually deactivated.
%    \begin{macrocode}
\def\babelshorthand{\active@prefix\babelshorthand\bbl@putsh}
\def\bbl@putsh#1{%
   \@ifundefined{bbl@active@\string#1}%
      {\bbl@putsh@i#1\@empty\@nnil}%
      {\csname bbl@active@\string#1\endcsname}}
\def\bbl@putsh@i#1#2\@nnil{%
  \csname\languagename @sh@\string#1@%
    \ifx\@empty#2\else\string#2@\fi\endcsname}
\ifx\bbl@opt@shorthands\@nnil\else
  \let\bbl@s@initiate@active@char\initiate@active@char
  \def\initiate@active@char#1{%
    \bbl@ifshorthand{#1}{\bbl@s@initiate@active@char{#1}}{}}
  \let\bbl@s@switch@sh\bbl@switch@sh
  \def\bbl@switch@sh#1#2{%
    \ifx#2\@nnil\else
      \bbl@afterfi
      \bbl@ifshorthand{#2}{\bbl@s@switch@sh#1{#2}}{\bbl@switch@sh#1}%
    \fi}
  \let\bbl@s@activate\bbl@activate
  \def\bbl@activate#1{%
    \bbl@ifshorthand{#1}{\bbl@s@activate{#1}}{}}
  \let\bbl@s@deactivate\bbl@deactivate
  \def\bbl@deactivate#1{%
    \bbl@ifshorthand{#1}{\bbl@s@deactivate{#1}}{}}
\fi
%    \end{macrocode}
%
% \changes{babel~3.9a}{2012/12/27}{Removed redundant system declarations}
%
%  \begin{macro}{\bbl@prim@s}
% \changes{babel~3.7f}{1999/12/01}{Need to redefine \cs{prim@s} as
%    well as plain \TeX's definition uses \cs{next}}
%  \begin{macro}{\bbl@pr@m@s}
% \changes{babel~3.5a}{1995/03/10}{Added macro}
% \changes{babel~3.9a}{2012/07/29}{\cs{bbl@pr@m@s} rewritten to
%    take into account catcodes for both the quote and the hat}
%    One of the internal macros that are involved in substituting
%    |\prime| for each right quote in mathmode is |\prim@s|. This
%    checks if the next character is a right quote. When the right
%    quote is active, the definition of this macro needs to be adapted
%    to look also for an active right quote; the hat could be active,
%    too.
%    \begin{macrocode}
\def\bbl@prim@s{%
  \prime\futurelet\@let@token\bbl@pr@m@s}
\def\bbl@if@primes#1#2{%
  \ifx#1\@let@token
    \expandafter\@firstoftwo
  \else\ifx#2\@let@token
    \bbl@afterelse\expandafter\@firstoftwo
  \else
    \bbl@afterfi\expandafter\@secondoftwo
  \fi\fi}
\begingroup
  \catcode`\^=7  \catcode`\*=\active  \lccode`\*=`\^
  \catcode`\'=12 \catcode`\"=\active  \lccode`\"=`\' 
  \lowercase{%
    \gdef\bbl@pr@m@s{%
      \bbl@if@primes"'%
        \pr@@@s
        {\bbl@if@primes*^\pr@@@t\egroup}}}
\endgroup
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%
%    Usually the |~| is active and expands to \verb*=\penalty\@M\ =.
%    When it is written to the \file{.aux} file it is written
%    expanded. To prevent that and to be able to use the character |~|
%    as a start character for a shorthand, it is redefined here as a
%    one character shorthand on system level. The system declaration
%    is in most cases redundant (when |~| is still a non-break space),
%    and in some cases is inconvenient (if |~| has been redefined);
%    however, for backward compatibility it is maintained (some
%    existing documents may rely on the \babel{} value).
%    \begin{macrocode}
\initiate@active@char{~}
\declare@shorthand{system}{~}{\leavevmode\nobreak\ }
\bbl@activate{~}
%    \end{macrocode}
%
%  \begin{macro}{\OT1dqpos}
%  \begin{macro}{\T1dqpos}
%    The position of the double quote character is different for the
%    OT1 and T1 encodings. It will later be selected using the
%    |\f@encoding| macro. Therefor we define two macros here to store
%    the position of the character in these encodings.
%    \begin{macrocode}
\expandafter\def\csname OT1dqpos\endcsname{127}
\expandafter\def\csname T1dqpos\endcsname{4}
%    \end{macrocode}
%    When the macro |\f@encoding| is undefined (as it is in plain
%    \TeX) we define it here to expand to \texttt{OT1}
%    \begin{macrocode}
\ifx\f@encoding\@undefined
  \def\f@encoding{OT1}
\fi
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%
%  \subsection{Language attributes}
%
%    Language attributes provide a means to give the user control over
%    which features of the language definition files he wants to
%    enable.
% \changes{babel~3.7c}{1998/07/02}{Added support for language
%    attributes}
%  \begin{macro}{\languageattribute}
% \changes{babel~3.9a}{2012/09/07}{Use \cs{@expandtwoargs} with \cs{in@}}
%    The macro |\languageattribute| checks whether its arguments are
%    valid and then activates the selected language attribute.
%    First check whether the language is known, and then process each
%    attribute in the list.
%    \begin{macrocode}
\newcommand\languageattribute[2]{%
  \def\bbl@tempc{#1}%
  \bbl@fixname\bbl@tempc
  \bbl@iflanguage\bbl@tempc{%
    \@for\bbl@attr:=#2\do{%
%    \end{macrocode}
%    We want to make sure that each attribute is selected only once;
%    therefor we store the already selected attributes in
%    |\bbl@known@attribs|. When that control sequence is not yet
%    defined this attribute is certainly not selected before.
%    \begin{macrocode}
      \ifx\bbl@known@attribs\@undefined
        \in@false
      \else
%    \end{macrocode}
%    Now we need to see if the attribute occurs in the list of
%    already selected attributes.
%    \begin{macrocode}
        \@expandtwoargs\in@{,\bbl@tempc-\bbl@attr,}{,\bbl@known@attribs,}%
      \fi
%    \end{macrocode}
%    When the attribute was in the list we issue a warning; this might
%    not be the users intention.
%    \begin{macrocode}
      \ifin@
        \bbl@warning{%
          You have more than once selected the attribute '\bbl@attr'\\%
          for language #1}%
      \else
%    \end{macrocode}
%    When we end up here the attribute is not selected before. So, we
%    add it to the list of selected attributes and execute the
%    associated \TeX-code.
%    \begin{macrocode}
        \edef\bbl@tempa{%
          \noexpand\bbl@add@list
          \noexpand\bbl@known@attribs{\bbl@tempc-\bbl@attr}}%
        \bbl@tempa
        \edef\bbl@tempa{\bbl@tempc-\bbl@attr}%
        \expandafter\bbl@ifknown@ttrib\expandafter{\bbl@tempa}\bbl@attributes%
        {\csname\bbl@tempc @attr@\bbl@attr\endcsname}%
        {\@attrerr{\bbl@tempc}{\bbl@attr}}%
     \fi}}}
%    \end{macrocode}
%    This command should only be used in the preamble of a document.
%    \begin{macrocode}
\@onlypreamble\languageattribute
%    \end{macrocode}
%    The error text to be issued when an unknown attribute is
%    selected.
%    \begin{macrocode}
\newcommand*{\@attrerr}[2]{%
  \bbl@error
    {The attribute #2 is unknown for language #1.}%
    {Your command will be ignored, type <return> to proceed}}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\bbl@declare@ttribute}
%    This command adds the new language/attribute combination to the
%    list of known attributes.
%
%    Then it defines a control sequence to be executed when the
%    attribute is used in a document. The result of this should be
%    that the macro |\extras...| for the current language is extended,
%    otherwise the attribute will not work as its code is removed from
%    memory at |\begin{document}|.
%    \begin{macrocode}
\def\bbl@declare@ttribute#1#2#3{%
  \@expandtwoargs\in@{,#2,}{,\BabelModifiers,}%
  \ifin@
    \AfterBabelLanguage{#1}{\languageattribute{#1}{#2}}%
  \fi
  \bbl@add@list\bbl@attributes{#1-#2}%
  \expandafter\def\csname#1@attr@#2\endcsname{#3}}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\bbl@ifattributeset}
% \changes{babel~3.7f}{2000/02/12}{macro added}
%    This internal macro has 4 arguments. It can be used to interpret
%    \TeX\ code based on whether a certain attribute was set. This
%    command should appear inside the argument to |\AtBeginDocument|
%    because the attributes are set in the document preamble,
%    \emph{after} \babel\ is loaded.
%
%    The first argument is the language, the second argument the
%    attribute being checked, and the third and fourth arguments are
%    the true and false clauses.
%    \begin{macrocode}
\def\bbl@ifattributeset#1#2#3#4{%
%    \end{macrocode}
%    First we need to find out if any attributes were set; if not
%    we're done.
%    \begin{macrocode}
  \ifx\bbl@known@attribs\@undefined
    \in@false
  \else
%    \end{macrocode}
%    The we need to check the list of known attributes.
%    \begin{macrocode}
    \@expandtwoargs\in@{,#1-#2,}{,\bbl@known@attribs,}%
  \fi
%    \end{macrocode}
%    When we're this far |\ifin@| has a value indicating if the
%    attribute in question was set or not. Just to be safe the code to
%    be executed is `thrown over the |\fi|'.
%    \begin{macrocode}
  \ifin@
    \bbl@afterelse#3%
  \else
    \bbl@afterfi#4%
  \fi
  }
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\bbl@add@list}
%    This internal macro adds its second argument to a comma
%    separated list in its first argument. When the list is not
%    defined yet (or empty), it will be initiated
%    \begin{macrocode}
\def\bbl@add@list#1#2{%
  \ifx#1\@undefined
    \def#1{#2}%
  \else
    \ifx#1\@empty
      \def#1{#2}%
    \else
      \edef#1{#1,#2}%
    \fi
  \fi
  }
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\bbl@ifknown@ttrib}
%    An internal macro to check whether a given language/attribute is
%    known. The macro takes 4 arguments, the language/attribute, the
%    attribute list, the \TeX-code to be executed when the attribute
%    is known and the \TeX-code to be executed otherwise.
%    \begin{macrocode}
\def\bbl@ifknown@ttrib#1#2{%
%    \end{macrocode}
%    We first assume the attribute is unknown.
%    \begin{macrocode}
  \let\bbl@tempa\@secondoftwo
%    \end{macrocode}
%    Then we loop over the list of known attributes, trying to find a
%    match.
%    \begin{macrocode}
  \@for\bbl@tempb:=#2\do{%
    \expandafter\in@\expandafter{\expandafter,\bbl@tempb,}{,#1,}%
    \ifin@
%    \end{macrocode}
%    When a match is found the definition of |\bbl@tempa| is changed.
%    \begin{macrocode}
      \let\bbl@tempa\@firstoftwo
    \else
    \fi}%
%    \end{macrocode}
%    Finally we execute |\bbl@tempa|.
%    \begin{macrocode}
  \bbl@tempa
}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\bbl@clear@ttribs}
%    This macro removes all the attribute code from \LaTeX's memory at
%    |\begin{document}| time (if any is present).
% \changes{babel~3.7e}{1999/09/24}{When \cs{bbl@attributes} is
%    undefined this should be a no-op} 
%    \begin{macrocode}
\def\bbl@clear@ttribs{%
  \ifx\bbl@attributes\@undefined\else
    \@for\bbl@tempa:=\bbl@attributes\do{%
      \expandafter\bbl@clear@ttrib\bbl@tempa.
      }%
    \let\bbl@attributes\@undefined
  \fi
  }
\def\bbl@clear@ttrib#1-#2.{%
  \expandafter\let\csname#1@attr@#2\endcsname\@undefined}
\AtBeginDocument{\bbl@clear@ttribs}
%    \end{macrocode}
%  \end{macro}
%
%  \subsection{Support for saving macro definitions}
%
%  To save the meaning of control sequences using |\babel@save|, we
%  use temporary control sequences.  To save hash table entries for
%  these control sequences, we don't use the name of the control
%  sequence to be saved to construct the temporary name.  Instead we
%  simply use the value of a counter, which is reset to zero each time
%  we begin to save new values.  This works well because we release
%  the saved meanings before we begin to save a new set of control
%  sequence meanings (see |\selectlanguage| and |\originalTeX|). Note
%  undefined macros are not undefined any more when saved -- they are
%  |\relax|'ed.
%
%  \begin{macro}{\babel@savecnt}
% \changes{babel~3.2}{1991/11/10}{Added macro}
%  \begin{macro}{\babel@beginsave}
% \changes{babel~3.2}{1991/11/10}{Added macro}
%    The initialization of a new save cycle: reset the counter to
%    zero.
%    \begin{macrocode}
\def\babel@beginsave{\babel@savecnt\z@}
%    \end{macrocode}
%    Before it's forgotten, allocate the counter and initialize all.
%    \begin{macrocode}
\newcount\babel@savecnt
\babel@beginsave
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%
%  \begin{macro}{\babel@save}
% \changes{babel~3.2}{1991/11/10}{Added macro}
%    The macro |\babel@save|\meta{csname} saves the current meaning of
%    the control sequence \meta{csname} to
%    |\originalTeX|\footnote{\cs{originalTeX} has to be
%    expandable, i.\,e.\ you shouldn't let it to \cs{relax}.}.
%    To do this, we let the current meaning to a temporary control
%    sequence, the restore commands are appended to |\originalTeX| and
%    the counter is incremented.
% \changes{babel~3.2c}{1992/03/17}{missing backslash led to errors
%    when executing \cs{originalTeX}}
% \changes{babel~3.2d}{1992/07/02}{saving in \cs{babel@i} and
%    restoring from \cs{@babel@i} doesn't work very well...}
%    \begin{macrocode}
\def\babel@save#1{%
  \expandafter\let\csname babel@\number\babel@savecnt\endcsname#1\relax
  \begingroup
    \toks@\expandafter{\originalTeX\let#1=}%
    \edef\x{\endgroup
      \def\noexpand\originalTeX{\the\toks@ \expandafter\noexpand
         \csname babel@\number\babel@savecnt\endcsname\relax}}%
  \x
  \advance\babel@savecnt\@ne}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\babel@savevariable}
% \changes{babel~3.2}{1991/11/10}{Added macro}
%    The macro |\babel@savevariable|\meta{variable} saves the value of
%    the variable.  \meta{variable} can be anything allowed after the
%    |\the| primitive.
%    \begin{macrocode}
\def\babel@savevariable#1{\begingroup
    \toks@\expandafter{\originalTeX #1=}%
    \edef\x{\endgroup
      \def\noexpand\originalTeX{\the\toks@ \the#1\relax}}%
  \x}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\bbl@frenchspacing}
%  \begin{macro}{\bbl@nonfrenchspacing}
%    Some languages need to have |\frenchspacing| in effect. Others
%    don't want that. The command |\bbl@frenchspacing| switches it on
%    when it isn't already in effect and |\bbl@nonfrenchspacing|
%    switches it off if necessary.
%    \begin{macrocode}
\def\bbl@frenchspacing{%
  \ifnum\the\sfcode`\.=\@m
    \let\bbl@nonfrenchspacing\relax
  \else
    \frenchspacing
    \let\bbl@nonfrenchspacing\nonfrenchspacing
  \fi}
\let\bbl@nonfrenchspacing\nonfrenchspacing
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%
% \subsection{Support for extending macros}
%
%  \begin{macro}{\addto}
%    For each language four control sequences have to be defined that
%    control the language-specific definitions. To be able to add
%    something to these macro once they have been defined the macro
%    |\addto| is introduced. It takes two arguments, a \meta{control
%    sequence} and \TeX-code to be added to the \meta{control
%    sequence}.
%
%    If the \meta{control sequence} has not been defined before it is
%    defined now.  The control sequence could also expand to |\relax|,
%    in which case a circular definition results. The net result is a
%    stack overflow.  Otherwise the replacement text for the
%    \meta{control sequence} is expanded and stored in a token
%    register, together with the \TeX-code to be added.  Finally the
%    \meta{control sequence} is \emph{re}defined, using the contents
%    of the token register.
%
% \changes{babel~3.1}{1991/11/05}{Added macro}
% \changes{babel~3.4}{1994/02/04}{Changed to use toks register}
% \changes{babel~3.6b}{1996/12/30}{Also check if control sequence
%    expands to \cs{relax}}
%    \begin{macrocode}
\def\addto#1#2{%
  \ifx#1\@undefined
    \def#1{#2}%
  \else
    \ifx#1\relax
      \def#1{#2}%
    \else
      {\toks@\expandafter{#1#2}%
       \xdef#1{\the\toks@}}%
    \fi
  \fi}
%    \end{macrocode}
%  \end{macro}
%
% \subsection{Hyphens}
%
%  \begin{macro}{\babelhyphenation}
%
%     \changes{babel~3.9a}{2012/08/28}{Macro added}
%
%     This macro saves hyphenation exceptions. Two macros are used to
%     store them: |\bbl@hyphenation@| for the global ones and
%     |\bbl@hyphenation<lang>| for language ones. See |\bbl@patterns|
%     above for further details. We make sure there is a space between
%     words when multiple commands are used.
%
%    \begin{macrocode}
\@onlypreamble\babelhyphenation
\AtEndOfPackage{%
  \newcommand\babelhyphenation[2][\@empty]{%
    \ifx\bbl@hyphenation@\relax
      \let\bbl@hyphenation@\@empty
    \fi
    \ifx\bbl@hyphlist\@empty\else
      \bbl@warning{%
        You must not intermingle \string\selectlanguage\space and\\%
        \string\babelhyphenation\space or some exception will not\\%
        be taken into account. Reported}%
    \fi
    \ifx\@empty#1%
      \protected@edef\bbl@hyphenation@{\bbl@hyphenation@\space#2}%
    \else
      \edef\bbl@tempb{\zap@space#1 \@empty}%
      \bbl@for\bbl@tempa\bbl@tempb{%
        \bbl@fixname\bbl@tempa
        \bbl@iflanguage\bbl@tempa{%
          \bbl@csarg\protected@edef{hyphenation@\bbl@tempa}{%
            \@ifundefined{bbl@hyphenation@\bbl@tempa}%
              \@empty
              {\csname bbl@hyphenation@\bbl@tempa\endcsname\space}%
            #2}}}%
    \fi}}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\bbl@allowhyphens}
% \changes{babel~3.2b}{1992/02/16}{Moved macro from language
%    definition files}
% \changes{babel~3.7a}{1998/03/12}{Make \cs{allowhyphens} a no-op for
%    T1 fontencoding}
% \changes{babel-3.9a}{2012/07/28}{Replaced many \cs{allowhyphens} by
%    \cs{bbl@allowhyphen}. They were either no-op or executed always.}
%    This macro makes hyphenation possible. Basically its definition
%    is nothing more than |\nobreak| |\hskip| \texttt{0pt plus
%    0pt}\footnote{\TeX\ begins and ends a word for hyphenation at a
%    glue node. The penalty prevents a linebreak at this glue node.}.
%    \begin{macrocode}
\def\bbl@allowhyphens{\nobreak\hskip\z@skip}
\def\bbl@t@one{T1}
\def\allowhyphens{\ifx\cf@encoding\bbl@t@one\else\bbl@allowhyphens\fi}
%    \end{macrocode}
%  \end{macro}
%
% \changes{babel-3.9a}{2012/08/27}{Added \cs{babelhyphen} and related
%    macros}
% \begin{macro}{\babelhyphen}
%    Macros to insert common hyphens. Note the space before |@| in
%    |\babelhyphen|. Instead of protecting it with
%    |\DeclareRobustCommand|, which could insert a |\relax|, we use
%    the same procedure as shorthands.
%    \begin{macrocode}
\newcommand\babelnullhyphen{\char\hyphenchar\font}
\def\babelhyphen{\active@prefix\babelhyphen\bbl@hyphen}
\def\bbl@hyphen{%
  \@ifstar{\bbl@hyphen@i @}{\bbl@hyphen@i\@empty}}
\def\bbl@hyphen@i#1#2{%
  \@ifundefined{bbl@hy@#1#2\@empty}%
    {\csname bbl@#1usehyphen\endcsname{\discretionary{#2}{}{#2}}}%
    {\csname bbl@hy@#1#2\@empty\endcsname}}
%    \end{macrocode}
%    The following two commands are used to wrap the ``hyphen'' and
%    set the behaviour of the rest of the word -- the version with a
%    single |@| is used when further hyphenation is allowed, while
%    that with |@@| if no more hyphen are allowed. In both cases, if
%    the hyphen is preceded by a positive space, breaking after the
%    hyphen is disallowed.
%
%    There should not be a discretionaty after a hyphen at the
%    beginning of a word, so it is prevented if preceded by a
%    skip. Unfortunately, this does handle cases like ``(-suffix)''.
%    |\nobreak| is always preceded by |\leavevmode|, in case the
%    shorthand starts a paragraph.
%    \begin{macrocode}
\def\bbl@usehyphen#1{%
  \leavevmode
  \ifdim\lastskip>\z@\mbox{#1}\nobreak\else\nobreak#1\fi
  \hskip\z@skip}
\def\bbl@@usehyphen#1{%
  \leavevmode\ifdim\lastskip>\z@\mbox{#1}\else#1\fi}
%    \end{macrocode}
%    The following macro inserts the hyphen char.
%    \begin{macrocode}
\def\bbl@hyphenchar{%
  \ifnum\hyphenchar\font=\m@ne
    \babelnullhyphen
  \else
    \char\hyphenchar\font
  \fi}
%    \end{macrocode}
%    Finally, we define the hyphen ``types''. Their names will not
%    change, so you may use them in |ldf|'s.
%    \begin{macrocode}
\def\bbl@hy@soft{\bbl@usehyphen{\discretionary{\bbl@hyphenchar}{}{}}}
\def\bbl@hy@@soft{\bbl@@usehyphen{\discretionary{\bbl@hyphenchar}{}{}}}
\def\bbl@hy@hard{\bbl@usehyphen\bbl@hyphenchar}
\def\bbl@hy@@hard{\bbl@@usehyphen\bbl@hyphenchar}
\def\bbl@hy@nobreak{\bbl@usehyphen{\mbox{\bbl@hyphenchar}\nobreak}}
\def\bbl@hy@@nobreak{\mbox{\bbl@hyphenchar}}
\def\bbl@hy@repeat{%
  \bbl@usehyphen{%
    \discretionary{\bbl@hyphenchar}{\bbl@hyphenchar}{\bbl@hyphenchar}%
    \nobreak}}
\def\bbl@hy@@repeat{%
  \bbl@@usehyphen{%
    \discretionary{\bbl@hyphenchar}{\bbl@hyphenchar}{\bbl@hyphenchar}}}
\def\bbl@hy@empty{\hskip\z@skip}
\def\bbl@hy@@empty{\discretionary{}{}{}}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\bbl@disc}
% \changes{babel~3.5f}{1996/01/24}{Macro moved from language
%    definition files}
%    For some languages the macro |\bbl@disc| is used to ease the
%    insertion of discretionaries for letters that behave `abnormally'
%    at a breakpoint.
%    \begin{macrocode}
\def\bbl@disc#1#2{\nobreak\discretionary{#2-}{}{#1}\bbl@allowhyphens}
%    \end{macrocode}
%  \end{macro}
%
% \subsection{Macros common to a number of languages}
%
%  \begin{macro}{\set@low@box}
% \changes{babel~3.2b}{1992/02/16}{Moved macro from language
%    definition files}
%    The following macro is used to lower quotes to the same level as
%    the comma.  It prepares its argument in box register~0.
%    \begin{macrocode}
\def\set@low@box#1{\setbox\tw@\hbox{,}\setbox\z@\hbox{#1}%
    \dimen\z@\ht\z@ \advance\dimen\z@ -\ht\tw@%
    \setbox\z@\hbox{\lower\dimen\z@ \box\z@}\ht\z@\ht\tw@ \dp\z@\dp\tw@}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\save@sf@q}
% \changes{babel~3.2b}{1992/02/16}{Moved macro from language
%    definition files}
%    The macro |\save@sf@q| is used to save and reset the current
%    space factor.
% \changes{babel~3.7f}{2000/09/19}{PR3119, don't start a paragraph in
%    a local group}
%    \begin{macrocode}
\def\save@sf@q#1{\leavevmode
  \begingroup 
    \edef\@SF{\spacefactor\the\spacefactor}#1\@SF
  \endgroup}
%    \end{macrocode}
%  \end{macro}
%
% \changes{babel~3.5c}{1995/06/14}{Repaired a typo (itlaic, PR1652)}
%
%  \subsection{Making glyphs available}
%
%    The file \file{\filename}\footnote{The file described in this
%    section has version number \fileversion, and was last revised on
%    \filedate.} makes a number of glyphs available that either do not
%    exist in the \texttt{OT1} encoding and have to be `faked', or
%    that are not accessible through \file{T1enc.def}.
%
%  \subsection{Quotation marks}
%
%  \begin{macro}{\quotedblbase}
%    In the \texttt{T1} encoding the opening double quote at the
%    baseline is available as a separate character, accessible via
%    |\quotedblbase|. In the \texttt{OT1} encoding it is not
%    available, therefor we make it available by lowering the normal
%    open quote character to the baseline.
%    \begin{macrocode}
\ProvideTextCommand{\quotedblbase}{OT1}{%
  \save@sf@q{\set@low@box{\textquotedblright\/}%
    \box\z@\kern-.04em\bbl@allowhyphens}}
%    \end{macrocode}
%    Make sure that when an encoding other than \texttt{OT1} or
%    \texttt{T1} is used this glyph can still be typeset.
%    \begin{macrocode}
\ProvideTextCommandDefault{\quotedblbase}{%
  \UseTextSymbol{OT1}{\quotedblbase}}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\quotesinglbase}
%    We also need the single quote character at the baseline.
%    \begin{macrocode}
\ProvideTextCommand{\quotesinglbase}{OT1}{%
  \save@sf@q{\set@low@box{\textquoteright\/}%
    \box\z@\kern-.04em\bbl@allowhyphens}}
%    \end{macrocode}
%    Make sure that when an encoding other than \texttt{OT1} or
%    \texttt{T1} is used this glyph can still be typeset.
%    \begin{macrocode}
\ProvideTextCommandDefault{\quotesinglbase}{%
  \UseTextSymbol{OT1}{\quotesinglbase}}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\guillemotleft}
%  \begin{macro}{\guillemotright}
%    The guillemet characters are not available in \texttt{OT1}
%    encoding. They are faked.
%    \begin{macrocode}
\ProvideTextCommand{\guillemotleft}{OT1}{%
  \ifmmode
    \ll
  \else
    \save@sf@q{\nobreak
      \raise.2ex\hbox{$\scriptscriptstyle\ll$}\bbl@allowhyphens}%
  \fi}
\ProvideTextCommand{\guillemotright}{OT1}{%
  \ifmmode
    \gg
  \else
    \save@sf@q{\nobreak
      \raise.2ex\hbox{$\scriptscriptstyle\gg$}\bbl@allowhyphens}%
  \fi}
%    \end{macrocode}
%    Make sure that when an encoding other than \texttt{OT1} or
%    \texttt{T1} is used these glyphs can still be typeset.
%    \begin{macrocode}
\ProvideTextCommandDefault{\guillemotleft}{%
  \UseTextSymbol{OT1}{\guillemotleft}}
\ProvideTextCommandDefault{\guillemotright}{%
  \UseTextSymbol{OT1}{\guillemotright}}
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%
%  \begin{macro}{\guilsinglleft}
%  \begin{macro}{\guilsinglright}
%    The single guillemets are not available in \texttt{OT1}
%    encoding. They are faked.
%    \begin{macrocode}
\ProvideTextCommand{\guilsinglleft}{OT1}{%
  \ifmmode
    <%
  \else
    \save@sf@q{\nobreak
      \raise.2ex\hbox{$\scriptscriptstyle<$}\bbl@allowhyphens}%
  \fi}
\ProvideTextCommand{\guilsinglright}{OT1}{%
  \ifmmode
    >%
  \else
    \save@sf@q{\nobreak
      \raise.2ex\hbox{$\scriptscriptstyle>$}\bbl@allowhyphens}%
  \fi}
%    \end{macrocode}
%    Make sure that when an encoding other than \texttt{OT1} or
%    \texttt{T1} is used these glyphs can still be typeset.
%    \begin{macrocode}
\ProvideTextCommandDefault{\guilsinglleft}{%
  \UseTextSymbol{OT1}{\guilsinglleft}}
\ProvideTextCommandDefault{\guilsinglright}{%
  \UseTextSymbol{OT1}{\guilsinglright}}
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%
%
%  \subsection{Letters}
%
%  \begin{macro}{\ij}
%  \begin{macro}{\IJ}
%    The dutch language uses the letter `ij'. It is available in
%    \texttt{T1} encoded fonts, but not in the \texttt{OT1} encoded
%    fonts. Therefor we fake it for the \texttt{OT1} encoding.
% \changes{dutch-3.7a}{1995/02/04}{Changed the kerning in the faked ij
%    to match the dc-version of it}
% \changes{babel~3.9a}{2012/07/28}{Removed the first \cs{allowhyphens}.
%    Moved the second one just after the kern.}
%    \begin{macrocode}
\DeclareTextCommand{\ij}{OT1}{%
  i\kern-0.02em\bbl@allowhyphens j}
\DeclareTextCommand{\IJ}{OT1}{%
  I\kern-0.02em\bbl@allowhyphens J}
\DeclareTextCommand{\ij}{T1}{\char188}
\DeclareTextCommand{\IJ}{T1}{\char156}
%    \end{macrocode}
%    Make sure that when an encoding other than \texttt{OT1} or
%    \texttt{T1} is used these glyphs can still be typeset.
%    \begin{macrocode}
\ProvideTextCommandDefault{\ij}{%
  \UseTextSymbol{OT1}{\ij}}
\ProvideTextCommandDefault{\IJ}{%
  \UseTextSymbol{OT1}{\IJ}}
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%
%  \begin{macro}{\dj}
%  \begin{macro}{\DJ}
%    The croatian language needs the letters |\dj| and |\DJ|; they are
%    available in the \texttt{T1} encoding, but not in the
%    \texttt{OT1} encoding by default.
%
%    Some code to construct these glyphs for the \texttt{OT1} encoding
%    was made available to me by Stipcevic Mario,
%    (\texttt{stipcevic@olimp.irb.hr}).
% \changes{babel~3.5f}{1996/03/28}{New definition of \cs{dj}, see PR
%    2058}
%    \begin{macrocode}
\def\crrtic@{\hrule height0.1ex width0.3em}
\def\crttic@{\hrule height0.1ex width0.33em}
\def\ddj@{%
  \setbox0\hbox{d}\dimen@=\ht0
  \advance\dimen@1ex
  \dimen@.45\dimen@
  \dimen@ii\expandafter\rem@pt\the\fontdimen\@ne\font\dimen@
  \advance\dimen@ii.5ex
  \leavevmode\rlap{\raise\dimen@\hbox{\kern\dimen@ii\vbox{\crrtic@}}}}
\def\DDJ@{%
  \setbox0\hbox{D}\dimen@=.55\ht0
  \dimen@ii\expandafter\rem@pt\the\fontdimen\@ne\font\dimen@
  \advance\dimen@ii.15ex %            correction for the dash position
  \advance\dimen@ii-.15\fontdimen7\font %     correction for cmtt font
  \dimen\thr@@\expandafter\rem@pt\the\fontdimen7\font\dimen@
  \leavevmode\rlap{\raise\dimen@\hbox{\kern\dimen@ii\vbox{\crttic@}}}}
%
\DeclareTextCommand{\dj}{OT1}{\ddj@ d}
\DeclareTextCommand{\DJ}{OT1}{\DDJ@ D}
%    \end{macrocode}
%    Make sure that when an encoding other than \texttt{OT1} or
%    \texttt{T1} is used these glyphs can still be typeset.
%    \begin{macrocode}
\ProvideTextCommandDefault{\dj}{%
  \UseTextSymbol{OT1}{\dj}}
\ProvideTextCommandDefault{\DJ}{%
  \UseTextSymbol{OT1}{\DJ}}
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%
%  \begin{macro}{\SS}
%    For the \texttt{T1} encoding |\SS| is defined and selects a
%    specific glyph from the font, but for other encodings it is not
%    available. Therefor we make it available here.
%    \begin{macrocode}
\DeclareTextCommand{\SS}{OT1}{SS}
\ProvideTextCommandDefault{\SS}{\UseTextSymbol{OT1}{\SS}}
%    \end{macrocode}
%  \end{macro}
%
% \subsection{Shorthands for quotation marks}
%
%    Shorthands are provided for a number of different quotation
%    marks, which make them usable both outside and inside mathmode.
%
%  \begin{macro}{\glq}
%  \begin{macro}{\grq}
% \changes{babel~3.7a}{1997/04/25}{Make the definition of \cs{grq}
%    dependent on the font encoding}
% \changes{babel~3.8b}{2004/05/02}{Made \cs{glq} fontencoding
%    dependent as well} 
%    The `german' single quotes.
%    \begin{macrocode}
\ProvideTextCommand{\glq}{OT1}{%
  \textormath{\quotesinglbase}{\mbox{\quotesinglbase}}}
\ProvideTextCommand{\glq}{T1}{%
  \textormath{\quotesinglbase}{\mbox{\quotesinglbase}}}
\ProvideTextCommandDefault{\glq}{\UseTextSymbol{OT1}\glq}
%    \end{macrocode}
%    The definition of |\grq| depends on the fontencoding. With
%    \texttt{T1} encoding no extra kerning is needed.
%    \begin{macrocode}
\ProvideTextCommand{\grq}{T1}{%
  \textormath{\textquoteleft}{\mbox{\textquoteleft}}}
\ProvideTextCommand{\grq}{OT1}{%
  \save@sf@q{\kern-.0125em%
  \textormath{\textquoteleft}{\mbox{\textquoteleft}}%
  \kern.07em\relax}}
\ProvideTextCommandDefault{\grq}{\UseTextSymbol{OT1}\grq}
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%
%  \begin{macro}{\glqq}
%  \begin{macro}{\grqq}
% \changes{babel~3.7a}{1997/04/25}{Make the definition of \cs{grqq}
%    dependent on the font encoding}
% \changes{babel~3.8b}{2004/05/02}{Made \cs{grqq} fontencoding
%    dependent as well} 
%    The `german' double quotes.
%    \begin{macrocode}
\ProvideTextCommand{\glqq}{OT1}{%
  \textormath{\quotedblbase}{\mbox{\quotedblbase}}}
\ProvideTextCommand{\glqq}{T1}{%
  \textormath{\quotedblbase}{\mbox{\quotedblbase}}}
\ProvideTextCommandDefault{\glqq}{\UseTextSymbol{OT1}\glqq}
%    \end{macrocode}
%    The definition of |\grqq| depends on the % fontencoding. With
%    \texttt{T1} encoding no extra kerning is needed.
%    \begin{macrocode}
\ProvideTextCommand{\grqq}{T1}{%
  \textormath{\textquotedblleft}{\mbox{\textquotedblleft}}}
\ProvideTextCommand{\grqq}{OT1}{%
  \save@sf@q{\kern-.07em%
  \textormath{\textquotedblleft}{\mbox{\textquotedblleft}}%
  \kern.07em\relax}}
\ProvideTextCommandDefault{\grqq}{\UseTextSymbol{OT1}\grqq}
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%
%  \begin{macro}{\flq}
%  \begin{macro}{\frq}
% \changes{babel~3.5f}{1995/08/07}{corrected spelling of
%    \cs{quilsingl...}}
% \changes{babel~3.5f}{1995/09/05}{now use \cs{textormath} in these
%    definitions}
% \changes{babel~3.8b}{2004/05/02}{Made \cs{flq} and \cs{frq}
%    fontencoding dependent} 
%    The `french' single guillemets.
%    \begin{macrocode}
\ProvideTextCommand{\flq}{OT1}{%
  \textormath{\guilsinglleft}{\mbox{\guilsinglleft}}}
\ProvideTextCommand{\flq}{T1}{%
  \textormath{\guilsinglleft}{\mbox{\guilsinglleft}}}
\ProvideTextCommandDefault{\flq}{\UseTextSymbol{OT1}\flq}
%    \end{macrocode}
%    
%    \begin{macrocode}
\ProvideTextCommand{\frq}{OT1}{%
  \textormath{\guilsinglright}{\mbox{\guilsinglright}}}
\ProvideTextCommand{\frq}{T1}{%
  \textormath{\guilsinglright}{\mbox{\guilsinglright}}}
\ProvideTextCommandDefault{\frq}{\UseTextSymbol{OT1}\frq}
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%
%  \begin{macro}{\flqq}
%  \begin{macro}{\frqq}
% \changes{babel~3.5f}{1995/08/07}{corrected spelling of
%    \cs{quillemot...}}
% \changes{babel~3.5f}{1995/09/05}{now use \cs{textormath} in these
%    definitions}
% \changes{babel~3.8b}{2004/05/02}{Made \cs{flqq} and \cs{frqq}
%    fontencoding dependent} 
%    The `french' double guillemets.
%    \begin{macrocode}
\ProvideTextCommand{\flqq}{OT1}{%
  \textormath{\guillemotleft}{\mbox{\guillemotleft}}}
\ProvideTextCommand{\flqq}{T1}{%
  \textormath{\guillemotleft}{\mbox{\guillemotleft}}}
\ProvideTextCommandDefault{\flqq}{\UseTextSymbol{OT1}\flqq}
%    \end{macrocode}
%    
%    \begin{macrocode}
\ProvideTextCommand{\frqq}{OT1}{%
  \textormath{\guillemotright}{\mbox{\guillemotright}}}
\ProvideTextCommand{\frqq}{T1}{%
  \textormath{\guillemotright}{\mbox{\guillemotright}}}
\ProvideTextCommandDefault{\frqq}{\UseTextSymbol{OT1}\frqq}
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%
%  \subsection{Umlauts and trema's}
%
%    The command |\"| needs to have a different effect for different
%    languages. For German for instance, the `umlaut' should be
%    positioned lower than the default position for placing it over
%    the letters a, o, u, A, O and U. When placed over an e, i, E or I
%    it can retain its normal position. For Dutch the same glyph is
%    always placed in the lower position.
%
%  \begin{macro}{\umlauthigh}
% \changes{v3.8a}{2004/02/19}{Use \cs{leavevmode}\cs{bgroup} to
%    prevent problems when this command occurs in vertical mode.}
%  \begin{macro}{\umlautlow}
%    To be able to provide both positions of |\"| we provide two
%    commands to switch the positioning, the default will be
%    |\umlauthigh| (the normal positioning).
%    \begin{macrocode}
\def\umlauthigh{%
  \def\bbl@umlauta##1{\leavevmode\bgroup%
      \expandafter\accent\csname\f@encoding dqpos\endcsname
      ##1\bbl@allowhyphens\egroup}%
  \let\bbl@umlaute\bbl@umlauta}
\def\umlautlow{%
  \def\bbl@umlauta{\protect\lower@umlaut}}
\def\umlautelow{%
  \def\bbl@umlaute{\protect\lower@umlaut}}
\umlauthigh
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%
%  \begin{macro}{\lower@umlaut}
%    The command |\lower@umlaut| is used to position the |\"| closer
%    the the letter.
%
%    We want the umlaut character lowered, nearer to the letter. To do
%    this we need an extra \meta{dimen} register.
%    \begin{macrocode}
\expandafter\ifx\csname U@D\endcsname\relax
  \csname newdimen\endcsname\U@D
\fi
%    \end{macrocode}
%    The following code fools \TeX's \texttt{make\_accent} procedure
%    about the current x-height of the font to force another placement
%    of the umlaut character.
%    First we have to save the current x-height of the font, because
%    we'll change this font dimension and this is always done
%    globally.
% \changes{v3.8a}{2004/02/19}{Use \cs{leavevmode}\cs{bgroup} to
%    prevent problems when this command occurs in vertical mode.}
%
%    Then we compute the new x-height in such a way that the umlaut
%    character is lowered to the base character.  The value of
%    \texttt{.45ex} depends on the \MF\ parameters with which the
%    fonts were built.  (Just try out, which value will look best.)
%    If the new x-height is too low, it is not changed.
%    Finally we call the |\accent| primitive, reset the old x-height
%    and insert the base character in the argument.
% \changes{babel~3.5f}{1996/04/02}{Added a \cs{allowhyphens}}
% \changes{babel~3.5f}{1996/06/25}{removed \cs{allowhyphens}}
%    \begin{macrocode}
\def\lower@umlaut#1{%
  \leavevmode\bgroup
    \U@D 1ex%
    {\setbox\z@\hbox{%
      \expandafter\char\csname\f@encoding dqpos\endcsname}%
      \dimen@ -.45ex\advance\dimen@\ht\z@
      \ifdim 1ex<\dimen@ \fontdimen5\font\dimen@ \fi}%
    \expandafter\accent\csname\f@encoding dqpos\endcsname
    \fontdimen5\font\U@D #1%
  \egroup}
%    \end{macrocode}
%  \end{macro}
%
%    For all vowels we declare |\"| to be a composite command which
%    uses |\bbl@umlauta| or |\bbl@umlaute| to position the umlaut
%    character. We need to be sure that these definitions override the
%    ones that are provided when the package \pkg{fontenc} with
%    option \Lopt{OT1} is used. Therefor these declarations are
%    postponed until the beginning of the document. Note these
%    definitions only apply to some languages, but 
%    babel sets them for \textit{all} languages -- you may want to
%    redefine |\bbl@umlauta| and/or |\bbl@umlaute| for a language
%    in the corresponding |ldf| (using the babel switching mechanism,
%    of course).
%    \begin{macrocode}
\AtBeginDocument{%
  \DeclareTextCompositeCommand{\"}{OT1}{a}{\bbl@umlauta{a}}%
  \DeclareTextCompositeCommand{\"}{OT1}{e}{\bbl@umlaute{e}}%
  \DeclareTextCompositeCommand{\"}{OT1}{i}{\bbl@umlaute{\i}}%
  \DeclareTextCompositeCommand{\"}{OT1}{\i}{\bbl@umlaute{\i}}%
  \DeclareTextCompositeCommand{\"}{OT1}{o}{\bbl@umlauta{o}}%
  \DeclareTextCompositeCommand{\"}{OT1}{u}{\bbl@umlauta{u}}%
  \DeclareTextCompositeCommand{\"}{OT1}{A}{\bbl@umlauta{A}}%
  \DeclareTextCompositeCommand{\"}{OT1}{E}{\bbl@umlaute{E}}%
  \DeclareTextCompositeCommand{\"}{OT1}{I}{\bbl@umlaute{I}}%
  \DeclareTextCompositeCommand{\"}{OT1}{O}{\bbl@umlauta{O}}%
  \DeclareTextCompositeCommand{\"}{OT1}{U}{\bbl@umlauta{U}}%
}
%    \end{macrocode}
%  \subsection{Multiencoding strings}
%
% \changes{babel~3.9a}{2012/09/05}{Added tentative code for string
%  declarations}
% \changes{babel~3.9a}{2012/12/24}{Added hooks}
%
% The aim following commands is to provide a commom interface for
% strings in several encodings. They also contains several hooks which
% can be ued by \luatex{} and \xetex.
%
% This is the main command.  With the first use it is redefined to
% omit the basic setup in subsequent blocks. We make sure strings
% contain actual letters in the range 128-255, not active characters.
%    \begin{macrocode}
\def\bbl@recatcode#1{%
  \@tempcnta="7F
  \def\bbl@tempa{%
    \ifnum\@tempcnta>"FF\else
      \catcode\@tempcnta=#1\relax
      \advance\@tempcnta\@ne
      \expandafter\bbl@tempa
    \fi}%
  \bbl@tempa}
\@onlypreamble\StartBabelCommands
\def\StartBabelCommands{%
  \begingroup   
  \bbl@recatcode{11}%
  \def\bbl@scuse{%
    \ifx\bbl@opt@strings\@nnil\def\bbl@opt@strings{generic}\fi}%
  \def\UseStrings{\bbl@scuse\aftergroup\bbl@scuse}%
  \def\SetStringLoop{\afterassignment\bbl@sclp\def\bbl@templ####1}%
  \def\bbl@sclp##1{%
    \count@\z@ % dangerous if a hook is used
    \@for\bbl@tempm:=##1\do{%
      \advance\count@\@ne
      \toks@\expandafter{\bbl@tempm}%
      \edef\bbl@tempn{%
        \expandafter\noexpand
        \csname\bbl@templ{\romannumeral\count@}\endcsname%
        {\the\toks@}}%
      \expandafter\SetString\bbl@tempn}}%
  \def\SetCase{%
    \@ifundefined{bbl@tolower}{%
      \g@addto@macro\@uclclist{%
        \reserved@b{\reserved@b\@gobble}% stops processing the list
        \@ifundefined{\languagename @bbl@uclc}% and resumes it
          {\reserved@a}%
          {\csname\languagename @bbl@uclc\endcsname}%
        {\bbl@tolower\@empty}{\bbl@toupper\@empty}}%
      \gdef\bbl@tolower{\csname\languagename @bbl@lc\endcsname}%
      \gdef\bbl@toupper{\csname\languagename @bbl@uc\endcsname}}{}%
    \let\SetCase\bbl@setcase
    \SetCase}%
  \def\bbl@provstring##1{%
    \@ifundefined{\expandafter\@gobble\string##1}{\gdef##1}\@gobble}%
  \def\bbl@dftstring##1##2{%
    \@dec@text@cmd\gdef##1?{##2}%
    \global\let##1##1}%
  \def\bbl@encstring##1##2{%
    \bbl@for\bbl@tempc\bbl@sc@fontenc{%
      \@ifundefined{T@\bbl@tempc}%
        \@empty
        {\@dec@text@cmd\gdef##1\bbl@tempc{##2}%
         \global\let##1##1}}}%
  \let\StartBabelCommands\bbl@startcmds
  \begingroup
  \let\bbl@screset\@nnil % local flag - disable 1st stopcommands
  \StartBabelCommands}
\def\bbl@startcmds#1#2{%
  \ifx\bbl@screset\@nnil\else
    \bbl@usehooks{stopcommands}{}%
  \fi
  \endgroup
  \begingroup
  \edef\bbl@L{\zap@space#1 \@empty}%
  \edef\bbl@G{\zap@space#2 \@empty}%
  \let\bbl@sc@charset\space
  \let\bbl@sc@fontenc\space
  \let\SetString\@gobbletwo
  \let\bbl@stringdef\@gobbletwo
  \bbl@startcmds@i}
%    \end{macrocode}
%    Parse the encoding info to get the label, input, and font parts.
%
%    Select the behaviour of |\SetString|. Thre are two main cases:
%    |*| blocks, which are always taken into account, and labelled
%    blocks, which are not always taken into account. With |*| and
%    |strings| set to |encoded| or |generic|, strings are defined
%    always; otherwise, they are set only if they are still undefined
%    (ie, fallback values). With labelled blocks and
%    |strings=encoded|, define the strings, but with another value,
%    define strings only if the current label or font encoding is the
%    value of |strings|; otherwise (ie, no |strings| or a block whose
%    label is not in |strings=|) do nothing.
%
%    We presume the current block is not loaded, and therefore set
%    (above) a couple of default values to gobble the arguments. Then,
%    these macros are redefined if necessary according to several
%    parameters.
%
%    \begin{macrocode}
\newcommand\bbl@startcmds@i[1][\@empty]{%
  \ifx\@empty#1%
    \def\bbl@sc@label{generic}%
    \bbl@scswitch{%
      \ifx\bbl@opt@strings\@nnil
        \let\bbl@stringdef\bbl@dftstring
      \else\ifx\bbl@opt@strings\relax
        \let\SetString\bbl@setstring
        \let\bbl@stringdef\bbl@dftstring
      \else
        \let\SetString\bbl@setstring
        \let\bbl@stringdef\bbl@provstring
      \fi\fi}%
    \@expandtwoargs
    \bbl@usehooks{defaultcommands}{}%
  \else
    \def\bbl@tempa##1=##2\@nil{%
      \bbl@csarg\edef{sc@\zap@space##1 \@empty}{##2 }}%
    \bbl@for\bbl@tempb{label=#1}{\expandafter\bbl@tempa\bbl@tempb\@nil}%
    \def\bbl@tempa##1 ##2{%
      ##1%
      \ifx\@empty##2\else\ifx,##1,\else,\fi\bbl@afterfi\bbl@tempa##2\fi}%
    \edef\bbl@sc@fontenc{\expandafter\bbl@tempa\bbl@sc@fontenc\@empty}%
    \edef\bbl@sc@label{\expandafter\zap@space\bbl@sc@label\@empty}%
    \edef\bbl@sc@charset{\expandafter\zap@space\bbl@sc@charset\@empty}%
    \bbl@scswitch{%
      \ifx\bbl@opt@strings\@nnil
        \let\bbl@stringdef\bbl@encstring
      \else\ifx\bbl@opt@strings\relax
        \let\SetString\bbl@setstring
        \let\bbl@stringdef\bbl@encstring
      \else
      \@expandtwoargs
      \in@{,\bbl@opt@strings,}{,\bbl@sc@label,\bbl@sc@fontenc,}%
      \ifin@
        \let\SetString\bbl@setstring
        \let\bbl@stringdef\bbl@provstring
      \fi\fi\fi}%
    \@expandtwoargs
    \bbl@usehooks{encodedcommands}{{\bbl@sc@charset}{\bbl@sc@fontenc}}%
  \fi}
%    \end{macrocode}
%
%   There are two versions of |\bbl@scswitch|. The first version
%   is used when |ldf|s are read, and with it blocks not intented for
%   the current language (as set in |\CurrentOption|) are ignored; it
%   also makes sure |\|\m{group}\m{language} is reset, but only once
%   (|\bbl@screset| is used to keep track of this). The second version
%   is used in the preamble and packages loaded after \babel{} and
%   defines strings for all known languages.
%
%   \begin{macrocode}
\def\bbl@scswitch#1{%
  \@expandtwoargs\in@{,\CurrentOption,}{,\bbl@L,}%
  \ifin@
    \let\bbl@L\CurrentOption
    #1\relax
    \bbl@scswitch@i
    \ifx\bbl@G\@empty\else
      \ifx\SetString\@gobbletwo\else
        \edef\bbl@GL{\bbl@G\bbl@L}%
        \@expandtwoargs\in@{,\bbl@GL,}{,\bbl@screset,}%
        \ifin@\else
          \global\expandafter\let\csname\bbl@GL\endcsname\@undefined
          \xdef\bbl@screset{\bbl@screset,\bbl@GL}%
        \fi
      \fi
    \fi
  \fi}
\def\bbl@scswitch@i{%
  \ifx\bbl@G\@empty
    \def\SetString##1##2{%
      \bbl@error{Missing group for string \string##1}%
        {You must assign strings to some category, typically\\%
         captions or extras, but you set none}}%
  \fi}
\AtEndOfPackage{\def\bbl@scswitch#1{#1\relax\bbl@scswitch@i}}
\@onlypreamble\EndBabelCommands
\def\EndBabelCommands{%
  \bbl@usehooks{stopcommands}{}%
  \endgroup
  \endgroup}
%    \end{macrocode}
%    
%    First save the ``switcher''. Create it if undefined. Strings are
%    defined only if undefined (ie, like |\providescommmand|). With
%    the event |stringprocess| you can preprocess the string by
%    manipulating the value of |\BabelString|. If there are several
%    hooks assigned to this event, preprocessing is done in the same
%    order as defined.  Finally, the string is set.
%
%    \begin{macrocode}
\def\bbl@scset#1#2{\def#1{#2}}
\def\bbl@setstring#1#2{%
  \bbl@for\bbl@tempa\bbl@L{%
    \edef\bbl@LC{\bbl@tempa\expandafter\@gobble\string#1}%
    \@ifundefined{\bbl@LC}% eg, \germanchaptername
      {\global\expandafter
       \bbl@add\csname\bbl@G\bbl@tempa\expandafter\endcsname\expandafter
         {\expandafter\bbl@scset\expandafter#1\csname\bbl@LC\endcsname}}%
      {}%
    \def\BabelString{#2}%
    \bbl@usehooks{stringprocess}{}%
    \expandafter\bbl@stringdef
      \csname\bbl@LC\expandafter\endcsname\expandafter{\BabelString}}}
\newcommand\bbl@setcase[3][]{%
  \bbl@for\bbl@tempa\bbl@L{%
    \expandafter\bbl@stringdef
      \csname\bbl@tempa @bbl@uclc\endcsname{\reserved@a#1}%
    \expandafter\bbl@stringdef
      \csname\bbl@tempa @bbl@uc\endcsname{#2}% 
    \expandafter\bbl@stringdef
      \csname\bbl@tempa @bbl@lc\endcsname{#3}}}
%    \end{macrocode}
%
%  \subsection{Hooks}
%
%  Note they are loaded in babel.def. switch.def only provides a
%  ``hook'' for hooks (with a default value which is a no-op,
%  below). Admittedly, the current implementation is a somewhat
%  simplistic and does vety little to catch errors, but it is intended
%  for developpers, after all. |\bbl@usehooks| is the commands used by
%  babel to execute hooks defined for an event.  
%
%    \begin{macrocode}
\def\AddBabelHook#1#2{%
  \@ifundefined{bbl@hk@#1}{\EnableBabelHook{#1}}{}%
  \def\bbl@tempa##1,#2=##2,##3\@empty{\def\bbl@tempb{##2}}%
  \expandafter\bbl@tempa\bbl@evargs,#2=,\@empty
  \@ifundefined{bbl@ev@#1@#2}%
    {\bbl@csarg\bbl@add{ev@#2}{\bbl@elt{#1}}%
     \bbl@csarg\newcommand}%
    {\bbl@csarg\renewcommand}%
  {ev@#1@#2}[\bbl@tempb]}
\def\EnableBabelHook#1{\bbl@csarg\let{hk@#1}\@firstofone}
\def\DisableBabelHook#1{\bbl@csarg\let{hk@#1}\@gobble}
\def\bbl@usehooks#1#2{%
  \def\bbl@elt##1{%
    \@nameuse{bbl@hk@##1}{\@nameuse{bbl@ev@##1@#1}#2}}%
  \@nameuse{bbl@ev@#1}}
%    \end{macrocode}
%    To ensure forward compatibility, arguments in hooks are set
%    implicitly. So, if a further argument is added in the future,
%    there is no need to change the existing code. Note events
%    intended for \textsf{hyphen.cfg} are also loaded (just in
%    case you need them). 
%    \begin{macrocode}
\def\bbl@evargs{,% don't delete the comma
  everylanguage=1,loadkernel=1,loadpatterns=1,loadexceptions=1,%
  adddialect=2,patterns=2,defaultcommands=0,encodedcommands=2,write=0,%
  beforeextras=0,afterextras=0,stopcommands=0,stringprocess=0,%
  hyphenation=2}
\ifx\directlua\@undefined
  \ifx\XeTeXinputencoding\@undefined\else
    \input xebabel.def
  \fi
\else
  \input luababel.def
\fi
%    \end{macrocode}
%
% \subsection{The redefinition of the style commands}
%
%    The rest of the code in this file can only be processed by
%    \LaTeX, so we check the current format. If it is plain \TeX,
%    processing should stop here. But, because of the need to limit
%    the scope of the definition of |\format|, a macro that is used
%    locally in the following |\if|~statement, this comparison is done
%    inside a group. To prevent \TeX\ from complaining about an
%    unclosed group, the processing of the command |\endinput| is
%    deferred until after the group is closed. This is accomplished by
%    the command |\aftergroup|.
%    \begin{macrocode}
{\def\format{lplain}
\ifx\fmtname\format
\else
  \def\format{LaTeX2e}
  \ifx\fmtname\format
  \else
    \aftergroup\endinput
  \fi
\fi}
%    \end{macrocode}
%
% \subsection{Cross referencing macros}
%
%    The \LaTeX\ book states:
%  \begin{quote}
%    The \emph{key} argument is any sequence of letters, digits, and
%    punctuation symbols; upper- and lowercase letters are regarded as
%    different.
%  \end{quote}
%    When the above quote should still be true when a document is
%    typeset in a language that has active characters, special care
%    has to be taken of the category codes of these characters when
%    they appear in an argument of the cross referencing macros.
%
%    When a cross referencing command processes its argument, all
%    tokens in this argument should be character tokens with category
%    `letter' or `other'.
%
%    The only way to accomplish this in most cases is to use the trick
%    described in the \TeX book~\cite{DEK} (Appendix~D, page~382).
%    The primitive |\meaning| applied to a token expands to the
%    current meaning of this token.  For example, `|\meaning\A|' with
%    |\A| defined as `|\def\A#1{\B}|' expands to the characters
%    `|macro:#1->\B|' with all category codes set to `other' or
%    `space'.
%  \begin{macro}{\newlabel}
% \changes{babel~3.5f}{1995/11/15}{Now use \cs{bbl@redefine}}
%    The macro |\label| writes a line with a |\newlabel| command
%    into the |.aux| file to define labels.
%    \begin{macrocode}
%\bbl@redefine\newlabel#1#2{%
%  \@safe@activestrue\org@newlabel{#1}{#2}\@safe@activesfalse}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\@newl@bel}
% \changes{babel~3.6i}{1997/03/01}{Now redefine \cs{@newl@bel} instead
%    of \cs{@lbibitem} and \cs{newlabel}}
%    We need to change the definition of the \LaTeX-internal macro
%    |\@newl@bel|. This is needed because we need to make sure that
%    shorthand characters expand to their non-active version.
%
%    First we open a new group to keep the changed setting of
%    |\protect| local and then we set the |@safe@actives| switch to
%    true to make sure that any shorthand that appears in any of the
%    arguments immediately expands to its non-active self.
% \changes{babel~3.7a}{1997/12/19}{Call \cs{@safe@activestrue}
%    directly}
%    \begin{macrocode}
\ifx\bbl@opt@safe\@empty\else
  \def\@newl@bel#1#2#3{%
   {\@safe@activestrue
    \@ifundefined{#1@#2}%
       \relax
       {\gdef\@multiplelabels{%
          \@latex@warning@no@line{There were multiply-defined labels}}%
        \@latex@warning@no@line{Label `#2' multiply defined}}%
    \global\@namedef{#1@#2}{#3}}}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\@testdef}
%    An internal \LaTeX\ macro used to test if the labels that have
%    been written on the |.aux| file have changed.  It is called by
%    the |\enddocument| macro. This macro needs to be completely
%    rewritten, using |\meaning|. The reason for this is that in some
%    cases the expansion of |\#1@#2| contains the same characters as
%    the |#3|; but the character codes differ. Therefor \LaTeX\ keeps
%    reporting that the labels may have changed.
% \changes{babel~3.4g}{1994/08/30}{Moved the \cs{def} inside the
%    macrocode environment}
% \changes{babel~3.5f}{1995/11/15}{Now use \cs{bbl@redefine}}
% \changes{babel~3.5f}{1996/01/09}{Complete rewrite of this macro as
%    the same character ended up with different category codes in the
%    labels that are being compared. Now use \cs{meaning}}
% \changes{babel~3.5f}{1996/01/16}{Use \cs{strip@prefix} only on
%    \cs{bbl@tempa} when it is not \cs{relax}}
% \changes{babel~3.6i}{1997/02/28}{Make sure that shorthands don't get
%    expanded at the wrong moment.}
% \changes{babel~3.6i}{1997/03/01}{\cs{@safe@activesfalse} is now
%    part of the label definition}
% \changes{babel~3.7a}{1998/03/13}{Removed \cs{@safe@activesfalse}
%    from the label definition}
%    \begin{macrocode}
  \CheckCommand*\@testdef[3]{%
    \def\reserved@a{#3}%
    \expandafter\ifx\csname#1@#2\endcsname\reserved@a
    \else
      \@tempswatrue
    \fi}
%    \end{macrocode}
%    Now that we made sure that |\@testdef| still has the same
%    definition we can rewrite it. First we make the shorthands
%    `safe'.
%    \begin{macrocode}
  \def\@testdef#1#2#3{%
    \@safe@activestrue
%    \end{macrocode}
%    Then we use |\bbl@tempa| as an `alias' for the macro that
%    contains the label which is being checked.
%    \begin{macrocode}
    \expandafter\let\expandafter\bbl@tempa\csname #1@#2\endcsname
%    \end{macrocode}
%    Then we define |\bbl@tempb| just as |\@newl@bel| does it.
%    \begin{macrocode}
    \def\bbl@tempb{#3}%
    \@safe@activesfalse
%    \end{macrocode}
%    When the label is defined we replace the definition of
%    |\bbl@tempa| by its meaning.
%    \begin{macrocode}
    \ifx\bbl@tempa\relax
    \else
      \edef\bbl@tempa{\expandafter\strip@prefix\meaning\bbl@tempa}%
    \fi
%    \end{macrocode}
%    We do the same for |\bbl@tempb|.
%    \begin{macrocode}
    \edef\bbl@tempb{\expandafter\strip@prefix\meaning\bbl@tempb}%
%    \end{macrocode}
%    If the label didn't change, |\bbl@tempa| and |\bbl@tempb| should
%    be identical macros.
%    \begin{macrocode}
    \ifx\bbl@tempa\bbl@tempb
    \else
      \@tempswatrue
    \fi}
\fi
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\ref}
%  \begin{macro}{\pageref}
%    The same holds for the macro |\ref| that references a label
%    and |\pageref| to reference a page. So we redefine |\ref| and
%    |\pageref|. While we change these macros, we make them robust as
%    well (if they weren't already) to prevent problems if they should
%    become expanded at the wrong moment.
% \changes{babel~3.5b}{1995/03/07}{Made \cs{ref} and \cs{pageref}
%    robust (PR1353)}
% \changes{babel~3.5d}{1995/07/04}{use a different control sequence
%    while making \cs{ref} and \cs{pageref} robust}
% \changes{babel~3.5f}{1995/11/06}{redefine \cs*{ref } if it exists
%    instead of \cs{ref}}
% \changes{babel~3.5f}{1995/11/15}{Now use \cs{bbl@redefinerobust}}
% \changes{babel~3.5f}{1996/01/19}{redefine \cs{\@setref} instead of
%    \cs{ref} and \cs{pageref} in \LaTeXe.}
% \changes{babel~3.5f}{1996/01/21}{Reverse the previous change as it
%    inhibits the use of active characters in labels}
%    \begin{macrocode}
\@expandtwoargs\in@{R}\bbl@opt@safe
\ifin@
  \bbl@redefinerobust\ref#1{%
    \@safe@activestrue\org@ref{#1}\@safe@activesfalse}
  \bbl@redefinerobust\pageref#1{%
    \@safe@activestrue\org@pageref{#1}\@safe@activesfalse}
\else
  \let\org@ref\ref
  \let\org@pageref\pageref
\fi
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%
%  \begin{macro}{\@citex}
% \changes{babel~3.5f}{1995/11/15}{Now use \cs{bbl@redefine}}
%    The macro used to cite from a bibliography, |\cite|, uses an
%    internal macro, |\@citex|.
%    It is this internal macro that picks up the argument(s),
%    so we redefine this internal macro and leave |\cite| alone. The
%    first argument is used for typesetting, so the shorthands need
%    only be deactivated in the second argument.
% \changes{babel~3.7g}{2000/10/01}{The shorthands need to be
%    deactivated for the second argument of \cs{@citex} only.}
%    \begin{macrocode}
\@expandtwoargs\in@{B}\bbl@opt@safe
\ifin@
  \bbl@redefine\@citex[#1]#2{%
    \@safe@activestrue\edef\@tempa{#2}\@safe@activesfalse
    \org@@citex[#1]{\@tempa}}
%    \end{macrocode}
%    Unfortunately, the packages \pkg{natbib} and \pkg{cite} need a
%    different definition of |\@citex|...
%    To begin with, \pkg{natbib} has a definition for |\@citex| with
%    \emph{three} arguments... We only know that a package is loaded
%    when |\begin{document}| is executed, so we need to postpone the
%    different redefinition.
%    \begin{macrocode}
  \AtBeginDocument{%
    \@ifpackageloaded{natbib}{%
%    \end{macrocode}
%    Notice that we use |\def| here instead of |\bbl@redefine| because
%    |\org@@citex| is already defined and we don't want to overwrite
%    that definition (it would result in parameter stack overflow
%    because of a circular definition).
%
%   (Recent versions of natbib change dynamically |\@citex|, so PR4087
%     doesn't seem fixable in a simple way. Just load natbib before.)
%    \begin{macrocode}
    \def\@citex[#1][#2]#3{%
      \@safe@activestrue\edef\@tempa{#3}\@safe@activesfalse
      \org@@citex[#1][#2]{\@tempa}}%
  }{}}
%    \end{macrocode}
%    The package \pkg{cite} has a definition of |\@citex| where the
%    shorthands need to be turned off in both arguments.
%    \begin{macrocode}
  \AtBeginDocument{%
    \@ifpackageloaded{cite}{%
      \def\@citex[#1]#2{%
        \@safe@activestrue\org@@citex[#1]{#2}\@safe@activesfalse}%
      }{}}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\nocite}
% \changes{babel~3.5f}{1995/11/15}{Now use \cs{bbl@redefine}}
%    The macro |\nocite| which is used to instruct BiB\TeX\ to
%    extract uncited references from the database.
%    \begin{macrocode}
  \bbl@redefine\nocite#1{%
    \@safe@activestrue\org@nocite{#1}\@safe@activesfalse}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\bibcite}
% \changes{babel~3.5f}{1995/11/15}{Now use \cs{bbl@redefine}}
%    The macro that is used in the |.aux| file to define citation
%    labels. When packages such as \pkg{natbib} or \pkg{cite} are not
%    loaded its second argument is used to typeset the citation
%    label. In that case, this second argument can contain active
%    characters but is used in an environment where
%    |\@safe@activestrue| is in effect. This switch needs to be reset
%    inside the |\hbox| which contains the citation label. In order to
%    determine during \file{.aux} file processing which definition of
%    |\bibcite| is needed we define |\bibcite| in such a way that it
%    redefines itself with the proper definition.
% \changes{babel~3.6s}{1999/04/13}{Need to determine `online' which
%    definition of \cs{bibcite} is needed}
% \changes{babel~3.6v}{1999/04/21}{Also check for \pkg{cite} it can't
%    handle \cs{@safe@activesfalse} in its second argument}
%    \begin{macrocode}
 \bbl@redefine\bibcite{%
%    \end{macrocode}
%    We call |\bbl@cite@choice| to select the proper definition for
%    |\bibcite|. This new definition is then activated.
%    \begin{macrocode}
    \bbl@cite@choice
    \bibcite}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\bbl@bibcite}
% \changes{babel~3.6v}{1999/04/21}{Macro \cs{bbl@bibcite} added}
%    The macro |\bbl@bibcite| holds the definition of |\bibcite|
%    needed when neither \pkg{natbib} nor \pkg{cite} is loaded.
%    \begin{macrocode}
  \def\bbl@bibcite#1#2{%
    \org@bibcite{#1}{\@safe@activesfalse#2}}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\bbl@cite@choice}
% \changes{babel~3.6v}{1999/04/21}{Macro \cs{bbl@cite@choice} added}
%    The macro |\bbl@cite@choice| determines which definition of
%    |\bibcite| is needed.
%    \begin{macrocode}
  \def\bbl@cite@choice{%
%    \end{macrocode}
%    First we give |\bibcite| its default definition.
%    \begin{macrocode}
    \global\let\bibcite\bbl@bibcite
%    \end{macrocode}
%    Then, when \pkg{natbib} is loaded we restore the original
%    definition of |\bibcite| .
%    \begin{macrocode}
    \@ifpackageloaded{natbib}{\global\let\bibcite\org@bibcite}{}%
%    \end{macrocode}
%    For \pkg{cite} we do the same.
%    \begin{macrocode}
    \@ifpackageloaded{cite}{\global\let\bibcite\org@bibcite}{}%
%    \end{macrocode}
%    Make sure this only happens once.
%    \begin{macrocode}
    \global\let\bbl@cite@choice\relax}
%    \end{macrocode}
%
%    When a document is run for the first time, no \file{.aux} file is
%    available, and |\bibcite| will not yet be properly defined. In
%    this case, this has to happen before the document starts.
%    \begin{macrocode}
  \AtBeginDocument{\bbl@cite@choice}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\@bibitem}
% \changes{babel~3.5f}{1995/11/15}{Now use \cs{bbl@redefine}}
%    One of the two internal \LaTeX\ macros called by |\bibitem|
%    that write the citation label on the |.aux| file.
%    \begin{macrocode}
  \bbl@redefine\@bibitem#1{%
    \@safe@activestrue\org@@bibitem{#1}\@safe@activesfalse}
\else
  \let\org@nocite\nocite
  \let\org@@citex\@citex
  \let\org@bibcite\bibcite
  \let\org@@bibitem\@bibitem
\fi
%    \end{macrocode}
%  \end{macro}
%
%  \subsection{Marks}
%
%  \begin{macro}{\markright}
% \changes{babel~3.6i}{1997/03/15}{Added redefinition of \cs{mark...}
%    commands}
%    Because the output routine is asynchronous, we must
%    pass the current language attribute to the head lines, together
%    with the text that is put into them. To achieve this we need to
%    adapt the definition of |\markright| and |\markboth| somewhat.
% \changes{babel~3.7c}{1999/04/08}{Removed the use of \cs{head@lang}
%    (PR 2990)}
% \changes{babel~3.7c}{1999/04/09}{Avoid expanding the arguments by
%    storing them in token registers}
% \changes{babel~3.7m}{2003/11/15}{added \cs{bbl@restore@actives} to
%    the mark}
% \changes{babel~3.8c}{2004/05/26}{No need to add \emph{anything} to
%    an empty mark; prevented this by checking the contents of the
%    argument}
% \changes{babel~3.8f}{2005/05/15}{Make the definition independent of
%    the original definition; expand \cs{languagename} before passing
%    it into the token registers} 
%    \begin{macrocode}
\bbl@redefine\markright#1{%
%    \end{macrocode}
%    First of all we temporarily store the language switching command,
%    using an expanded definition in order to get the current value of
%    |\languagename|. 
%    \begin{macrocode}
  \edef\bbl@tempb{\noexpand\protect
    \noexpand\foreignlanguage{\languagename}}%
%    \end{macrocode}
%    Then, we check whether the argument is empty; if it is, we
%    just make sure the scratch token register is empty.
%    \begin{macrocode}
  \def\bbl@arg{#1}%
  \ifx\bbl@arg\@empty
    \toks@{}%
  \else
%    \end{macrocode}
%    Next, we store the argument to |\markright| in the scratch token
%    register, together with the expansion of |\bbl@tempb| (containing
%    the language switching command) as defined before. This way
%    these commands will not be expanded by using |\edef| later
%    on, and we make sure that the text is typeset using the
%    correct language settings. While doing so, we make sure that
%    active characters that may end up in the mark are not disabled by
%    the output routine kicking in while \cs{@safe@activestrue} is in
%    effect.
%    \begin{macrocode}
    \expandafter\toks@\expandafter{%
             \bbl@tempb{\protect\bbl@restore@actives#1}}%
  \fi
%    \end{macrocode}
%    Then we define a temporary control sequence using |\edef|.
%    \begin{macrocode}
  \edef\bbl@tempa{%
%    \end{macrocode}
%     When |\bbl@tempa| is executed, only |\languagename| will be
%    expanded, because of the way the token register was filled.
%    \begin{macrocode}
    \noexpand\org@markright{\the\toks@}}%
  \bbl@tempa
}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\markboth}
%  \begin{macro}{\@mkboth}
%    The definition of |\markboth| is equivalent to that of
%    |\markright|, except that we need two token registers. The
%    documentclasses \cls{report} and \cls{book} define and set the
%    headings for the page. While doing so they also store a copy of
%    |\markboth| in |\@mkboth|. Therefor we need to check whether
%    |\@mkboth| has already been set. If so we neeed to do that again
%    with the new definition of |\makrboth|.
% \changes{babel~3.7m}{2003/11/15}{added \cs{bbl@restore@actives} to
%    the mark}
% \changes{babel~3.8c}{2004/05/26}{No need to add \emph{anything} to
%    an empty mark, prevented this by checking the contents of the
%    arguments} 
% \changes{babel~3.8f}{2005/05/15}{Make the definition independent of
%    the original definition; expand \cs{languagename} before passing
%    it into the token registers} 
% \changes{babel~3.8j}{2008/03/21}{Added setting of \cs{@mkboth} (PR
%    3826)} 
%    \begin{macrocode}
\ifx\@mkboth\markboth
  \def\bbl@tempc{\let\@mkboth\markboth}
\else
  \def\bbl@tempc{}
\fi
%    \end{macrocode}
%    Now we can start the new definition of |\markboth|
%    \begin{macrocode}
\bbl@redefine\markboth#1#2{%
  \edef\bbl@tempb{\noexpand\protect
    \noexpand\foreignlanguage{\languagename}}%
  \def\bbl@arg{#1}%
  \ifx\bbl@arg\@empty
    \toks@{}%
  \else
   \expandafter\toks@\expandafter{%
             \bbl@tempb{\protect\bbl@restore@actives#1}}%
  \fi
  \def\bbl@arg{#2}%
  \ifx\bbl@arg\@empty
    \toks8{}%
  \else
    \expandafter\toks8\expandafter{%
             \bbl@tempb{\protect\bbl@restore@actives#2}}%
  \fi
  \edef\bbl@tempa{%
    \noexpand\org@markboth{\the\toks@}{\the\toks8}}%
  \bbl@tempa
}
%    \end{macrocode}
%    and copy it to |\@mkboth| if necesary.
%    \begin{macrocode}
\bbl@tempc
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%
%  \subsection{Preventing clashes with other packages}
%
%  \subsubsection{\pkg{ifthen}}
%
%  \begin{macro}{\ifthenelse}
% \changes{babel~3.5g}{1996/08/11}{Redefinition of \cs{ifthenelse}
%    added to circumvent problems with \cs{pageref} in the argument of
%    \cs{isodd}}
% \changes{babel~3.9a}{2012/09/07}{Redefine only if `ref' is `safe'}%
% \changes{babel~3.9a}{2013/01/03}{Moved to babel.def}
%    Sometimes a document writer wants to create a special effect
%    depending on the page a certain fragment of text appears on. This
%    can be achieved by the following piece of code:
% \begin{verbatim}
%    \ifthenelse{\isodd{\pageref{some:label}}}
%               {code for odd pages}
%               {code for even pages}
%\end{verbatim}
%    In order for this to work the argument of |\isodd| needs to be
%    fully expandable. With the above redefinition of |\pageref| it is
%    not in the case of this example. To overcome that, we add some
%    code to the definition of |\ifthenelse| to make things work.
%
%    The first thing we need to do is check if the package
%    \pkg{ifthen} is loaded. This should be done at |\begin{document}|
%    time.
%    \begin{macrocode}
\@expandtwoargs\in@{R}\bbl@opt@safe
\ifin@
  \AtBeginDocument{%
    \@ifpackageloaded{ifthen}{%
%    \end{macrocode}
%    Then we can redefine |\ifthenelse|:
% \changes{babel~3.6f}{1997/01/14}{\cs{ifthenelse} needs to be long}
% \changes{babel~3.9a}{2012/06/22}{\cs{ref} is also taken into account}
%    \begin{macrocode}
      \bbl@redefine@long\ifthenelse#1#2#3{%
%    \end{macrocode}
%    We want to revert the definition of |\pageref| and |\ref| to
%    their original definition for the duration of |\ifthenelse|,
%    so we first need to store their current meanings.
%    \begin{macrocode}
        \let\bbl@tempa\pageref
        \let\pageref\org@pageref
        \let\bbl@tempb\ref
        \let\ref\org@ref
%    \end{macrocode}
%    Then we can set the |\@safe@actives| switch and call the original
%    |\ifthenelse|. In order to be able to use shorthands in the
%    second and third arguments of |\ifthenelse| the resetting of the
%    switch \emph{and} the definition of |\pageref| happens inside
%    those arguments.  When the package wasn't loaded we do nothing.
% \changes{babel~3.6i}{1997/02/25}{Now reset the @safe@actives switch
%    inside the 2nd and 3rd arguments of \cs{ifthenelse}}
% \changes{babel~3.7f}{2000/06/29}{\cs{pageref} needs to have its
%    babel definition reinstated in the second and third arguments}
%    \begin{macrocode}
        \@safe@activestrue
        \org@ifthenelse{#1}{%
          \let\pageref\bbl@tempa
          \let\ref\bbl@tempb
          \@safe@activesfalse
          #2}{%
          \let\pageref\bbl@tempa
          \let\ref\bbl@tempb
          \@safe@activesfalse
          #3}%
        }%
      }{}%
    }
%    \end{macrocode}
%  \end{macro}
%
%  \subsubsection{\pkg{varioref}}
%
%  \begin{macro}{\@@vpageref}
% \changes{babel~3.6a}{1996/10/29}{Redefinition of \cs{@@vpageref}
%    added to circumvent problems with active \texttt{:} in the
%    argument of \cs{vref} when \pkg{varioref} is used}
%  \begin{macro}{\vrefpagenum}
% \changes{babel~3.7o}{2003/11/18}{Added redefinition of
%    \cs{vrefpagenum} which deals with ranges of pages}
%  \begin{macro}{\Ref}
% \changes{babel~3.8g}{2005/05/21}{We also need to adapt \cs{Ref}
%    which needs to be able to uppercase the first letter of the
%    expansion of \cs{ref}} 
%    When the package varioref is in use we need to modify its
%    internal command |\@@vpageref| in order to prevent problems when
%    an active character ends up in the argument of |\vref|.
%    \begin{macrocode}
  \AtBeginDocument{%
    \@ifpackageloaded{varioref}{%
      \bbl@redefine\@@vpageref#1[#2]#3{%
        \@safe@activestrue
        \org@@@vpageref{#1}[#2]{#3}%
        \@safe@activesfalse}%
%    \end{macrocode}
%    The same needs to happen for |\vrefpagenum|.
%    \begin{macrocode}
      \bbl@redefine\vrefpagenum#1#2{%
        \@safe@activestrue
        \org@vrefpagenum{#1}{#2}%
        \@safe@activesfalse}%
%    \end{macrocode}
%    The package \pkg{varioref} defines |\Ref| to be a robust command
%    wich uppercases the first character of the reference text. In
%    order to be able to do that it needs to access the exandable form
%    of |\ref|. So we employ a little trick here. We redefine the
%    (internal) command \verb*|\Ref | to call |\org@ref| instead of
%    |\ref|. The disadvantgage of this solution is that whenever the
%    derfinition of |\Ref| changes, this definition needs to be updated
%    as well.
%    \begin{macrocode}
      \expandafter\def\csname Ref \endcsname#1{%
        \protected@edef\@tempa{\org@ref{#1}}\expandafter\MakeUppercase\@tempa}
      }{}%
    }
\fi
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%  \end{macro}
%
%  \subsubsection{\pkg{hhline}}
%
%  \begin{macro}{\hhline}
%    Delaying the activation of the shorthand characters has introduced
%    a problem with the \pkg{hhline} package. The reason is that it
%    uses the `:' character which is made active by the french support
%    in \babel. Therefor we need to \emph{reload} the package when
%    the `:' is an active character.
%
%    So at |\begin{document}| we check whether \pkg{hhline} is loaded.
%    \begin{macrocode}
\AtEndOfPackage{%
  \AtBeginDocument{%
    \@ifpackageloaded{hhline}%
%    \end{macrocode}
%    Then we check whether the expansion of |\normal@char:| is not
%    equal to |\relax|.
% \changes{babel~3.8b}{2004/04/19}{added \cs{string} to prevent
%    unwanted expansion of the colon}
%    \begin{macrocode}
      {\expandafter\ifx\csname normal@char\string:\endcsname\relax
       \else
%    \end{macrocode}
%    In that case we simply reload the package. Note that this happens
%    \emph{after} the category code of the @-sign has been changed to
%    other, so we need to temporarily change it to letter again.
%    \begin{macrocode}
         \makeatletter
         \def\@currname{hhline}\input{hhline.sty}\makeatother
       \fi}%
      {}}}
%    \end{macrocode}
%  \end{macro}
%
%  \subsubsection{\pkg{hyperref}}
%
%  \begin{macro}{\pdfstringdefDisableCommands}
% \changes{babel~3.8j}{2008/03/16}{Inform \pkg{hyperref} to use
%    shorthands at system level (PR4006)}
%
%    A number of interworking problems between \pkg{babel} and
%    \pkg{hyperref} are tackled by \pkg{hyperref} itself. The
%    following code was introduced to prevent some annoying warnings
%    but it broke bookmarks. This was quickly fixed in \pkg{hyperref},
%    which essentially made it no-op. However, it will not removed for
%    the moment because \pkg{hyperref} is expecting it, .
%    
%    \begin{macrocode}
\AtBeginDocument{%
  \@ifundefined{pdfstringdefDisableCommands}%
    {}%
    {\pdfstringdefDisableCommands{%
       \languageshorthands{system}}%
    }%
}
%    \end{macrocode}
%  \end{macro}
%
%  \subsubsection{\pkg{fancyhdr}}
%
%  \begin{macro}{\FOREIGNLANGUAGE}
%    The package \pkg{fancyhdr} treats the running head and fout lines
%    somewhat differently as the standard classes. A symptom of this is
%    that the command |\foreignlanguage| which \babel\ adds to the
%    marks can end up inside the argument of |\MakeUppercase|. To
%    prevent unexpected results we need to define |\FOREIGNLANGUAGE|
%    here.
% \changes{babel~3.7j}{2003/05/23}{Define \cs{FOREIGNLANGUAGE}
%    unconditionally}
%    \begin{macrocode}
\DeclareRobustCommand{\FOREIGNLANGUAGE}[1]{%
  \lowercase{\foreignlanguage{#1}}}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\substitutefontfamily}
%    The command |\substitutefontfamily| creates an
%    \file{.fd} file on the fly. The first argument is an encoding
%    mnemonic, the second and third arguments are font family names.
%    \changes{babel~3.7j}{2003/06/15}{create file with lowercase name}
%    \begin{macrocode}
\def\substitutefontfamily#1#2#3{%
  \lowercase{\immediate\openout15=#1#2.fd\relax}%
  \immediate\write15{%
    \string\ProvidesFile{#1#2.fd}%
    [\the\year/\two@digits{\the\month}/\two@digits{\the\day}
     \space generated font description file]^^J
    \string\DeclareFontFamily{#1}{#2}{}^^J
    \string\DeclareFontShape{#1}{#2}{m}{n}{<->ssub * #3/m/n}{}^^J
    \string\DeclareFontShape{#1}{#2}{m}{it}{<->ssub * #3/m/it}{}^^J
    \string\DeclareFontShape{#1}{#2}{m}{sl}{<->ssub * #3/m/sl}{}^^J
    \string\DeclareFontShape{#1}{#2}{m}{sc}{<->ssub * #3/m/sc}{}^^J
    \string\DeclareFontShape{#1}{#2}{b}{n}{<->ssub * #3/bx/n}{}^^J
    \string\DeclareFontShape{#1}{#2}{b}{it}{<->ssub * #3/bx/it}{}^^J
    \string\DeclareFontShape{#1}{#2}{b}{sl}{<->ssub * #3/bx/sl}{}^^J
    \string\DeclareFontShape{#1}{#2}{b}{sc}{<->ssub * #3/bx/sc}{}^^J
    }%
  \closeout15
  }
%    \end{macrocode}
%    This command should only be used in the preamble of a document.
%    \begin{macrocode}
\@onlypreamble\substitutefontfamily
%    \end{macrocode}
%  \end{macro}
%
%  \subsection{Encoding issues (part 2)}
%
% \changes{babel~3.7c}{1999/04/16}{Removed redefinition of \cs{@roman}
%    and \cs{@Roman}}
%
%  \begin{macro}{\TeX}
%  \begin{macro}{\LaTeX}
% \changes{babel~3.7a}{1998/03/12}{Make \TeX\ and \LaTeX\ logos
%    encoding-independent}
%    Because documents may use font encodings other than one of the
%    latin encodings, we make sure that the logos of \TeX\ and
%    \LaTeX\ always come out in the right encoding.
%    \begin{macrocode}
\bbl@redefine\TeX{\textlatin{\org@TeX}}
\bbl@redefine\LaTeX{\textlatin{\org@LaTeX}}
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%
%  \begin{macro}{\nfss@catcodes}
% \changes{babel~3.5g}{1996/08/18}{Need to add the double quote and
%    acute characters to \cs{nfss@catcodes} to prevent problems when
%    reading in .fd files}
%    \LaTeX's font selection scheme sometimes wants to read font
%    definition files in the middle of processing the document. In
%    order to guard against any characters having the wrong
%    |\catcode|s it always calls |\nfss@catcodes| before loading a
%    file. Unfortunately, the characters |"| and |'| are not dealt
%    with. Therefor we have to add them until \LaTeX\ does that
%    itself.
%    \begin{macrocode}
\bbl@add\nfss@catcodes{%
  \@makeother\'%
  \@makeother\"}
%    \end{macrocode}
%  \end{macro}
%
% \subsection{Local Language Configuration}
%
%  \begin{macro}{\loadlocalcfg}
%    At some sites it may be necessary to add site-specific actions to
%    a language definition file. This can be done by creating a file
%    with the same name as the language definition file, but with the
%    extension \file{.cfg}. For instance the file \file{norsk.cfg}
%    will be loaded when the language definition file \file{norsk.ldf}
%    is loaded.
%
% \changes{babel~3.5d}{1995/06/22}{Added macro}
%    For plain-based formats we don't want to override the definition
%    of |\loadlocalcfg| from \file{plain.def}.
%    \begin{macrocode}
\ifx\loadlocalcfg\@undefined
  \@ifpackagewith{babel}{noconfigs}%
    {\let\loadlocalcfg\@gobble}%
    {\def\loadlocalcfg#1{%
      \InputIfFileExists{#1.cfg}%
        {\typeout{*************************************^^J%
                       * Local config file #1.cfg used^^J%
                       *}}%
        \@empty}}
\fi
%    \end{macrocode}
%    Just to be compatible with \LaTeX$\:$2.09 we add a few more lines
%    of code:
%    \begin{macrocode}
\ifx\@unexpandable@protect\@undefined
  \def\@unexpandable@protect{\noexpand\protect\noexpand}
  \long\def\protected@write#1#2#3{%
    \begingroup
      \let\thepage\relax
      #2%
      \let\protect\@unexpandable@protect
      \edef\reserved@a{\write#1{#3}}%
      \reserved@a
    \endgroup
    \if@nobreak\ifvmode\nobreak\fi\fi}
\fi
%    \end{macrocode}
%    Finally, the default is to use English as the main language.
% \changes{babel~3.6c}{1997/01/05}{When \file{hyphen.cfg} is not
%    loaded in the format \cs{l@english} might not be defined; assume
%    english is language 0}
% \changes{babel~3.9a}{2012-05-17}{Languages are best assigned with
%    \cs{chardef}, not \cs{let}}
%    \begin{macrocode}
\ifx\l@english\@undefined
  \chardef\l@english\z@
\fi
\main@language{english}
%</core>
%    \end{macrocode}
%  \end{macro}
%
%
%    Now that we're sure that the code is seen by \LaTeX\ only, we
%    have to find out what the main (primary) document style is
%    because we want to redefine some macros.  This is only necessary
%    for releases of \LaTeX\ dated before December~1991. Therefor
%    this part of the code can optionally be included in
%    \file{babel.def} by specifying the \texttt{docstrip} option
%    \texttt{names}.
%    \begin{macrocode}
%<*names>
%    \end{macrocode}
%
%    The standard styles can be distinguished by checking whether some
%    macros are defined. In table~\ref{styles} an overview is given of
%    the macros that can be used for this purpose.
%  \begin{table}[htb]
%  \begin{center}
% \DeleteShortVerb{\|}
%  \begin{tabular}{|lcp{8cm}|}
%   \hline
%   article         & : & both the \verb+\chapter+ and \verb+\opening+
%                         macros are undefined\\
%   report and book & : & the \verb+\chapter+ macro is defined and
%                         the \verb+\opening+ is undefined\\
%   letter          & : & the \verb+\chapter+ macro is undefined and
%                         the \verb+\opening+ is defined\\
%   \hline
%  \end{tabular}
% \caption{How to determine the main document style}\label{styles}
% \MakeShortVerb{\|}
%  \end{center}
%  \end{table}
%
%    \noindent The macros that have to be redefined for the
%    \texttt{report} and \texttt{book} document styles happen to be
%    the same, so there is no need to distinguish between those two
%    styles.
%
%  \begin{macro}{\doc@style}
%    First a parameter |\doc@style| is defined to identify the current
%    document style. This parameter might have been defined by a
%    document style that already uses macros instead of hard-wired
%    texts, such as \file{artikel1.sty}~\cite{BEP}, so the existence of
%    |\doc@style| is checked. If this macro is undefined, i.\,e., if
%    the document style is unknown and could therefore contain
%    hard-wired texts, |\doc@style| is defined to the default
%    value~`0'.
% \changes{babel~3.0d}{1991/10/29}{Removed use of \cs{@ifundefined}}
%    \begin{macrocode}
\ifx\@undefined\doc@style
  \def\doc@style{0}%
%    \end{macrocode}
%    This parameter is defined in the following \texttt{if}
%    construction (see table~\ref{styles}):
%
%    \begin{macrocode}
  \ifx\@undefined\opening
    \ifx\@undefined\chapter
      \def\doc@style{1}%
    \else
      \def\doc@style{2}%
    \fi
  \else
    \def\doc@style{3}%
  \fi%
\fi%
%    \end{macrocode}
%  \end{macro}
%
% \changes{babel~3.1}{1991/11/05}{Removed definition of
%    \cs{if@restonecol}}
%
%    \subsubsection{Redefinition of macros}
%
%    Now here comes the real work: we start to redefine things and
%    replace hard-wired texts by macros. These redefinitions should be
%    carried out conditionally, in case it has already been done.
%
%    For the \texttt{figure} and \texttt{table} environments we have
%    in all styles:
%    \begin{macrocode}
\@ifundefined{figurename}{\def\fnum@figure{\figurename{} \thefigure}}{}
\@ifundefined{tablename}{\def\fnum@table{\tablename{} \thetable}}{}
%    \end{macrocode}
%
%    The rest of the macros have to be treated differently for each
%    style.  When |\doc@style| still has its default value nothing
%    needs to be done.
%    \begin{macrocode}
\ifcase \doc@style\relax
\or
%    \end{macrocode}
%
%    This means that \file{babel.def} is read after the
%    \texttt{article} style, where no |\chapter| and |\opening|
%    commands are defined\footnote{A fact that was pointed out to me
%    by Nico Poppelier and was already used in Piet van Oostrum's
%    document style option~\texttt{nl}.}.
%
%    First we have the |\tableofcontents|,
%    |\listoffigures| and |\listoftables|:
%    \begin{macrocode}
\@ifundefined{contentsname}%
    {\def\tableofcontents{\section*{\contentsname\@mkboth
          {\uppercase{\contentsname}}{\uppercase{\contentsname}}}%
      \@starttoc{toc}}}{}
\@ifundefined{listfigurename}%
    {\def\listoffigures{\section*{\listfigurename\@mkboth
          {\uppercase{\listfigurename}}{\uppercase{\listfigurename}}}%
     \@starttoc{lof}}}{}
\@ifundefined{listtablename}%
    {\def\listoftables{\section*{\listtablename\@mkboth
          {\uppercase{\listtablename}}{\uppercase{\listtablename}}}%
      \@starttoc{lot}}}{}
%    \end{macrocode}
%
% Then the |\thebibliography| and |\theindex| environments.
%
%    \begin{macrocode}
\@ifundefined{refname}%
    {\def\thebibliography#1{\section*{\refname
      \@mkboth{\uppercase{\refname}}{\uppercase{\refname}}}%
      \list{[\arabic{enumi}]}{\settowidth\labelwidth{[#1]}%
        \leftmargin\labelwidth
        \advance\leftmargin\labelsep
        \usecounter{enumi}}%
        \def\newblock{\hskip.11em plus.33em minus.07em}%
        \sloppy\clubpenalty4000\widowpenalty\clubpenalty
        \sfcode`\.=1000\relax}}{}
\@ifundefined{indexname}%
    {\def\theindex{\@restonecoltrue\if@twocolumn\@restonecolfalse\fi
     \columnseprule \z@
     \columnsep 35pt\twocolumn[\section*{\indexname}]%
       \@mkboth{\uppercase{\indexname}}{\uppercase{\indexname}}%
       \thispagestyle{plain}%
       \parskip\z@ plus.3pt\parindent\z@\let\item\@idxitem}}{}
%    \end{macrocode}
%
% The |abstract| environment:
%
%    \begin{macrocode}
\@ifundefined{abstractname}%
    {\def\abstract{\if@twocolumn
    \section*{\abstractname}%
    \else \small
    \begin{center}%
    {\bf \abstractname\vspace{-.5em}\vspace{\z@}}%
    \end{center}%
    \quotation
    \fi}}{}
%    \end{macrocode}
%
% And last but not least, the macro |\part|:
%
%    \begin{macrocode}
\@ifundefined{partname}%
{\def\@part[#1]#2{\ifnum \c@secnumdepth >\m@ne
        \refstepcounter{part}%
        \addcontentsline{toc}{part}{\thepart
        \hspace{1em}#1}\else
      \addcontentsline{toc}{part}{#1}\fi
   {\parindent\z@ \raggedright
    \ifnum \c@secnumdepth >\m@ne
      \Large \bf \partname{} \thepart
      \par \nobreak
    \fi
    \huge \bf
    #2\markboth{}{}\par}%
    \nobreak
    \vskip 3ex\@afterheading}%
}{}
%    \end{macrocode}
%
%    This is all that needs to be done for the \texttt{article} style.
%
%    \begin{macrocode}
\or
%    \end{macrocode}
%
%    The next case is formed by the two styles \texttt{book} and
%    \texttt{report}.  Basically we have to do the same as for the
%    \texttt{article} style, except now we must also change the
%    |\chapter| command.
%
%    The tables of contents, figures and tables:
%    \begin{macrocode}
\@ifundefined{contentsname}%
    {\def\tableofcontents{\@restonecolfalse
      \if@twocolumn\@restonecoltrue\onecolumn
      \fi\chapter*{\contentsname\@mkboth
          {\uppercase{\contentsname}}{\uppercase{\contentsname}}}%
      \@starttoc{toc}%
      \csname if@restonecol\endcsname\twocolumn
      \csname fi\endcsname}}{}
\@ifundefined{listfigurename}%
    {\def\listoffigures{\@restonecolfalse
      \if@twocolumn\@restonecoltrue\onecolumn
      \fi\chapter*{\listfigurename\@mkboth
          {\uppercase{\listfigurename}}{\uppercase{\listfigurename}}}%
      \@starttoc{lof}%
      \csname if@restonecol\endcsname\twocolumn
      \csname fi\endcsname}}{}
\@ifundefined{listtablename}%
    {\def\listoftables{\@restonecolfalse
      \if@twocolumn\@restonecoltrue\onecolumn
      \fi\chapter*{\listtablename\@mkboth
          {\uppercase{\listtablename}}{\uppercase{\listtablename}}}%
      \@starttoc{lot}%
      \csname if@restonecol\endcsname\twocolumn
      \csname fi\endcsname}}{}
%    \end{macrocode}
%
%    Again, the |bibliography| and |index| environments; notice that
%    in this case we use |\bibname| instead of |\refname| as in the
%    definitions for the \texttt{article} style.  The reason for this
%    is that in the \texttt{article} document style the term
%    `References' is used in the definition of |\thebibliography|. In
%    the \texttt{report} and \texttt{book} document styles the term
%    `Bibliography' is used.
%    \begin{macrocode}
\@ifundefined{bibname}%
    {\def\thebibliography#1{\chapter*{\bibname
     \@mkboth{\uppercase{\bibname}}{\uppercase{\bibname}}}%
     \list{[\arabic{enumi}]}{\settowidth\labelwidth{[#1]}%
     \leftmargin\labelwidth \advance\leftmargin\labelsep
     \usecounter{enumi}}%
     \def\newblock{\hskip.11em plus.33em minus.07em}%
     \sloppy\clubpenalty4000\widowpenalty\clubpenalty
     \sfcode`\.=1000\relax}}{}
\@ifundefined{indexname}%
    {\def\theindex{\@restonecoltrue\if@twocolumn\@restonecolfalse\fi
    \columnseprule \z@
    \columnsep 35pt\twocolumn[\@makeschapterhead{\indexname}]%
      \@mkboth{\uppercase{\indexname}}{\uppercase{\indexname}}%
    \thispagestyle{plain}%
    \parskip\z@ plus.3pt\parindent\z@ \let\item\@idxitem}}{}
%    \end{macrocode}
%
% Here is the |abstract| environment:
%    \begin{macrocode}
\@ifundefined{abstractname}%
    {\def\abstract{\titlepage
    \null\vfil
    \begin{center}%
    {\bf \abstractname}%
    \end{center}}}{}
%    \end{macrocode}
%
%     And last but not least the |\chapter|, |\appendix| and
%    |\part| macros.
%    \begin{macrocode}
\@ifundefined{chaptername}{\def\@chapapp{\chaptername}}{}
%
\@ifundefined{appendixname}%
    {\def\appendix{\par
      \setcounter{chapter}{0}%
      \setcounter{section}{0}%
      \def\@chapapp{\appendixname}%
      \def\thechapter{\Alph{chapter}}}}{}
%
\@ifundefined{partname}%
    {\def\@part[#1]#2{\ifnum \c@secnumdepth >-2\relax
            \refstepcounter{part}%
            \addcontentsline{toc}{part}{\thepart
            \hspace{1em}#1}\else
            \addcontentsline{toc}{part}{#1}\fi
       \markboth{}{}%
       {\centering
        \ifnum \c@secnumdepth >-2\relax
          \huge\bf \partname{} \thepart
        \par
        \vskip 20pt \fi
        \Huge \bf
        #1\par}\@endpart}}{}%
%    \end{macrocode}
%
%    \begin{macrocode}
\or
%    \end{macrocode}
%
%    Now we address the case where \file{babel.def} is read after the
%    \texttt{letter} style. The \texttt{letter} document style
%    defines the macro |\opening| and some other macros that are
%    specific to \texttt{letter}. This means that we have to redefine
%    other macros, compared to the previous two cases.
%
%    First two macros for the material at the end of a letter, the
%    |\cc| and |\encl| macros.
%    \begin{macrocode}
\@ifundefined{ccname}%
    {\def\cc#1{\par\noindent
     \parbox[t]{\textwidth}%
     {\@hangfrom{\rm \ccname : }\ignorespaces #1\strut}\par}}{}
\@ifundefined{enclname}%
    {\def\encl#1{\par\noindent
     \parbox[t]{\textwidth}%
     {\@hangfrom{\rm \enclname : }\ignorespaces #1\strut}\par}}{}
%    \end{macrocode}
%
%    The last thing we have to do here is to redefine the
%    \texttt{headings} pagestyle:
% \changes{babel~3.3}{1993/07/11}{\cs{headpagename} should be
%    \cs{pagename}}
%    \begin{macrocode}
\@ifundefined{headtoname}%
  {\def\ps@headings{%
     \def\@oddhead{\sl \headtoname{} \ignorespaces\toname \hfil
                      \@date \hfil \pagename{} \thepage}%
     \def\@oddfoot{}}}{}
%    \end{macrocode}
%
%    This was the last of the four standard document styles, so if
%    |\doc@style| has another value we do nothing and just close the
%    \texttt{if} construction.
%    \begin{macrocode}
\fi
%</names>
%    \end{macrocode}
%    Here ends the code that can be optionally included when a version
%    of \LaTeX\ is in use that is dated \emph{before} December~1991.
%
%
%    We also need to redefine a number of commands to ensure that the
%    right font encoding is used, but this can't be done before
%    \file{babel.def} is loaded.
% \changes{babel~3.6o}{1999/04/07}{Moved the rest of the font encoding
%    related definitions to their original place}
%
% \subsection{Multiple languages}
%
%  \begin{macro}{\language}
%    Plain \TeX\ version~3.0 provides the primitive |\language| that
%    is used to store the current language. When used with a pre-3.0
%    version this function has to be implemented by allocating a
%    counter.
%    \begin{macrocode}
%<*kernel|patterns>
\ifx\language\@undefined
  \csname newcount\endcsname\language
\fi
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\last@language}
%    Another counter is used to store the last language defined.  For
%    pre-3.0 formats an extra counter has to be allocated.
%
%  \begin{macro}{\addlanguage}
%
%    To add languages to \TeX's memory plain \TeX\ version~3.0
%    supplies |\newlanguage|, in a pre-3.0 environment a similar macro
%    has to be provided. For both cases a new macro is defined here,
%    because the original |\newlanguage| was defined to be |\outer|.
%
%    For a format based on plain version~2.x, the definition of
%    |\newlanguage| can not be copied because |\count 19| is used for
%    other purposes in these formats. Therefor |\addlanguage| is
%    defined using a definition based on the macros used to define
%    |\newlanguage| in plain \TeX\ version~3.0.
% \changes{babel~3.2}{1991/11/11}{Added a \texttt{\%}, removed
%    \texttt{by}}
%
%    For formats based on plain version~3.0 the definition of
%    |\newlanguage| can be simply copied, removing |\outer|.
%    \begin{macrocode}
\ifx\newlanguage\@undefined
  \csname newcount\endcsname\last@language
  \def\addlanguage#1{%
    \global\advance\last@language\@ne
    \ifnum\last@language<\@cclvi
    \else
        \errmessage{No room for a new \string\language!}%
    \fi
    \global\chardef#1\last@language
    \wlog{\string#1 = \string\language\the\last@language}}
%    \end{macrocode}
%    plain \TeX\ version 3.0 uses |\count 19| for this purpose.
%    \begin{macrocode}
\else
  \countdef\last@language=19
  \def\addlanguage{\alloc@9\language\chardef\@cclvi}
\fi
%</kernel|patterns>
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%
%  \begin{macro}{\adddialect}
%    The macro |\adddialect| can be used to add the name of a dialect
%    or variant language, for which an already defined hyphenation
%    table can be used.
% \changes{babel~3.2}{1991/11/11}{Added \cs{relax}}
%    \begin{macrocode}
%<*kernel>
\def\adddialect#1#2{%
  \global\chardef#1#2\relax
  \bbl@usehooks{adddialect}{{#1}{#2}}%
  \wlog{\string#1 = a dialect from \string\language#2}}
%    \end{macrocode}
%  \end{macro}
% \changes{babel~3.9a}{2012/09/07}{Added macro}
% \changes{babel~3.9a}{2013/01/23}{New macro to normalize 
%    a macro (eg, \cs{languagename}) to lowercase if necessary}
%
%    |\bbl@iflanguage| executes code only of the language
%    exists. Otherwise raises and error.
%
%    The argument of |\bbl@fixname| has to be a macro name, as it may get
%    ``fixed'' if casing (lc/uc) is wrong. It's intented to fix a
%    long-standing bug when |\foreignlanguage| and the like appear in
%    a |\MakeXXXcase|. However, a lowercase form is not imposed to
%    improve backward compatibility (perhaps you defined a language
%    named |MYLANG|, but unfortunately mixed case names cannot be
%    trapped).
%    \begin{macrocode}
\def\bbl@fixname#1{%
  \begingroup
    \def\bbl@tempe{l@}%
    \edef\bbl@tempd{\noexpand\@ifundefined{\noexpand\bbl@tempe#1}}%
    \bbl@tempd
      {\lowercase\expandafter{\bbl@tempd}%
         {\uppercase\expandafter{\bbl@tempd}%
           \@empty
           {\edef\bbl@tempd{\def\noexpand#1{#1}}%
            \uppercase\expandafter{\bbl@tempd}}}%
         {\edef\bbl@tempd{\def\noexpand#1{#1}}%
          \lowercase\expandafter{\bbl@tempd}}}%
      \@empty
    \edef\bbl@tempd{\endgroup\def\noexpand#1{#1}}%
  \bbl@tempd}
\def\bbl@iflanguage#1{%
  \@ifundefined{l@#1}{\@nolanerr{#1}\@gobble}\@firstofone}
%    \end{macrocode}
%
%  \begin{macro}{\iflanguage}
%    Users might want to test (in a private package for instance)
%    which language is currently active. For this we provide a test
%    macro, |\iflanguage|, that has three arguments.  It checks
%    whether the first argument is a known language. If so, it
%    compares the first argument with the value of |\language|. Then,
%    depending on the result of the comparison, it executes either the
%    second or the third argument.
% \changes{babel~3.2}{1991/11/11}{Rephrased \cs{ifnum} test}
% \changes{babel~3.7a}{1998/06/10}{Now evaluate the \cs{ifnum} test
%    \emph{after} the \cs{fi} from the \cs{ifx} test and use
%    \cs{@firstoftwo} and \cs{@secondoftwo}}
%    \begin{macrocode}
\def\iflanguage#1{%
  \bbl@iflanguage{#1}{%
    \ifnum\csname l@#1\endcsname=\language
      \expandafter\@firstoftwo
    \else
      \expandafter\@secondoftwo
    \fi}}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\selectlanguage}
%    The macro |\selectlanguage| checks whether the language is
%    already defined before it performs its actual task, which is to
%    update |\language| and activate language-specific definitions.
%
%    To allow the call of |\selectlanguage| either with a control
%    sequence name or with a simple string as argument, we have to use
%    a trick to delete the optional escape character.
%
%    To convert a control sequence to a string, we use the |\string|
%    primitive.  Next we have to look at the first character of this
%    string and compare it with the escape character.  Because this
%    escape character can be changed by setting the internal integer
%    |\escapechar| to a character number, we have to compare this
%    number with the character of the string.  To do this we have to
%    use \TeX's backquote notation to specify the character as a
%    number.
%
%    If the first character of the |\string|'ed argument is the
%    current escape character, the comparison has stripped this
%    character and the rest in the `then' part consists of the rest of
%    the control sequence name.  Otherwise we know that either the
%    argument is not a control sequence or |\escapechar| is set to a
%    value outside of the character range~$0$--$255$.
%
%    If the user gives an empty argument, we provide a default
%    argument for |\string|.  This argument should expand to nothing.
%
% \changes{babel~3.0c}{1991/06/06}{Made \cs{selectlanguage}
%    robust}
% \changes{babel~3.2}{1991/11/11}{Modified to allow arguments that
%    start with an escape character}
% \changes{babel~3.2a}{1991/11/17}{Simplified the modification to
%    allow the use in a \cs{write} command}
% \changes{babel~3.5b}{1995/05/13}{Store the name of the current
%    language in a control sequence instead of passing the whole macro
%    construct to strip the escape character in the argument of
%    \cs{selectlanguage }.}
% \changes{babel~3.5f}{1995/11/16}{Moved check for escape character
%    one level down in the expansion}
% \changes{babel~3.9a}{2012/11/16}{\cs{bbl@select@type} keep tracks of
%    the selection method: 0 is select, 1 is foreign}
%    \begin{macrocode}
\let\bbl@select@type\z@
\edef\selectlanguage{%
  \noexpand\protect
  \expandafter\noexpand\csname selectlanguage \endcsname}
%    \end{macrocode}
%    Because the command |\selectlanguage| could be used in a moving
%    argument it expands to \verb*=\protect\selectlanguage =.
%    Therefor, we have to make sure that a macro |\protect| exists.
%    If it doesn't it is |\let| to |\relax|.
%    \begin{macrocode}
\ifx\@undefined\protect\let\protect\relax\fi
%    \end{macrocode}
%    As \LaTeX$\:$2.09 writes to files \textit{expanded} whereas
%    \LaTeXe\ takes care \textit{not} to expand the arguments of
%    |\write| statements we need to be a bit clever about the way we
%    add information to \file{.aux} files. Therefor we introduce the
%    macro |\xstring| which should expand to the right amount of
%    |\string|'s.
%    \begin{macrocode}
\ifx\documentclass\@undefined
  \def\xstring{\string\string\string}
\else
  \let\xstring\string
\fi
%    \end{macrocode}
% \end{macro}
%
% \changes{babel~3.5b}{1995/03/04}{Changed the name of the internal
%    macro to \cs{selectlanguage }.}
% \changes{babel~3.5b}{1995/03/05}{Added an extra level of expansion to
%    separate the switching mechanism from writing to aux files}
% \changes{babel~3.7f}{2000/09/25}{Use \cs{aftergroup} to keep the
%    language grouping correct in auxiliary files {PR3091}}
%    Since version 3.5 \babel\ writes entries to the auxiliary files in
%    order to typeset table of contents etc. in the correct language
%    environment.
%  \begin{macro}{\bbl@pop@language}
%    \emph{But} when the language change happens \emph{inside} a group
%    the end of the group doesn't write anything to the auxiliary
%    files. Therefor we need \TeX's |aftergroup| mechanism to help
%    us. The command |\aftergroup| stores the token immediately
%    following it to be executed when the current group is closed. So
%    we define a temporary control sequence |\bbl@pop@language| to be
%    executed at the end of the group. It calls |\bbl@set@language|
%    with the name of the current language as its argument.
%
% \changes{babel~3.7j}{2003/03/18}{Introduce the language stack
%    mechanism}
%  \begin{macro}{\bbl@language@stack}
%    The previous solution works for one level of nesting groups, but
%    as soon as more levels are used it is no longer adequate. For
%    that case we need to keep track of the nested languages using a
%    stack mechanism. This stack is called |\bbl@language@stack| and
%    initially empty.
%    \begin{macrocode}
\def\bbl@language@stack{}
%    \end{macrocode}
%    When using a stack we need a mechanism to push an element on the
%    stack and to retrieve the information afterwards.
%  \begin{macro}{\bbl@push@language}
%  \begin{macro}{\bbl@pop@language}
%    The stack is simply a list of languagenames, separated with a `+'
%    sign; the push function can be simple:
%    \begin{macrocode}
\def\bbl@push@language{%
  \xdef\bbl@language@stack{\languagename+\bbl@language@stack}}
%    \end{macrocode}
%    Retrieving information from the stack is a little bit less simple,
%    as we need to remove the element from the stack while storing it
%    in the macro |\languagename|. For this we first define a helper function.
%  \begin{macro}{\bbl@pop@lang}
%    This macro stores its first element (which is delimited by the
%    `+'-sign) in |\languagename| and stores the rest of the string
%    (delimited by `-') in its third argument.
%    \begin{macrocode}
\def\bbl@pop@lang#1+#2-#3{%
  \edef\languagename{#1}\xdef#3{#2}}
%    \end{macrocode}
%  \end{macro}
%    The reason for the somewhat weird arrangement of arguments to the
%    helper function is the fact it is called in the following way.
%    This means that before |\bbl@pop@lang| is executed \TeX\ first
%    \emph{expands} the stack, stored in |\bbl@language@stack|. The
%    result of that is that the argument string of |\bbl@pop@lang|
%    contains one or more language names, each followed by a `+'-sign
%    (zero language names won't occur as this macro will only be
%    called after something has been pushed on the stack) followed by
%    the `-'-sign and finally the reference to the stack.
%    \begin{macrocode}
\def\bbl@pop@language{%
  \expandafter\bbl@pop@lang\bbl@language@stack-\bbl@language@stack
  \expandafter\bbl@set@language\expandafter{\languagename}}
%    \end{macrocode}
%    Once the name of the previous language is retrieved from the stack,
%    it is fed to |\bbl@set@language| to do the actual work of
%    switching everything that needs switching.
%  \end{macro}
%  \end{macro}
%  \end{macro}
%
% \changes{babel~3.7j}{2003/03/18}{Now use the language stack mechanism}
%    \begin{macrocode}
\expandafter\def\csname selectlanguage \endcsname#1{%
  \bbl@push@language
  \aftergroup\bbl@pop@language
  \bbl@set@language{#1}}
%    \end{macrocode}
% \changes{babel~3.7m}{2003/11/12}{Removed the superfluous empty
%    definition of \cs{bbl@pop@language}}
%  \end{macro}
%
%  \begin{macro}{\bbl@set@language}
%    \changes{babel~3.7f}{2000/09/25}{Macro \cs{bbl@set@language}
%    introduced}
% 
%    The macro |\bbl@set@language| takes care of switching the
%    language environment \emph{and} of writing entries on the
%    auxiliary files.  For historial reasons, language names can be
%    either |language| of |\language|. To catch either form a trick is
%    used, but unfortunately as a side effect the catcodes of letters
%    in |\languagename| are not well defined. The list of auxiliary
%    files can be extended by redefining |\BabelContentsFiles|, but
%    make sure they are loaded inside a group (as |aux|, |toc|,
%    |lof|, and |lot| do) or the last language of the document will
%    remain active afterwards.
%
%    We also write a command to change the current language in the
%    auxiliary files.
% \changes{babel~3.5a}{1995/02/17}{Write the language change to the
%    auxiliary files}
% \changes{babel~3.9a}{2012/09/09}{Added hook}
% \changes{babel~3.9a}{2012/11/07}{Use a loop for contents files, with
%    the help of \cs{BabelContentsFiles}}
% \changes{babel~3.9a}{2013/03/08}{Don't write to aux if language is
%    unknown}
%    \begin{macrocode}
\def\BabelContentsFiles{toc,lof,lot}%
\def\bbl@set@language#1{%
  \edef\languagename{%
    \ifnum\escapechar=\expandafter`\string#1\@empty
    \else\string#1\@empty\fi}%
  \select@language{\languagename}%
  \expandafter\ifx\csname date\languagename\endcsname\relax\else
    \if@filesw
      \protected@write\@auxout{}{\string\select@language{\languagename}}%
      \bbl@for\bbl@tempa\BabelContentsFiles{%
        \addtocontents{\bbl@tempa}{\xstring\select@language{\languagename}}}%
      \bbl@usehooks{write}{}%
    \fi
  \fi}
\def\select@language#1{%
  \edef\languagename{#1}%
  \bbl@fixname\languagename
  \bbl@iflanguage\languagename{%
    \expandafter\ifx\csname date\languagename\endcsname\relax
      \bbl@error
        {You haven't loaded the language #1\space yet}%
        {You may proceed, but expect unexpected results}%
    \else
      \let\bbl@select@type\z@
      \expandafter\bbl@switch\expandafter{\languagename}%
    \fi}}
% A bit of optmization:
\def\select@language@x#1{%
  \ifcase\bbl@select@type
    \bbl@ifsamestring\languagename{#1}{}{\select@language{#1}}%
  \else
    \select@language{#1}%
  \fi}
%    \end{macrocode}
%  \end{macro}
%
%    First, check if the user asks for a known language. If so,
%    update the value of |\language| and call |\originalTeX|
%    to bring \TeX\ in a certain pre-defined state.
% \changes{babel~3.0a}{1991/05/29}{Added \cs{@bsphack} and
%    \cs{@esphack}}
% \changes{babel~3.0d}{1991/08/08}{Removed superfluous
%    \cs{expandafter}}
% \changes{babel~3.0d}{1991/10/07}{Removed space hacks and use of
%    \cs{@ifundefined}}
% \changes{babel~3.2a}{1991/11/17}{Added \cs{relax} as first command
%    to stop an expansion if \cs{protect} is empty}
% \changes{babel~3.6a}{1996/11/07}{Check for the existence of
%    \cs{date...} instead of \cs{l@...}}
% \changes{babel~3.7m}{2003/11/16}{Check for the existence of both
%    \cs{l@...} and \cs{date...}}
% \changes{babel~3.8l}{2008/07/06}{Use \cs{bbl@patterns}}
% \changes{babel~3.9a}{2012/07/27}{Moved \cs{bbl@patterns} to the
%    correct place, after setting the extras for the current
%    language}
% \changes{babel~3.9a}{2012/08/01}{Created \cs{bbl@swith} with code
%    shared by \cs{select@language} and \cs{foreing@language}}
%    \begin{macrocode}
%    \end{macrocode}
%    The name of the language is stored in the control sequence
%    |\languagename|.
%
%    Then we have to \emph{re}define |\originalTeX| to compensate for
%    the things that have been activated.  To save memory space for
%    the macro definition of |\originalTeX|, we construct the control
%    sequence name for the |\noextras|\langvar\ command at definition
%    time by expanding the |\csname| primitive.
%
%    Now activate the language-specific definitions. This is done by
%    constructing the names of three macros by concatenating three
%    words with the argument of |\selectlanguage|, and calling these
%    macros. \nb{What if \cs{hyphenation} was used in |extras|? Patch
%    temply set@hyphenmins and hyphenation. It can be done in hooks if
%    necessary.}
% \changes{babel~3.5b}{1995/05/13}{Separated the setting of the
%    hyphenmin values}%
% \changes{babel~3.9c}{2013/04/08}{Removed an extra empty line}
%
%    The switching of the values of |\lefthyphenmin| and
%    |\righthyphenmin| is somewhat different. First we save their
%    current values, then we check if |\|\langvar|hyphenmins| is
%    defined. If it is not, we set default values (2 and 3), otherwise
%    the values in |\|\langvar|hyphenmins| will be used.
% \changes{babel~3.5b}{1995/06/05}{Addedd default setting of hyphenmin
%    parameters}
% \changes{babel~3.9a}{2012/08/01}{Adddd \cs{bbl@iflanguagename} and
%   \cs{select@language@x}, which is no-op if the language is the same}
% \changes{babel~3.9a}{2013/01/23}{\cs{select@language} sets 
%   \textsc{languagename} so that it has the correct value in the aux
%   file (eg, shorthand expansion was wrong)}
% \changes{babel~3.0a}{1991/06/06}{Replaced \cs{gdef} with \cs{def}}
% \changes{babel~3.1}{1991/10/31}{\cs{originalTeX} should only be
%    executed once}
% \changes{babel~3.2a}{1991/11/17}{Added three \cs{expandafter}s
%    to save macro space for \cs{originalTeX}}
% \changes{babel~3.2a}{1991/11/20}{Moved definition of
%    \cs{originalTeX} before \cs{extras\langvar}}
% \changes{babel~3.2a}{1991/11/24}{Set \cs{originalTeX} to
%    \cs{empty}, because it should be expandable.}
% \changes{babel~3.6d}{1997/01/07}{set the language shorthands to
%    `none' before switching on the extras}
% \changes{babel~3.9a}{2012/08/14}{Make sure the save counter is reset
%    even in \cs{originalTeX} is used in other contexts}
%    \begin{macrocode}
\def\bbl@switch#1{%
  \originalTeX
  \expandafter\def\expandafter\originalTeX\expandafter{%
    \csname noextras#1\endcsname
    \let\originalTeX\@empty
    \babel@beginsave}%
  \languageshorthands{none}%
  \ifcase\bbl@select@type
    \csname captions#1\endcsname
    \csname date#1\endcsname
  \fi
  \bbl@usehooks{beforeextras}{}%
  \csname extras#1\endcsname\relax
  \bbl@usehooks{afterextras}{}%
  \bbl@patterns{#1}%
  \babel@savevariable\lefthyphenmin
  \babel@savevariable\righthyphenmin
  \expandafter\ifx\csname #1hyphenmins\endcsname\relax
    \set@hyphenmins\tw@\thr@@\relax
  \else
    \expandafter\expandafter\expandafter\set@hyphenmins
      \csname #1hyphenmins\endcsname\relax
  \fi}
%    \end{macrocode}
%    \begin{macrocode}
\def\bbl@ifsamestring#1#2{%
  \protected@edef\bbl@tempb{#1}%
  \edef\bbl@tempb{\expandafter\strip@prefix\meaning\bbl@tempb}%
  \protected@edef\bbl@tempc{#2}%
  \edef\bbl@tempc{\expandafter\strip@prefix\meaning\bbl@tempc}%
  \ifx\bbl@tempb\bbl@tempc
    \expandafter\@firstoftwo
  \else
    \expandafter\@secondoftwo
  \fi}
%    \end{macrocode}
%
%  \begin{environment}{otherlanguage}
%    The \Lenv{otherlanguage} environment can be used as an
%    alternative to using the |\selectlanguage| declarative
%    command. When you are typesetting a document which mixes
%    left-to-right and right-to-left typesetting you have to use this
%    environment in order to let things work as you expect them to.
%
%    The first thing this environment does is store the name of the
%    language in |\languagename|; it then calls
%    \verb*=\selectlanguage = to switch on everything that is needed for
%    this language The |\ignorespaces| command is necessary to hide
%    the environment when it is entered in horizontal mode.
% \changes{babel~3.5d}{1995/06/22}{environment added}
% \changes{babel~3.5e}{1995/07/07}{changed name}
% \changes{babel~3.7j}{2003/03/18}{rely on \cs{selectlanguage } to
%    keep track of the nesting}
% \changes{babel~3.9a}{2012/07/31}{Removed \cs{originalTeX}}
%    \begin{macrocode}
\long\def\otherlanguage#1{%
  \csname selectlanguage \endcsname{#1}%
  \ignorespaces}
%    \end{macrocode}
%    The |\endotherlanguage| part of the environment tries to hide
%    itself when it is called in horizontal mode.
%    \begin{macrocode}
\long\def\endotherlanguage{%
  \global\@ignoretrue\ignorespaces}
%    \end{macrocode}
%  \end{environment}
%
%  \begin{environment}{otherlanguage*}
%    The \Lenv{otherlanguage} environment is meant to be used when a
%    large part of text from a different language needs to be typeset,
%    but without changing the translation of words such as `figure'.
%    This environment makes use of |\foreign@language|.
% \changes{babel~3.5f}{1996/05/29}{environment added}
% \changes{babel~3.6d}{1997/01/07}{Introduced \cs{foreign@language}}
%    \begin{macrocode}
\expandafter\def\csname otherlanguage*\endcsname#1{%
  \foreign@language{#1}}
%    \end{macrocode}
%    At the end of the environment we need to switch off the extra
%    definitions. The grouping mechanism of the environment will take
%    care of resetting the correct hyphenation rules and ``extras''.
%    \begin{macrocode} 
\expandafter\let\csname endotherlanguage*\endcsname\relax
%    \end{macrocode}
%  \end{environment}
%
%  \begin{macro}{\foreignlanguage}
%    The |\foreignlanguage| command is another substitute for the
%    |\selectlanguage| command. This command takes two arguments, the
%    first argument is the name of the language to use for typesetting
%    the text specified in the second argument.
%
%    Unlike |\selectlanguage| this command doesn't switch
%    \emph{everything}, it only switches the hyphenation rules and the
%    extra definitions for the language specified. It does this within
%    a group and assumes the |\extras|\langvar\ command doesn't make
%    any |\global| changes. The coding is very similar to part of
%    |\selectlanguage|.
% \changes{babel~3.5d}{1995/06/22}{Macro added}
% \changes{babel~3.6d}{1997/01/07}{Introduced \cs{foreign@language}}
% \changes{babel~3.7a}{1998/03/12}{Added executing \cs{originalTeX}}
% \changes{babel~3.9a}{2012/07/30}{Removed unnecesary \cs{noextras}
%    just before closing the group}
% \changes{babel~3.9a}{2012/07/31}{Moved \cs{originalTeX} to
%    \cs{foreing@language} so that it's also used in
%    \texttt{otherlanguage*}}
% \changes{babel~3.9a}{2012/12/24}{\cs{foreignlanguage} defined
%    similarly to \cs{selectlanguage}, protecting the whole macro}
%    \begin{macrocode}
\edef\foreignlanguage{%
  \noexpand\protect
  \expandafter\noexpand\csname foreignlanguage \endcsname}
\expandafter\def\csname foreignlanguage \endcsname#1#2{%
  \begingroup
    \foreign@language{#1}%
    #2%
  \endgroup}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\foreign@language}
% \changes{babel~3.6d}{1997/01/07}{New macro} This macro does the
%    work for |\foreignlanguage| and the \Lenv{otherlanguage*}
%    environment. First we need to store the name of the language and
%    check that it is a known language. Then it just calls
%    |bbl@switch|.
%    \begin{macrocode}
\def\foreign@language#1{%
  \edef\languagename{#1}%
  \bbl@fixname\languagename
  \bbl@iflanguage\languagename{%
    \expandafter\ifx\csname date\languagename\endcsname\relax
      \bbl@warning
        {You haven't loaded the language #1\space yet\\%
         I'll proceed, but expect unexpected results.\\%
         Reported}%
    \fi
    \let\bbl@select@type\@ne
    \expandafter\bbl@switch\expandafter{\languagename}}}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\bbl@patterns}
% \changes{babel~3.8l}{2008/07/06}{Macro added}
% \changes{babel~3.9a}{2012/08/28}{Extended to set hyphenation
%    exceptions as defined with \cs{babelhyphenation}}
%    This macro selects the hyphenation patterns by changing the
%    \cs{language} register.  If special hyphenation patterns
%    are available specifically for the current font encoding,
%    use them instead of the default.
%
%    It also sets hyphenation exceptions, but only once, because they
%    are global (here language |\lccode|'s has been set,
%    too). |\bbl@hyphenation@| is set to relax until the very first
%    |\babelhyphenation|, so do nothing with this value. If the
%    exceptions for a language (by its number, not its name, so that
%    |:ENC| is taken into account) has been set, then use
%    |\hyphenation| with both global and language exceptions and empty
%    the latter to mark they must not be set again.
%    \begin{macrocode}
\let\bbl@hyphlist\@empty
\let\bbl@hyphenation@\relax
\def\bbl@patterns#1{%
  \language=\expandafter\ifx\csname l@#1:\f@encoding\endcsname\relax
      \csname l@#1\endcsname
      \edef\bbl@tempa{#1}%
    \else
      \csname l@#1:\f@encoding\endcsname
      \edef\bbl@tempa{#1:\f@encoding}%
    \fi\relax
  \@expandtwoargs\bbl@usehooks{patterns}{{#1}{\bbl@tempa}}%
  \@ifundefined{bbl@hyphenation@}{}{%
    \begingroup
      \@expandtwoargs\in@{,\number\language,}{,\bbl@hyphlist}%
      \ifin@\else
        \@expandtwoargs\bbl@usehooks{hyphenation}{{#1}{\bbl@tempa}}%
        \hyphenation{%
          \bbl@hyphenation@
          \@ifundefined{bbl@hyphenation@#1}%
            \@empty
            {\space\csname bbl@hyphenation@#1\endcsname}}%
        \xdef\bbl@hyphlist{\bbl@hyphlist\number\language,}%
      \fi
    \endgroup}}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{environment}{hyphenrules}
% \changes{babel~3.7e}{2000/01/28}{Added environment hyphenrules}
%    The environment \Lenv{hyphenrules} can be used to select
%    \emph{just} the hyphenation rules. This environment does
%    \emph{not} change |\languagename| and when the hyphenation rules
%    specified were not loaded it has no effect. Note however,
%    |\lccode|'s and font encodings are not set at all, so in most
%    cases you should use |otherlanguage*|.
% \changes{babel~3.8j}{2008/03/16}{Also set the hyphenmin parameters to
%    the correct value (PR3997)} 
% \changes{babel~3.8l}{2008/07/06}{Use \cs{bbl@patterns}}
%    \begin{macrocode}
\def\hyphenrules#1{%
  \edef\languagename{#1}%
  \bbl@fixname\languagename
  \bbl@iflanguage\languagename{%
    \expandafter\bbl@patterns\expandafter{\languagename}%
    \languageshorthands{none}%
    \expandafter\ifx\csname\languagename hyphenmins\endcsname\relax
      \set@hyphenmins\tw@\thr@@\relax
    \else
      \expandafter\expandafter\expandafter\set@hyphenmins
      \csname\languagename hyphenmins\endcsname\relax
    \fi}}
\let\endhyphenrules\@empty
%    \end{macrocode}
%  \end{environment}
%
%  \begin{macro}{\providehyphenmins}
% \changes{babel~3.7f}{2000/02/18}{added macro}
%    The macro |\providehyphenmins| should be used in the language
%    definition files to provide a \emph{default} setting for the
%    hyphenation parameters |\lefthyphenmin| and |\righthyphenmin|. If
%    the macro |\|\langvar|hyphenmins| is already defined this command
%    has no effect.
%    \begin{macrocode}
\def\providehyphenmins#1#2{%
  \expandafter\ifx\csname #1hyphenmins\endcsname\relax
    \@namedef{#1hyphenmins}{#2}%
  \fi}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\set@hyphenmins}
%    This macro sets the values of |\lefthyphenmin| and
%    |\righthyphenmin|. It expects two values as its argument.
%    \begin{macrocode}
\def\set@hyphenmins#1#2{\lefthyphenmin#1\relax\righthyphenmin#2\relax}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\LdfInit}
% \changes{babel~3.6a}{1996/10/16}{Macro added}
%    This macro is defined in two versions. The first version is to be
%    part of the `kernel' of \babel, ie. the part that is loaded in
%    the format; the second version is defined in \file{babel.def}.
%    The version in the format just checks the category code of the
%    ampersand and then loads \file{babel.def}.
%
%    The category code of the ampersand is restored and the macro
%    calls itself again with the new definition from
%    \file{babel.def}
%    \begin{macrocode}
\def\LdfInit{%
  \chardef\atcatcode=\catcode`\@
  \catcode`\@=11\relax
  \input babel.def\relax
  \catcode`\@=\atcatcode \let\atcatcode\relax
  \LdfInit}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\originalTeX}
%    The macro|\originalTeX| should be known to \TeX\ at this moment.
%    As it has to be expandable we |\let| it to |\@empty| instead of
%    |\relax|.
% \changes{babel~3.2a}{1991/11/24}{Set \cs{originalTeX} to
%    \cs{empty}, because it should be expandable.}
%    \begin{macrocode}
\ifx\originalTeX\@undefined\let\originalTeX\@empty\fi
%    \end{macrocode}
%    Because this part of the code can be included in a format, we
%    make sure that the macro which initialises the save mechanism,
%    |\babel@beginsave|, is not considered to be undefined.
%    \begin{macrocode}
\ifx\babel@beginsave\@undefined\let\babel@beginsave\relax\fi
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\@nolanerr}
% \changes{babel~3.4e}{1994/06/25}{Use \cs{PackageError} in \LaTeXe\
%    mode}
%  \begin{macro}{\@nopatterns}
% \changes{babel~3.4e}{1994/06/25}{Macro added}
%    The \babel\ package will signal an error when a documents tries
%    to select a language that hasn't been defined earlier. When a
%    user selects a language for which no hyphenation patterns were
%    loaded into the format he will be given a warning about that
%    fact. We revert to the patterns for |\language|=0 in that case.
%    In most formats that will be (US)english, but it might also be
%    empty.
%  \begin{macro}{\@noopterr}
% \changes{babel~3.7m}{2003/11/16}{Macro added}
%    When the package was loaded without options not everything will
%    work as expected. An error message is issued in that case.
%
%    When the format knows about |\PackageError| it must be \LaTeXe,
%    so we can safely use its error handling interface. Otherwise
%    we'll have to `keep it simple'.
% \changes{babel~3.0d}{1991/10/07}{Added a percent sign to remove
%    unwanted white space}
% \changes{babel~3.5a}{1995/02/15}{Added \cs{@activated} to log active
%    characters}
% \changes{babel~3.5c}{1995/06/19}{Added missing closing brace}
% \changes{babel~3.9a}{2012/07/30}{\cs{newcommand}s replaced by
%    \cs{def}'s, so that the file can be loaded twice}
% \changes{babel~3.9a}{2013/01/26}{Define generic variants instead of
%    duplicating each predefined message}    
%    \begin{macrocode}
\edef\bbl@nulllanguage{\string\language=0}
\ifx\PackageError\@undefined
  \def\bbl@error#1#2{%
    \begingroup
      \newlinechar=`\^^J
      \def\\{^^J(babel) }%
      \errhelp{#2}\errmessage{\\#1}%
    \endgroup}
  \def\bbl@warning#1{%
    \begingroup
      \newlinechar=`\^^J
      \def\\{^^J(babel) }%
      \message{\\#1}%
    \endgroup}
  \def\bbl@info#1{%
    \begingroup
      \newlinechar=`\^^J
      \def\\{^^J}%
      \wlog{#1}%
    \endgroup}
\else
  \def\bbl@error#1#2{%
    \begingroup
      \def\\{\MessageBreak}%
      \PackageError{babel}{#1}{#2}%
    \endgroup}
  \def\bbl@warning#1{%
    \begingroup
      \def\\{\MessageBreak}%
      \PackageWarning{babel}{#1}%
    \endgroup}
  \def\bbl@info#1{%
    \begingroup
      \def\\{\MessageBreak}%
      \PackageInfo{babel}{#1}%
    \endgroup}
\fi
\def\@nolanerr#1{%
  \bbl@error
    {You haven't defined the language #1\space yet}%
    {Your command will be ignored, type <return> to proceed}}
\def\@nopatterns#1{%
  \bbl@warning
    {No hyphenation patterns were preloaded for\\%
     the language `#1' into the format.\\%
     Please, configure your TeX system to add them and\\%
     rebuild the format. Now I will use the patterns\\%
     preloaded for \bbl@nulllanguage\space instead}}
\let\bbl@usehooks\@gobbletwo
%</kernel>
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%  \end{macro}
%
%    The following code is meant to be read by ini\TeX\ because it
%    should instruct \TeX\ to read hyphenation patterns. To this end
%    the \texttt{docstrip} option \texttt{patterns} can be used to
%    include this code in the file \file{hyphen.cfg}. Code is at lower
%    level than the rest.
%
%    |toks8| stores info to be shown when the program is run.
%
%    \begin{macrocode}
%<*patterns>
\toks8{Babel <3.9f> and hyphenation patterns for }%
%    \end{macrocode}
%
% \changes{babel~3.5g}{1996/07/09}{Removed the use of
%    \cs{patterns@loaded} altogether}
%
%  \begin{macro}{\process@line}
% \changes{babel~3.5b}{1995/04/28}{added macro}
%    Each line in the file \file{language.dat} is processed by
%    |\process@line| after it is read. The first thing this macro does
%    is to check whether the line starts with \texttt{=}.
%    When the first token of a line is an \texttt{=}, the macro
%    |\process@synonym| is called; otherwise the macro
%    |\process@language| will continue.
% \changes{babel~3.5g}{1996/07/09}{Simplified code, removing
%    \cs{bbl@eq@}}
% \changes{babel~3.9a}{2012/12/12}{Use spaces as delimiters, to avoid
%    extra spaces. Once parsed, pass them in the traditional way}
%    \begin{macrocode}   
\def\process@line#1#2 #3 #4 {%
  \ifx=#1%
    \process@synonym{#2}%
  \else
    \process@language{#1#2}{#3}{#4}%
  \fi
  \ignorespaces}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\process@synonym}
% \changes{babel~3.5b}{1995/04/28}{added macro}
% \changes{babel~3.7c}{1999/04/27}{Use a token register to temporarily
%    store a command to set hyphenmin parameters for the synonym which
%    is defined \emph{before} the first pattern file is processed}
%
%    This macro takes care of the lines which start with an
%    \texttt{=}. It needs an empty token register to begin with.
%    |\bbl@languages| is also set to empty. 
%    \begin{macrocode}
\toks@{}
\def\bbl@languages{}
%    \end{macrocode}
%    When no languages have been loaded yet, the name following the
%    \texttt{=} will be a synonym for hyphenation register 0. So, it is stored
%    in a token register and executed when the first pattern file has
%    been processed. (The |\relax| just helps to the |\if| below
%    catching synonyms without a language.)
%
%    Otherwise the name will be a synonym for the language loaded last.
%
%    We also need to copy the hyphenmin parameters for the synonym.
% \changes{babel~3.7c}{1999/04/22}{Now also store hyphenmin parameters
%    for language synonyms}
% \changes{babel~3.9a}{2012/06/25}{Added \cs{bbl@languages}}
%    \begin{macrocode}
\def\process@synonym#1{%
  \ifnum\last@language=\m@ne
    \toks@\expandafter{\the\toks@\relax\process@synonym{#1}}%
  \else
    \expandafter\chardef\csname l@#1\endcsname\last@language
    \wlog{\string\l@#1=\string\language\the\last@language}%
    \expandafter\let\csname #1hyphenmins\expandafter\endcsname
      \csname\languagename hyphenmins\endcsname
    \let\bbl@elt\relax
    \edef\bbl@languages{\bbl@languages\bbl@elt{#1}{\the\last@language}{}{}}%
  \fi}
%    \end{macrocode}
%  \end{macro}
%
%  \begin{macro}{\process@language}
%    The macro |\process@language| is used to process a non-empty line
%    from the `configuration file'. It has three arguments, each
%    delimited by white space. The first argument is the `name' of a
%    language; the second is the name of the file that contains the
%    patterns. The optional third argument is the name of a file
%    containing hyphenation exceptions.
%
%    The first thing to do is call |\addlanguage| to allocate a
%    pattern register and to make that register `active'.
% \changes{babel~3.0d}{1991/08/08}{Removed superfluous
%    \cs{expandafter}}
% \changes{babel~3.0d}{1991/08/21}{Reinserted \cs{expandafter}}
% \changes{babel~3.0d}{1991/10/27}{Added the collection of pattern
%    names.}
% \changes{babel~3.7c}{1999/04/22}{Also store \cs{languagename} for
%    possible later use in \cs{process@synonym}}
%    Then the `name' of the language that will be loaded now is
%    added to the token register |\toks8|. and finally
%    the pattern file is read.
% \changes{babel~3.7f}{2000/02/18}{Allow for the encoding to be used
%    as part of the language name} 
% \changes{babel~3.9a}{2012/12/10}{Removed \cs{selectfont} (I presume
%    it was intended to catch wrong encoding codes, but I don't think
%    this is necessary and as a side effect it might preload fonts)} 
%
%    For some hyphenation patterns it is needed to load them with a
%    specific font encoding selected. This can be specified in the
%    file \file{language.dat} by adding for instance `\texttt{:T1}' to
%    the name of the language. The macro |\bbl@get@enc| extracts the
%    font encoding from the language name and stores it in
%    |\bbl@hyph@enc|. The latter can be used in hyphenation files if
%    you need to set a behaviour depending on the given encoding (it
%    is set to empty if no encoding is given).
%
% \changes{babel~3.4e}{1994/06/24}{Added code to detect assignments to
%    left- and righthyphenmin in the patternfile.}
% \changes{babel~3.7a}{1998/03/27}{Read pattern files in a group}
% \changes{babel~3.7c}{1999/04/05}{need to set hyphenmin values
%    globally}
% \changes{babel~3.7c}{1999/04/22}{Set \cs{lefthyphenmin} to \cs{m@ne}
%    \emph{inside} the group; explicitly set the hyphenmin parameters
%    for language 0}
% \changes{babel~3.7c}{1999/04/25}{Only set hyphenmin values when the
%    pattern file changed them}
%    Pattern files may contain assignments to |\lefthyphenmin| and
%    |\righthyphenmin|. \TeX\ does not keep track of these
%    assignments. Therefor we try to detect such assignments and
%    store them in the |\|\langvar|hyphenmins| macro. When no
%    assignments were made we provide a default setting.
%
%    Some pattern files contain changes to the |\lccode| en |\uccode|
%    arrays. Such changes should remain local to the language;
%    therefor we process the pattern file in a group; the |\patterns|
%    command acts globally so its effect will be remembered.
%
%    Then we globally store the settings of |\lefthyphenmin| and
%    |\righthyphenmin| and close the group.
%
%    When the hyphenation patterns have been processed we need to see
%    if a file with hyphenation exceptions needs to be read. This is
%    the case when the third argument is not empty and when it does
%    not contain a space token. (Note however there is no need to save
%    hyphenation exceptions into the format.)
% \changes{babel~3.5b}{1995/04/28}{Added optional reading of file with
%    hyphenation exceptions}
% \changes{babel~3.5f}{1995/07/25}{Use \cs{empty} instead of
%    \cs{@empty} as the latter is unknown in plain}
%
% \changes{babel~3.9a}{2012/06/25}{Added \cs{bbl@languages}}
% \changes{babel~3.9f}{2013/05/16}{Restored code to set default
%    hyphenmins, which was deleted mistakenly} 
%    \cs{bbl@languages} saves a snapshot of the loaded languagues in the
%    form  \cs{bbl@elt}\marg{language-name}\marg{number}%
%    \marg{patterns-file}\marg{exceptions-file}. Note the last 2
%    arguments are empty in `dialects' defined in |language.dat| with
%    |=|. Note also the language name can have encoding info.
%
% \changes{babel~3.7c}{1999/04/27}{Added the execution of the contents
%    of \cs{toks@}}
%    Finally, if the counter |\language| is equal to zero we execute the
%    synonyms stored.
%    \begin{macrocode}
\def\process@language#1#2#3{%
  \expandafter\addlanguage\csname l@#1\endcsname
  \expandafter\language\csname l@#1\endcsname
  \edef\languagename{#1}%
  \bbl@hook@everylanguage{#1}%
  \bbl@get@enc#1::\@@@
  \begingroup
    \lefthyphenmin\m@ne
    \bbl@hook@loadpatterns{#2}%
    \ifnum\lefthyphenmin=\m@ne
    \else
      \expandafter\xdef\csname #1hyphenmins\endcsname{%
        \the\lefthyphenmin\the\righthyphenmin}%
    \fi
  \endgroup
  \def\bbl@tempa{#3}%
  \ifx\bbl@tempa\@empty\else
    \bbl@hook@loadexceptions{#3}%
  \fi
  \let\bbl@elt\relax
  \edef\bbl@languages{%
    \bbl@languages\bbl@elt{#1}{\the\language}{#2}{\bbl@tempa}}%
  \ifnum\the\language=\z@
    \expandafter\ifx\csname #1hyphenmins\endcsname\relax
      \set@hyphenmins\tw@\thr@@\relax
    \else
      \expandafter\expandafter\expandafter\set@hyphenmins
        \csname #1hyphenmins\endcsname
    \fi
    \the\toks@
    \toks@{}%
  \fi}
%    \end{macrocode}
%
%  \begin{macro}{\bbl@get@enc}
% \changes{babel~3.7f}{2000/02/18}{Added macro}
% \changes{babel~3.9a}{2012/12/11}{Code much simplified}
%  \begin{macro}{\bbl@hyph@enc}
%    The macro |\bbl@get@enc| extracts the font encoding from the
%    language name and stores it in |\bbl@hyph@enc|. It uses delimited
%    arguments to achieve this.
%    \begin{macrocode}
\def\bbl@get@enc#1:#2:#3\@@@{\def\bbl@hyph@enc{#2}}
%    \end{macrocode}
%  \end{macro}
%  \end{macro}
%  \end{macro}
%
%    Now, hooks are defined. For efficiency reasons, they are dealt
%    here in a special way. Besides \luatex, format specific
%    configuration files are taken into account.
% \changes{babel~3.9b}{2013/03/25}{Fixed an idiot slip: \cs{def}
%   intead of \cs{let}}
%    \begin{macrocode}
\def\bbl@hook@everylanguage#1{}
\def\bbl@hook@loadpatterns#1{\input #1\relax}
\let\bbl@hook@loadexceptions\bbl@hook@loadpatterns
\let\bbl@hook@loadkernel\bbl@hook@loadpatterns
\begingroup
  \def\AddBabelHook#1#2{%
    \expandafter\ifx\csname bbl@hook@#2\endcsname\relax
      \def\next{\toks1}%
    \else
      \def\next{\expandafter\gdef\csname bbl@hook@#2\endcsname####1}%
    \fi
    \next}
  \ifx\directlua\@undefined
    \ifx\XeTeXinputencoding\@undefined\else
      \input xebabel.def
    \fi
  \else
    \input luababel.def
  \fi
  \openin1 = babel-\bbl@format.cfg
  \ifeof1
  \else
    \input babel-\bbl@format.cfg\relax
  \fi
  \closein1
\endgroup
\bbl@hook@loadkernel{switch.def}
%    \end{macrocode}
%  \begin{macro}{\readconfigfile}
%    The configuration file can now be opened for reading.
%    \begin{macrocode}
\openin1 = language.dat
%    \end{macrocode}
%
%    See if the file exists, if not, use the default hyphenation file
%    \file{hyphen.tex}. The user will be informed about this.
%
%    \begin{macrocode}
\def\languagename{english}%
\ifeof1
  \message{I couldn't find the file language.dat,\space
           I will try the file hyphen.tex}
  \input hyphen.tex\relax
  \chardef\l@english\z@
\else
%    \end{macrocode}
%
%    Pattern registers are allocated using count register
%    |\last@language|. Its initial value is~0. The definition of the
%    macro |\newlanguage| is such that it first increments the count
%    register and then defines the language. In order to have the
%    first patterns loaded in pattern register number~0 we initialize
%    |\last@language| with the value~$-1$.
%
% \changes{babel~3.1}{1991/05/21}{Removed use of \cs{toks0}}
%    \begin{macrocode}
  \last@language\m@ne
%    \end{macrocode}
%
%    We now read lines from the file until the end is found
%
%    \begin{macrocode}
  \loop
%    \end{macrocode}
%
%    While reading from the input, it is useful to switch off
%    recognition of the end-of-line character. This saves us stripping
%    off spaces from the contents of the control sequence.
%
%    \begin{macrocode}
    \endlinechar\m@ne
    \read1 to \bbl@line
    \endlinechar`\^^M
%    \end{macrocode}
%
% \changes{babel~3.9a}{2012/12/14}{Test simplified and moved}
% \changes{babel~3.9a}{2012/12/12}{Use only spaces as delimiters and
%    not /, as previouly done} 
%
%    If the file has reached its end, exit from the loop here. If not,
%    empty lines are skipped. Add 3 space characters to the end of
%    |\bbl@line|. This is needed to be able to recognize the arguments
%    of |\process@line| later on. The default language should be the
%    very first one.
%
%    \begin{macrocode}
    \if T\ifeof1F\fi T\relax
      \ifx\bbl@line\@empty\else
        \edef\bbl@line{\bbl@line\space\space\space}%
        \expandafter\process@line\bbl@line\relax
      \fi
  \repeat
%    \end{macrocode}
%
%    Check for the end of the file. We must reverse the test for
%    |\ifeof| without |\else|. Then reactivate the default patterns,
% \changes{babel~3.8m}{2008/07/08}{Also restore the name of the
%    language in \cs{languagename} (PR 4039)} 
%    \begin{macrocode}
  \begingroup
    \def\bbl@elt#1#2#3#4{%
      \global\language=#2\relax
      \gdef\languagename{#1}%
      \def\bbl@elt##1##2##3##4{}}%
    \bbl@languages
  \endgroup
\fi
%    \end{macrocode}
%    and close the configuration file.
% \changes{babel~3.2a}{1991/11/20}{Free macro space for
%    \cs{process@language}}
%    \begin{macrocode}
\closein1
%    \end{macrocode}
%
% \changes{babel~3.5f}{1995/11/08}{Moved the fiddling with \cs{dump}
%     to \file{bbplain.dtx} as it is no longer needed for \LaTeX}
%    We add a message about the fact that babel is loaded in the
%    format and with which language patterns to the \cs{everyjob}
%    register.
% \changes{babel~3.6h}{1997/01/23}{Added a couple of \cs{expandafter}s
%    to copy the contents of \cs{toks8} into \cs{everyjob} instead of
%    the reference}
% \changes{babel~3.9a}{2012/09/25}{The list of languages is not
%    printed every  job any more (it is saved in \cs{bbl@languages}).} 
%    \begin{macrocode}
\if/\the\toks@/\else
  \errhelp{language.dat loads no language, only synonyms}
  \errmessage{Orphan language synonym}
\fi
\ifx\addto@hook\@undefined
\else
  \edef\bbl@tempa{%
    \noexpand\typeout{\the\toks8 \the\last@language\space languages
    loaded.}}%
  \expandafter\addto@hook\expandafter\everyjob\expandafter{\bbl@tempa}
\fi
%    \end{macrocode}
%    Also remove some macros from memory and raise an error
%    if |\toks@| is not empty. Finally load \file{switch.def}, but the
%    letter is not required and the line inputting it may be commented out.
% \changes{babel~3.9a}{2012/12/11}{Raise error if there are synonyms
%    without languages}
%    \begin{macrocode}
\let\bbl@line\@undefined
\let\process@line\@undefined
\let\process@synonym\@undefined
\let\process@language\@undefined
\let\bbl@get@enc\@undefined
\let\bbl@hyph@enc\@undefined
\let\bbl@tempa\@undefined
\let\bbl@hook@loadkernel\@undefined
\let\bbl@hook@everylanguage\@undefined
\let\bbl@hook@loadpatterns\@undefined
\let\bbl@hook@loadexceptions\@undefined
%</patterns>
%    \end{macrocode}
%    Here the code for ini\TeX\ ends.
%  \end{macro}
%
%    \section{The `nil' language}
%
%    This `language' does nothing, except setting the hyphenation patterns to
%    nohyphenation.
%
%    For this language currently no special definitions are needed or
%    available.
%
%    The macro |\LdfInit| takes care of preventing that this file is
%    loaded more than once, checking the category code of the
%    \texttt{@} sign, etc.
%    \begin{macrocode}
%<*nil>
\LdfInit{nil}{datenil}
%    \end{macrocode}
%
%    When this file is read as an option, i.e. by the |\usepackage|
%    command, \texttt{nil} could be an `unknown' language in which
%    case we have to make it known. 
%    \begin{macrocode}
\ifx\l@nohyphenation\@undefined
   \@nopatterns{nil}
   \adddialect\l@nil0
\else
   \let\l@nil\l@nohyphenation
\fi
%    \end{macrocode}
%    This macro is used to store the values of the hyphenation
%    parameters |\lefthyphenmin| and |\righthyphenmin|.
%    \begin{macrocode}
\providehyphenmins{\CurrentOption}{\m@ne\m@ne}
%    \end{macrocode}
%
%    The next step consists of defining commands to switch to (and
%    from) the `nil' language.
% \begin{macro}{\captionnil}
% \begin{macro}{\datenil}
%    \begin{macrocode}
\let\captionsnil\@empty
\let\datenil\@empty
%    \end{macrocode}
% \end{macro}
% \end{macro}
%  
%    The macro |\ldf@finish| takes care of looking for a
%    configuration file, setting the main language to be switched on
%    at |\begin{document}| and resetting the category code of
%    \texttt{@} to its original value.
%    \begin{macrocode}
\ldf@finish{nil}
%</nil>
%    \end{macrocode}
%
% \Finale
%
%%
%% \CharacterTable
%%  {Upper-case    \A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z
%%   Lower-case    \a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z
%%   Digits        \0\1\2\3\4\5\6\7\8\9
%%   Exclamation   \!     Double quote  \"     Hash (number) \#
%%   Dollar        \$     Percent       \%     Ampersand     \&
%%   Acute accent  \'     Left paren    \(     Right paren   \)
%%   Asterisk      \*     Plus          \+     Comma         \,
%%   Minus         \-     Point         \.     Solidus       \/
%%   Colon         \:     Semicolon     \;     Less than     \<
%%   Equals        \=     Greater than  \>     Question mark \?
%%   Commercial at \@     Left bracket  \[     Backslash     \\
%%   Right bracket \]     Circumflex    \^     Underscore    \_
%%   Grave accent  \`     Left brace    \{     Vertical bar  \|
%%   Right brace   \}     Tilde         \~}
\endinput
