23

The listings package transforms source-code hyphens (-, U+002D) into minus signs (, U+2212) when using the default proportional fonts, though not when using the default monospaced typewriter font. A minimal working example:

\documentclass{article}
\usepackage{listings}
\lstset{language=C}

\begin{document}
  \lstinline[basicstyle=\rmfamily]{--x} \textrm{-{}-x} \par
  \lstinline[basicstyle=\sffamily]{--x} \textsf{-{}-x} \par
  \lstinline[basicstyle=\ttfamily]{--x} \texttt{-{}-x}
\end{document}

The first two rendered lines clearly show the difference between the long minus signs and the short hyphens:

long minus signs replacing short hyphens in Roman and sans serif listings, but not monospaced

This is not just an aesthetic problem. The listing is genuinely no longer correct code. A minus sign is not a hyphen, and the syntax of C (and most other languages) does not treat them as interchangeable. --x is valid C code, but −−x is not. If a non-Unicode-savvy person tries to copy and paste the code from such a listing, she may find that it does not compile but be baffled as to the problem.

How can I prevent listings from turning hyphens into minus signs?

marked as duplicate by Stefan Pinnow, Phelype Oleinik, siracusa, Sebastiano, Zarko Jul 18 at 19:45

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

4

Add literate={-}{-}1 to lstset. E.g:

\documentclass{article}
\usepackage{listings}
\lstset{language=C, literate={-}{-}1}

\begin{document}
  \lstinline[basicstyle=\rmfamily]{--x} \textrm{-{}-x} \par
  \lstinline[basicstyle=\sffamily]{--x} \textsf{-{}-x} \par
  \lstinline[basicstyle=\ttfamily]{--x} \texttt{-{}-x}
\end{document}

enter image description here

See lstlisting manual section 6.4.

  • 1
    +1 It's nice to see how 7 years later a better solution to this problem has been given! I've deleted my old answer, as this one is much cleaner and doesn't have the unwanted side effects that mine did. – Alan Munn Jun 10 at 15:27
  • Simply set literate={-}{-}1 may let - absorbs following spaces in flexible and fullflexible column mode, see tex.stackexchange.com/q/445691. I recommend the solution in tex.stackexchange.com/a/424193, which redefines the processor of - to get rid of math mode minus sign. – Johannes Z Jul 18 at 12:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.