  % !TeX program = lualatex

\documentclass{ltxdoc}

\usepackage{minted}

\usepackage[arabic,persian,english]{babelbidi}

\babelprovide[import , mapdigits  ,onchar = ids fonts letters]{arabic}
\babelprovide[import,,onchar=ids fonts letters]{persian}
\babelprovide[import,main,onchar=ids fonts letters]{english}

\babelfont{rm}[english]{Times New Roman}
\babelfont{tt}[english]{JetBrains Mono}
\babelfont{rm}[arabic]{Amiri}
\babelfont{rm}[persian]{Vazirmatn}
\babelfont{tt}[persian]{Vazir Code}
\babelfont{tt}[arabic]{Kawkab Mono}
% Hasubi Mono
% Kawkab Mono

\usepackage{pkgmeta}
\usepackage{datemultical}
\dmcset{babelbidi}{\pkgmeta[year]{babelbidi}}{\pkgmeta[month]{babelbidi}}{\pkgmeta[day]{babelbidi}}

\usepackage[svgnames]{xcolor}


\usepackage{tabularx}
\usepackage{xltabular}
\usepackage{booktabs}





\usepackage{hyperref}

\setminted{
    breaklines=true,
   % breakanywhere=true,
    escapeinside=||
}
\setminted[latex]{bgcolor=Gold, bgcolorpadding=0.5em}
\setminted[bash]{bgcolor=Gainsboro}

\hypersetup{
    colorlinks=true,
    linkcolor=blue,
    urlcolor=blue
}




\title{The \textsf{babelbidi} Package}
\author{Amer Amikhteh}
\date{%
    Version \pkgmeta[version]{babelbidi}\\[2pt]
    \dmc{babelbidi}{long}
}


\begin{document}
\maketitle

\begin{abstract}
    \textsf{babelbidi} extends Babel's bidirectional support by fixing direction-sensitive behaviour and providing interfaces for explicit text direction, language selection, and font configuration, including glyph fallback with Lua\TeX. It supports languages available through Babel and works with \LuaTeX~(recommended), Xe\TeX, or pdf\TeX, with either an LTR or RTL main language.
\end{abstract}

\section{Introduction}

Babel provides the infrastructure for typesetting documents containing
both left-to-right (LTR) and right-to-left (RTL) languages. Some layout
components, however, do not always behave correctly in RTL contexts,
and Babel does not provide all the basic direction interfaces that may
be useful in a document.

\textsf{babelbidi} addresses these gaps in two ways:
\begin{enumerate}
    \item
          it patches
          direction-sensitive layout behaviour
    \item
          and provides a small set of bidi
          and language-selection APIs.
\end{enumerate}

Most layout patches concern Lua\LaTeX. For documents whose main language
does not use the Latin script, code-related direction handling is provided
with Lua\LaTeX, Xe\LaTeX, and pdf\LaTeX.


The basic direction commands follow interfaces found in bidi
implementations such as \textsf{luabidi}. The commands \verb|\lr|,
\verb|\rl|, and the \texttt{latin} environment are inspired in part by
interfaces familiar to users of \textsf{xepersian}.


\section{Obtaining and Installing}

The official version of the \texttt{babelbidi} package is available from CTAN:

