[Tex/LaTex] Avoiding “minus sign” dash in listings commentstyle

listingspunctuation

Is there a general way to get listings package to

  • typeset a hyphen as a minus character in the rest of the code (the default behavior), but
  • typeset a hyphen as a true hyphen if it occurs in comments (using roman typeface)?

Here is relatively minimal example demonstrating my concern. Note the minus sign character in the second comment.

\documentclass{article}
\usepackage{listings}
\lstset{language=C, commentstyle=\rmfamily, columns=flexible}

\begin{document}
\noindent
$x = a - b$  // perform standard sanity-check
\begin{lstlisting}
x = a - b // perform listings sanity-check
\end{lstlisting}
\end{document}

enter image description here

Techniques that do not seem to suffice:

  1. using literate for replacements. As best I can tell, those affect both basicstyle and commentstyle, so they would not differentiate as desired.

  2. using escapechar to render comment differently. If at all possible, I would like a general solution that does not require any change to the original program source code (presuming use of \lstinputlisting).

Revision (in response to Marco's answer below).

It would be ideal if it could properly handle any form of legal comment without needing to edit source code, for example:

\begin{lstlisting}
x = a - b // perform $5 worth of listings sanity-check [ideally]
\end{lstlisting}

Note: my question is related to past question about hyphens and minus sign however in my case, I like the use of the minus sign in the actual code, just not in the comment.

Best Answer

You can use the option texcl. For more information have look to the documentation.

EDIT

Based on the edit of Michael -- A simple solution is to change the catcode of special characters:

\documentclass{article}
\usepackage{listings}
\lstset{language=C, commentstyle={\rmfamily\catcode`\$=11}, columns=flexible,texcl}

\begin{document}
\noindent
$x = a - b$  // perform standard sanity-check
\begin{lstlisting}
x = a - b // perform listings sanity-check
\end{lstlisting}

\begin{lstlisting}
x = a - b // perform $5 worth of listings sanity-check [ideally]
\end{lstlisting}
\end{document}

enter image description here

EDIT 2 (thanks to egreg)

Michael requests a solution without using texcl. AFAIK this isn't possible. If you don't say texcl, the - is always interpreted as $-$; this has nothing to do with the catcode of -

One should change the interpretation of -; but, AFAIK, it's not possible to change it in comments and not in the code proper.

Related Question