I'm trying to use the listings
package to typeset some code in a PDF document, in a way that allows me to copy-paste the resulting code. This mostly works well, if basicstyle=\ttfamily,columns=flexible
is used as suggested here: Phantom spaces in listings (pdf)
The problem is that the leading whitespace is not copy-pasted correctly. Sure, it visually shows up correctly in the PDF, but selecting it and copy-pasting it omits leading whitespace and blank lines.
\documentclass{article}
\usepackage{listings}
\lstset{basicstyle=\ttfamily, columns=flexible}
\begin{document}
Some text.
\begin{lstlisting}
def f(x):
return x+1
Previous line intentionally left blank.
\end{lstlisting}
\end{document}
Is there anything I can do to make it copy-paste correctly? I prefer using listings unless it's absolutely impossible with this package. (The document base I'm working on is pretty large so I'd like to make as few changes as possible to prevent unforeseen bugs.)
Best Answer
I found a solution to the leading whitespace!
Edit: Actually, it doesn't work in Adobe reader. It works in SumatraPDF.
Thanks to Daniel and cgnieder for their comments above.
As described by Martin Monperrus you can use the
accsupp
package to differentiate text that you copy-paste from the type-set text.Note that the linked page is not usable out of the box. The way it is written there, surplus spaces are introduced during the accsupp replacement. Removing all the whitespace in the \newcommand seems to solve it. Here is a minimal example that does work:
Notes:
The basicstyle=\ttfamily and the columns=fullflexible are required to get the font monospaced and to prevent alignment-spaces from being introduced in the middle of your code, as detailed here.
The blank newlines still can't be copy pasted. Does anyone know if this can be done with accsupp as well?
I have for the time being ignored the special unicode characters and such that Martin Monperrus talks about. See that page if you have any problems with that. (Using "upquotes=true" fixes the most common problem)
If you don't want to use the accsupp package, this also works somewhat:
If you set showspaces=true, it turns all spaces into a visible space character, including leading spaces. This doesn't look very pretty, but they are indeed copyable.
The listings package allows you to set visible
tab
characters yourself, but unfortunately not visible space characters. Perhaps someone with more LaTeX knowledge can offer a suggestion on how to replace the visible space character with some form of invisible space character. I assume the copy-paste-ability would be maintained.This also doesn't solve the blank newlines problem.
Proof of concept: