% \iffalse
%<*internal>
\iffalse
%</internal>
%<*readme>
------------------------
THE BIDI PACKAGE v0.3

This package provides a convenient interface for typesetting 
bidirectional texts with XeLaTeX. 

This version adds support for tabular environments and captions
and brings several other improvements and bugfixes.

The code for alphabetic numerals has been moved to the relevant
"language definition files" of the new polyglossia package.

--------------
François Charette
July 2008
%</readme>
%<*example>
\documentclass{article}
\usepackage[no-math]{fontspec}
\usepackage{bidi}
\newfontfamily\arab[Script=Arabic, Scale=1.5]{Scheherazade}
\begin{document}

This is some text in English with Arabic insertion (\RL{\arab بعض الكلمات العربية}).\footnote{ 1 2 3}

\setRL\arab
وهذه فقرةٌ بالعربي مع كلمات انكليزية (\LR{\rmfamily Some English words}).\footnote{ 1 2 3}
\setLR\rmfamily

Back to left-to-right mode…\footnote{ 1 2 3}

\begin{table}[h]
\centering
\begin{tabular}{cc}
1 & 2\\
3 & 4
\end{tabular}
\caption{This is a caption}
\end{table}

\begin{equation}
x^2 + y^2 = z^2
\end{equation}

\setRL
\begin{table}[h]
\centering
\begin{tabular}{cc}
1 & 2\\
3 & 4
\end{tabular}
\caption{This is a caption}
\end{table}

\begin{equation}
x^2 + y^2 = z^2
\end{equation}
\end{document}
%</example>
%<*internal>
\fi
%</internal>
%
%<*internal>
\begingroup
%</internal>
%<*batchfile>
\input docstrip.tex
\keepsilent
\preamble

  ____________________________

  The bidi package         
  (C) 2007-2008  François Charette    
  License information appended


\endpreamble
\postamble

Copyright (C) 2007-2008 by François Charette <firmicus at gmx dot net>

Distributable under the LaTeX Project Public License,
version 1.3c or higher (your choice). The latest version of
this license is at: http://www.latex-project.org/lppl.txt

This work is "maintained" (as per LPPL maintenance status) 
by François Charette.

This work consists of the file  \jobname.dtx
          and the derived files \jobname.sty and \jobname.pdf.

\endpostamble
\askforoverwritefalse
\generate{\file{\jobname.sty}{\from{\jobname.dtx}{package}}}
\nopreamble\nopostamble
%</batchfile>
%<batchfile>\endbatchfile
%<*internal>
\generate{\file{\jobname.ins}{\from{\jobname.dtx}{batchfile}}}
\generate{\file{bidi-example.tex}{\from{\jobname.dtx}{example}}}
\generate{\file{README.txt}{\from{\jobname.dtx}{readme}}}
\endgroup
%</internal>
%
%<*driver>
\documentclass[12pt]{ltxdoc}
\usepackage{fontspec,xltxtra}
\usepackage{bidi}
\usepackage{xspace,fancyvrb,paralist}
\usepackage[xetex]{color}
\definecolor{myblue}{rgb}{0.02,0.04,0.48}
\definecolor{myred}{rgb}{0.65,0.04,0.07}
\definecolor{darkgray}{gray}{0.3}
\definecolor{lightgray}{gray}{0.6}
\definecolor{mygreen}{rgb}{0,.43,0}
\usepackage[dvipdfm,
    bookmarks=true,
    colorlinks=true,
    linkcolor=myblue,
    urlcolor=myblue,
    citecolor=myblue,
    hyperindex=false,
    hyperfootnotes=false,
    pdftitle={The bidi package},
    pdfauthor={F Charette <firmicus@gmx.net>},
    pdfsubject={An interface for typesetting bidirectional texts with XeLaTeX},
    pdfkeywords={XeTeX, XeLaTeX, Right-to-Left, Bidi, Arabic, Hebrew}
    ]{hyperref}
