Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer 1

up vote 16 down vote accepted

This is one place where the listings package could provide a hook to allow the user to specify this as an option, as it does for the ' character. Here's a solution:

\documentclass{article}
\usepackage{listings}
\makeatletter
\lst@CCPutMacro\lst@ProcessOther {"2D}{\lst@ttfamily{-{}}{-{}}}
\@empty\z@\@empty
\makeatother
\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}

output of code

If you also want real hyphens in the listings captions, see Listing index uses wrong dashes.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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