[Tex/LaTex] Minus signs vanish with listings and breqn – any solutions

breqnlistings

When using listings and breqn, the minus signs (or dashes, according to the unix.SX site then there's some controversy about which it is) disappear from code listing. Here's an example:

\documentclass{article}
\pagestyle{empty}
\usepackage{breqn}
\usepackage{listings}

\begin{document}


\lstset{language=Perl}
\begin{lstlisting}
#! /usr/bin/perl -w

if ($ARGV[0] =~ /^-/) {
    print "Option given";
}
\end{lstlisting}
\end{document}

with result:

listings and breqn

Changing the order of package loading doesn't help. breqn does warn that it might break other packages, but it would be really useful to have both working. If it helps, the code listings are in appendices so happen after the equations which breqn is meant to help with so I can happily reset anything that got changed.

Best Answer

Your problem comes from the fact that \lstlisting likes to typeset a hypen-minus as $-$, and the the breqn package plays around with math so much. In particular, it sets the mathcode of the minus to "8000, which makes it active and seems to break things.

\documentclass{article}
\pagestyle{empty}
\mathchardef\hyphenmathcode=\mathcode`\-
\usepackage{breqn}
\usepackage{listings}

\let\origlstlisting=\lstlisting
\let\endoriglstlisting=\endlstlisting
\renewenvironment{lstlisting}
    {\mathcode`\-=\hyphenmathcode
     \everymath{}\mathsurround=0pt\origlstlisting}
    {\endoriglstlisting}

\begin{document}

\lstset{language=Perl}
\everymath{}
\begin{lstlisting}
#! /usr/bin/perl -w

if ($ARGV[0] =~ /^-/) {
    print "Option given";
}
\end{lstlisting}
\end{document}

(The \everymath{}\mathsurround is not necessary for this, but it should be there for good measure.)

Edit: Added the mathcode bit. I'll say more on this edit in the comments.

Related Question