minted icon indicating copy to clipboard operation
minted copied to clipboard

Support copy pasting code keeping formatting intact

Open maxnoe opened this issue 3 years ago • 1 comments

An often requested feature without a clear solution available in the docs / on tex.stackexchange is to be able to copy paste the code from minted code blocks in PDFs.

It seems that this is as much a limitation of how PDFs handle text as LaTeX / minted to provide this information. So this might maybe be more about better documenting the limitations than finding an actual solution (but maybe I'm wrong and there is one that is general enough to be integrated directly into minted). It also seems to depend on the pdf viewer.

Questions about this without a clear answer are for example:

  • https://tex.stackexchange.com/questions/459591/how-to-keep-formating-when-copy-paste-code-sections-with-minted
  • https://tex.stackexchange.com/questions/472099/how-to-configure-tcblisting-with-minted-to-allow-copy-paste-from-listing-with-wh
  • https://tex.stackexchange.com/questions/83204/how-can-i-make-source-code-included-with-minted-copyable
  • https://latex.org/forum/viewtopic.php?t=22250

The main issues are line numbers (where a solution is to use the accsupp package to clear the alternative text) and whitespace, which there is no solution currently to make it copyable, resulting in broken formatting when pasting the code.

Example:

\documentclass{article}

\usepackage{minted}


\begin{document}
This results in a syntax error when copy/pasted:
\begin{minted}{python}
if __name__ == "__main__":
    print("Hello World")
\end{minted}
\end{document}

Screenshot with text selection showing no whitespace is selected:

Screenshot_20210518_124110

Result of pasting the selected text:

if __name__ == "__main__":
print("Hello World")

maxnoe avatar May 18 '21 10:05 maxnoe

I believe you are correct: there doesn't seem to be an existing solution for properly copying code. I can add a note in the documentation at some point.

My guess is that using attachfile or a similar package is probably the best way to approximate exact copying. But apparently even that doesn't work in some PDF viewers.

gpoore avatar May 18 '21 14:05 gpoore