[Tex/LaTex] algorithm2e: Applying color to an entire line, excluding the line number

algorithm2ecolor

Consider the following MWE:

\documentclass{article}

\usepackage{xcolor}
\usepackage[boxed, noline, linesnumbered]{algorithm2e}

\begin{document}

\begin{algorithm}[t]
    \textcolor{red}{\If{test}{\KwRet $-1$\;}}
    blah\;
    blah\;
    blah\;
\end{algorithm}

\end{document}

The output looks like this:
sample output with colored line numbers

As you can see, not only the lines, but also the line numbers are drawn in red. I want to apply the red color only to lines.

Best Answer

You can set/change the way the numbering is formatted. And, in this case, reformat it to set it using \color{black}. The macro provided to set this is \SetNlSty:

enter image description here

\documentclass{article}

\usepackage{xcolor}% http://ctan.org/pkg/xcolor
\usepackage[boxed, noline, linesnumbered]{algorithm2e}% http://ctan.org/pkg/algorithm2e
\SetNlSty{bfseries}{\color{black}}{}
\begin{document}

\begin{algorithm}[t]
    \textcolor{red}{\If{test}{\KwRet $-1$\;}}
    blah\;
    blah\;
    blah\;
\end{algorithm}

\end{document}

The reason for the somewhat bizarre formatting choices when using \SetNlSty stems from its definition in algorithm2e.sty, together with the default of \NlSty:

\newcommand{\NlSty}[1]
  {\textnormal{\textbf{\relsize{\algocf@nlrelsize}#1}}}% default definition
\newcommand{\SetNlSty}[3]{\renewcommand{\NlSty}[1]
  {\textnormal{\csname#1\endcsname{\relsize{\algocf@nlrelsize}#2##1#3}}}}%