tags:

views:

37

answers:

2

Writing some docs with code snippets which I want to be copyable to run as written. These snippets may include lines with preceding spaces. The listings package formats the text fine, but the spaces are not copyable.

Let's say I have the following example:

\documentclass{article}
\usepackage{listings}
\begin{document}
\lstset{
    basicstyle=\ttfamily,
    frame=single,
    columns=fullflexible
}
\begin{lstlisting}[language=python]
def foo():
    return "bar"
\end{lstlisting}
\end{document}

If I copy and paste the listing somewhere, it becomes:

def foo():
return "bar"

which must be corrected by hand.

Is there a way to make the listings package include the original spaces? Or is there a package better suited for cases like this?

+1  A: 

You can try the following:

\begin{lstlisting}[language=python,tabsize=2,showtabs=true,showspaces=true]
def foo():
    return "bar"
\end{lstlisting}
phimuemue
This does get me somewhere. The spaces are copied as 0x20 spaces, just like I want. Works in Adobe Acrobat, even.However, I don't really like the visual spaces; it makes the source listings an eyesore in my opinion. Any way to get these spaces in there without printing the underline characters in the PDF?
Vultaire
@Vultaire: I read somewhere `\lstset{basewidth=0.5em}` resp. `\lstset{basewidth={0.5em,0.45em}}`. You could try this and report if it worked out.
phimuemue
@Vultaire: Note that the "visible spaces" are copied not as normal spaces but (correctly) as visible spaces in PDFKit-based readers. Otherwise, you could hide them by painting them white. Overriding the command `\lst@visiblespace`.
grddev
+2  A: 

This is (most likely) not a problem with listings (or latex at all), but with your PDF rendering software. For instance, with PDFKit-based (Preview, Skim, ...) on OSX, I get the behavior that you describe. By using Xpdf, however, the text is copied correctly.

grddev
I do indeed see what you're saying with Xpdf, and that's good to know. However, not everyone I'm working with uses Linux, and forcing a cygwin install for Xpdf seems overkill...With Adobe Acrobat 9 for Linux, the spaces don't show up. Haven't tried the Windows version yet though.
Vultaire
I see the same problem with space copying if I use a verbatim block instead of listings. Same with plain TeX and "\ "'s. Perhaps this is the best I'm going to get without significant trouble. Thanks.
Vultaire