\begin{center}
    \url{https://ctan.org/pkg/babelbidi}
\end{center}

Once the \TeX{} Live package database has been updated, the package can be
installed with the following command:

\begin{minted}{bash}
    tlmgr install babelbidi
\end{minted}


\section{Loading}

The package is loaded as follows:

\begin{minted}{latex}
     \usepackage[<options>]{babelbidi}
 \end{minted}

The package accepts options for both Babel and
\textsf{babelbidi}. Options not defined by
\textsf{babelbidi} are passed to Babel. The \texttt{bidi} and
\texttt{layout} options are Babel options for which
\textsf{babelbidi} provides engine-dependent defaults.


If \texttt{bidi} is not specified, \textsf{babelbidi} selects
its default value according to the engine:

\begin{center}
    \begin{tabular}{ll}
        \toprule
        Engine  & Default value of \texttt{bidi} \\
        \midrule
        Lua\TeX & \texttt{basic}                 \\
        Xe\TeX  & \texttt{bidi-r}                \\
        Pdf\TeX & \texttt{default}               \\
        \bottomrule
    \end{tabular}
\end{center}

With \LuaTeX, \textsf{babelbidi} selects the following default
value for \texttt{layout}:


\begin{minted}{latex}
     counters graphics footnotes lists
 \end{minted}

Specifying \texttt{layout} replaces this default; it does not
add to it. For example:

\begin{minted}{latex}
     layout={counters footnotes}
 \end{minted}

This selects only \texttt{counters} and \texttt{footnotes}
for the \texttt{layout} option. To retain \texttt{graphics}
and \texttt{lists}, include them explicitly in the value.
When the value contains multiple selectors, the value must be
enclosed in \textbf{braces}.


For best results, consider the following recommendations:
\begin{enumerate}
    \item For slides with an RTL main language, \textsf{beamer-rl} is
          recommended over \textsf{beamer}, though it is not required.

    \item Lua\LaTeX~is recommended for its broader capabilities and
          Lua\footnote{Lua is a lightweight programming language designed
              to be embedded in applications.} extensibility. Separately,
          Babel's \texttt{onchar} option can automatically select a language
          based on the characters in the text. For Arabic:
          \begin{minted}{latex}
        \babelprovide[import, mapdigits, onchar=ids fonts letters]{arabic}
    \end{minted}
          Punctuation such as parentheses may still require explicit
          language selection.
\end{enumerate}



With \LuaTeX, the \texttt{fontcache} option controls caching of
font mappings used by Babel's \texttt{onchar=fonts} option.
It is a boolean option and is enabled by default to improve
compilation speed. In special cases, such as font changes made
through the \texttt{rmfamily} hook, cached mappings may prevent
these changes from taking effect. The cache can be disabled
when necessary:

\begin{minted}{latex}
    \usepackage[fontcache=false]{babelbidi}
\end{minted}





\section{Font fallback}

With Lua\LaTeX, \textsf{babelbidi} can use fonts from other Babel languages
when the current font lacks a required glyph. Declare an ordered fallback
chain in the preamble:

\begin{minted}{latex}
    \fontfallback{english}{persian,greek}
\end{minted}

The source and candidate languages must be known to Babel. They can be
specified as package options or loaded explicitly with \verb|\babelprovide|.
Their fonts must be declared with \verb|\babelfont|. Candidates are tried in
order, while the text language, direction, font family, series, shape, and
size are preserved. Fallback applies to text fonts, including custom
families, but not to math fonts. It works with or without
\texttt{onchar=fonts} and also uses the \texttt{fontcache} setting.
An explicit \cmd{\latinttfamily} selection uses the selected Latin language's
fallback chain without changing the text language or direction.

A later declaration replaces the previous chain; an empty candidate list
disables fallback:

\begin{minted}{latex}
    \fontfallback{english}{}
\end{minted}

Unknown languages, repeated candidates, and self-references are ignored with
a warning where appropriate. Fallback is not recursive and is applied per
glyph before shaping. It is available only with Lua\LaTeX; Xe\LaTeX~and
pdf\LaTeX~warn and ignore explicit fallback declarations.

\section{Direction APIs}

\textsf{babelbidi} provides commands and environments for controlling
text direction without switching the language context, matching the
traditional \textsf{bidi} and \textsf{luabidi} approach.

\subsection{Commands}

\subsubsection*{Direction commands without arguments}

\begin{tabularx}{\linewidth}{@{}lX@{}}
    \toprule
    Command & Description \\
    \midrule
    \verb|\beginL|, \verb|\endL| & Begin and end an explicit LTR text group \\
    \verb|\beginR|, \verb|\endR| & Begin and end an explicit RTL text group \\
    \verb|\setRTL|, \verb|\setRL|, \verb|\unsetLTR| & Set paragraph direction to RTL \\
    \verb|\setLTR|, \verb|\setLR|, \verb|\unsetRTL| & Set paragraph direction to LTR \\
    \bottomrule
\end{tabularx}

\subsubsection*{Footnote-rule controls}

\begin{tabularx}{\linewidth}{@{}lX@{}}
    \toprule
    Command & Description \\
    \midrule
    \verb|\leftfootnoterule| & Left-aligned footnote rule \\
    \verb|\rightfootnoterule| & Right-aligned footnote rule \\
    \verb|\textwidthfootnoterule| & Full-width footnote rule \\
    \verb|\footnoterulewidth| & Length controlling the width of short footnote rules \\
    \verb|\autofootnoterule| & Automatically selects the rule alignment based on footnote direction \\
    \bottomrule
\end{tabularx}

\subsubsection*{Commands taking text argument: \mdseries\texttt{\char`\{text\char`\}}}

