1
votes

To the naked eye, minted (Konrad Rudolph's LaTeX package for code highlighting using the Pygments library) faithfully renders code blocks that are passed to it, displaying them with whatever indentation was contained in the source code.

If, however, you attempt to copy and paste code from one of those blocks, you'll notice that their visible indentation is achieved using non-copyable spaces, such that the pasted code loses each line's leading spaces. This is particularly problematic with Python code blocks, because in Python indentation has actual meaning as a part of the code.

So, here's my question: Is there some way to get minted to render code blocks that, when copy-and-pasted, keep the indentation of the source code they display?

For examples of what I mean, see any of the several indented code blocks in the minted manual (found here), or compile the following minimal-ish reproducible example:

\documentclass{article}

\usepackage{minted}
\newminted[python]{python}{frame=single}

\begin{document}

\begin{python}
def example1():
    if verbose:
        print 'Running example1'

verbose = True
example1()
\end{python}

\end{document}
1
@G.Poore Thanks, but as far as I can see, that doesn't help me with minted, which I'm wanting for its code highlighting. (I just tried copying all of the relevant code from the accepted answer to the question you linked into my preamble (plus the bit that goes below \begin{document}), and it made no difference to the output.) I suspect (?) this is an issue with Pygments, which is why I chose to post here rather than tex.stackexchange.com ....Josh O'Brien

1 Answers

2
votes

This works in Acrobat Reader, at least on my system, but not in SumatraPDF and perhaps some other programs. There may be other, better solutions.

\usepackage{color}
\usepackage{minted}
\newminted[python]{python}{frame=single}
\fvset{showspaces}
\renewcommand\FancyVerbSpace{\textcolor{white}{\char32}}

This sets fancyvrb, which Pygments uses for formatting output, to use visible space characters (), and then makes the characters "invisible" by making them white. Ultimately, this does end up being a TeX question, since Pygments is using the fancyvrb package for its output, and the trick is to get fancyvrb to create (leading) spaces that can be copied.