TikZ and Babel disagree when Hebrew is loaded

I was looking for a solution because I knew one must exist. The original TikZ code was from some example for using ntheorem shady theorems environment, and I had a working example of that.

So obviously something in the ntheorem preamble was making the TikZ code work. But after a couple hours of sleep, my brain cracked up the mystery.

\documentclass[10pt]{article}

\usepackage{tikz}
\usetikzlibrary{shadows}

\tikzstyle{testbox} = [rectangle, rounded corners, draw=black,
  fill=blue!20, inner sep=10pt, drop shadow={fill=black, opacity=.4}]
\tikzstyle{titlebox} =[fill=gray!20, text=black!80, draw=black]

\usepackage[utf8x]{inputenc}
\usepackage[english,hebrew]{babel}

\begin{document}
\L{  \noindent\begin{tikzpicture}%
  \node [testbox] (box){%
    \begin{minipage}{.7\textwidth}%
      \raggedleft\R{אני לררר שליט הכוכב אומיקרון פריסיי שמונה!}%
    \end{minipage}%
  };
  \node [titlebox, right=-35pt] at (box.north east) {\R{\textbf{לררר}}};%
  \end{tikzpicture}}
\end{document}

I realized that setting everything into a babel \L{} group, and adding a modifying \R{} group for the text itself might work. And it does. Beautifully.

enter image description here


Not remotely an expert on RTL languages and LaTeX, and also not remotely and expert on Hebrew, but my "experience" (based entirely on one answer to questions on this site), suggests that compiling with lualatex and using the fontspec package may be helpful.

You will need to replace freesans with a different font name if you don't have it on your system.

Apologies for the (probably rubbish) Hebrew translation.

\documentclass[tikz,border=5]{standalone}
\usepackage{fontspec}
\newfontfamily\hebrewfont[Script=Hebrew]{freesans}
\usepackage{tikz}
\usetikzlibrary{shadows}

\tikzset{%
  testbox/.style={
    rectangle, 
    rounded corners, 
    draw=black,
    fill=blue!20, 
    inner sep=10pt, 
    drop shadow={fill=black, opacity=.4}
  },
  titlebox/.style={
    fill=gray!20, 
    text=black!80, 
    draw=black
  },
  hebrew text/.style={
    align=right,
    font=\hebrewfont,
    execute at begin node={\luatextextdir TRT}
  }
}

\begin{document}
\begin{tikzpicture}%
  \node [testbox, text width=3in] (box1)
  {%
      I am Lrrr, of the planet Omicron Persei Eight.%
  };
  \node [titlebox, right=5pt] at (box1.north west) {\textbf{Lrrr}};%

  \node [testbox, text width=3in, hebrew text] at (0,-2) (box2)
  {%
אני לררר, של כדור הארץ אומיקרון פרטאי שמונה
  };
  \node [titlebox, left=5pt, hebrew text] at (box2.north east) {\textbf{לררר}};
\end{tikzpicture}
\end{document}

enter image description here