\begin{tabularx}{\linewidth}{@{}lX@{}}
    \toprule
    Command & Description \\
    \midrule
    \verb|\LRE|, \verb|\LR| & Inline LTR embedding \\
    \verb|\RLE|, \verb|\RL| & Inline RTL embedding \\
    \bottomrule
\end{tabularx}

\subsubsection*{Footnote commands: \mdseries\texttt{[num]\{text\}}}

\begin{tabularx}{\linewidth}{@{}lX@{}}
    \toprule
    Command & Description \\
    \midrule
    \verb|\LTRfootnote| & Typeset footnote in LTR direction \\
    \verb|\RTLfootnote| & Typeset footnote in RTL direction \\
    \bottomrule
\end{tabularx}

\subsubsection*{Directional boxes}

\begin{tabularx}{\linewidth}{@{}lX@{}}
    \toprule
    Command & Description \\
    \midrule
    \verb|\hboxL|, \verb|\hboxR| & Horizontal box with LTR or RTL direction \\
    \verb|\vboxL|, \verb|\vboxR| & Vertical box with LTR or RTL direction \\
    \verb|\vtopL|, \verb|\vtopR| & Top-aligned vertical box with LTR or RTL direction \\
    \bottomrule
\end{tabularx}

The commands \cmd{\hbox}, \cmd{\vbox}, and \cmd{\vtop} construct
boxes containing the material enclosed in braces. An \cmd{\hbox}
arranges its contents horizontally, without line breaking.
A \cmd{\vbox} arranges its contents vertically; text inside it
is broken into lines according to \cmd{\hsize}. A \cmd{\vtop}
works like \cmd{\vbox}, but aligns with surrounding material
at its top rather than its bottom: for boxes containing lines
of text, the reference point is on the first line's baseline
for \cmd{\vtop} and the last line's baseline for \cmd{\vbox}.

The directional variants listed above set the box direction
to LTR or RTL without changing the language. Before the opening
brace, an optional \texttt{to <dimension>} specifies the final
width of a horizontal box or height of a vertical box;
\texttt{spread <dimension>} adds the given amount to its natural
width or height. These sizes are achieved by adjusting stretchable
or shrinkable space within the box. A box can also be stored
with \cmd{\setbox} and later inserted with \cmd{\box}.

\subsection{Environments}

\begin{center}
    \begin{tabular}{@{}ll@{}}
        \toprule
        Environment & Description \\
        \midrule
        \texttt{RTL}
        & Typesets its contents from right to left \\
        \texttt{LTR}
        & Typesets its contents from left to right \\
        \bottomrule
    \end{tabular}
\end{center}


\section{Language and Font APIs}

\textsf{babelbidi} provides commands, environments, and package options
for selecting languages and setting fonts.

\subsection{Font Selection}

When running under Xe\LaTeX~or Lua\LaTeX, \textsf{babelbidi} provides the
following commands:

