% !TeX program = lualatex
% Portions of the presentation code are adapted from Babel's user guide
% (babel.dtx, version 26.14, 2026-10-15).
% Copyright (C) 2012-2026 Javier Bezos and Johannes L. Braams.
% Copyright (C) 1989-2012 Johannes L. Braams and individual authors
% listed in the original file. Babel is distributed under the LPPL,
% version 1.3 or later; see THIRD-PARTY-NOTICES.md and LICENSE.
% Changes: the documentation helpers and page layout have been adapted
% to this manual; the cover and manual text describe babelbidi.
% This is not the Babel manual, nor is it maintained by its authors.

\documentclass{ltxdoc}

% --------------------------------------------------------------------
% 1. Engine, packages and languages
% --------------------------------------------------------------------
\usepackage{iftex}
\RequireLuaTeX
\usepackage[svgnames]{xcolor}
\usepackage{graphics}

% Load minted first so babelbidi can configure its integration.
\usepackage{minted}
\usepackage[arabic,persian,english]{babelbidi}

% Required before the font-existence tests below.
% Keep this after babelbidi so its fontspec hooks are registered first.
\usepackage{fontspec}

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

\usepackage{tikz}
\usetikzlibrary{arrows.meta}
\usepackage[manual]{amikhteh-logo}
\usepackage{pkgmeta}
\usepackage{datemultical}
\usepackage{tabularx}
\usepackage{booktabs}
\usepackage{multicol}
\usepackage{needspace}

% ltxdoc or babelbidi may already have loaded hyperref.
\makeatletter
\@ifpackageloaded{hyperref}{}{\RequirePackage{hyperref}}
\makeatother

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

% --------------------------------------------------------------------
% 2. Body fonts: language-specific families managed by Babel
% --------------------------------------------------------------------
\IfFontExistsTF{Noto Serif}{%
    \babelfont[english]{rm}[Scale=.88]{Noto Serif}
}{%
    \babelfont[english]{rm}{Latin Modern Roman}
}
\IfFontExistsTF{Noto Sans}{%
    \babelfont[english]{sf}[Scale=.88]{Noto Sans}
}{%
    \babelfont[english]{sf}{Latin Modern Sans}
}
\IfFontExistsTF{DejaVu Sans Mono}{%
    \babelfont[english]{tt}[Scale=.86,FakeStretch=.97]{DejaVu Sans Mono}
}{%
    \babelfont[english]{tt}[Scale=MatchLowercase]{Latin Modern Mono}
}

\IfFontExistsTF{Amiri}{%
    \babelfont[arabic]{rm}{Amiri}
    \babelfont[arabic]{sf}{Amiri}
}{%
    \babelfont[arabic]{rm}{FreeSerif}
    \babelfont[arabic]{sf}{FreeSerif}
}
\IfFontExistsTF{Kawkab Mono}{%
    \babelfont[arabic]{tt}{Kawkab Mono}
}{%
    \babelfont[arabic]{tt}{DejaVu Sans Mono}
}

\IfFontExistsTF{Vazirmatn}{%
    \babelfont[persian]{rm}{Vazirmatn}
    \babelfont[persian]{sf}{Vazirmatn}
}{%
    \IfFontExistsTF{Amiri}{%
        \babelfont[persian]{rm}{Amiri}
        \babelfont[persian]{sf}{Amiri}
    }{%
        \babelfont[persian]{rm}{FreeSerif}
        \babelfont[persian]{sf}{FreeSerif}
    }
}
\IfFontExistsTF{Vazir Code}{%
    \babelfont[persian]{tt}{Vazir Code}
}{%
    \babelfont[persian]{tt}{DejaVu Sans Mono}
}

% Main cover title only.
% Requires Cormorant Garamond to be installed.
\deflatinfont{\bbCoverTitle}[
Ligatures=TeX
]{Cormorant Garamond}

\deflatinfont{\bbCoverTitleBold}[
Ligatures=TeX
]{Cormorant Garamond Bold}

