26

As the title says, the option breaklines=true seems to have an undesired interaction when using literate; in the following example the closing parenthesis doesn't get colorized

\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}

\lstset{
  literate=
    {)}{{\textcolor{red}{)}}}{1}
    {(}{{\textcolor{red}{(}}}{1},
  breaklines=true,
}

\begin{document}

\begin{lstlisting}
()
\end{lstlisting}

\end{document}

enter image description here

Commenting out the breaklines=true option produces the desired result. What is producing this odd behaviour and how can it be prevented?

Gonzalo Medina
  • 505,128
  • related: http://tex.stackexchange.com/questions/110641/help-defining-pdf-syntax-with-listings-package – jub0bs Mar 11 '14 at 21:18

1 Answers1

17

When the breaklines=true option is given, a code that's executed after doing \lst@literate (which assigns the special meaning to the defined characters) is

\lst@ifbreaklines \lst@Def {`)}{\lst@breakProcessOther )}\fi

and this expands to

\lccode `\~=#1\lowercase {\def ~}{\lst@breakProcessOther )}

which makes the active ) expand to

\lst@breakProcessOther )

where ) is not active. All this happens when \lsthk@SelectCharTable is executed.

If, just for trying, I apply a patch with etoolbox

\makeatletter
\patchcmd{\lsthk@SelectCharTable}{`)}{`]}{}{}
\makeatother

then the right parenthesis will be printed red, but a similar problem will appear with the ] in case, say,

literate=
  {[}{{\textcolor{red}{[}}}{1}
  {]}{{\textcolor{red}{]}}}{1},

is specified (the right bracket will become a black right parenthesis, which I expected).

I believe this has to do with precautions listings makes in order to correctly treat parenthesized expressions. And I suspect that not much can be done about this.

If I try to patch the definition of \lsthk@SelectCharTable removing that conditional part, then the right parenthesis comes out red. But I don't know if other problems will arise.

egreg
  • 1,121,712
  • Surely, the fact that breaklines breaks literate replacements is not the intended behaviour. Should this be reported as a bug? – jub0bs Dec 09 '13 at 14:22
  • @Jubobs I believe so. – egreg Dec 09 '13 at 14:46
  • There is an explanation underneath the line \lst@ifbreaklines \lst@Def {\)}{\lst@breakProcessOther )}\fiinlistings.dtx: *A bug [...] has been removed by using\lst@ProcessOtherinstead of\lst@AppendOther`*. I guess fixing that original bug introduced another, which is the object of Gonzalo's question... – jub0bs Mar 09 '14 at 13:54