\begin{itemize}
    \item \cmd{\settextfont}\oarg{options}\marg{font}:
    Sets the \texttt{rm}, \texttt{sf}, and \texttt{tt} fonts for the
    main language.

    \item \cmd{\setlatintextfont}\oarg{options}\marg{font}:
    Sets the \texttt{rm}, \texttt{sf}, and \texttt{tt} fonts for the
    selected Latin language.

    \item \cmd{\deflatinfont}\marg{command}\oarg{options}\marg{font}:
    Defines a Latin font family command.

    \item \cmd{\setlatinsansfont}\oarg{options}\marg{font}:
    Sets the sans-serif font for the selected Latin language.

    \item \sloppy \cmd{\setlatinmonofont}\oarg{options}\marg{font}:
    Sets the monospaced font for the selected Latin language and
    configures it for use by \cmd{\latinttfamily}.

    \item \cmd{\setmonofont}\oarg{options}\marg{font}:
    In the preamble, also sets Babel's monospaced font for the main
    language, so it is available to font fallback.
\end{itemize}

\subsection{Commands}

These commands provide language selection, Latin-script dates,
and Latin monospaced or verbatim text. The commands \cmd{\lr}
and \cmd{\rl} switch the active language context in addition
to setting the script direction, and are not part of the
standard \textsf{bidi} package.

\begin{tabularx}{\linewidth}{@{}llX@{}}
    \toprule
    Command & Arguments & Description \\
    \midrule
    \verb|\lr| & \verb|{text}| & Typeset text using LTR language \\
    \verb|\rl| & \verb|{text}| & Typeset text using RTL language \\
    \verb|\latintoday| & -- & Print current date in Latin script \\
    \verb|\latinttfamily| & -- & Select Latin monospaced font family \\
    \verb|\latinverb| & \textsl{verb} & Typeset verbatim code in Latin \\
    \verb|\latinverb*| & \textsl{verb} & Typeset verbatim with visible spaces \\
    \bottomrule
\end{tabularx}

\subsection{Environments}

\begin{center}
    \begin{tabular}{@{}ll@{}}
        \toprule
        Environment & Description \\
        \midrule
        \texttt{latin}
        & Typesets its contents in the selected Latin language \\
        \texttt{latinverbatim}
        & Typesets a verbatim block in the \texttt{code} language \\
        \texttt{latinverbatim*}
        & Same, displaying spaces \\
        \bottomrule
    \end{tabular}
\end{center}

\subsection{Language Selection}
\label{sec:language-selection}

The following package keys select the languages used for Latin text,
directional text, and code-related material:

\begin{center}
    \begin{tabular}{@{}ll@{}}
        \toprule
        Key & Used for \\
        \midrule
        \texttt{latin}
        & The \texttt{latin} environment and Latin font commands \\
        \texttt{ltr}
        & The \verb|\lr| command \\
        \texttt{rtl}
        & The \verb|\rl| command \\
        \texttt{code}
        & Code-related material \\
        \bottomrule
    \end{tabular}
\end{center}

For example:

\begin{minted}{latex}
    \usepackage[code=dutch,rtl=arabic]{babelbidi}
\end{minted}

Unless specified explicitly, the values of these keys are selected
automatically and updated after each \verb|\babelprovide| call. Explicit
values remain unchanged.

The automatic selections are determined as follows:

\begin{description}
    \item[\texttt{latin}:]
    The main language if it uses the Latin script; otherwise, the first
    loaded Latin-script language; otherwise, \texttt{english}.

    \item[\texttt{ltr}:]
    The main language if it is left to right; otherwise, the first loaded
    left-to-right language; otherwise, \texttt{english}.

    \item[\texttt{rtl}:]
    The main language if it is right to left; otherwise, the first loaded
    right-to-left language; otherwise, \texttt{arabic}.

    \item[\texttt{code}:]
    The main Latin-script language, if available; otherwise,
    \texttt{english}, if loaded; otherwise, the first loaded
    Latin-script language; otherwise, the main or first loaded
    left-to-right language; finally, the main language.
\end{description}

Languages should be declared before their fonts are configured.


\section{Patches}

The package applies the following patches automatically when the
corresponding engine or package is in use.

