Minus signs vanish with listings and breqn - any solutions?
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.
By default listings uses a math minus here and this clashes with breqn. You can change the symbol listings uses for the hyphen. For example this uses \textminus and will work also with breqn:
\documentclass{article}
\usepackage{listings}
\usepackage{breqn}
\begin{document}
\lstinline +ABC-ABC+
\makeatletter
\lst@CCPutMacro
\lst@ProcessOther {"2D}{%
\lst@ttfamily
{\textminus}% used with ttfamily
\textminus}% used with other fonts
\@empty\z@\@empty
\makeatother
\lstinline +ABC-ABC+
\lstset{basicstyle=\ttfamily}
\lstinline +ABC-ABC+
\end{document}
Here is a solution:
\documentclass{tufte-book}
\pagestyle{empty}
\usepackage{listings}
\usepackage{breqn}
\begin{document}
\normalfont
\makeatletter
\texttt{\meaning\lst@InputCatcodes\relax}
\makeatother
\lstset{language=Perl,escapeinside={(*@}{@*)}}
\begin{lstlisting}
#! /usr/bin/perl -w
if ($ARGV[0] =~ /^(*@-@*)/) {
print "Option given";
}
\end{lstlisting}
\end{document}
It is really a font problem. The - sign in your font is an active character in listings. (See the meaning
). If you escape it though it gets the right catcode
and the error disappears. You escape using funny eyes:)
(*@ @*)
and you can insert anything you want. Perhaps someone else can come with an easier solution as I guess it is a hassle to have to escape the sign always.
I use MikTeX for compiling.
Edit
Another hack would be to define a new environment using the listings
lstnewenvironment
command to protect the definitions from other packages:
\lstnewenvironment{perl}[1][]
{\lstset{language=Perl}\lstset{%
#1
}}
{}
This also worked,
Use: \begin{perl}...\end{perl}
This solution is very similar to that given by Harald.