% --------------------------------------------------------------------
% 3. Cover fonts: independent families defined through babelbidi
% --------------------------------------------------------------------
% Arguments: regular face, emphasis face, light face.
% These commands do not redefine Babel's body-font families.
\newcommand*\bbdDefineCoverFonts[3]{%
    \deflatinfont{\bbCoverFont}[
    Ligatures=TeX,
    UprightFont={#1},
    BoldFont={#2}
    ]{#1}%
    \deflatinfont{\bbCoverLight}[
    Ligatures=TeX
    ]{#3}%
    \deflatinfont{\bbCoverLabel}[
    Ligatures=TeX,
    LetterSpace=9
    ]{#1}%
}

\newcommand*\bbdFallbackCoverFonts{%
    \bbdDefineCoverFonts
    {TeX Gyre Heros}
    {TeX Gyre Heros Bold}
    {TeX Gyre Heros}%
}

% Use the Fira design only when all three required weights are present.
\IfFontExistsTF{Fira Sans Regular}{%
    \IfFontExistsTF{Fira Sans Medium}{%
        \IfFontExistsTF{Fira Sans Light}{%
            \bbdDefineCoverFonts
            {Fira Sans Regular}
            {Fira Sans Medium}
            {Fira Sans Light}%
        }{\bbdFallbackCoverFonts}%
    }{\bbdFallbackCoverFonts}%
}{\bbdFallbackCoverFonts}

% --------------------------------------------------------------------
% 4. Palette: body colours and an independent cover palette
% --------------------------------------------------------------------
\definecolor{thered}{rgb}{0.65,0.04,0.07}
\definecolor{thegrey}{gray}{0.8}
\definecolor{thegreyed}{gray}{0.6}
\definecolor{shadecolor}{rgb}{0.97,0.97,0.94}
\definecolor{coverrose}{rgb}{0.86,0.73,0.67}
\definecolor{covercream}{rgb}{0.92,0.86,0.73}
\definecolor{covergrey}{rgb}{0.95,0.95,0.95}
\definecolor{coverink}{rgb}{0.55,0.40,0.35}

\definecolor{bbCoverInk}{HTML}{283F46}
\definecolor{bbCoverCream}{HTML}{EBDDB9}
\definecolor{bbCoverRose}{HTML}{DDBBAA}

% --------------------------------------------------------------------
% 5. Body layout and documentation helpers
% --------------------------------------------------------------------
% Preserve the existing ltxdoc-based layout of the manual body.
\addtolength{\oddsidemargin}{-2em}
\addtolength{\evensidemargin}{-2em}
\addtolength{\textwidth}{25.5pt}
\addtolength{\textheight}{3.5cm}
\addtolength{\topmargin}{-2cm}
\setlength{\columnsep}{1.5em}
\setlength{\emergencystretch}{2em}
\frenchspacing
\raggedright
\setlength{\parindent}{.8em}

\makeatletter
% Preserve the two-argument interface used throughout the manual.
% The command token is printed rather than executed.
\def\Describe#1#2{%
    \par\vskip 1.7ex plus .7ex minus .2ex
    \noindent\hspace*{-1.7cm}%
    {\color{thegreyed}\normalsize\ttfamily
        \underline{\strut{\color{thered}\string#1}\color{black}#2}}%
    \par\nobreak\vskip 1.1ex plus .2ex\relax
}
\def\DescribeOther{\nobreak\vskip-1.1\baselineskip\Describe}

% Environment signatures: \begin{environment} ... \end{environment}.
\def\menv#1{\char`\{#1\char`\}}
\def\Eenv#1{%
    \quad...\quad
    \texttt{\color{thered}\string\end\menv{#1}}%
}

% Manual-only helper: no dependency on a newer installed package API.
\newcommand*\bbdManualContents{%
    \pdfbookmark[0]{\contentsname}{bbd-manual-contents}%
    \begingroup
    \small
    \setlength{\parindent}{0pt}%
    \begin{multicols}{2}[\section*{\contentsname}]
        \@starttoc{toc}%
    \end{multicols}%
    \endgroup
}
\makeatother

% --------------------------------------------------------------------
% 6. Code examples
% --------------------------------------------------------------------
\usemintedstyle{friendly}
\setminted{
    fontsize=\small,
    breaklines=true,
    autogobble=true,
    escapeinside=||,
    bgcolor=shadecolor,
    bgcolorpadding=1.5mm,
    frame=single,
    framerule=.4pt,
    framesep=1.5mm,
    rulecolor=\color{black!45},
    baselinestretch=1
}
\setminted[bash]{bgcolor=covergrey}

% --------------------------------------------------------------------
% 7. PDF metadata and title information
% --------------------------------------------------------------------
\hypersetup{
    colorlinks=true,
    linkcolor=thered,
    urlcolor=blue,
    citecolor=thered,
    pdfdisplaydoctitle=true,
    pdftitle={The babelbidi Package -- User Guide},
    pdfauthor={Amer Amikhteh},
    pdfsubject={Bidirectional typesetting with Babel},
    pdfkeywords={babelbidi, Babel, LuaLaTeX, XeLaTeX, bidirectional typesetting, RTL},
    bookmarksnumbered=true
}

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

% --------------------------------------------------------------------
% 8. Cover styles: typography is separate from page geometry
% --------------------------------------------------------------------
\tikzset{
    bb cover node/.style={
        inner sep=0pt,
        outer sep=0pt,
        align=left,
        font=\bbCoverFont
    },
    bb cover label/.style={
        font=\bbCoverLabel\fontsize{9}{12}\selectfont
    },
    bb cover arrow/.style={
        line width=1.1pt,
        -{Stealth[length=3mm,width=2mm]}
    }
}



% Shared cover placement and optional manual page style.
% The package owns mark placement, sizing, section tracking and footer layout.
\AmikhtehLogoCoverSetup{primary=bbCoverCream,accent=bbCoverRose}

\begin{document}

    % The cover must not share a page anchor with page 1 of the manual body.
    \hypersetup{pageanchor=false}
    \begin{titlepage}
        \thispagestyle{empty}
        \begingroup
        \hypersetup{urlcolor=bbCoverInk}

        \noindent
        \begin{tikzpicture}[remember picture,overlay]
            \begin{scope}[
                shift={(current page.south west)},
                x=\paperwidth,
                y=\paperheight,
                every node/.style={bb cover node}
                ]
                % Full-bleed fields, independent of the body margins.
                \fill[bbCoverCream] (0,0) rectangle (1,1);
                \fill[bbCoverInk]   (0,.36) rectangle (1,1);
                \fill[bbCoverRose]  (.975,0) rectangle (1,1);

                % Shared baseline for the two top labels.
                \node[bb cover label,anchor=base west,text=bbCoverCream]
                at (.09,.915) {A \LaTeX\ PACKAGE};
                \node[bb cover label,anchor=base east,text=bbCoverRose]
                at (.90,.915) {USER GUIDE};

                % One baseline, two weights, no artificial gap in the package name.
                \node[
                anchor=base west,
                font=\fontsize{74}{80}\selectfont
                ]
                at (.09,.775) {%
                    {\bbCoverTitle\color{bbCoverCream}babel}%
                    {\bbCoverTitleBold\color{bbCoverRose}bidi}%
                };

                \node[
                anchor=north west,
                text=bbCoverCream,
                text width=.81\paperwidth,
                font=\bbCoverFont\fontsize{23}{31}\selectfont
                ] at (.09,.675) {An extension to Babel's\\bidirectional support};

                % Opposing directions; both arrows share the content grid.
                \node[bb cover label,anchor=base west,text=bbCoverCream]
                at (.09,.535) {LEFT TO RIGHT};
                \draw[bb cover arrow,draw=bbCoverCream]
                (.09,.51) -- (.90,.51);
                \draw[bb cover arrow,draw=bbCoverRose]
                (.90,.445) -- (.09,.445);
                \node[bb cover label,anchor=base east,text=bbCoverRose]
                at (.90,.415) {RIGHT TO LEFT};

                % Scope, deliberately separate from the release information.
                \node[
                anchor=north west,
                text=bbCoverInk,
                text width=.81\paperwidth,
                font=\bbCoverFont\fontsize{12}{19}\selectfont
                ] at (.09,.31) {%
                    Text direction \enspace\textperiodcentered\enspace
                    Bidirectional layout \enspace\textperiodcentered\enspace
                    Language selection \enspace\textperiodcentered\enspace
                    Font configuration
                };

                % Two-column metadata, aligned by label and value baselines.
                \node[bb cover label,anchor=base west,text=bbCoverInk]
                at (.09,.225) {VERSION};
                \node[bb cover label,anchor=base west,text=bbCoverInk]
                at (.55,.225) {MAINTAINER};

                \node[
                anchor=base west,
                text=bbCoverInk,
                font=\bbCoverFont\fontsize{20}{25}\selectfont
                ] at (.09,.175) {\pkgmeta[version]{babelbidi}};
                \node[
                anchor=base west,
                text=bbCoverInk,
                font=\bbCoverFont\fontsize{15}{21}\selectfont
                ] at (.55,.175) {Amer Amikhteh};
                \node[
                anchor=base west,
                text=bbCoverInk,
                font=\bbCoverFont\fontsize{10}{14}\selectfont
                ] at (.09,.14) {\dmc{babelbidi}{long}};

                % Quiet footer separator and compact technical information.
                \draw[bbCoverInk,opacity=.25,line width=.4pt]
                (.09,.12) -- (.90,.12);
                \node[
                anchor=base west,
                text=bbCoverInk,
                font=\bbCoverFont\fontsize{10}{14}\selectfont
                ] at (.09,.09) {%
                    Lua\TeX (recommended)
                    \enspace\textperiodcentered\enspace Xe\TeX
                    \enspace\textperiodcentered\enspace pdf\TeX
                };
                \node[
                anchor=base west,
                text=bbCoverInk,
                font=\bbCoverFont\fontsize{10}{14}\selectfont
                ] at (.09,.05) {%
                    \href{https://github.com/gambi-shah/babelbidi}
                    {github.com/gambi-shah/babelbidi}%
                };
            \end{scope}
        \end{tikzpicture}%
        \AmikhtehLogoCover\par
        \null
        \endgroup
    \end{titlepage}
    \hypersetup{pageanchor=true}

    \pagestyle{amikhteh-logo}
    \AmikhtehLogoFooterTitle{}

    \begin{abstract}
        The \textsf{babelbidi} package extends Babel's bidirectional
        support by correcting specific direction-sensitive behaviour
        and providing interfaces for text direction, layout, language
        selection, and font configuration. These include directional
        boxes and controls for footnotes, lists, bibliographies, margin
        notes, and columns, as well as Latin-language citations and
        language selection for verbatim text. The package also supplies
        targeted compatibility patches for commonly used packages.
        It works with Babel under \LuaTeX (recommended), \XeTeX, and
        \pdfTeX, in documents with either an LTR or RTL main language.
    \end{abstract}



    \AmikhtehLogoFooterTitle{\contentsname}
    \bbdManualContents
    \clearpage


    \section{Introduction}
    \label{sec:introduction}

    Babel is a powerful, long-established framework for multilingual
    typesetting and localisation in \LaTeX. It brings together language
    and script support, hyphenation, localised document conventions,
    language-specific fonts, and bidirectional typesetting, with support
    for pdf\LaTeX, \XeLaTeX, and \LuaLaTeX. Its broad language coverage
    and extensible language model make it a strong foundation for
    multilingual documents.

    Bidirectional documents can require additional control over
    direction-sensitive elements and their interaction with other
    packages. Footnotes, directional boxes, columns, and package-specific
    output are examples. \textsf{babelbidi} complements Babel in these
    areas, providing direction-control interfaces and targeted
    compatibility adjustments while retaining Babel's language and font
    configuration as the foundation. Babel's own APIs are used directly,
    not replaced by a parallel system.

    One motivation for \textsf{babelbidi} is to provide a reusable
    Babel-based foundation for \textsf{unipersian}. More broadly, the
    aim is to adapt familiar typesetting interfaces, including those
    from \textsf{XePersian}, so that they can be used with different
    languages in a consistent Babel workflow.

    The approach taken here is to build on Babel's language declarations
    and keep language selection distinct from direction control.
    This distinction allows a document to change direction without
    changing language, or to select a language together with its
    associated direction and fonts. Understanding which operation is
    needed is the starting point for using the interfaces in this guide.

    This guide assumes basic familiarity with \LaTeX and Babel's
    language declarations. Its organisation is intended to be familiar
    to readers of Babel's guide, without repeating the documentation of
    Babel's APIs. Begin with Sections~\ref{sec:installation}--\ref{sec:quick-start}
    to install the package and prepare a document. The remaining
    sections serve as a reference for configuration and individual
    interfaces; engine-specific requirements and limitations are
    explained where they apply.


    \section{Interfaces and Engine Support}
    \label{sec:interfaces-engine-support}

    The package provides the complete user-level interfaces of
    \textsf{bidi} and \textsf{luabidi}, together with language and font
    interfaces built around Babel. Language-aware commands use the
    document's configured languages; direction-only commands leave
    the active language unchanged.

    \subsection{Engine Support}
    \label{sec:engine-support}

    \LuaLaTeX, \XeLaTeX, and \pdfLaTeX are supported, with either an
    LTR or RTL main language. \LuaLaTeX is recommended for its broader
    capabilities and extensibility. \XeTeX uses the \textsf{bidi}
    backend for direction and layout interfaces; \LuaTeX and \pdfTeX
    use implementations supplied by \textsf{babelbidi}.

    The main engine-dependent capabilities are summarized below.
    Here, \texttt{Native} means that the feature is implemented
    by \textsf{babelbidi}, while \texttt{Via bidi} indicates
    that it is provided by \textsf{bidi}.

    \begin{center}
        \begin{tabularx}{\linewidth}{@{}Xlll@{}}
            \toprule
            Feature & \LuaTeX & \XeTeX & \pdfTeX \\
            \midrule
            Direction and layout interfaces
            & Native & Via \textsf{bidi} & Native \\

            Unicode font commands
            & Native & Native & -- \\

            Glyph fallback
            & Native & -- & -- \\

            Extra footnote layouts
            & Native & Via \textsf{bidi} & Native \\

            \textsf{minted} \texttt{textlang} and \texttt{textdir}
            & Native & Native & Native \\

            \textsf{minted} \texttt{chardir}
            & Native & -- & -- \\
            \bottomrule
        \end{tabularx}
    \end{center}

    The table describes interface availability, not identical
    implementations, output, or language coverage. Unicode font
    commands require suitable OpenType fonts and \textsf{fontspec}.
    With \pdfLaTeX, language support depends on suitable input and
    font encodings, fonts, and Babel language support. See also
    Section~\ref{sec:limitations}.

    \subsection{Interface Overview}
    \label{sec:interface-overview}

    The following table locates the main interface groups.
    Availability and behaviour depend on the engine as described
    in the referenced sections.

    \begin{center}
        \begin{tabularx}{\linewidth}{@{}Xl@{}}
            \toprule
            Interface group & Sections \\
            \midrule
            Text direction and directional boxes
            & \ref{sec:text-direction}, \ref{sec:boxes-positioning} \\
            Footnotes, title notes, and footnote rules
            & \ref{sec:footnotes} \\
            Citations, lists, bibliographies, cases, and counters
            & \ref{sec:citations}, \ref{sec:lists-cases-counters} \\
            Margin notes, columns, and table of contents
            & \ref{sec:margins-columns} \\
            Language switching, fonts, and Latin verbatim text
            & \ref{sec:language-fonts} \\
            Glyph fallback (\LuaTeX)
            & \ref{sec:font-fallback} \\
            Engine logos
            & \ref{sec:engine-logos} \\
            Package patches and \textsf{minted} options
            & \ref{sec:patches}, \ref{sec:minted} \\
            \bottomrule
        \end{tabularx}
    \end{center}

    \section{Obtaining and Installing}
    \label{sec:installation}

    \textsf{babelbidi} is distributed through CTAN:

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

    With \TeX~Live, install the package from a terminal
    or command prompt:

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

    \section{Loading}
    \label{sec:loading}

    Load the package with:

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

    Normally, \textsf{babelbidi} loads Babel and chooses a
    bidirectional backend for the current engine. With \LuaLaTeX
    and \textsf{beamer-rl}, the class handles Babel setup instead.
    Options not recognized by \textsf{babelbidi} are forwarded to
    Babel. In particular, \texttt{bidi} and \texttt{layout} are Babel
    options with engine-dependent defaults supplied by this package.

    With \XeLaTeX, load \textsf{hyperref} before \textsf{babelbidi}
    if hyperlinks are needed; see Section~\ref{sec:xelatex-patches}.

    \Needspace{10\baselineskip}
    \Describe{bidi}{=\meta{value}}
    Selects the bidirectional backend. If it is not specified,
    its default value is selected according to the engine:

    \begin{center}
        \begin{tabular}{@{}ll@{}}
            \toprule
            Engine & Default value of \texttt{bidi} \\
            \midrule
            \LuaTeX & \texttt{basic} \\
            \XeTeX & \texttt{bidi-r} \\
            \pdfTeX & \texttt{default} \\
            \bottomrule
        \end{tabular}
    \end{center}

    \Describe{layout}{=\meta{selectors}}
    With \LuaTeX, the default value is:

    \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}. To retain
    \texttt{graphics} and \texttt{lists}, include them explicitly. Values
    containing multiple selectors must be enclosed in braces. The package
    applies this \texttt{layout} setting only with \LuaTeX; it has no
    effect in the \XeTeX and \pdfTeX loading branches.

    For slides with an RTL main language, \textsf{beamer-rl} is
    recommended over \textsf{beamer}, although it is not required.

    With \LuaTeX, the boolean option
    \Describe{fontcache}{=\meta{true}/\meta{false}}
    controls caching of Babel font mappings used by automatic font
    selection and glyph fallback. It 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
    changes from taking effect. Disable the cache when needed:

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

    To enable paragraph and multi-column footnote layouts, use the
    following option:

    \Describe{extrafootnotefeatures}{=\meta{on}/\meta{off}}
    Its default is \texttt{off}. The option also accepts explicit
    \texttt{=on} and \texttt{=off} values:

    \begin{minted}{latex}
        \usepackage[extrafootnotefeatures]{babelbidi}
    \end{minted}

    With \XeTeX, it is passed to \textsf{bidi}; with \LuaTeX and
    \pdfTeX, \textsf{babelbidi} provides its own implementation. See
    Section~\ref{sec:footnote-layouts} for the available commands.

    \Describe{logostyle}{=\meta{auto}/\meta{simple}}
    Selects the engine-logo style. The default is \texttt{auto}.
    Use \texttt{simple} for non-reflected logos, even when
    \textsf{graphicx} is loaded. See Section~\ref{sec:engine-logos}.

    \section{Quick Start}
    \label{sec:quick-start}

    The following example works with \LuaLaTeX and \XeLaTeX
    and requires the fonts Latin Modern Roman and Amiri:

    \begin{minted}{latex}
        \documentclass{article}
        \usepackage{hyperref} % Load before babelbidi for XeLaTeX.
        \usepackage{babelbidi}

        \babelprovide[import,main]{english}
        \babelprovide[import]{arabic}

        \babelfont{rm}{Latin Modern Roman}
        \babelfont[arabic]{rm}{Amiri}

        \begin{document}
            English text with \rl{نص عربي}.

            \begin{otherlanguage}{arabic}
                نص عربي مع \lr{English text}.
            \end{otherlanguage}
        \end{document}
    \end{minted}

    The lowercase commands \cmd{\lr} and \cmd{\rl} select the configured
    LTR or RTL language, together with its direction and fonts. The
    uppercase commands \cmd{\LR} and \cmd{\RL} change direction only.
    Use the lowercase forms when the passage belongs to another
    language; use the uppercase forms when only its direction should
    change.

    With \LuaLaTeX, Babel's \texttt{onchar} option can automate
    language and font selection from the characters in the text.
    To enable this in the example, replace the Arabic declaration with:

    \begin{minted}{latex}
        \babelprovide[import,mapdigits,onchar=ids fonts letters]{arabic}
    \end{minted}

    Punctuation shared by several scripts, such as parentheses, may
    still require explicit language selection. Automatic selection
    does not remove the need to declare languages and assign suitable
    fonts.


    \section{Text Direction}
    \label{sec:text-direction}

    These interfaces change direction while leaving the active
    language unchanged. They do not select another language's fonts
    or conventions. For text in another language, use the interfaces
    in Section~\ref{sec:language-commands} or Babel's own language
    commands. Use inline forms within a paragraph and switches or
    environments for whole paragraphs.

    \subsection{Inline Text}
    \label{sec:inline-direction}

    \Describe{\beginL}{}
    Begins an explicit LTR text segment; it must be matched by
    \cmd{\endL}.

    \Describe{\endL}{}
    Ends the explicit LTR text segment.

    \Describe{\beginR}{}
    Begins an explicit RTL text segment; it must be matched by
    \cmd{\endR}.

    \Describe{\endR}{}
    Ends the explicit RTL text segment.

    \Describe{\LR}{\marg{text}}
    \DescribeOther{\LRE}{\marg{text}}
    Typesets the argument as inline LTR text. The two names are equivalent.

    \Describe{\RL}{\marg{text}}
    \DescribeOther{\RLE}{\marg{text}}
    Typesets the argument as inline RTL text. The two names are equivalent.

    Prefer the argument-taking commands for short passages.

    \subsection{Paragraphs and Blocks}
    \label{sec:paragraph-direction}

    \Describe{\setLTR}{}
    \DescribeOther{\setLR}{}
    \DescribeOther{\unsetRTL}{}
    These equivalent commands set paragraph direction to LTR.

    \Describe{\setRTL}{}
    \DescribeOther{\setRL}{}
    \DescribeOther{\unsetLTR}{}
    These equivalent commands set paragraph direction to RTL.

    The switches take no arguments; place them between paragraphs and use
    a group to limit their scope. End the final paragraph before closing
    the group.

    \Describe{\begin\menv{LTR}}{\Eenv{LTR}}
    \DescribeOther{\begin\menv{RTL}}{\Eenv{RTL}}
    The \texttt{LTR} environment typesets an enclosed block in LTR direction;
    \texttt{RTL} typesets it in RTL direction. The environments handle
    paragraph boundaries and may contain several paragraphs.

    \section{Boxes and Positioning}
    \label{sec:boxes-positioning}

    \subsection{Directional Boxes}
    \label{sec:directional-boxes}

    These are directional variants of \cmd{\hbox}, \cmd{\vbox}, and
    \cmd{\vtop}; the suffix selects LTR or RTL direction.

    \Describe{\hboxL}{}
    Creates a horizontal LTR box without line breaking.

    \Describe{\hboxR}{}
    Creates a horizontal RTL box without line breaking.

    \Describe{\vboxL}{}
    Creates a vertical LTR box with a bottom reference point.

    \Describe{\vboxR}{}
    Creates a vertical RTL box with a bottom reference point.

    \Describe{\vtopL}{}
    Creates a vertical LTR box with a top reference point.

    \Describe{\vtopR}{}
    Creates a vertical RTL box with a top reference point.

    Text in vertical boxes is broken into lines according to
    \cmd{\hsize}. For boxes containing lines of text, \cmd{\vbox}
    uses the last line's baseline and \cmd{\vtop} the first.

    Before the opening brace, \texttt{to <dimension>} sets the final
    width of a horizontal box or height of a vertical box;
    \texttt{spread <dimension>} adds to its natural size. Stretchable
    or shrinkable space adjusts to the requested size. Use \cmd{\setbox}
    to store a box and \cmd{\box} to insert it.

    \subsection{Overlapping Text}
    \label{sec:text-overlap}

    These direction-sensitive variants of \cmd{\llap} and \cmd{\rlap}
    place text in a zero-width box.

    \Describe{\bidillap}{\marg{text}}
    Overlaps text to the left in LTR text and to the right in RTL text.

    \Describe{\bidirlap}{\marg{text}}
    Overlaps text to the right in LTR text and to the left in RTL text.

    \section{Footnotes and Title Notes}
    \label{sec:footnotes}

    Footnote direction, rule appearance, and layout are separate
    settings. Choose an explicit command to direct one note, or a
    switch to set the direction of subsequent ordinary footnotes.
    Neither choice by itself changes the note's language.

    \subsection{Footnote Direction}
    \label{sec:footnote-direction}

    The \texttt{LTR} and \texttt{RTL} forms select the direction
    of the footnote text, not its language. Use Babel's language
    commands when a footnote also requires a different language
    or font.

    \Describe{\LTRfootnote}{\oarg{num}\marg{text}}
    Inserts a footnote whose text is set in LTR direction.

    \Describe{\RTLfootnote}{\oarg{num}\marg{text}}
    Inserts a footnote whose text is set in RTL direction.

    \Describe{\LTRfootnotetext}{\oarg{num}\marg{text}}
    Inserts LTR footnote text without a mark in the main text.

    \Describe{\RTLfootnotetext}{\oarg{num}\marg{text}}
    Inserts RTL footnote text without a mark in the main text.

    The optional \meta{num} has the same meaning as in
    \cmd{\footnote} or \cmd{\footnotetext}. The
    \cmd{\LTRfootnotetext} and \cmd{\RTLfootnotetext} commands
    do not insert a mark in the main text; use them with
    \cmd{\footnotemark} when a mark is needed.

    \Describe{\LTRthanks}{\marg{text}}
    Inserts a title note in LTR direction.

    \Describe{\RTLthanks}{\marg{text}}
    Inserts a title note in RTL direction.

    The title-note commands are counterparts of \cmd{\thanks}
    and can be used in the \cmd{\author} or \cmd{\title}
    argument.

    \Describe{\setfootnoteLR}{}
    \DescribeOther{\unsetfootnoteRL}{}
    These equivalent commands set subsequent ordinary footnotes to LTR.

    \Describe{\setfootnoteRL}{}
    \DescribeOther{\unsetfootnoteLR}{}
    These equivalent commands set subsequent ordinary footnotes to RTL.

    The switches insert no note and take no arguments. Their
    direction setting is local to the current group and remains
    active until changed. The \texttt{unset} forms select the
    opposite direction; they do not restore Babel's initial behaviour.

    Explicitly directed footnotes take precedence over the
    policy: for example, \cmd{\RTLfootnote} still produces
    an RTL footnote after \cmd{\setfootnoteLR}. Before a
    direction policy is selected, the existing Babel
    behaviour is retained.

    \subsection{Footnote Rules}
    \label{sec:footnote-rules}

    The controls below position and size the rule above the footnote
    area. They do not change the direction of the footnote text.

    \Describe{\leftfootnoterule}{}
    \DescribeOther{\LRfootnoterule}{}
    These equivalent commands select a left-aligned footnote rule.

    \Describe{\rightfootnoterule}{}
    \DescribeOther{\RLfootnoterule}{}
    These equivalent commands select a right-aligned footnote rule.

    \Describe{\textwidthfootnoterule}{}
    Selects a full-width footnote rule.

    \Describe{\autofootnoterule}{}
    Selects rule alignment according to footnote direction.
    Automatic alignment is engine-dependent:

    \begin{description}
        \item[\LuaTeX:]
        Inspect the direction of the first line in the ordinary footnote
        insertion box; use a left rule if no line is found.

        \item[\pdfTeX:]
        Use the first explicitly directed footnote recorded since the
        preceding shipout; use a left rule if none was recorded. This is
        a fallback, not an inspection of the final footnote box.

        \item[\XeTeX:]
        Use the implementation supplied by \textsf{bidi}.
    \end{description}

    \Describe{\footnoterulewidth}{}
    Length controlling the width of short footnote rules.
    With \LuaTeX and \pdfTeX, the initial short-rule width is
    \texttt{.4}\cmd{\columnwidth}, evaluated when the length is set.

    For example:

    \begin{minted}{latex}
        \setlength{\footnoterulewidth}{.3\columnwidth}
        \rightfootnoterule
    \end{minted}

    \Describe{\SplitFootnoteRule}{}
    Selects a full-width rule above a continued footnote.
    Select the ordinary rule before \cmd{\SplitFootnoteRule}. It retains
    that rule on ordinary pages and uses a full-width rule above a
    continuation from the preceding page.

    \Describe{\debugfootnotedirection}{}
    Enables direction messages when the automatic rule is evaluated.
    To diagnose automatic rule selection, use:

    \begin{minted}{latex}
        \autofootnoterule
        \debugfootnotedirection
    \end{minted}

    The \LuaTeX and \pdfTeX implementations provide no corresponding
    public command to disable these diagnostic messages. Remove the
    diagnostic command for normal runs.

    With \LuaTeX and \pdfTeX, rule selectors make global assignments.
    In RTL-main documents, the package selects a right-aligned default
    rule only if no replacement rule has already been selected. Extra
    footnote layouts change rule handling as described below.

    \subsection{Extra Footnote Layouts}
    \label{sec:footnote-layouts}

    The \texttt{extrafootnotefeatures} package option enables the
    layouts below. With \LuaTeX and \pdfTeX, they support page and
    minipage footnotes while preserving each note's language,
    direction, labels, and hyperlinks. The grouping and output-order
    restrictions described after the command list still apply.

    \Describe{\normalfootnotes}{\texttt{[*]}}
    Selects the ordinary one-column layout.

    \Describe{\paragraphfootnotes}{\texttt{[*]}}
    Selects paragraph layout.

    \Describe{\twocolumnfootnotes}{\texttt{[*]}}
    Selects a two-column layout.

    \Describe{\threecolumnfootnotes}{\texttt{[*]}}
    Selects a three-column layout.

    \Describe{\fourcolumnfootnotes}{\texttt{[*]}}
    Selects a four-column layout.

    \Describe{\fivecolumnfootnotes}{\texttt{[*]}}
    Selects a five-column layout.

    \Describe{\sixcolumnfootnotes}{\texttt{[*]}}
    Selects a six-column layout.

    \Describe{\sevencolumnfootnotes}{\texttt{[*]}}
    Selects a seven-column layout.

    \Describe{\eightcolumnfootnotes}{\texttt{[*]}}
    Selects an eight-column layout.

    \Describe{\ninecolumnfootnotes}{\texttt{[*]}}
    Selects a nine-column layout.

    \Describe{\tencolumnfootnotes}{\texttt{[*]}}
    Selects a ten-column layout.

    Each layout command accepts an optional star. Without it, the
    footnote mark occupies a fixed-width box; with it, the box uses the
    mark's natural width:

    \begin{minted}{latex}
        \twocolumnfootnotes*
    \end{minted}

    With \LuaTeX and \pdfTeX, paragraph and multi-column layouts
    collect RTL and LTR notes separately. Output begins with ordinary
    one-column footnotes, followed by the RTL group and then the LTR
    group. Within a multi-column group, columns run right to left for
    RTL notes and left to right for LTR notes. The visual order may
    therefore differ from the order of note references in the text.
    With \XeTeX, the layouts and their detailed behaviour are supplied
    by \textsf{bidi}.

    With \LuaTeX and \pdfTeX, a layout assignment is local, but the
    collected notes are assembled later. Select the layout in the
    preamble or at a page boundary, and keep it in force until the
    affected notes have been output. Do not combine separate paragraph
    and multi-column settings within the same pending stream.
    For a document-wide layout:

    \begin{minted}{latex}
        \usepackage[extrafootnotefeatures]{babelbidi}
        \twocolumnfootnotes
    \end{minted}

    With \LuaTeX and \pdfTeX, to change the layout in the body, flush
    the preceding page first:

    \begin{minted}{latex}
        \clearpage
        \paragraphfootnotes
    \end{minted}

    With \XeTeX, select \cmd{\paragraphfootnotes} in the preamble;
    its implementation in \textsf{bidi} requires preamble-only setup.

    With \LuaTeX and \pdfTeX, the extra-layout implementation installs
    a rule spanning \cmd{\columnwidth} and disables
    \cmd{\autofootnoterule}, \cmd{\leftfootnoterule},
    \cmd{\LRfootnoterule}, \cmd{\rightfootnoterule},
    \cmd{\RLfootnoterule}, and \cmd{\textwidthfootnoterule}.
    Calling \cmd{\normalfootnotes} does not restore these selectors.
    The rule spans the footnote area of the current document column,
    not an individual footnote column.

    \section{Citations}
    \label{sec:citations}

    \Describe{\Latincite}{\oarg{note}\marg{keys}}
    Works like the active \cmd{\cite}, but uses the selected Latin
    language and font for citation labels and their separators.
    An optional \meta{note} keeps the surrounding language and text
    direction. With standard \LaTeX citations, an Arabic comma
    (U+060C) precedes the note in RTL text; the surrounding font or
    a fallback font must provide this character. LTR text uses an
    ordinary comma. With \textsf{cite}, \textsf{natbib}, or
    \textsf{biblatex}, argument syntax and citation formatting follow
    the active \cmd{\cite}.

    \begin{minted}{latex}
        \Latincite{knuth}
        \Latincite[page 23]{knuth}
        \Latincite{knuth,lamport}
    \end{minted}

    \section{Lists, Cases, and Counters}
    \label{sec:lists-cases-counters}

    \subsection{Lists and Bibliographies}
    \label{sec:lists-bibliographies}

    Use these environments to direct a group of entries within an
    existing list or bibliography. They change entry direction but
    do not create the surrounding list or select another language.

    \Describe{\begin\menv{LTRitems}}{\Eenv{LTRitems}}
    \DescribeOther{\begin\menv{RTLitems}}{\Eenv{RTLitems}}
    The \texttt{LTRitems} environment sets the direction of the enclosed
    list items to LTR; \texttt{RTLitems} sets it to RTL.

    The environments group consecutive \cmd{\item} entries. They can
    be used inside lists such as \texttt{itemize} and \texttt{enumerate};
    they do not replace those environments.

    For example, a list can contain an RTL group between ordinary items:

    \begin{minted}{latex}
        \begin{itemize}
            \item The first item
            \begin{RTLitems}
                \item مورد دوم
                \item مورد سوم
            \end{RTLitems}
            \item The fourth item
        \end{itemize}
    \end{minted}

    \Describe{\begin\menv{LTRbibitems}}{\Eenv{LTRbibitems}}
    \DescribeOther{\begin\menv{RTLbibitems}}{\Eenv{RTLbibitems}}
    The \texttt{LTRbibitems} environment sets the direction of the enclosed
    bibliography entries to LTR; \texttt{RTLbibitems} sets it to RTL.

    Place these environments inside \texttt{thebibliography}, using
    \cmd{\bibitem}, not \cmd{\item}, for each entry. The following
    example directs one entry without changing the bibliography heading:

    \begin{minted}{latex}
        \begin{thebibliography}{9}
            \begin{LTRbibitems}
                \bibitem{knuth}
                Donald E. Knuth. \textit{The TeXbook}. 1984.
            \end{LTRbibitems}
        \end{thebibliography}
    \end{minted}

    Here, \texttt{9} reserves space for a single-digit label, and
    \texttt{knuth} is the key used by \cmd{\cite\{<knuth>\}}.

    To set the direction of all bibliography entries, use one of the
    following switches before \texttt{thebibliography} begins. The
    setting is local; the heading and running marks retain the
    surrounding direction.

    \Describe{\setLTRbibitems}{}
    Sets all bibliography entries to LTR direction.

    \Describe{\setRTLbibitems}{}
    Sets all bibliography entries to RTL direction.

    \Describe{\setdefaultbibitems}{}
    Restores the default bibliography-entry direction.

    \subsection{RTL Cases}
    \label{sec:cases}

    \Describe{\begin\menv{RTLcases}}{\Eenv{RTLcases}}
    Typesets two columns with a brace on the right. Cells use text mode:
    separate columns with \texttt{\&}, rows with \cmd{\\}, and enclose
    mathematics in \texttt{\$...\$}.

    \begin{minted}{latex}
        \begin{RTLcases}
            $x$  & $x \geq 0$ \\
            $-x$ & $x < 0$
        \end{RTLcases}
    \end{minted}

    \subsection{Counter Separators}
    \label{sec:counter-separators}

    With \XeTeX, \cmd{\SepMark} is provided by
    \textsf{bidi}; its counter-formatting behaviour follows
    that implementation.

    \Describe{\SepMark}{\marg{separator}}
    Globally sets the separator in supported compound counters;
    the default is a period. With \LuaTeX~
    and \pdfTeX, the patch replaces a period immediately following the
    parent counter in standard sectioning formats, chapter-based
    equation, figure, and table numbers, and formats created by
    unstarred \cmd{\numberwithin}. It also sets the theorem-counter
    separator.

    This is not a general replacement of punctuation in counter
    definitions. Custom formats without the expected parent-counter
    pattern are left unchanged. Other formatting, including Babel's
    localized digits, is retained.

    \section{Margins and Columns}
    \label{sec:margins-columns}

    \subsection{Margin Notes}
    \label{sec:margin-notes}

    Use an explicit command to direct a single note. Use a switch to
    configure subsequent ordinary \cmd{\marginpar} calls. Text
    direction and margin placement are related but distinct settings.

    \Describe{\LTRmarginpar}{\oarg{left-text}\marg{right-text}}
    Inserts a margin note with LTR text.

    \Describe{\RTLmarginpar}{\oarg{left-text}\marg{right-text}}
    Inserts a margin note with RTL text.

    The optional \meta{left-text} argument has the same meaning as in
    \cmd{\marginpar}: alternative text for the left margin.
    Explicit commands change the note's text direction, not its
    placement policy.

    With \XeTeX, these explicit commands use the native
    \textsf{bidi} implementation, which may apply the
    explicit direction only to the first paragraph
    of a multi-paragraph margin note. With \LuaTeX
    and \pdfTeX, \textsf{babelbidi} keeps the selected
    direction throughout the note.

    \Describe{\setLTRmarginpar}{}
    Sets ordinary margin notes to LTR direction and placement.

    \Describe{\setRTLmarginpar}{}
    Sets ordinary margin notes to RTL direction and placement.

    \Describe{\setdefaultmarginpar}{}
    Restores behaviour based on the surrounding text direction.

    For ordinary \cmd{\marginpar} commands, the direction
    switches apply when no optional left-hand text is supplied.
    With the optional form, the surrounding text direction
    is retained. The switches are local; page parity,
    reversed margins, and document columns still participate
    in placement. By default, ordinary margin notes follow the
    surrounding text direction.

    \subsection{Two-Column Output}
    \label{sec:two-column-output}

    These commands choose the placement order of completed document
    columns. They neither enable two-column mode nor change the
    direction of text within a column.

    \Describe{\LTRdblcol}{}
    Places the first column on the left.

    \Describe{\RTLdblcol}{}
    Places the first column on the right.

    The default order follows the main document direction. For
    multi-column footnotes, see Section~\ref{sec:footnote-layouts}.

    \subsection{Two-Column Table of Contents}
    \label{sec:two-column-toc}

    \Describe{\twocolumnstableofcontents}{}
    Typesets the table of contents in two columns, with a full-width
    section heading and \cmd{\small} entries. It takes no arguments
    and does not change the current language or direction. Load
    \textsf{multicol} in the preamble.

    \section{Language and Font APIs}
    \label{sec:language-fonts}

    These interfaces use languages selected from the document's Babel
    configuration. ``Latin'' identifies an auxiliary Latin-script
    language, which need not be English. The main text language and
    its fonts are also taken from that configuration. The
    \texttt{latin}, \texttt{ltr}, \texttt{rtl}, and \texttt{code}
    selections serve different purposes; their defaults and explicit
    settings are described in Section~\ref{sec:language-selection}.

    \subsection{Font Selection}
    \label{sec:font-selection}

    These font commands are available with \XeLaTeX and \LuaLaTeX.
    Optional font features use \textsf{fontspec} syntax. Declare the
    relevant Babel language before assigning its fonts.

    \Describe{\settextfont}{\oarg{font features}\marg{font}}
    Sets the same font and font features for the \texttt{rm},
    \texttt{sf}, and \texttt{tt} families of the main language.

    \Describe{\setlatintextfont}{\oarg{font features}\marg{font}}
    Sets the same font and font features for all three font families
    of the selected Latin language.

    These two commands apply the same font and font features to all
    three families (\texttt{rm}, \texttt{sf}, and \texttt{tt}).
    For individual language--family assignments, use
    \cmd{\babelfont} directly.

    \Describe{\latinfont}{}
    Selects the roman font for the selected Latin language,
    without changing the current language or direction.
    Use a group to limit its scope:
    \texttt{\{\cmd{\latinfont} Latin text\}}.

    \Describe{\deflatinfont}{\marg{command}\oarg{font features}\marg{font}}
    Defines an independent font-family command with
    \texttt{Script=Latin}. Additional font features can be
    specified in the optional argument. This command does not
    register a font with Babel or select a language.

    \Describe{\setlatinsansfont}{\oarg{font features}\marg{font}}
    Sets the sans-serif font family for the selected Latin language.

    \Describe{\setlatinmonofont}{\oarg{font features}\marg{font}}
    Sets the monospaced font family for the selected Latin language
    and configures it for use by \cmd{\latinttfamily}.

    \Describe{\setmonofont}{\oarg{font features}\marg{font}\oarg{font features}}
    Sets the document's monospaced font through \textsf{fontspec}.
    When Babel is loaded, it also registers this font for the
    \texttt{tt} family of the main language, making it available
    to \LuaTeX glyph fallback.


    \subsection{Font Fallback}
    \label{sec:font-fallback}

    Glyph fallback supplies a character from another language's font
    when the current font lacks it. It is available with \LuaLaTeX
    and uses the fonts registered with Babel. Declare an ordered
    fallback chain in the preamble:

    \Describe{\fontfallback}{\marg{source}\marg{candidates}}
    Declares an ordered list of candidate languages whose fonts can
    provide missing glyphs for the source language.

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

    The source and candidate languages must be known to Babel,
    and their fonts must be declared with \cmd{\babelfont}.
    These declarations should be made in the preamble.
    The \cmd{\fontfallback} declaration may precede them;
    fallback mappings are resolved when the document begins.

    Fallback is a font operation, not a language switch. It applies
    to text fonts, including custom families, but not to math fonts.
    It works with or without \texttt{onchar=fonts} and 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 source or candidate languages produce warnings.
    Repeated candidates and self-references are ignored. Fallback is not recursive
    and is applied per glyph before shaping. If no candidate contains a
    glyph, it remains in the original font. Combining-mark placement,
    joining, and visual consistency across fonts are not guaranteed;
    choose compatible fonts for the scripts involved. \XeLaTeX and
    \pdfLaTeX warn and ignore explicit fallback declarations.



    \subsection{Language Commands}
    \label{sec:language-commands}

    The lowercase commands \cmd{\lr} and \cmd{\rl} select a Babel
    language and its associated direction. Use them when the passage
    requires that language context, rather than a direction change
    alone. The uppercase \cmd{\LR} and \cmd{\RL} leave the active
    language unchanged.

    \Describe{\lr}{\marg{text}}
    Typesets text using the selected LTR language.

    \Describe{\rl}{\marg{text}}
    Typesets text using the selected RTL language.

    \Describe{\latintoday}{}
    Prints the current date using the selected Latin language.

    \Describe{\latinttfamily}{}
    Selects the Latin monospaced font family; Unicode engines only.

    \Describe{\latinverb}{\meta{delimiter}\meta{text}\meta{delimiter}}
    Typesets inline verbatim text in the selected \texttt{code} language.

    \Describe{\latinverb*}{\meta{delimiter}\meta{text}\meta{delimiter}}
    Does the same, with visible spaces.

    Despite its name, \cmd{\latinverb} selects the \texttt{code}
    language, not the \texttt{latin} alias.

    \subsection{Language Environments}
    \label{sec:language-environments}

    \Describe{\begin\menv{latin}}{\Eenv{latin}}
    Typesets contents in the selected Latin language.

    \Describe{\begin\menv{latinverbatim}}{\Eenv{latinverbatim}}
    \DescribeOther{\begin\menv{latinverbatim*}}{\Eenv{latinverbatim*}}
    The \texttt{latinverbatim} environment typesets a verbatim block in the
    selected \texttt{code} language. The starred form does the same, with
    visible spaces.

    The Latin verbatim interfaces are available regardless of the
    main script.

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

    The following package keys assign Babel languages to the roles
    used by the language, font, citation, and verbatim interfaces:

    \Describe{latin}{=\meta{language}}
    Selects the language for the \texttt{latin} environment,
    \cmd{\latintoday}, \cmd{\latinttfamily}, \cmd{\latinfont}, \cmd{\Latincite}, and Latin font commands.

    \Describe{ltr}{=\meta{language}}
    Selects the language used by \cmd{\lr}.

    \Describe{rtl}{=\meta{language}}
    Selects the language used by \cmd{\rl}.

    \Describe{code}{=\meta{language}}
    Selects the language for Latin verbatim interfaces and
    code-package integration.

    These keys name languages; they do not declare or load them.
    Declare each selected language through Babel before using the
    corresponding interface. For example:

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

    A role without an explicit setting is chosen automatically and
    reconsidered after each \cmd{\babelprovide} call. An explicit
    setting remains fixed. The automatic choices follow these rules:

    \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 LTR; otherwise, the first loaded LTR
        language; otherwise, \texttt{english}.

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

        \item[\texttt{code}:]
        The main language if it uses the Latin script; otherwise,
        loaded \texttt{english}; otherwise, the first loaded Latin-script
        language; otherwise, the main or first loaded LTR language;
        finally, the main language. If the main language is Babel's
        \texttt{nil} placeholder, the final fallback is \texttt{english}.
    \end{description}

    Selections use Babel's language metadata and loading order. Ensure
    that a selected language is declared before using it, including a
    default such as \texttt{english} or \texttt{arabic}. Declare
    languages before configuring their fonts.

    \Needspace{11\baselineskip}
    These selections are handled by \textsf{babelbidi-lang}, which
    \textsf{babelbidi} loads automatically. For standalone use, load
    Babel first:

    \begin{minted}{latex}
        \usepackage[english]{babel}
        \usepackage{babelbidi-lang}
    \end{minted}

    The standalone package provides \cmd{\lr}, \cmd{\rl},
    \cmd{\latintoday}, and the \texttt{latin} environment, and accepts
    the language-selection keys above. Configure Babel's languages,
    direction support, and fonts as needed.



    \section{Engine Logos}
    \label{sec:engine-logos}

    \begingroup
    \newcommand*\LogoName[1]{%
        {\normalfont\normalsize\ttfamily\color{thegreyed}%
            \underline{\strut{\color{thered}\string#1}}}%
    }

    \par\medskip
    \noindent\hspace*{-1.7cm}%
    \begin{tabular*}{\dimexpr\linewidth+1.7cm\relax}
        {@{\extracolsep{\fill}}lll@{}}
        \LogoName{\TeX}
        & \LogoName{\LaTeX}
        & \LogoName{\LaTeXe} \\

        \LogoName{\XeTeX}
        & \LogoName{\LuaTeX}
        & \LogoName{\pdfTeX} \\

        \LogoName{\XeLaTeX}
        & \LogoName{\LuaLaTeX}
        & \LogoName{\pdfLaTeX}
    \end{tabular*}
    \par\medskip
    \endgroup


    These commands typeset the corresponding logos, preserving
    the surrounding language and direction. With \textsf{babelbidi},
    they locally use English or the selected Latin language,
    when available.

    All logos use \verb|\xspace| for automatic spacing.
    Append \verb|{}| for explicit control, as in
    \verb|\LaTeX{}-based|.

    The default \texttt{logostyle=auto} uses graphics-based
    variants when \textsf{graphics} or \textsf{graphicx} is loaded
    before \textsf{babelbidi}. Use \texttt{logostyle=simple}
    for variants without reflected letters. This option does
    not affect the standard \TeX, \LaTeX, and \LaTeXe constructions.

    For standalone use, load \textsf{babelbidi-logos} directly,
    with \texttt{style=auto} or \texttt{style=simple}.

    \section{Patches}
    \label{sec:patches}

    Patches are installed automatically when the relevant engine and
    packages are present. Load the affected packages in the preamble.
    The code-package integrations support loading their packages
    before or after \textsf{babelbidi}.

    \subsection{Common Patches}
    \label{sec:common-patches}

    \begin{itemize}
        \item
        \textbf{\LaTeX verbatim interfaces:}
        With a non-Latin main script, adjust direction and font handling
        for \cmd{\verb}, \cmd{\verb}\texttt{*}, \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 script, select the \texttt{code} language
        for display and inline listings, with direction handling for
        inline listings.

        \item
        \textsf{minted}:
        Register the options described in Section~\ref{sec:minted} for
        both Latin and non-Latin main scripts. Additional display wrappers
        are installed for non-Latin main scripts.

        \item
        \textbf{Labels and link targets:}
        Remove Babel counter-direction wrappers while constructing label
        keys and hyperlink target names, without removing them from
        displayed counter values.
    \end{itemize}

    \subsection{\texorpdfstring{\XeLaTeX}{XeLaTeX} Patches}
    \label{sec:xelatex-patches}

    With \XeLaTeX, load \textsf{hyperref} before \textsf{babelbidi}.
    With current \textsf{bidi} versions, the reverse order can cause
    errors in footnotes.

    \begin{itemize}
        \item
        \textsf{natbib}:
        Adjust citation-link handling in RTL text with recent
        \textsf{hyperref} versions.

        \item
        \textsf{fontspec}:
        Disable its automatic math-font setup when Babel bidi mode is
        active. This is not a general mathematics-direction patch.
    \end{itemize}

    \subsection{\texorpdfstring{\LuaLaTeX}{LuaLaTeX} Patches}
    \label{sec:lualatex-patches}

    \begin{itemize}
        \item
        \textbf{Boxes and tables:}
        Adjust \cmd{\makebox} positioning and interchange the handling of
        \texttt{l} and \texttt{r} alignment in RTL contexts. The table
        patch changes cell alignment, not the declared column sequence.

        \item
        \textbf{Footnotes:}
        Adjust paragraph direction in RTL contexts and handle footnotes
        issued in mathematics in RTL-main documents.

        \item
        \textsf{beamer}:
        Adjust rounded-box layout, except with \textsf{beamer-rl}.
    \end{itemize}

    For RTL-main documents, additional \LuaLaTeX patches apply:

    \begin{itemize}
        \item
        \textbf{TikZ:}
        Use LTR paragraph direction inside \texttt{tikzpicture}, except
        with \textsf{beamer-rl}.

        \item
        \textsf{fancyhdr}:
        Set \cmd{\headheight} to \texttt{1.2em} and wrap headers and
        footers in LTR runs. This value is not an automatic measurement
        of the header contents.
    \end{itemize}

    \section{Minted Package}
    \label{sec:minted}

    Load \textsf{minted} in the preamble and satisfy the external-tool
    requirements documented in its manual:

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

    The options in this section are extensions supplied by
    \textsf{babelbidi}, not standard \textsf{minted} options. They
    are available with both Latin and non-Latin main scripts. Select
    the language and direction separately from the syntax-highlighting
    lexer.

    \subsection{Language and Direction}
    \label{sec:minted-language-direction}

    \Describe{textlang}{=\meta{language}}
    Selects an already declared Babel language. If it is empty,
    the selected \texttt{code} language is used.

    \Describe{textdir}{=\meta{direction}}
    Accepts \texttt{ltr} or \texttt{rtl}. It is applied after
    language selection, so an explicit direction overrides the
    direction established by \texttt{textlang}.

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

    The language \texttt{persian} must already be declared and have a
    suitable font. The argument \texttt{text} above is the \textsf{minted}
    lexer, not the Babel language. Defaults can also be set with
    \cmd{\setminted}:

    \begin{minted}{latex}
        \setminted{textlang=english,textdir=ltr}
    \end{minted}

    \subsection{Character Directions}
    \label{sec:minted-character-directions}

    With \LuaLaTeX, the following option temporarily changes Babel
    character-direction properties:

    \Describe{chardir}{=\meta{pairs}}
    Accepts a comma-separated list of \texttt{\{character\}\{direction\}}
    pairs. Direction values include \texttt{l}, \texttt{r}, \texttt{al},
    \texttt{en}, \texttt{an}, \texttt{on}, \texttt{et}, and \texttt{cs}.

    For example, assign LTR direction to a backslash and closing brace:

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

    Saved properties are restored after the \texttt{minted} environment.
    The restoration hook is environment-based; do not assume equivalent
    restoration for inline commands or file-input interfaces. A nonempty
    \texttt{chardir} value raises an error with \XeLaTeX or \pdfLaTeX;
    it is not silently ignored.

    \subsection{Layout}
    \label{sec:minted-layout}

    Inside \texttt{minted} environments, line numbers use Latin digits.
    With \LuaLaTeX, frame lines and padding receive LTR geometry
    adjustments. For a non-Latin main script, the additional \LuaLaTeX
    display wrapper uses a minipage. Such wrapped displays cannot break
    across pages; keep this in mind for long listings.

    \Needspace{15\baselineskip}
    \section{Limitations and Compatibility}
    \label{sec:limitations}

    \begin{itemize}
        \item
        Interface compatibility does not guarantee identical output
        across engines. The \XeTeX implementations also depend on
        the installed \textsf{bidi} version.

        \item
        Direction control does not supply language data, input or
        font encodings, fonts, or missing glyphs. Some patches rely
        on Babel or other packages' internals. Inspect the resulting
        PDF, particularly when other packages also modify layout;
        a successful compilation is not a bidirectional-layout check.

        \item
        Extra footnote layouts modify insertion and output handling.
        Check their compatibility with classes or packages that
        modify these mechanisms, including the position and order of
        notes. See Section~\ref{sec:footnote-layouts} for the
        engine-specific behaviour and restrictions.
    \end{itemize}

    \section{License}
    \label{sec:license}

    The \textsf{babelbidi} package is released under the
    \LaTeX Project Public License (LPPL), version 1.3c or later. The full
    license text is available in the \texttt{LICENSE} file.
    This independent guide adapts presentation code from the Babel
    manual. Source and copyright notices for this and other reused
    material are in
    \href{https://github.com/gambi-shah/babelbidi/blob/main/THIRD-PARTY-NOTICES.md}
    {\texttt{THIRD-PARTY-NOTICES.md}}.

    \section{Author and Maintainer}
    \label{sec:author}

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

    Source code, development versions, and the issue tracker are
    available in the project repository:

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

    The repository also contains test documents in the
    \href{https://github.com/gambi-shah/babelbidi/tree/main/test}
    {\texttt{test/}} directory. These development files are not
    included in the CTAN distribution.

   Please report bugs on the
   \href{https://github.com/gambi-shah/babelbidi/issues}
   {project's GitHub issue tracker}
   and include:
   \begin{enumerate}
       \item A small, complete example that reproduces the problem.
       \item The \textsf{babelbidi} and Babel versions, and the
       \TeX engine used (with its version, if known).
       \item A brief description of the expected and actual results,
       with any error message or a screenshot of the affected output.
   \end{enumerate}




\end{document}
