5

I'm typesetting a document with examples of bash code. How do I make the code like

`pwd -P`

appear with the same kind of quotes? I want the readers of the document to be able to copy and paste the code directly into a terminal. Latex is giving me the opening single quote symbol ‘.

3

You could also use the literate key to define literate character replacements:

\documentclass{article}
\usepackage{listings}

\def\backtick{\char18}
\lstdefinestyle{mystyle}{literate={`}{\backtick}1, escapechar=@}

\begin{document}
\begin{lstlisting}[style=mystyle]
  @\backtick@pwd -P@\backtick@
  `pwd -P`
\end{lstlisting}
\end{document}

which gives

enter image description here

The copy/paste result from the PDF file is the same for both lines for me. However, note the small spacing difference. I'm not entirely sure which of these spacings is the correct one, but I'm temped to say it's the one of the second line because the literate explicitly tells listings to treat the replacement as a single character.

4

Load the upquote package:

\documentclass{article}
\usepackage{listings}
\usepackage{upquote}

\begin{document}

\begin{lstlisting}
`pwd -P`
\end{lstlisting}

\end{document}

enter image description here

This also changes the ' character into an undirected quote, which is probably also desired.

\documentclass{article}
\usepackage{listings}
\usepackage{upquote}

\begin{document}

\begin{lstlisting}
`pwd -P`
echo '$PATH'
\end{lstlisting}

\end{document}

enter image description here

  • I tried the upquote package. I guess it uses a metafont technique. It looked right, but the text copied from the pdf file had } and extra spaces instead of backticks. – SU3 Nov 26 '16 at 23:45
  • @SU3: Do you have the package cmap loaded to ensure proper copy'n'paste of text? – koppor Jan 18 '18 at 23:20
3

With CarLaTeX's comment I was able to find the solution.

First define escapechar within your style definition using the \lstdefinestyle command. For example,

\lstdefinestyle{mystyle}{escapechar=@}

Then, use the defined style with the lstlisting environment.

\begin{lstlisting}[style=mystyle]
  @\`{}@pwd -P@\`{}@
\end{lstlisting}

The combination of characters between @s will turn into a backtick.

Edit:

The solution above looks right on the paper but the characters aren't right when copied from the document. A solution that allows copying is to define a backtick character

\def\backtick{\char18}

and use it like this

\begin{lstlisting}[style=mystyle]
  @\backtick@pwd -P@\backtick@
\end{lstlisting}

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.