6

Here is a block of latex code to produce some Python code. I'd like to be able to copy and paste it into Python.

\documentclass{standalone}

\usepackage{listings}             % Include the listings-package
\begin{document}
\lstset{language=Python,
  columns=fullflexible,
  basicstyle=\ttfamily,
  showstringspaces=false
}

\begin{lstlisting}
def test(inputvariable):
    if inputvariable == 4:
        print("The input variable is 4 .")
        print("So I'm giving this response.")
    print("done with if statement.")

test(4)
test(3)
\end{lstlisting}

\end{document}

It looks right: enter image description here Unfortunately when I copy and paste it, the indentation is lost, and that's pretty key to how Python works.

Is it possible to get the spacing to appear when I copy/paste it?

5

Inho it is not really possible in a reliable way. It depends too much on the pdf viewer. It is possible to insert real spaces with the \pdffakespace primitive, but the indentation is preserved in sumatra only if I map the space (globally!) to the Unicode Character 'FIGURE SPACE' (U+2007), and in the adobe reader it still disappears.

\documentclass{article}

\usepackage{listings}             
\usepackage[T1]{fontenc}

\makeatletter
\lst@AddToHook{Init}
    {\def\lst@outputspace{ \pdffakespace}}
\makeatother

\input{glyphtounicode}

% saner but doesn't work
%\pdfglyphtounicode{space}{0020}

% works in sumatra:
\pdfglyphtounicode{space}{2007}

\begin{document}

\lstset{language=Python,
  columns=fullflexible,
  basicstyle=\ttfamily,
  showspaces,
  showstringspaces=false
}


\begin{lstlisting}
def test(inputvariable):
    if inputvariable == 4:
        print("The input variable is 4 .")
        print("So I'm giving this response.")
    print("done with if statement.")

test(4)
test(3)
\end{lstlisting}

\end{document}
  • {nodding vigorously} – jub0bs Aug 6 '16 at 15:04
  • I'd be very interested to see a recap of the available options: there's \pdffakespace, \pdfinterwordspaceon, the accsup package, and they all seem to do slightly different things. @UlrikeFischer, do you know how Chromium's "print to PDF" feature works? It produces PDFs with spaces that evince has no trouble copying, whereas all other solutions that I've seen failed with Evince. – Clément Aug 7 '16 at 22:26

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.