# How to add em-dash in listings environment?

I’m writing the documentation for some piece of code. In it a string containing an em-dash is defined, and I’d like to quote it to show an example of the defined object.

The trouble is the em-dash, which I can’t set in the listings environment. The MWE below shows what I’ve tried so far. Typing “---” prints just three hyphens, \emdash{} doesn’t print anything at all, escaping the listings environment does print the em-dash, but it creates trouble with the string formatting: The space characters are not displayed as they should (like in example 1).

So the question boils down to: How do I set an em-dash in a listings environment, and if that is impossible, how do I escape the listings environment in a way that doesn’t change the surrounding string?

Here’s the MWE:

\documentclass{article}

\usepackage{color}
\usepackage{listings}
\usepackage[utf8]{inputenc}

\lstdefinestyle{java}{
language          = java,
stringstyle       = \color{red}
}

\begin{document}

\begin{lstlisting}[style=java,escapechar=!]
pro: {
descr1: " -- This is some text",
descr2: " !{\color{red}---}! Here is some more text",
descr3: " !\emdash{}! And a third version",
descr4: " !{\color{red}—}! No. 4",
descr5: " !{\color{red}\textemdash}! No. 5",
descr6: " \textemdash No. 6"
}
\end{lstlisting}

\end{document}


• @Mico Unfortunately, that doesn’t change anything. If I use it unescaped, the listing just prints the characters. If I escape the listing, it looks like in descr4. Sep 16 '16 at 22:22

Use literate:

\documentclass{article}

\usepackage{color}
\usepackage{listings}
\usepackage[utf8]{inputenc}

\lstdefinestyle{java}{
language    = java,
stringstyle = \color{red},
literate    ={--}{\textendash}1 {---}{\textemdash}2,
}

\begin{document}

\begin{lstlisting}[style=java]
pro: {
descr1: " -- This is some text",
descr2: " --- Here is some more text",
}
\end{lstlisting}

\end{document}


• I think I don’t need to tell you that this is exactly what I was looking for, but If future beginners look at this question, I’d like to hint them at chapter 6.4 of the listtings documentation. The command works because it replaces “---“ with the character which is produced by \textemdash. The 2 specifies that the replacement character takes two places. Sep 16 '16 at 22:48