# Reverse direction of writing automatically with RTL script

A new interesting feature with latest release of babel a lua algorithm which detect the beginning and the end of Arabic sentences and revers direction of writing without adding explicit markup (\textdir TRT)

\documentclass{article}
\usepackage[bidi=basic-r]{babel}
\babelprovide[import, main]{arabic}
\babelfont{rm}{Amiri}
\begin{document}
Example of latin text - مثال لنص عربي
\end{document}


I have two questions

# First question

Can someone explain how this algorithm was built

# Second question

How to create a similaire effect with xelatex ( revers direction of writing without adding explicit markup )

The relevant code is lua code found in babel-bidi-basic-r.lua and babel-bidi.lua. As far as I know it uses the Unicode bidi algorithm.

Since it involves lua code it can not work with xetex which only supports the bidi=default babel option (and a new bidi=bidi option, but I haven't tried this) and requires explicit text markup.

There is an (oldish) experimental package called unicode-bidi for xelatex. This package is not connected with babel. Instead it is set up for use with the xepersian package. Even so it's output is not so reliable:

\documentclass{article}
\usepackage{xepersian}
\usepackage{unicode-bidi}
\settextfont{Amiri}
\begin{document}
Example of latin text - مثال لنص عربي
\end{document}


Compare with the output from your MWE with lualatex: