% !TeX spellcheck = en_US
% !TeX TS-program = lualatex
\documentclass[11pt]{ltxdoc}
\usepackage{color}
\usepackage{xspace,fancyvrb,booktabs}
\usepackage[neverdecrease]{paralist}
\definecolor{myblue}{rgb}{0.02,0.04,0.48}
\definecolor{lightblue}{rgb}{0.61,.8,.8}
\definecolor{myred}{rgb}{0.65,0.04,0.07}
\usepackage[
unicode=true,
bookmarks=true,
colorlinks=true,
linkcolor=myblue,
urlcolor=myblue,
citecolor=myblue,
hyperindex=false,
hyperfootnotes=false,
pdftitle={luabidi: Bidirectional typesetting in LuaLaTeX},
pdfauthor={V Khalighi, U Fogiel, A Reutenauer, J Spitzmüller},
pdfkeywords={luatex, lualatex, multilingual, bidi}
]{hyperref}
\usepackage{metalogo}
%\let\XeTeX\undefined
%\let\XeLaTeX\undefined
\usepackage{polyglossia}
\usepackage{luabidi}
\directlua{luatexbase.remove_from_callback("post_mlist_to_hlist_filter","luabidi.ensure_math_dir")}

\setmainlanguage{english}
\usepackage[protrusion]{microtype}
\partokencontext=0
\newcommand*\Cmd[1]{\cmd{#1}\DescribeMacro{#1}\xspace}
\newcommand*{\cscmd}[1]{\texttt{\textbackslash #1}}
\newcommand*\pkg[1]{\textsf{\color{myblue}#1}}
\newcommand*\file[1]{\texttt{\color{myblue}#1}}
\newcommand*\TR[1]{\textcolor{myred}{#1}}
\newcommand*\TX[1]{\hyperref[#1]{\textcolor{myred}{#1}}}
\newcommand*\TB[1]{\textcolor{myblue}{\bf #1}}
\newcommand*\TA[1]{\textsc{\color{myblue}#1}}
\newcommand*\link[1]{\href{#1}{#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}}

%% Sidenotes  << copied from fontspec.dtx
\newcommand\new[1]{%
	\edef\thisversion{#1}%
	\ifhmode\unskip~\fi{\ifx\thisversion\fileversion\color{blue}\else\color[gray]{0.5}\fi
		$\leftarrow$}%
	\marginpar{\centering
		\small\ifx\thisversion\fileversion\color{blue}\else\color[gray]{0.5}\fi
		\textsf{#1}}}
\newcommand\displaycmd[2]{%
	\\\DescribeMacro{#2}\centerline{\cmd{#1}}}
\renewenvironment{itemize}{\begin{compactitem}[\char"2023]}%[{\fontspec{DejaVu Sans}\char"25BB}]}%
	{\end{compactitem}}

\def\condbreak#1{%
	\vskip 0pt plus #1\pagebreak[3]\vskip 0pt plus -#1\relax}

\newcommand*\lbd{\pkg{luabidi}}
\newcommand*\Lbd{\pkg{Luabidi}}

%% fontspec declarations:
\setmainfont{Linux Libertine O}
\setsansfont{Linux Biolinum O}
\setmonofont[Scale=MatchLowercase]{DejaVu Sans Mono}

\linespread{1.05}
\frenchspacing
\EnableCrossrefs
\CodelineIndex
\RecordChanges
% COMMENT THE NEXT LINE TO INCLUDE THE CODE
\AtBeginDocument{\OnlyDescription}


\begin{document}
\hyphenation{Kha-li-ghi Reu-ten-auer}
\GetFileInfo{luabidi.sty}

\title{\lbd\\\color{myblue}Bidirectional typesetting in \LuaLaTeX}

\date{\color{myblue}\filedate \qquad \fileversion\\
	\footnotesize (\textsc{pdf} file generated on \today)}

\author{\TA{Vafa Khalighi} \and \TA{Udi Fogiel} \and \TA{Arthur Reutenauer}
	    \and \TA{Jürgen Spitzmüller}\thanks{%
	    Please submit bug reports and feature requests to \protect\url{https://codeberg.org/polyglossia/luabidi/issues}.}}

\maketitle

\DeleteShortVerb{\|}
\MakeShortVerb{\¦}

\tableofcontents

\condbreak{2\baselineskip}
\section{Objectives}
\Lbd\ is an attempt to provide bidirectional writing support for the \LuaTeX\ engine in the same vein as the \pkg{bidi} package\footnote{%
See \url{https://ctan.org/pkg/bidi}.} enables bidirectional writing with \XeTeX. The most prominent user of this package is \pkg{polyglossia}\footnote{%
See \url{https://ctan.org/pkg/polyglossia}.} which uses \lbd\ with RTL languages and \LuaTeX\ output (as opposed to \pkg{bidi} with \XeTeX).

The package tries to do so with the least amount of patches needed, and thus does not patch counters to be displayed correctly.
If you want short LTR text, such as arabic numbers, which are hidden inside other macros and cannot be marked explicitly
to have correct direction you can use the \pkg{unibidi-lua}\footnote{See \url{https://ctan.org/pkg/unibidi-lua}.} package
which implements the unicode bidirectional algorithm.

\section{Package Options}

\begin{description}
	\item[\TB{arabmaths}] By default, \lbd\ generates left-to-right maths. If you would like to have right-to-left maths, use this option.
	\item[\TB{textwidthfootnoterule}] expands the footnote rule to the whole text width.
	\item[\TB{autofootnoterule}] sets the footnote rule right or left aligned, depending on the direction of the first footnote
	that follows the rule (\ie that comes on the current page).
\end{description}

\section{User Commands}

\subsection{Main Text Direction}

By default, the main directionality of the document is left-to-right. To change it to right-to-left, use the switch

\begin{quote}
	\Cmd\setRTLmain
\end{quote}
%
This is advisable if your document consists mainly of right-to-left text.

\subsection{Paragraph Text Direction}

To change directionality for paragraphs, you can use the following switches:
\begin{description}
	\item[\cmd{\setRTL}]\DescribeMacro{\setRTL} (alias: \Cmd{\setRL}, \Cmd{\unsetLTR}) changes paragraph direction to right-to-left.
	\item[\cmd{\setLTR}]\DescribeMacro{\setLTR} (alias: \Cmd{\setLR}, \Cmd{\unsetRTL}) changes paragraph direction to left-to-right.
\end{description}
%
\condbreak{2\baselineskip}
Alternatively,\DescribeMacro{RTL}\DescribeMacro{LTR} you can also use the environments

\begin{quote}
	\begin{verbatim}
	\begin{RTL}
		...
	\end{RTL}
	\end{verbatim}
\end{quote}
%
or

\begin{quote}
	\begin{verbatim}
	\begin{LTR}
	...
	\end{LTR}
	\end{verbatim}
\end{quote}

\subsection{Inline Text Direction}

To change directionality for text chunks inside paragraphs, use
\begin{description}
	\item[\cmd\RLE\{...\}]\DescribeMacro{\RLE} (alias: \Cmd\RL) changes the directionality locally to right-to-left.
	\item[\cmd\LRE\{...\}]\DescribeMacro{\LRE} (alias: \Cmd\LR) changes the directionality locally to left-to-right.
\end{description}

\subsection{Footnotes}

\subsubsection{Horizontal Footnote Position}

\Lbd\ provides two additional footnote commands in addition to standard \cmd{\footnote}:
\Cmd{\RTLfootnote}\new{v0.5} and \Cmd{\LTRfootnote}\new{v0.5}.
The standard \cmd{\footnote} command thereby places the footnote always on the side that is currently the origin of direction:
on the left side of the page in LTR paragraphs and on the right in RTL paragraphs.

\cmd{\LTRfootnote}, in contrast, always places the footnote on the left side, notwithstanding the current
directionality. \cmd{\RTLfootnote} always places it on the right side. Like \cmd{\footnote}, \cmd{\RTLfootnote}
and \cmd{\LTRfootnote} have an optional argument to customize the number.


\subsubsection{Footnote Rule Length and Position}

By default, the placement of the footnote rule depends on the main text directionality:

\begin{itemize}
	\item In default mode (\ie if \cmd{\setRTLmain} is not used), the footnote rule is always set left-aligned (as usual in LTR documents).
	\item If the main direction is RTL (\ie if \cmd{\setRTLmain} is used), the footnote rule is always set right-aligned (as usual in RTL documents)
\end{itemize}
%
However, with the switch \Cmd{\leftfootnoterule}\new{v0.5}, all subsequent footnote rules are always placed on the left.
Likewise, \Cmd{\rightfootnoterule}\new{v0.5} causes all subsequent footnote rules to be always placed on the right.

The switch \Cmd{\autofootnoterule}\new{v0.5} and the corresponding package option advise \lbd\ to automatically determine the rule position,
depending on the directionality of the first footnote on the page.

If you want a footnote rule that spans the whole text width, you can use the switch \Cmd{\textwidth\-footnoterule}\new{v0.5}
or the respective package option.

The length of left and right footnote rules can be adjusted via

\begin{quote}
  ¦\setlength\footenoterulewidth{⟨length⟩}¦\DescribeMacro{\footenoterulewidth}
\end{quote}
%
The predefined ¦⟨length⟩¦ is ¦0.4\columnwidth¦.


\section{Commands for Package Authors}

The following tests are provided to be used in packages:

\begin{description}
	\item[\cscmd{if@RTL}]\DescribeMacro{\if@RTL} determines whether the current paragraph direction is right-to-left.
	\item[\cscmd{if@RTLmain}]\DescribeMacro{\if@RTLmain} determines whether the main direction is right-to-left.
\end{description}
%
The following macros are provided:
\begin{description}
    \item[\cscmd{hboxR\{...\}}]\DescribeMacro{\hboxR}\new{v0.5} Puts the material between \{ and \} in a RTL \cmd{\hbox}.
    It is similar to ¦\hbox bdir 1¦ but also set ¦\if@RTL¦. An explicit opening brace
    is needed, it cannot be used with ¦\bgroup¦, but verbatim can be used inside.
    \item[\cscmd{hboxL\{...\}}]\DescribeMacro{\hboxL}\new{v1.0} Similar to \cmd{\hboxR} but with LTR \cmd{\hbox}.
    \item[\cscmd{vboxR\{...\}}]\DescribeMacro{\vboxR}\new{v1.0} Similar to \cmd{\hboxR} but with \cmd{\vbox}.
    \item[\cscmd{vboxL\{...\}}]\DescribeMacro{\vboxL}\new{v1.0} Similar to \cmd{\hboxL} but with \cmd{\vbox}.
    \item[\cscmd{vtopR\{...\}}]\DescribeMacro{\vtopR}\new{v1.0} Similar to \cmd{\hboxR} but with \cmd{\vtop}.
    \item[\cscmd{vtopL\{...\}}]\DescribeMacro{\vtopL}\new{v1.0} Similar to \cmd{\hboxL} but with \cmd{\vtop}.
\end{description}

\section{Notes on \LuaTeX's Direction Model}

\subsection{Direction Registers}

\LuaTeX\ provides five direction registers that control text flow
and layout at different scopes:

\begin{description}
    \item[\cscmd{pagedirection}] Controls the location of the origin of the page.
        For RTL pages, the page origin shifts to \verb|\pagerightoffset|
        to the right of the top right edge (there is also \verb|\pageleftoffset|
        which is simply \verb|\hoffset| minus 1in). This register 
        should match the direction of the box being shipped out to avoid 
        misplacement warnings (the warning message mentions \cmd{\bodydirection} 
        but what actually matters is the box direction itself).
        If for example a RTL box is shipped when \cscmd{pagedirection} is
        0 (LTR) then the right edge of the box will be placed on the left
        edge of the media box, which will probably result with the text being
        mostly outside of the media box.
    
    \item[\cscmd{bodydirection}] Used as the default direction for boxes 
        created in vertical mode when no explicit direction is specified via 
        \texttt{dir} or \texttt{bdir} keywords. This applies to both 
        \cmd{\vbox}/\cmd{\vtop} and \cmd{\hbox} when typeset in vertical mode. 
        It is also used by \cmd{\vcenter} and \cmd{\valign} for determining 
        their box direction, and the direction of inserts and the output box.
        It used to have more roles during the build page and shipout phases,
        but only with directions that were dropped in \LuaTeX.
    
    \item[\cscmd{pardirection}] Determines the paragraph direction. When a 
        paragraph starts (i.e., when entering horizontal mode), the current 
        value of \cmd{\pardirection} is captured in a \verb|local_par_node| 
        that is inserted at the beginning of the paragraph. This captured value 
        is then used during line breaking to determine the direction of the line 
        boxes created from the paragraph.
    
    \item[\cscmd{textdirection}] Specifies the direction for boxes created in 
        horizontal mode when no explicit direction is given. It is also used by 
        \cmd{\halign} for determining the direction of row and cell boxes. Additionally, 
        changes to \cmd{\textdirection} updates a special direction stack that is mostly
        used to make \cmd{\textdirection} respect grouping. If used
        within horizontal mode then direction 
        nodes are inserted into the horizontal list.
        If there was a direction in the stack, \cmd{\textdirection} will first insert
        an enddir node to close the previous direction, then a begindir node to start
        the new one. \cmd{\linedirection} is pretty similar to \cmd{\textdirection},
        but if there is a glue node before \cmd{\linedirection} is used, the enddir
        node is inserted before that glue node.
    
    \item[\cscmd{mathdirection}] Controls the direction for mathematics.
\end{description}

\subsection{Directions In Paragraphs}

When \LuaTeX\ starts a new paragraph (entering horizontal mode), it creates a 
\verb|local_par_node| at the beginning of the paragraph's horizontal list. 
This node captures the current value of \cmd{\pardirection} in its 
dir field. 

Then, \LuaTeX\ compares \cmd{\pardirection} with 
the current text direction stack. If they differ, 
direction nodes are automatically inserted at the beginning of the paragraph to 
ensure the text direction matches the paragraph direction.

Specifically, the \verb|new_graf| function walks through 
\verb|text_dir_ptr| and inserts begindir nodes for any text directions 
that differ from \cmd{\pardirection}.

These dir nodes comes before the indent box is added,
thus the indent location is affected by them (which means
the indent location is affected by \cmd{\textdirection}).

Later, when the paragraph is broken into lines by the line breaking algorithm, 
the paragraph direction is read from the \verb|local_par_node|.
This captured direction determines the direction of the line boxes 
created during line breaking.

When a paragraph contains direction changes (dir nodes), and these direction 
changes span across line breaks, the line breaking algorithm automatically 
handles the direction nesting properly:

\begin{enumerate}
    \item During line breaking, as the algorithm scans through the paragraph, 
        it maintains a direction stack that tracks all 
        currently active (unclosed) direction changes.
    
    \item After break points are chosen and lines are being constructed 
        (in the post-line-break phase):
        \begin{itemize}
            \item At the beginning of each line: If there are unclosed 
                directions from the previous line, new begindir nodes are automatically inserted at 
                the start of the line to re-establish those directions.
            
            \item During line construction: The code scans through the line's 
                content, tracking direction nodes and updating the direction 
                stack.
            
            \item At the end of each line: For each unclosed direction 
                in the stack, a canceldir node is automatically inserted at the end of 
                the line to properly close it.
        \end{itemize}
\end{enumerate}

These nodes comes after \cmd{\leftskip} and before \cmd{\rightskip} and
\cmd{\parfillskip} so the location of these glues is determined by the
line box direction.

\subsection{Math Mode}

The \cmd{\mathdirection} register controls the direction for mathematics. When 
entering math mode (both inline and display), \LuaTeX\ performs the following 
operations:

\begin{enumerate}
    \item Saves the current \verb|text_dir_ptr| (the current direction node 
        state)
    \item Creates a new \verb|text_dir_ptr| based on \cmd{\mathdirection}
    \item Synchronizes all direction registers: Inside the math group, 
        all of \cmd{\bodydirection}, \cmd{\pardirection}, and 
        \cmd{\textdirection} are set to the value of \cmd{\mathdirection}
\end{enumerate}

If \cmd{\mathdirection} differs from 
the surrounding \cmd{\textdirection}, direction nodes are automatically 
inserted:

\begin{itemize}
    \item A begin-dir node is inserted before the math content
    \item The math list is converted to an hlist in the math direction
    \item A cancel-dir node (enddir) is inserted after the math content
\end{itemize}

This allows inline math to have a different direction from the surrounding text. 
These nodes are added inside the equation (after mathon and before mathoff nodes
or inside the equation box (probably not needed for display)).

\subsubsection{Display Math}

When entering display math the \cmd{\predisplaydirection} register is set to -1 if 
\cmd{\mathdirection} and \cmd{\pardirection} differs, otherwise it is set to 0.

Later, when the display equation is finalized, if there is an equation number,
if \cmd{\predisplaydirection} is negative then \cmd{\eqno} will put the equation
number on the left, and \cmd{\leqno} on the right.

This means that if you don't manually set \cmd{\predisplaydirection} inside the equation,
\cmd{\eqno} will put the equation number on the same side of \cmd{\parfillskip} of the paragraph
before the display.

Finally when the equation and equation number are boxed, the box direction
is determined by the value of \cmd{\textdirection}.

\subsection{Box Directions}

\subsubsection{Direction Specification}

Box direction can be specified in two ways:

\begin{enumerate}
    \item Explicit specification: Using the \texttt{dir} or 
        \texttt{bdir} keywords with box commands:
        \begin{verbatim}
        \hbox dir TRT {...}
        \vbox bdir 1 {...}
        \end{verbatim}
    
    \item Implicit inheritance: When no direction is explicitly given, 
        boxes inherit from the appropriate direction register based on the 
        current mode:
        \begin{itemize}
            \item In vertical mode: uses \cmd{\bodydirection}
            \item In horizontal mode: uses \cmd{\textdirection}
            \item In math mode: uses \cmd{\mathdirection}
        \end{itemize}
\end{enumerate}

Note that \cmd{\vcenter}, \cmd{\halign}, and \cmd{\valign} do \emph{not} 
accept \texttt{dir} or \texttt{bdir} keywords:
\begin{itemize}
    \item \cmd{\vcenter} always uses \cmd{\bodydirection}
    \item \cmd{\halign} always uses \cmd{\textdirection} for row and cell boxes
    \item \cmd{\valign} always uses \cmd{\bodydirection} for column and cell boxes
\end{itemize}

\subsubsection{Boxes Created From Lua}
\begin{itemize}
    \item \cmd{token.scan\_list} is ran in horizontal mode, so the above rules apply
    \item \cmd{node.hpack} use \cmd{\textdirection} if a dir argument is not specified
    \item \cmd{node.vpack} use \cmd{\bodydirection} if a dir argument is not specified
\end{itemize}

\subsubsection{Direction Registers Inside Boxes}

When entering \cmd{\hbox}, \cmd{\vbox}, or \cmd{\vtop},
the registers \cmd{\bodydirection}, \cmd{\pardirection} and \cmd{\textdirection}
are set inside the box to match the box's direction 
(whether specified explicitly via \texttt{dir}/\texttt{bdir} or inherited 
implicitly from the current mode).

This synchronization does not occur for \cmd{\vcenter}, \cmd{\halign}, 
and \cmd{\valign}, which use the simpler scanning mechanism and do not modify 
the direction registers upon entry.

\subsection{Output and Shipout}

During the shipout phase, box directions critically affect the final page 
layout:

\subsubsection{Page Origin}

The \cmd{\pagedirection} determines the page origin (From LuaTeX's point of view):
\begin{itemize}
    \item For LTR pages, the reference point is positioned with 
        the standard offset from the left edge: 
        \verb|refpoint.h = h_offset|
    \item For RTL pages, the reference point shifts to account 
        for the right edge: 
        \verb|refpoint.h = page_width - page_right_offset - 1in|
\end{itemize}

\subsubsection{Box Traversal}

When outputting boxes to PDF/DVI, the direction of each box determines:

\begin{enumerate}
    \item Starting position: 
        \begin{itemize}
            \item In LTR vboxes, nested boxes start at horizontal position~0 
                (left edge), positive shift (\cmd{\moveright}) is right offset.
            \item In RTL vboxes, nested boxes start at the box width (right 
                edge), positive shift (\cmd{\moveright}) is left offset.
        \end{itemize}
    
    \item Content flow:
        \begin{itemize}
            \item In LTR hboxes, the horizontal cursor advances rightward as 
                content is placed
            \item In RTL hboxes, coordinate transformations ensure content 
                flows right-to-left
        \end{itemize}
    
    \item Rule positioning:
        \begin{itemize}
            \item In LTR contexts, rules are drawn from the current position 
                extending rightward
            \item In RTL contexts, the position is first shifted left by the 
                rule width, then the rule is drawn
        \end{itemize}
\end{enumerate}

\subsubsection{Direction Nodes}

Direction nodes (\cmd{\begindir} ... \cmd{\enddir}) create local direction 
changes within a box. They establish a nested coordinate system:
\begin{itemize}
    \item The begindir node saves the current state and switches to a new 
        direction with reset coordinates
    \item Content within the direction pair is processed in the new direction
    \item The enddir node restores the previous direction and position
\end{itemize}

During output, when a begindir node is encountered, the system calculates
the width to the matching enddir node and stores the current position and
reference point information in the enddir node itself. The direction is then switched,
and the horizontal and vertical positions are reset to zero.
Content is output in the new direction. 
When the matching enddir node is later encountered during normal list traversal,
it retrieves the pre-stored position, reference point, and direction values to restore the previous state.

\subsubsection{PDF Glyph Positioning}
The directions affects how glyphs are positioned in the final PDF output.
For example
\begin{verbatim}
\parindent=0pt
foo

\textdirection=1
foo
\end{verbatim}
gives something like
\begin{verbatim}
BT
/F1 9.96264 Tf
1 0 0 1 72 759.927 Tm [(fo)-27(o)]TJ
1 0 0 1 82.239 747.972 Tm [(f)805(o)1028(o)]TJ
ET
\end{verbatim}
For LTR text, glyphs are output in reading order, as in \verb|[(fo)-27(o)]|. 
For RTL text, we start at the end position (82.239), then
glyphs are output with large positive spacing values that shift 
each subsequent glyph leftward, as in \verb|[(f)805(o)1028(o)]|, which 
positions the glyphs as o-o-f on the page.

\subsubsection{Paragraph Shapes}

When directions are involved, \cmd{\parshape} and \cmd{\hangindent}
might bring surprising results. One need to remember that in RTL
vlists, boxes are aligned to the right, positive shift means shift to the left
and \cmd{\hangindent} and \cmd{\parshape} adds indent to line boxes by setting their shift field.

This means the side of the indent is determined by the direction of the box containing
the line box, not by the paragraph direction.

\LuaTeX\ provides the \cmd{\shapemode} primitive, which when set to some values,
\cmd{\parshape} and \cmd{\hangindent} will be `mirrored', which means for \cmd{\hangindent} the
indent (the shift of the line box) will be negated, and for \cmd{parshape} it will be 
calculated as \verb|hsize_par - width - indentation|.

In fact having a couple of LTR paragraphs in RTL vbox with different hsize might give surprising result,
as the narrower paragraph will be aligned to the right, this fact \cmd{\shapemode} cannot change.

\subsection{Changing Directions In Different Stages}
\label{changedir}
\LuaTeX\ provides several ways to set the direction of objects.
Up until now, we discussed what happens from the \TeX\
side naturally, but what happens when the direction is changed after typesetting?
Or from Lua?

For example \LuaTeX\ provides the \cmd{\boxdirection0} primitive,
which can set the direction of a saved box. Consider the following (assuming vertical mode and \cmd{\bodydirection}=0):
\begin{verbatim}
\setbox0\hbox bdir 1{foo $abc$}
\box0
\setbox0\hbox{foo $abc$}
\boxdirection0=1
\box0
\end{verbatim}
which gives

\setbox0\hbox bdir 1{foo $abc$}
\box0
\setbox0\hbox{foo $abc$}
\boxdirection0=1
\box0

As mentioned, when entering an hbox \cmd{\textdirection} is set to the box direction,
so in the first box at the time the equation is typeset \cmd{\textdirection} is 1 while
\cmd{\mathdirection} is 0 so \LuaTeX\ adds dir nodes around the equation to ensure it has
correct direction, while in the second box \cmd{\textdirection} and \cmd{\mathdirection} are 0
so no such dir nodes are added. Then in the output the equation is inside RTL coordinates from \LuaTeX's
point of view so it is typeset from right to left.

\LuaTeX\ could have work around that by always adding dir nodes around equation I guess, but there are more such subtleties.
What about nested boxes? Boxes (\cmd{\vbox},\cmd{\vtop} and \cmd{\hbox}) inside the first box will be RTL by default, and LTR
by default in the second.

Another example can be changing the direction of the \verb|local_par_node| in the \verb|insert_local_par| callback to RTL,
what will happen to the following paragraph?
\begin{verbatim}
foo $abc$
\end{verbatim}

\subsection{Mode Primitives}

After \LuaTeX\ was declared as stable,
some changes were still desired, so for
backwards compatibility these changes
requires setting a register. Some of these
are related to directions:

\begin{description}
    \item[\cscmd{matheqdirmode}] By default \LuaTeX\ use short skip before a display if
        the equation number is on the right side (assuming short last line),
        regardless of the paragraph direction before the display. Setting \cmd{\matheqdirmode}
        to one will make \LuaTeX\ use short skip if the equation number is on the side
        of the \cmd{\parfillskip} before the display.
    
    \item[\cscmd{breakafterdirmode}] By default dir nodes prevent line breaking, setting
        \cmd{\breakafterdirmode} to one allows line breaks after dir nodes.
    
    \item[\cscmd{mathemptydisplaymode}] As described above, when \cmd{\pardirection}
        and \cmd{\textdirection} differs when entering horizontal mode, dir nodes are added
        to the paragraph. When \TeX\ see an empty paragraph he discards it. But in LuaTeX
        things are a bit more complicated, even simply using \cmd{\noindent} can add a local par
        node and maybe dir nodes. Initially if a paragraph contained dir nodes it was not considered
        empty. Then it was decided to consider such paragraphs, as empty but the change accidentally
        was not made for paragraphs created before display equation (which internally use different function).
        setting \cmd{\mathemptydisplaymode} to one will make such paragraphs be considered empty.
    
    \item[\cscmd{fixupboxesmode}] When \LuaTeX\ encounters a closing group in the main loop, it adds closing dir nodes
        if needed and update the directions stack. By default this is done only for groups that are not associated with boxes.
        This can create some problems with unboxing. For example with \verb|\setbox0\hbox{\textdirection=1 foo}\unhbox0 bar|
        the box contains only begindir node, and when it is unboxed the begindir node is closed only at the end of the line
        (from the line breaking algorithm) and thus the direction switch affects the whole paragraph. Setting \cmd{\fixupboxesmode}
        to one will make \LuaTeX\ fix directions at the end of hbox as well. 
\end{description}


\section{Revision Log}

\begin{description}
    \item[v. 1.1 (2026/06/01)] support \cmd{xalignat*}, remove tabular patch that is no longer needed,
    ensure math direction (see section \ref{changedir}).
    \item[v. 1.0 (2026/04/10)] Setting \cmd{\mathemptydisplaymode} and \cmd{\fixupboxesmode} to 1,
    fixing tabulars, ensure \cmd{\bodydirection} is equal
    to \cmd{\pagedirection} in the outputroutine in a more general way, adding more box variants, support \pkg{tabularray},
    fix equation numbers, support text in math using \pkg{amsmath}, fix \cmd{\underline}, improve \cmd{\autofootnoterule}.
    Most of the internals were revised and rewritten.
	\item[v. 0.6 (2023/10/01)] Fixing a bug in \cmd{\RLE} and \cmd{\LRE}; Switching \cmd{\bodydir} inside long RTL/LTR text;
		 ensuring \cmd{\bodydir} and \cmd{\pagedir} are equal at shipout; patching lists to use a correct value of \cmd{\shapemode};
		 Setting \cmd{\breakafterdirmode} and \cmd{\matheqdirmode} to 1. Patch kindly provided by Udi Fogiel.
	\item[v. 0.5 (2019/10/27)] Add \cmd{\RTLfootnote}, \cmd{\LTRfootnote}, and \cmd{\hboxR}; fix \texttt{autofootnoterule} option; add \cmd{\autofootnoterule},
	     \cmd{\leftfootnoterule}, \cmd{\rightfootnoterule} and \cmd{\textwidthfootnoterule}; add manual.
	\item[v. 0.4 (2019/08/24)] Fix \cmd{\@ensure@RTL}.
	\item[v. 0.3 (2019/07/10)] Fix compatibility with recent \LuaTeX\ (this version was never released to CTAN).
	\item[v. 0.2 (2013/05/27)] Fix additional files.
	\item[v. 0.1 (2009/04/01)] Initial release.
\end{description}

\end{document}