\begin{enumerate}
    \item \textbf{Common patches}
    \begin{enumerate}
        \item \textbf{Code support}
        \begin{enumerate}
            \item \textbf{LaTeX verbatim interfaces:}
            With a non-Latin main language, adjusts the
            font and direction handling of \cmd{\verb},
            \cmd{\verb*}, \texttt{verbatim}, and
            \texttt{verbatim*}. With Unicode engines, the
            font patch selects \cmd{\latinttfamily} without
            changing the text language.

            \item \textsf{listings}: With a non-Latin main
            language, selects the \texttt{code} language
            for display and inline listings, with direction
            handling for inline listings.

            \item \textsf{minted}: With a non-Latin main
            language, applies the \texttt{code} language
            and direction handling to the
            \texttt{minted} environment and its processing
            commands. Lua\LaTeX~also receives the required
            layout adjustments.
        \end{enumerate}

        \item \texttt{\string\label}: prevents errors caused by Babel's
        direction commands in label keys derived from enumeration counters.
    \end{enumerate}

    \item \textbf{Xe\LaTeX~patches}
    \begin{enumerate}
        \item \textsf{natbib}: corrects citation links in RTL text with
        recent \textsf{hyperref} versions.
        \item \textsf{fontspec}: disables its math-mode handling when
        Babel bidi mode is active.
    \end{enumerate}

    \item \textbf{Lua\LaTeX~patches}
    \begin{enumerate}
        \item \texttt{\string\makebox} and tables: adjust the positions
        of \texttt{l} and \texttt{r} material and swap table-column
        alignment in RTL text.
        \item Footnotes: adjust footnote paragraph direction in RTL contexts;
        footnotes issued in math mode in RTL-main documents are treated as RTL.
        \item TikZ: use LTR paragraph direction inside
        \texttt{tikzpicture}, except with \textsf{beamer-rl}.
        \item \textsf{fancyhdr}: increase the head height and typeset
        headers and footers in LTR direction.
        \item \textsf{beamer}: correct the layout of rounded boxes, except
        when \textsf{beamer-rl} is loaded.
    \end{enumerate}

    \item \textbf{RTL-main footnote-rule patch}
    \begin{enumerate}
        \item Typesets the default rule on the right in RTL-main documents,
        with stable LTR geometry, preserving explicit rule selections.
    \end{enumerate}
\end{enumerate}



\section{Minted package}

BabelBidi supports the \textsf{minted} package:

\begin{minted}{latex}
    \usepackage{minted}
\end{minted}

The \texttt{textlang} option selects a Babel language already declared
with \verb|\babelprovide| or loaded as a Babel package option:

\begin{minted}{latex}
    \begin{minted}[textlang=persian]{latex}
        متن فارسی
    \end{min||ted}
\end{minted}

It can also be set with \verb|\setminted|:

\begin{minted}{latex}
    \setminted{textlang=persian}
\end{minted}

The \texttt{textdir} option sets the code direction:
\texttt{rtl} (right-to-left) or \texttt{ltr} (left-to-right).

\sloppy
With Lua\LaTeX, \texttt{chardir} uses Babel's
\verb|\babelcharproperty| to temporarily set character directions.
It takes comma-separated \texttt{\{character\}\{direction\}} pairs.
Direction values include \texttt{l}, \texttt{al}, \texttt{r},
\texttt{en}, \texttt{an}, \texttt{on}, \texttt{et}, and \texttt{cs}.
Previous values are restored after the environment ends.

This example sets right-to-left code with the backslash and closing
brace assigned direction \texttt{l}:

\begin{minted}[chardir={{.}{r}}]{latex}
    \begin{min||ted}[textdir=rtl,
        chardir={{\\}{l},{\}}{l}}]{latex}
        این روش در
        \lr{Chapter 2 (Examples)}
        توضیح داده شده است.
    \end{min||ted}
\end{minted}

With Lua\LaTeX, frames retain left-to-right geometry.
Line numbers use Latin digits.





\section{License}

The \texttt{BabelBidi} package is released under the
\lr{\LaTeX~Project Public License (LPPL)},
version \lr{1.3c} or later.
The full text of the license is available in the \texttt{LICENSE} file.

\section{Author and Maintainer}

The \texttt{babelbidi} package is developed and maintained by
\textbf{Amer Amikhteh}.

The project's source code, development versions, and issue tracker are
available in the project repository:

\begin{center}
    \url{https://github.com/gambi-shah/babelbidi}
\end{center}

\end{document}