% NB some of this preamble is taken or adapted from fontspec-doc-style.sty
\newcommand*\pkg[1]{\textsf{#1}}
\def\eg{\textit{e.g.,}\xspace}
\def\ie{\textit{i.e.,}\xspace}
\def\ca{\textit{ca.}\@\xspace}
\def\Eg{\textit{E.g.,}\xspace}
\def\Ie{\textit{I.e.,}\xspace}
\def\etc{\@ifnextchar.{\textit{etc}}{\textit{etc.}\@\xspace}}
\def\arabxetex{Arab\XeTeX}

\newlength{\oldparindent}
\newcommand{\parindentoff}{\setlength{\oldparindent}{\parindent} \setlength{\parindent}{0pt}}
\newcommand{\parindenton}{\setlength{\parindent}{\oldparindent}}

%% LOGOS, tuned for Palatino (seems also OK with Junicode):
\makeatletter
\TeX@logo@spacing{-0.12em}{-0.12em}%
  {0.5ex}{-0.3em}{-0.12em}{-0.1em}
\makeatother
%% fontspec declarations:
\setromanfont[Mapping=tex-text]{Junicode}%{FPL Neu}
\defaultfontfeatures{Scale=MatchLowercase}
\setmonofont{DejaVu Sans Mono}%{Inconsolata}%{Latin Modern Typewriter Proportional}%{Luxi Mono}%{Courier New}
\setsansfont{DejaVu Sans}
\newfontfamily\arabicfont[Script=Arabic,Scale=1.5]{Scheherazade}
\newfontfamily\hebrewfont[Script=Hebrew]{Ezra SIL}
%\newfontfamily\syriacfont[Script=Syriac]{Estrangelo Talada}
\newfontfamily\damase{MPH 2B Damase}
\linespread{1.05}
\frenchspacing
\renewcommand{\footnoterule}{}
\skip\footins=2\bigskipamount
%% ToC
\def\@dotsep{1000}
\setcounter{tocdepth}{2}
\setlength\columnseprule{0.4pt}
\makeatletter
\renewcommand\tableofcontents{%
  \begin{multicols}{2}[\section*{\contentsname}]%
    \small
    \@starttoc{toc}%
  \end{multicols}}
\makeatother
\EnableCrossrefs
\CodelineIndex
\RecordChanges
%\OnlyDescription
\begin{document}
  \DocInput{\jobname.dtx}
\end{document}
%</driver>
%
% \fi
% \makeatletter                         ^^A% To document @-cmds
% \errorcontextlines=999                ^^A% Show up all my mistakes
%
% \GetFileInfo{\jobname.sty}
% 
% \title{The \pkg{bidi} package}
% ^^A \author{\textcolor{myblue}{François Charette}\\
% \author{François Charette\\
% \footnotesize\texttt{<fιrmιcus@gmχ.νετ>}}
% \date{\filedate \qquad \fileversion}
%
% \maketitle
% \tableofcontents
%
% \section{Basic direction switching commands}
%
% The \pkg{bidi} package provides a useful interface for typesetting bidirectional 
% texts with \XeLaTeX.\footnote{ %
%	Actually, \pkg{bidi} can also be used with any \eTeX-based
%	engine, notably pdf\LaTeX, but at this time I do not see how it
%	could be useful outside of the \XeTeX\ world.}
% ^^A\eTeX-based typesetting engines and the \LaTeX\ format, 
% Most of its macros are directly copied or adapted from
% the Babel bidirectional module for Hebrew (by Boris Lavva).\footnote{ See
% 	^^A\url{ftp://dante.ctan.org/tex-archive/macros/latex/required/babel/hebrew.dtx}
% 	section 60.4 of the \href{ftp://dante.ctan.org/tex-archive/macros/latex/required/babel/babel.pdf}{Babel user documentation.}} 
%
% For short right-to-left ^^A(|\RL{R 2 L}| $\rightarrow$ \RL{R\,2\,L})
% insertions in left-to-right environments, \DescribeMacro{\RL}\cmd\RL|{…}| does the job, 
% as does \DescribeMacro{\LR}\cmd\LR|{…}| in the opposite case. 
% To typeset a full paragraph right-to-left, use the switch
% \DescribeMacro{\setRL}\cmd\setRL, and to revert to left-to-right, use 
% \DescribeMacro{\setLR}\cmd\setLR\ (or equivalently \cmd\unsetRL). 
%
% \begin{Verbatim}[gobble=2]
% \setRL
% This is a right-to-left paragraph.
% \setLR
% \end{Verbatim}
%
% \setRL\setfootnoteLR
% This is a right-to-left paragraph.\footnote{ %
%	Note that when processing fonts that are not TFM-based, 
%	\XeTeX, contrary to \TeX, uses (roughly speaking) one box per word, 
%	instead of one per character. The command \cmd\RL\ is thus usually 
%	superfluous when inserting a single word.}
% \setLR
%
%
% \subsection{Direction of plain footnotes}
% \setfootnoteRL
% With \DescribeMacro{\setfootnoteRL}\cmd\setfootnoteRL, one can insert RL
% footnotes in LR mode,\footnote{ %
% 	^^A\textarab[novoc]{mulA.hi.zaT min al-yamIn 'ilY al-ya.sAr}
%	 \arabicfont ملاحظات من اليمين إلى اليصار}
% and conversely with
% \DescribeMacro{\setfootnoteLR}\cmd\setfootnoteLR\ 
% (or equivalently \cmd\unsetfootnoteRL). 
% \unsetfootnoteRL
%
% With the package \pkg{manyfoot}, it is possible to have several layers
% of footnotes, each of which can be set in a different direction.
% See the documentation to Arab\XeTeX\ for more details. This should also be
% possible with \pkg{bigfoot}.
% 
% Some other \LaTeX\ macros are redefined internally to ensure their correct
% behaviour in bidirectional display. Contrary to the Babel approach, we leave
% the commands defined in standard \LaTeX\ classes untouched, as we think this
% should be done by class authors themselves (who are of course encouraged to
% make them \pkg{bidi}-compatible :-).
%
% 
% \section{Colored text} \label{bidicolor}
%
% Because of the way bidirectionality is implemented in \eTeX, no information on 
% directionality is included in the dvi (or xdv) output. Consequently, if a color
% \cmd\special\ is inserted in the middle of a paragraph, the color change will 
% be in effect as though the text would run from left to right. For \cmd\textcolor,
% the output will be correct only if the textual argument falls on a single line.
% A better approach is to set the color of text by means of \XeTeX's font features,
% as in this example:
% \begin{Verbatim}[gobble=2]
% \newcommand{\textblue}[1]{{\addfontfeature{Color=0000FF}#1}}
% \setRL
% {\arabicfont
% اسود اسود اسود اسود اسود اسود اسود اسود اسود اسود اسود اسود 
% اسود \textblue{ازرق ازرق ازرق ازرق ازرق ازرق ازرق } اسود اسود 
% اسود اسود اسود اسود
% }
% \end{Verbatim}
% \newcommand{\textblue}[1]{{\addfontfeature{Color=0000FF}#1}}
% \setRL 
% {\arabicfont
% اسود اسود اسود اسود اسود اسود اسود اسود اسود اسود اسود اسود اسود
% \textblue{ازرق ازرق ازرق ازرق ازرق ازرق ازرق} اسود اسود 
% اسود اسود اسود اسود}
% \setLR
%
% \section{Scripts written from right-to-left}
%
% The Arabic and Hebrew scripts are of course not the only ones to be written from right-to-left. 
% The following is a list of historical\footnote{ %
%	The historical right-to-left scripts that are part of Unicode 5.0 are:
% 	Cypriot, Old Italic (i.e., Etruscan), Kharosthi and Phoenician.}
% and contemporary scripts that are written 
% primarily or exclusively from right-to-left.\footnote{ %
%	See \url{http://www.omniglot.com/writing/direction.htm\#rtl},
% 	\url{http://www.unicode.org/iso15924/}, and 
% 	\url{http://www.ancientscripts.com/ws.html}.} 
% Those still in use today are marked with an asterisk.
% 
% \begin{center} 
% \small
% \begin{tabular}{ll}\hline
% Aramaic and Sogdian	~~~~~~~~~~~~~~~	&  Nabatean			\\
% Arabic$^*$				&  N'Ko$^*$			\\
% Avestan				&  Old Hungarian		\\
% Berber (ancient)			&  Orkhon (Turkic runes)	\\
% Cypriot Syllabary			&  Pahlavi and Parthian		\\
% Etruscan and Oscan			&  Phoenician 			\\
% Hebrew$^*$				&  Proto-Sinaitic		\\
% Iberian (Northern)			&  Samaritan			\\
% Kharosthi				&  South Arabian and Thamudic   \\
% Lydian				&  Syriac$^*$			\\
% Mandaean				&  Thâna$^*$			\\
% Meroitic (cursive)			&  				\\
% \hline
% \end{tabular}
% \end{center}
% 
% Some examples (random glyphs for Kharosthi and Cypriot):
% \begin{compactitem}[\textbf{·}]
% \item Old Italic (Etruscan):\footnote{ %
%	The Unicode standard 5.0 specifies left-to-right directionality for the
%	Old Italic script, contrary to historical evidence but in accordance to
%	conventional scholarly usage. To display from right to left the Unicode 
%	\textsc{right-to-left override} character \textsf{U+202E}
%	^^A \textsc{\addfontfeature{Numbers=Lowercase}u+202e} 
%	must be inserted before each 
%	word. This could be easily automated by means of a TECkit font mapping.
%	Etruscanists interested in this can contact me directly.}
% \hfill  \RL{\damase 𐌀𐌖𐌋𐌄𐌑𐌉 𐌌𐌄𐌕𐌄𐌋𐌉𐌑} ^^A\addfontfeature{Mapping=etruscan}auleśi meteliś}
% \item N'ko:\footnote{ %
%	As can be seen in this example, the ICU rendering engine does not yet
%	support contextual substitutions for N'Ko.}
% \hfill  \RL{\fontspec[Script=N'ko]{Code2000} ߌ ߣߌ ߛߐߡߊ߫} ^^A i ni somâ = good morning < http://www.fakoli.net/nko/tutorial/samples.html
% \item Thâna:    \hfill   {\fontspec[Script=Thaana]{MPH 2B Damase} ކައްޓަލަ} ^^A kattala = sweet potato < http://www.maldivesculture.com/thaana03.html
% \item Phoenician: \hfill {\fontspec[Script=Phoenician]{MPH 2B Damase} 𐤊𐤁𐤂𐤃} ^^A abgd
% \item Kharosthi: \hfill {\fontspec[Script=Kharosthi]{MPH 2B Damase} 𐨗𐨁𐨙𐨪} ^^A random gibberish
% \item Cypriot: \hfill    {\fontspec[Script=Cypriot Syllabary]{MPH 2B Damase} 𐠌𐠥𐠯} ^^A random gibberish
% \end{compactitem}
%
% \section{Acknowledgements}
%
% Thanks to Boris Lavva (author of \pkg{rlbabel.def}), 
% the authors of Farsi\TeX,
% Youssef Jabri [\RL{\arabicfont يوسف جبري}] (author of \pkg{Arabi}),
% and Vafa Khalighi [\RL{\arabicfont وفا خليقي}] (author of \pkg{xepersian}). 
%
% \StopEventually{}
% 
% \section{Implementation}
% \iffalse
%<*package>
% \fi
%    \begin{macrocode}
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{bidi}
  [2008/07/07 v0.3  Bidirectional typesetting in XeLaTeX]
\newif\if@rlmain
\@rlmainfalse
\DeclareOption{rldocument}{\@rlmaintrue}
\ProcessOptions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
\ifx\TeXXeTstate\undefined\else%
   \TeXXeTstate=1
\fi
\ifx\beginL\@undefined%
   \newlinechar`\^^J
   \typeout{^^JTo avoid this error message,^^J%
     run TeX--XeT or e-TeX engine instead of regular TeX.^^J}
   \errmessage{Right-to-Left Support Error: use TeX--XeT or e-TeX
     engine}%
\fi
\newif\if@rl
\AtBeginDocument{% Here we set the main document direction
  \if@rlmain\else
    \if@rl\@rlmaintrue%
    \else\@rlmainfalse%
    \fi%
  \fi%
}
%    \end{macrocode}
% \subsection{Basic bidi macros}
% This defines the macros for RL insertion in LR context and conversely. 
% Most of it is taken from the file \texttt{rlbabel.def} in the Babel distribution,
% with minor changes. 
%
%    \begin{macrocode}
\let\n@xt=\
\def\LR{\protect\pLR}%
\def\pLR{\protect\afterassignment\moreLR \let\n@xt= }
\def\moreLR{\bracetext \aftergroup\endL \beginL\@rlfalse}
\def\RL{\protect\pRL}
\def\pRL{\protect\afterassignment\moreRL \let\n@xt= }
\def\moreRL{\bracetext \aftergroup\endR \beginR\@rltrue}
\def\bracetext{\ifcat\n@xt{\else\ifcat\n@xt}\fi
  \errmessage{Missing left brace has been substituted}\fi \bgroup}
\everydisplay{\if@rl\aftergroup\beginR\fi }
%    \end{macrocode}
%
% For global right-to-left typesetting, the directional primitive must be
% included within an \cmd\everypar\ construct. The traditional approach was to
% redefine \cmd\everypar\ as a one-argument macro, but since some packages such
% as \pkg{ledmac} also play tricks with \cmd\everypar, this can become
% problematic. Hence we have adopted Youssef Jabri's approach in his
% \pkg{Arabi} package (\,\RL{\arabicfont شكراً جزيلاً}). 
%    \begin{macrocode}
\def\rl@everypar{\if@rl{\setbox\z@\lastbox\beginR\usebox\z@}\fi}
\let\o@everypar=\everypar
%The following, surely, will not play well with all packages, e.g. ledmac
%\def\everypar#1{\o@everypar{\rl@everypar#1}}
% But we now use this instead, taken from Arabicore.sty
\newtoks\n@everypar 
\n@everypar\expandafter{\the\o@everypar} 
\o@everypar{\rl@everypar\the\n@everypar} 
\let\everypar=\n@everypar 
%    \end{macrocode}
%
% This is similar to |\ensuremath| in \LaTeX:
%    \begin{macrocode}
\def\@ensure@RL#1{\if@rl#1\else\RL{#1}\fi}
\def\@ensure@LR#1{\if@rl\LR{#1}\else#1\fi}
%    \end{macrocode}
%
% This does the opposite (which is useful for ensuring correct directionality 
% in boxes or tabular environments, for instance):
%    \begin{macrocode}
\def\@ensure@dir#1{\if@rl\RL{#1}\else{#1}\fi}
\def\@ensure@maindir#1{\if@rlmain\RL{#1}\else{#1}\fi}
%    \end{macrocode}
% These are not yet used…
%    \begin{macrocode}
\def\@@RL{RL}
\def\@@LR{LR}
\def\save@dir{\if@rl\gdef\saved@@dir{RL}\else\gdef\saved@@dir{LR}\fi}
\def\reset@dir{\ifx\saved@@dir\@@RL\setRL\else\ifx\saved@@dir\@@LR\setLR\else\relax\fi\fi}
%    \end{macrocode}
%
% \subsection{Logos}
% The following redefinitions ensure proper typesetting of the various logos.
%    \begin{macrocode}
%preserve logos
\let\@@TeX\TeX
\def\TeX{\@ensure@LR{\@@TeX}}
\let\@@LaTeX\LaTeX
\def\LaTeX{\@ensure@LR{\@@LaTeX}}
\let\@@LaTeXe\LaTeXe
\def\LaTeXe{\@ensure@LR{\@@LaTeXe}}
\@ifpackageloaded{xltxtra}{
\let\@@XeTeX\XeTeX
\def\XeTeX{\@ensure@LR{\@@XeTeX}}
\let\@@XeLaTeX\XeLaTeX
\def\XeLaTeX{\@ensure@LR{\@@XeLaTeX}}
}{}
%    \end{macrocode}
% \subsection{Redefinition of various internal \LaTeX\ macros}
% \subsubsection{\cmd{\text}}
% \cmd{\text} is defined in \pkg{amstext.sty}.
%    \begin{macrocode}
\@ifundefined{text}{}{%
\let\t@xt=\text
\def\text#1{\t@xt{\@ensure@dir{#1}}}}
%    \end{macrocode}
% \subsubsection{\cmd{\list}}
%    \begin{macrocode}
\def\list#1#2{%
  \ifnum \@listdepth >5\relax
    \@toodeep
  \else
    \global\advance\@listdepth\@ne
  \fi
  \rightmargin\z@
  \listparindent\z@
  \itemindent\z@
  \csname @list\romannumeral\the\@listdepth\endcsname
  \def\@itemlabel{#1}%
  \let\makelabel\@mklab
  \@nmbrlistfalse
  #2\relax
  \@trivlist
  \parskip\parsep
  \parindent\listparindent
  \advance\linewidth -\rightmargin
  \advance\linewidth -\leftmargin
  \if@rl
    \advance\@totalleftmargin \rightmargin
  \else
    \advance\@totalleftmargin \leftmargin
  \fi
  \parshape \@ne \@totalleftmargin \linewidth
  \ignorespaces}
%    \end{macrocode}
% \subsubsection{Dotted line in table of contents}
%    \begin{macrocode}
\def\@dottedtocline#1#2#3#4#5{%
  \ifnum #1>\c@tocdepth \else
    \vskip \z@ \@plus.2\p@
    {\if@rl\rightskip\else\leftskip\fi #2\relax
      \if@rl\leftskip\else\rightskip\fi \@tocrmarg \parfillskip
      -\if@rl\leftskip\else\rightskip\fi
     \parindent #2\relax\@afterindenttrue
     \interlinepenalty\@M
     \leavevmode
     \@tempdima #3\relax
     \advance\if@rl\rightskip\else\leftskip\fi \@tempdima
     \null\nobreak\hskip -\if@rl\rightskip\else\leftskip\fi
     {#4}\nobreak
     \leaders\hbox{$\m@th
        \mkern \@dotsep mu\hbox{.}\mkern \@dotsep
        mu$}\hfill
     \nobreak
     \hb@xt@\@pnumwidth{\hfil\normalfont \normalcolor \beginL#5\endL}%
     \par}%
  \fi}
%    \end{macrocode}
% \subsubsection{\cmd{\raggedright} and \cmd{\raggedleft}}
%    \begin{macrocode}
\def\raggedright{%
  \let\\\@centercr
  \leftskip\z@skip\rightskip\@flushglue
  \parindent\z@\parfillskip\z@skip}
\let\@@raggedleft=\raggedleft
\let\@@raggedright=\raggedright
\renewcommand\raggedleft{\if@rl\@@raggedright%
                         \else\@@raggedleft\fi}
\renewcommand\raggedright{\if@rl\@@raggedleft%
                          \else\@@raggedright\fi}
%    \end{macrocode}
% \subsubsection{\cmd{\underline}}
%    \begin{macrocode}
\let\@@@underline=\underline
\def\underline#1{\@@@underline{\if@rl\RL{#1}\else #1\fi}}
\if@compatibility
   \let\undertext=\underline
\fi
%    \end{macrocode}
% \subsubsection{\cmd\@outputdblcol}
%    \begin{macrocode}
\let\lr@outputdblcol\@outputdblcol
\renewcommand{\@outputdblcol}{%
  \if@rlmain%
    \rl@outputdblcol%
  \else%
    \lr@outputdblcol%
  \fi%
}
\newcommand{\rl@outputdblcol}{%
  \if@firstcolumn
    \global \@firstcolumnfalse
    \global \setbox\@leftcolumn \box\@outputbox
  \else
    \global \@firstcolumntrue
    \setbox\@outputbox \vbox {\hb@xt@\textwidth {%
                              \hskip\columnwidth%
                              \hfil\vrule\@width\columnseprule\hfil
                              \hb@xt@\columnwidth {%
                                \box\@leftcolumn \hss}%
                              \hb@xt@\columnwidth {%
                                \hskip-\textwidth%
                                \box\@outputbox \hss}%
                              \hskip\columnsep%
                              \hskip\columnwidth}}%
    \@combinedblfloats
    \@outputpage
    \begingroup
      \@dblfloatplacement
      \@startdblcolumn
      \@whilesw\if@fcolmade \fi
        {\@outputpage
         \@startdblcolumn}%
    \endgroup
 \fi}

% \subsection{Footnotes}
% This implements the bidirectionality of plain \LaTeX\ footnotes. 
%    \begin{macrocode}
\newif\if@rl@footnote
\if@rlmain\@rl@footnotetrue\else\@rl@footnotefalse\fi
\let\@@footnoterule=\footnoterule
\def\LRfootnoterule{\@@footnoterule}
%%bug?-->this causes new par to be set, hence hack with vskip :-{ 
\def\RLfootnoterule{\vskip -\baselineskip\hb@xt@\hsize{\hss\vbox{\@@footnoterule}}} 
%
\def\setfootnoteRL{\@rl@footnotetrue}
\def\unsetfootnoteRL{\@rl@footnotefalse}
\def\setfootnoteLR{\unsetfootnoteRL}
%
\def\footnoterule{\if@rlmain\RLfootnoterule\else\LRfootnoterule\fi}
%    \end{macrocode}
% \subsection{Bidi switching commands}
% Commands for switching between LR and RL global contexts. 
%    \begin{macrocode}
\def\setRL{\@rltrue\@rl@footnotetrue} 
\def\unsetRL{\@rlfalse\@rl@footnotefalse}
\def\setLR{\unsetRL}
%    \end{macrocode}
% \subsection{Footnotes (cont.)}
% This redefines \LaTeX's internal footnote macros.
%    \begin{macrocode}
\long\def\@footnotetext#1{\insert\footins{%
    \if@rl@footnote\@rltrue\else\@rlfalse\fi
    \reset@font\footnotesize
    \interlinepenalty\interfootnotelinepenalty
    \splittopskip\footnotesep
    \splitmaxdepth \dp\strutbox \floatingpenalty \@MM
    \hsize\columnwidth \@parboxrestore
    \protected@edef\@currentlabel{%
       \csname p@footnote\endcsname\@thefnmark
    }%
    \color@begingroup
      \@makefntext{%
        \rule\z@\footnotesep\ignorespaces#1\@finalstrut\strutbox}%
    \color@endgroup}}%
%%... also in minipages
\long\def\@mpfootnotetext#1{%
  \global\setbox\@mpfootins\vbox{%
    \if@rl@footnote\@rltrue\else\@rlfalse\fi
    \unvbox\@mpfootins
    \reset@font\footnotesize
    \hsize\columnwidth
    \@parboxrestore
    \protected@edef\@currentlabel
         {\csname p@mpfootnote\endcsname\@thefnmark}%
    \color@begingroup
      \@makefntext{%
        \rule\z@\footnotesep\ignorespaces#1\@finalstrut\strutbox}%
    \color@endgroup
    }}
%    \end{macrocode}
% \subsection{Captions}
% This redefines the macros responsible for captions in various popular classes 
% (article, book, report, scrartcl, scrbook, scrreprt, and memoir).
%    \begin{macrocode}
\@ifundefined{KOMAClassName}{%
\@ifclassloaded{memoir}{%
\long\def\@makecaption#1#2{\let\@memtempa\relax
  \ifdim\prevdepth>-99\p@ \vskip\abovecaptionskip
  \else \def\@memtempa{\vbox to\topskip{}}\fi
  \let\@contfnote\footnote \renewcommand{\footnote}[2][]{}
  \let\@contfmark\footnotemark \renewcommand{\footnotemark}[1][]{}
  \sbox\@tempboxa{\@contnfont #1\@contdelim \@conttfont #2}
  \let\footnote\@contfnote
  \let\footnotemark\@contfmark
  \ifdim\wd\@tempboxa<\linewidth \centering \fi
  \if@contcw
    \centering
    \parbox{\@contcwidth}{%
    \ifdim\wd\@tempboxa<\@contcwidth \centering \fi
  \fi
  \if@conthang
    \sbox\@tempboxa{\@contnfont #1\@contdelim}
    \@contpre%
    \@ensure@dir{\@contcstyle\hangindent=\wd\@tempboxa
         \noindent\box\@tempboxa\@memtempa \@conttfont #2}\par
  \else
    \if@contindent
      \@contpre%
      \@ensure@dir{\@contnfont #1\@contdelim}\@memtempa
      \@ensure@dir{\@contcstyle\hangindent=\@contindw
         \hangafter=\@ne\@conttfont #2}\par% <- v1.4
    \else
      \@contpre%
      \@ensure@dir{\@contnfont #1\@contdelim}\@memtempa
      \@ensure@dir{\ifdim\wd\@tempboxa<\linewidth
         \@contcshortstyle\else \@contcstyle\fi%  <- v1.4
	 \@conttfont #2}\par
    \fi
  \fi
  \@contpost
  \if@contcw
    \par
    }  % end of the \parbox
  \fi
  \vskip\belowcaptionskip}
}% else we redefine \@makecaption for the standard classes
{\@ifundefined{@makecaption}{%
%warning ??
}{\long\def\@makecaption#1#2{%
  \vskip\abovecaptionskip
  \sbox\@tempboxa{\@ensure@dir{#1: #2}}%
  \ifdim \wd\@tempboxa >\hsize
    \@ensure@dir{#1: #2}\par
  \else
    \global \@minipagefalse
    \hb@xt@\hsize{\hfil\box\@tempboxa\hfil}%
  \fi
  \vskip\belowcaptionskip}%
  }%
 }%
}% ELSE KOMASCRIPT
{\@ifclassloaded{scrlttr2}{}% do nothing for letter class
{\renewcommand{\@@makecaption}[3]{%
  \cap@margin
  \ifonelinecaptions
    \@tempcnta=\value{mpfootnote}\@tempcntb=\value{footnote}%
    \let\scr@tmp@footnotetext=\@footnotetext
    \let\@footnotetext=\@gobble
    \sbox\@tempboxa{%
      {\capfont\strut\ignorespaces
        #1{{\caplabelfont#2\captionformat}}%
        #3\unskip\strut}%
    }%
    \let\@footnotetext=\scr@tmp@footnotetext
    \let\scr@tmp@footnotetext=\undefined
    \setcounter{footnote}{\@tempcntb}%
    \setcounter{mpfootnote}{\@tempcnta}%
  \else
    \sbox\@tempboxa{\hspace*{2\cap@width}}%
  \fi
  \begingroup%
    \setlength{\@tempdima}{\cap@width}%
    \ifdim \wd\@tempboxa >\@tempdima
      \hb@xt@\hsize{%
        \setbox\@tempboxa\vbox{\hsize=\cap@width
          \ifdofullc@p
            \@ensure@dir{\capfont\@hangfrom{\scr@smashdp{\strut\ignorespaces
                  #1{{\caplabelfont#2\captionformat}}}}%
              {#3\unskip\strut\par}}%
          \else%
            \ifdim\cap@indent<\z@
              \@ensure@dir{\capfont\strut\ignorespaces
                #1{{\caplabelfont #2\captionformat\par}}%
                \noindent\hspace*{-\cap@indent}#3\unskip\strut\par}%
            \else%
              \if@capbreak
                \@ensure@dir{\capfont\strut\ignorespaces
                  #1{{\caplabelfont #2\captionformat\par}}%
                  \noindent\@hangfrom{\hspace*{\cap@indent}}{#3\par}}%
              \else
                \@ensure@dir{\capfont\@hangfrom{\scr@smashdp\strut\hspace*{\cap@indent}}%
                  {\hspace{-\cap@indent}\scr@smashdp{\ignorespaces#1%
                    {{\caplabelfont#2\captionformat}}}#3\unskip\strut\par}}%
              \fi
            \fi
          \fi
        }%
        \setlength{\@tempdima}{\ht\@tempboxa}%
        \addtolength{\@tempdima}{\dp\@tempboxa}%
        \addtolength{\@tempdima}{-\ht\strutbox}%
        \ht\@tempboxa\ht\strutbox
        \dp\@tempboxa\@tempdima
        \strut\cap@left
        \box\@tempboxa
        \cap@right\strut
	}%
    \else
      \global \@minipagefalse
      \sbox\@tempboxa{%
        \@ensure@dir{\capfont\scr@smashdp{\strut\ignorespaces
          #1{{\caplabelfont#2\captionformat}}}%
          #3}%
      }%
      \hb@xt@\hsize{\strut\cap@left\box\@tempboxa\cap@right\strut}%
    \fi
  \endgroup}
}}%
%    \end{macrocode}
% \subsection{\cmd{\textcolor}}
% \cmd\textcolor\ needs to be redefined so that the color-switching 
% commands in the output will affect the correct portion of text also
% in RL context, but this only works if the textual argument does not overlap
% more than one line, which is why we issue a warning. See §~\ref{bidicolor}
% above for an alternative approach to colored text using \XeTeX\ font features.
% The following code (less the warning) is again taken from \texttt{rlbabel.def}. 
%    \begin{macrocode}
\ifx\@textcolor\@undefined\else%
\AtBeginDocument{%
    \def\@textcolor#1#2#3{%
    \if@rl\PackageWarning{bidi}{%
    \textcolor will not work in RL mode if the textual argument spans more than one line.^^J%
    With XeTeX you should set color as a font feature instead.}%
      \beginL\protect\leavevmode{\color#1{#2}\beginR#3\endR}\endL%
      \else%
        \protect\leavevmode{\color#1{#2}#3}%
      \fi%
    }%
}%
\fi
%    \end{macrocode}
% \subsection{Tabular environments}
% This is taken almost verbatim from Farsi\TeX, with the addition of a 
% patch for the \pkg{array} package (which does not work correctly yet).
%    \begin{macrocode}
\newif\if@tab@rl
\if@rlmain\@tab@rltrue\else\@tab@rlfalse\fi
\@ifpackageloaded{array}%
{\PackageWarningNoLine{bidi}{%
  You are using the package array (or the memoir class). ^^J
  Unfortunately right-to-left tabular environments are not ^^J
  yet supported with the array package.}
\let\@uthor=\author
\def\author#1{\@uthor{\@ensure@dir{#1}}}
}%
%\def\@array[#1]#2{%
%  \@tempdima \ht \strutbox
%  \advance \@tempdima by\extrarowheight
%  \setbox \@arstrutbox \hbox{\vrule
%             \@height \arraystretch \@tempdima
%             \@depth \arraystretch \dp \strutbox
%             \@width \z@}%
%  \begingroup
%  \@mkpream{#2}%
%  \xdef\@preamble{\noexpand \ialign \@halignto
%                  \bgroup \@arstrut \@preamble
%                          \tabskip \z@ \cr}%
%  \endgroup
%  \@arrayleft
%  \if #1t\vtop \else \if#1b\vbox \else \vcenter \fi \fi
%  \bgroup
%  \let \@sharp ##\let \protect \relax
%  \lineskip \z@
%  \baselineskip \z@
%  \if@tab@rl\hbox\bgroup\beginR\vbox\bgroup\fi
%  \m@th
%  \let\\\@arraycr \let\tabularnewline\\\let\par\@empty
%  \@preamble}
%\def\@tabular{%
%  \if@rl\global\@tab@rltrue\fi
%  \leavevmode
%  \hbox \bgroup\if@tab@rl\beginR\fi
%  $\col@sep\tabcolsep
%  \let\d@llarbegin\begingroup \let\d@llarend\endgroup
%  \@tabarray}
%\def\endtabular{\endarray\if@tab@rl\egroup\endR\egroup\fi 
%$\if@tab@rl\endR\fi
%\egroup}%
{% ELSE DEFAULT LATEX MACROS
\def\@tabular{%
     \if@rl\global\@tab@rltrue\fi
     \leavevmode \hbox \bgroup \if@tab@rl\beginR\fi
     $\let\@acol\@tabacol
     \let\@classz\@tabclassz
     \let\@classiv\@tabclassiv \let\\\@tabularcr\@tabarray}
\def\endtabular{\crcr\egroup\if@tab@rl\egroup\endR\egroup\fi
 \egroup $\if@tab@rl\endR\fi \egroup}%
\def\@array[#1]#2{\setbox\@arstrutbox=\hbox{\vrule
     height\arraystretch \ht\strutbox
     depth\arraystretch \dp\strutbox
     width\z@}\@mkpream{#2}\edef\@preamble{%
\halign \noexpand\@halignto
\bgroup \tabskip\z@ \@arstrut \@preamble \tabskip\z@ \cr}%
\let\@startpbox\@@startpbox \let\@endpbox\@@endpbox
\if #1t\vtop \else \if#1b\vbox \else \vcenter \fi\fi
\bgroup \let\par\relax
\let\@sharp##\let\protect\relax \lineskip\z@\baselineskip\z@
\if@tab@rl\hbox\bgroup\beginR\vbox\bgroup\fi
\@preamble}
}
%    \end{macrocode}
% \subsection{Equation labels in RL documents}
% Adapted from Farsi\TeX.
%    \begin{macrocode}
\def\@open@paren{\if@rlmain)\else(\fi}
\def\@close@paren{\if@rlmain(\else)\fi}
\def\tagform@#1{\maketag@@@{\@open@paren\ignorespaces#1\unskip\@@italiccorr\@close@paren}}
%    \end{macrocode}
% \subsection{TODO}
% \subsubsection{Unicode CTRL Chars}
%    \begin{macrocode}
%% Make these Unicode chars active and define them so that they work 
%% in conformance to the Unicode bidi algorithm!
%% \catcode"200E=\active
%% \catcode"200F=\active
%% \def‎{\setLR}
%% \def‏{\setRL}
%% 202A -> {\@ensure@LR\bgroup} ? or \LR
%% 202B -> {\@ensure@RL\bgroup} ? or \RL
%% 202C -> {\egroup} ? or \if@rl\@rlfalse\else\@rltrue\fi ?
%% 202D -> {?} %LRO
%% 202E -> {?} %RLO
%    \end{macrocode}
%
% \iffalse
%</package>
% \fi
%
% ^^A\clearpage
% ^^A\PrintChanges
%
% ^^A\clearpage
% ^^A\PrintIndex
%
% \Finale
%
%
% \typeout{*************************************************************}
% \typeout{*}
% \typeout{* To finish the installation you have to move the following}
% \typeout{* file into a directory searched by XeTeX:}
% \typeout{*}
% \typeout{* \space\space\space bidi.sty}
% \typeout{*}
% \typeout{*************************************************************}
%
\endinput
