# xcolor \color command affects the wrong word in a Hebrew sequence

When compiling

\documentclass{article}
\usepackage[utf8x]{inputenc}
\usepackage[hebrew,english]{babel}
\usepackage{xcolor}
\begin{document}
\sethebrew
ראשונה
\color{red} שניה \color{black}
שלישית
\end{document}


I get the following output

instead of the middle word being red.

Is there a way to fix it?

• Does it work if you use \textcolor{red}{second word} instead? – Torbjørn T. Nov 11 '13 at 15:03

Here's what's happening (it's a bit of a rough description, mind you):

Essentially, the line is set in left-to-right order, and what you gave as input is reordered so as to appear correctly. Now, what does pdfLaTeX see on the line, taking things from left to right?

1. The third word - שלישית
2. The \color{black} command
3. The second word - שניה
4. The \color{red} command
5. The first word - ראשונה

The \color command changes the color from here on, and neither xcolor nor babel know that they need to apply it in right-to-left (that is, reverse) order. Thus the line begins with black color, the \color{black} command does nothing, and the the \color{red} command affects the word right after it - being the last word taken from left-to-right, but the first word taken right-to-left.

If you use \textcolor{red}{text to be made red}, you're avoiding the direction reversal mix-up, since the redness will apply exactly to the second argument of the \textcolor command, and nothing else.

Bonus Riddle: What happens when you compile the following?

\documentclass{article}
\usepackage[utf8x]{inputenc}
\usepackage[hebrew,english]{babel}
\usepackage{xcolor}
\begin{document}
\sethebrew
ראשונה
\color{red} שניה \color{green}
שלישית
\end{document}

• Can you explain how latex breaks line if he reads backwards? – user26713 Nov 13 '13 at 7:25
• @user26713: Well, IIANM the ordering happens at the paragraph level, or at least before lines are broken. – einpoklum Nov 13 '13 at 9:24

For a detailed explanation see this post on xetex mailing list. The author of e-tex is already aware of this and I hope it gets fixed for TeXLive 2014.

Despite the existence of this engine bug, bidi package patches color and xcolor packages. so with bidi both \color and \textcolor work fine partially (i.e. if the colored text does not span more than a line):

\documentclass{article}
\usepackage{xcolor}
\usepackage{bidi}
\setRTL
\begin{document}
This is \textcolor{red}{red colour} as you can see.

This is {\color{red} red colour} as you can see.
\end{document}