4

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}

enter image description here

1
  • @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.
    – bleistift2
    Sep 16 '16 at 22:22
5

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}

enter image description here

1
  • 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.
    – bleistift2
    Sep 16 '16 at 22:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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