14

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?

1

1 Answer 1

10

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}
2
  • {nodding vigorously}
    – jub0bs
    Commented Aug 6, 2016 at 15:04
  • 3
    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
    Commented Aug 7, 2016 at 22:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .