\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{polyglossia}[2010/03/23 v1.1.1
  Babel replacement for XeLaTeX]
\RequirePackage{etoolbox}
\RequirePackage{makecmds}
\RequirePackage{fontspec} %which itself depends on xkeyval

%% This is for compatibility with Babel-aware package:
\cslet{ver@babel.sty}{\@empty} % this "fakes" babel
\def\languageshorthands#1{\relax} %this is for scrlttr2 class
\AtEndPreamble{\let\bbl@set@language\xpg@set@language} %for biblatex
\AtEndPreamble{\let\bbl@main@language\xpg@main@language} %for biblatex

%% custom message macros
\providecommand*{\xpg@warning}[1]{%
   \PackageWarning{polyglossia}%
   {#1}}      
\providecommand*{\xpg@info}[1]{%
   \PackageInfo{polyglossia}%
   {#1\@gobble}} %% the \@gobble is to prevent displaying the line nr
\providecommand*{\xpg@nopatterns}[1]{%
   \xpg@warning{No hyphenation patterns were loaded for `#1'\MessageBreak
    I will use the patterns for \string\language=\string\l@nohyphenation\space instead}}
\providecommand*{\xpg@nolang}[1]{%
   \xpg@warning{File gloss-#1.ldf does not exist!^^J
    I will nevertheless try to use hyphenation patterns for #1.}}%
      %TODO try at least to load the hyphenation patterns for #1.
\def\xpg@ill@value#1#2{%
  \xpg@warning{Illegal value (#1) for #2}}

%% use macro if defined, else warn that it is not
\def\csuse@warn#1{%
  \ifcsundef{#1}{\xpg@warning{ \expandafter\string\csname #1\endcsname\space is not defined}}%
   {\csname #1\endcsname}}

%% ensure directionality if bidi is loaded, else ignore
\def\@@ensure@dir#1{\ifcsundef{@ensure@dir}{#1}{\@ensure@dir{#1}}}
\def\@@ensure@maindir#1{\ifcsundef{@ensure@maindir}{#1}{\@ensure@maindir{#1}}}

%% compatibility with babel
\let\addto\gappto% gappto is defined in etoolbox
%%
%% ensure localization of \markright and \markboth commands
\def\opt@enabled{on}
\def\opt@disabled{off}
\define@key{polyglossia}{localmarks}[on]{%
   \def\@tmpa{#1}
   \ifx\@tmpa\opt@enabled
      \def\local@marks##1{%
         \def\markboth####1####2{%
            \begingroup%
               \let\label\relax \let\index\relax \let\glossary\relax%
               \unrestored@protected@xdef\@themark%
         {{\foreignlanguage{##1}{%           
            \protect\@@ensure@maindir{####1}}}%
          {\foreignlanguage{##1}{% 
      \protect\@@ensure@maindir{####2}}}}%
               \@temptokena \expandafter{\@themark}%
               \mark{\the\@temptokena}%
            \endgroup%
            \if@nobreak\ifvmode\nobreak\fi\fi}%
            \def\markright####1{%
               \begingroup%
                  \let\label\relax \let\index\relax \let\glossary\relax%
                  \expandafter\@markright\@themark%
      {\foreignlanguage{##1}{\protect\@@ensure@maindir{####1}}}%
                  \@temptokena \expandafter{\@themark}%
                  \mark{\the\@temptokena}%
               \endgroup%
               \if@nobreak\ifvmode\nobreak\fi\fi}%
            \def\@markright####1####2####3{\@temptokena{\protect\@@ensure@maindir{####1}}%
               \unrestored@protected@xdef\@themark{{\the\@temptokena}%
               {\protect\@@ensure@maindir{####3}}}}}
   \else
      \def\local@marks##1{}
      \xpg@info{Option: localmarks=off}
   \fi
}
\setkeys{polyglossia}{localmarks=on}

% to reset the intercharclass of a character to "normal"
\newXeTeXintercharclass\xpg@normalclass %TODO

%% when no patterns are available, we use \l@nohyphenation, assigned to 255
%%  (suggestion by Enrico Gregorio)
\@ifundefined{l@nohyphenation}{\chardef\l@nohyphenation=255 }{}

\newcommand{\setdefaultlanguage}[2][]{%
   \IfFileExists{gloss-#2.ldf}%
   {\ifcsundef{#2@loaded}%
     {\input{gloss-#2.ldf}%
     \xpg@info{Default language is #2.}
     \def\languagename{#2}%
      % This is needed because \arabic is a built-in LaTeX command:
      % so now we have \begin{Arabic}... instead of \begin{arabic}...  
      \edef\@tmpa{arabic}%
      \edef\@tmpb{#2}%
      \ifx\@tmpb\@tmpa%
      \newenvironment{Arabic}[1][]{\begin{otherlanguage}[####1]{arabic}}%
         {\end{otherlanguage}}%
      \else%   
      \newenvironment{#2}[1][]{\begin{otherlanguage}[####1]{#2}}%
         {\end{otherlanguage}}%
      \fi
      \expandafter\newcommand\csname text#2\endcsname[2][]{%
      \ifcsdef{RL}%
      {\ifcsundef{#2@RL}%
          {\@ensure@LTR{\foreignlanguage[####1]{#2}{####2}}}%
    {\@ensure@RTL{\foreignlanguage[####1]{#2}{####2}}}}%
      {\foreignlanguage[####1]{#2}{####2}}%
      }%
      \csletcs{local#2}{text#2}%
      \csgdef{#2@loaded}{}%
      \gdef\xpg@main@language{#2}%
      }%
    {\PackageWarning{polyglossia}{gloss-#2.ldf is already loaded!}}%
    %% The following settings are for the default language and script:
    \ifcsundef{#2@RL}{}{\@RTLmaintrue}% this tells bidi.sty that the document is RTL
    \AtBeginDocument{%
    \selectlanguage[#1]{#2}%
    \selectbackgroundlanguage{#2}}%
   }%
   %ELSE
   {\xpg@nolang{#2}\hyphenrules{#2}}}%

\let\setmainlanguage=\setdefaultlanguage

\newcommand{\resetdefaultlanguage}[2][]{%
    \ifcsundef{#2@loaded}{%
     \PackageError{polyglossia}{gloss-#2.ldf is not loaded!}}%
    {\csuse{no\xpg@main@language @globalnumbers}% disable globalnumbers of previously defined default language
    \csuse{noextras@\xpg@main@language}%
    \def\languagename{#2}%
    \ifcsundef{#2@RL}{}{\@rlmaintrue\@rl@footnotetrue}%
    \selectlanguage[#1]{#2}%
    \selectbackgroundlanguage{#2}}}

\def\familytype{rm}
\gappto\rmfamily{\def\familytype{rm}}
\gappto\sffamily{\def\familytype{sf}}
\gappto\ttfamily{\def\familytype{tt}}
% This saves the normalfont for the latin script since we may change normalfont in other scripts
\let\normalfontlatin=\normalfont%
\let\rmfamilylatin=\rmfamily%
\let\sffamilylatin=\sffamily%
\let\ttfamilylatin=\ttfamily%

\def\reset@latin@script{%
   \let\rmfamily=\rmfamilylatin%
   \let\sffamily=\sffamilylatin%
   \let\ttfamily=\ttfamilylatin%
   \normalfontlatin}

\def\reset@LR{\csuse{setLR}}

\def\selectnormalfontlatin{%
  \if\normalfont\ttfamily\ttfamilylatin\else
    \if\normalfont\sffamily\sffamilylatin\else
      \normalfontlatin\fi\fi}

\DeclareRobustCommand\selectfontfamilylatin{%
  \def\tmp@tt{tt}\def\tmp@sf{sf}%
  \ifx\familytype\tmp@tt%
    \ttfamilylatin%
    \else\ifx\familytype\tmp@sf%
      \sffamilylatin%
      \else\rmfamilylatin\fi\fi}

\let\@@fterindentfalse\@afterindentfalse
\def\french@indent{\let\@afterindentfalse\@afterindenttrue
                        \@afterindenttrue}
\def\nofrench@indent{\let\@afterindentfalse\@@fterindentfalse
                          \@afterindentfalse}

\newcommand{\selectbackgroundlanguage}[1]{%
    \csuse{selectnormalfont#1}%
    \csuse{#1@globalnumbers}%
    }

\newcommand{\setotherlanguage}[2][]{%
   \IfFileExists{gloss-#2.ldf}%
   {\ifcsundef{#2@loaded}%
     {\input{gloss-#2.ldf}%
      \setkeys{#2}{#1}%
      \edef\@tmpa{arabic}%
      \edef\@tmpb{#2}%
      \ifx\@tmpb\@tmpa%
      \newenvironment{Arabic}[1][]{\begin{otherlanguage}[####1]{arabic}}%
         {\end{otherlanguage}}%
      \else%   
      \newenvironment{#2}[1][]{\begin{otherlanguage}[####1]{#2}}%
         {\end{otherlanguage}}%
      \fi
      \expandafter\newcommand\csname text#2\endcsname[2][]{%
      \ifcsdef{RL}{%
        \ifcsundef{#2@RL}%
          {\@ensure@LTR{\foreignlanguage[####1]{#2}{####2}}}%
          {\@ensure@RTL{\foreignlanguage[####1]{#2}{####2}}}%
      }{% else
          \foreignlanguage[####1]{#2}{####2}%
      }}%
      \csletcs{local#2}{text#2}%
      \csgdef{#2@loaded}{}%
     }%
     {\PackageWarning{polyglossia}{gloss-#2.ldf is already loaded!}}%
   }%
   %ELSE  
   {\xpg@nolang{#2}\hyphenrules{#2}}%
   %TODO ? \expandafter\ifx\csname l@#2\endcsname\@undefined
   %\xpg@nopatterns{#2}\expandafter\adddialect\csname l@#2\endcsname 0%
   %\else\expandafter\expandafter\protect\language=\csname l@#2\endcsname\fi
}

\newcommand\setotherlanguages[1]{%
   \def\do##1{\setotherlanguage{##1}}%
   \docsvlist{#1}}%

\def\common@language{%
   \language=\z@
   \lefthyphenmin=\tw@
   \righthyphenmin=\thr@@}

\def\noextrascurrent#1{\csuse{noextras@#1}}

\def\xpg@initial@setup{\ifcsundef{languagename}{}%
   {\noextrascurrent{\languagename}}%
   \common@language}

\AtBeginDocument{\xpg@initial@setup}

\providecommand{\foreignlanguage}{}

\renewcommand{\foreignlanguage}[3][]{%
   \ifcsundef{#2@loaded}{\xpg@nolang{#2}\hyphenrules{#2}}{%
     {\def\languagename{#2}%
      \setkeys{#2}{#1}%
      \csuse@warn{#2@font}%
      \csuse@warn{#2@language}%
      \csuse{date#2}%
      \csuse{#2@numbers}%
      \use@localhyphenmins{#2}%
      \csuse{inlineextras@#2}%
      #3}%
   }%
}

%Hook that other package authors can use
%(for instance biblatex):
\newcommand*{\xpg@hook@setlanguage}{}

\providecommand{\selectlanguage}{}
\renewcommand{\selectlanguage}[2][]{%
   \ifcsundef{#2@loaded}{\xpg@nolang{#2}\hyphenrules{#2}}{%
      \def\xpg@pop@language{%
         \xpg@set@language{\languagename}%
         \xpg@hook@setlanguage%
         \let\emp@langname\@undefined}%
      \aftergroup\xpg@pop@language%
      \setkeys{#2}{#1}%
      \xpg@set@language{#2}%
}}

\newcommand{\xpg@set@language}[1]{%
   \select@language{#1}%
   \if@filesw%
      \protected@write\@auxout{}{\protect\select@language{#1}}%
      \addtocontents{toc}{\protect\select@language{#1}}%
      \addtocontents{lof}{\protect\select@language{#1}}%
      \addtocontents{lot}{\protect\select@language{#1}}%
   \fi
}

\def\select@language#1{%
   \xpg@initial@setup%
   \edef\languagename{#1}%
   \ifcsundef{RL}{}%
   {\ifcsundef{#1@RL}{\setLR}{\setRL}}%
   \csuse@warn{#1@font}%
   \csuse@warn{#1@language}%
   \use@localhyphenmins{#1}%
   \csuse{captions#1}%
   \csuse{date#1}%
   \csuse{#1@numbers}%
   \local@marks{#1}%
   \csuse{blockextras@#1}%
}

\let\xpg@pop@language\relax

\provideenvironment{otherlanguage}{}{}

\renewenvironment{otherlanguage}[2][]
   {\selectlanguage[#1]{#2}}
   {}

\newcommand{\setlocalhyphenmins}[3]{%
   \expandafter\ifx\csname l@#1\endcsname\relax%
     \xpg@warning{\string\setlocalhyphenmin useless for unknown language #1}%
   \else
      \expandafter\ifx\csname l@#1\endcsname\l@nohyphenation%
        \xpg@warning{\string\setlocalhyphenmin useless for unhyphenated language #1}%
      \else
      \providehyphenmins{#1}{#2#3}%
      \fi
   \fi}

\def\use@localhyphenmins#1{%
   \ifcsundef{#1hyphenmins}{}%
   {\expandafter\expandafter\expandafter\set@hyphenmins\csname #1hyphenmins\endcsname\relax}}

% FIXME: remove this eventually, say in 2012 :)
% taken from xelatex.ini, in case the xelatex format is too old
\ifcsundef{newXeTeXintercharclass}{%
  \xpg@warning{Your xelatex format appears to be outdated!^^J
    Please update your system and recreate it with fmtutil.}
  \newcount\xe@alloc@intercharclass % allocates intercharclass
  \xe@alloc@intercharclass=\thr@@ % from 4 (1,2 and 3 are used by CJK, AFAIK)
  \def\xe@alloc@#1#2#3#4#5{\global\advance#1\@ne
  \xe@ch@ck#1#4#2% make sure there's still room
  \allocationnumber#1%
  \global#3#5\allocationnumber
  \wlog{\string#5=\string#2\the\allocationnumber}}
  \def\xe@ch@ck#1#2#3{%
  \ifnum#1<#2\else
    \errmessage{No room for a new #3}%
  \fi}
  \def\newXeTeXintercharclass{%
  \xe@alloc@\xe@alloc@intercharclass\XeTeXintercharclass\chardef\@cclv} %at most 254
  }
  {}

%% patch lastpage to avoid problem with \thepage when \@arabic is redefined for non-Latin numbers
%\@ifpackageloaded{lastpage}{%
%\xpg@info{Redefining lastpage command \string\lastpage@putlabel}%
%\def\lastpage@putlabel{\addtocounter{page}{-1}%
%   \immediate\write\@auxout{\string
%   \newlabel{LastPage}{{}{\number\c@page}}}%
%   \addtocounter{page}{1}}}%
%   {}
%
\define@boolkey{polyglossia}[system@]{babelshorthands}[false]{}

%% Package Options %%
\DeclareOption{nolocalmarks}{\setkeys{polyglossia}{localmarks=off}}
\DeclareOption{babelshorthands}{\setkeys{polyglossia}{babelshorthands=true}}
\DeclareOption{quiet}{%
   \gdef\@latex@info#1{\relax}% no latex info
   \gdef\@font@info#1{\relax}% no latex font info
   \gdef\@font@warning#1{\relax}% no latex font warnings
   \gdef\zf@PackageInfo#1{\relax}% no fontspec info
   \gdef\xpg@info#1{\relax}}% no polyglossia info
\def\xpg@option#1#2{%
  \ifcsundef{xpg@main@language}{\setdefaultlanguage}{\setotherlanguage}%
    [#1]{#2}}
\DeclareOption{USenglish}{\xpg@option{variant=american}{english}}
\DeclareOption{american}{\xpg@option{variant=american}{english}}
\DeclareOption{UKenglish}{\xpg@option{variant=british}{english}}
\DeclareOption{british}{\xpg@option{variant=british}{english}}
\DeclareOption{australian}{\xpg@option{variant=australian}{english}}
\DeclareOption{newzealand}{\xpg@option{variant=newzealand}{english}}
\DeclareOption{ngerman}{\xpg@option{spelling=new}{german}}
\DeclareOption{polygreek}{\xpg@option{variant=poly}{greek}}
\DeclareOption{monogreek}{\xpg@option{variant=mono}{greek}}
\DeclareOption{ancientgreek}{\xpg@option{variant=ancient}{greek}}
\DeclareOption*{%
  \edef\@temp{%
    \noexpand\ifcsundef{xpg@main@language}%
      \noexpand\setdefaultlanguage
      \noexpand\setotherlanguage
    {\CurrentOption}%
  }%
  \expandafter\AtEndOfPackage\expandafter{\@temp}%
}
\ProcessOptions*
\endinput
