I'm trying to write code in a LaTeX document that can be copy/pasted from an outputted pdf using Adobe Reader and that also word wraps, rather than breach the right margin.
I've found that in verbatim mode I can copy/paste, but there isn't an option to enable word wrapping. In lstlistings I can enable word wrapping, but can't figure out how to make the text copy/paste properly. I get extra spaces when trying to copy/paste from Adobe Reader X. From searching online, it seems like I just need to choose what's inside lstset{...} correctly, but can't figure it out.
See the following example and the results after copy/pasting from the compiled document (notice the additional spacing)
\documentclass[letterpaper]{article}
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage{fancyhdr}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage[lmargin=2.5cm,rmargin=2.5cm,tmargin=1.5cm,bmargin=3.5cm]{geometry}
\usepackage{listings} % Environment meant for source code (useful for word-wrapping verbatim text)
\lstset{language=[LaTeX]TeX,breaklines=true} % Word wrap within listings environment
\begin{document}
\lstset{basicstyle = \verbatim@font}
\begin{lstlisting}
//Define Variables
Test1_up = [XZ:This (Index)][1];
Test2_down = [XZ:This Index][1];
//Specify Parameter Values
beta1 = .2238202445016966;
beta2 = .6676275732948469;
\end{lstlisting}
\begin{verbatim}
//Define Variables
Test1_up = [XZ:This (Index)][1];
Test2_down = [XZ:This Index][1];
//Specify Parameter Values
beta1 = .2238202445016966;
beta2 = .6676275732948469;
\end{verbatim}
\end{document}
And the output after copy/pasting:
// Define Variables
Test 1_ up = [XZ: This ( Index ) ][1];
Test 2_ down = [XZ: This Index ][1];
// Specify Parameter Values
beta 1 = .2238202445016966;
beta 2 = .6676275732948469;
//Define Variables
Test1_up = [XZ:This (Index)][1];
Test2_down = [XZ:This Index][1];
//Specify Parameter Values
beta1 = .2238202445016966;
beta2 = .6676275732948469;

\lstset(which I don't agree with, by the way). – egreg Jun 17 '13 at 14:10columns=fullflexibleeliminates the spaces from the listing completely, not just removes the "extra" artificaial spaces from the rendered output. That corrupts the listing's formatting. – ajeh Dec 02 '14 at 18:13\lstset{basicstyle = \ttfamily,columns=fullflexible}– egreg Dec 02 '14 at 18:24columns=fullflexiblethe spaces disappeared. I tested it inevince. – Daniel Jul 21 '16 at 20:35listings. – egreg Jan 15 '17 at 22:52