[Tex/LaTex] LaTeX trick to prevent a PDF viewer from copying the line number

copy/pasteline-numberinglistings

A PDF output is obtained by compiling the following code.

\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}

\lstset
{
    language={[LaTeX]TeX},
        numbers=left,
        numbersep=1em,
        numberstyle=\tiny,
    frame=single,
    framesep=\fboxsep,
    framerule=\fboxrule,
    rulecolor=\color{red},
    xleftmargin=\dimexpr\fboxsep+\fboxrule\relax,
    xrightmargin=\dimexpr\fboxsep+\fboxrule\relax,
    breaklines=true,
    basicstyle=\small\tt,
    keywordstyle=\color{blue},
    commentstyle=\color[rgb]{0.13,0.54,0.13},
    backgroundcolor=\color{yellow!10},
    tabsize=2,
    columns=flexible,
    morekeywords={maketitle},
}

\begin{document}

\begin{lstlisting}
\documentclass{article}
\usepackage{listings}
\title{Sample Document}
\author{John Smith}
\date{\today}
\begin{document}
\maketitle
Hello World!
% This is a comment.
\end{document}
\end{lstlisting}

\end{document}

I attempted to copy the code only inside Acrobat Reader. Unfortunately, the line numbers also got copied as shown on the following screen shot.

enter image description here

The line numbers are useful, but readers want not to copy them.

Is there a LaTeX trick to prevent a PDF viewer from copying the line number?

Best Answer

This solution is very similar to that contained in How to make text copy in PDF previewers ignore lineno line numbers? \protecting the accsupp is the only requirement, perhaps due to the nature in which listings treats everything:

enter image description here

\documentclass{article}
\usepackage{xcolor}% http://ctan.org/pkg/xcolor
\usepackage{listings}% http://ctan.org/pkg/listings
\usepackage{accsupp}% http://ctan.org/pkg/accsupp
\renewcommand{\thelstnumber}{% Line number printing mechanism
  \protect\BeginAccSupp{ActualText={}}\arabic{lstnumber}\protect\EndAccSupp{}%
}
\lstset
{
    language={[LaTeX]TeX},
        numbers=left,
        numbersep=1em,
        numberstyle=\tiny,
    frame=single,
    framesep=\fboxsep,
    framerule=\fboxrule,
    rulecolor=\color{red},
    xleftmargin=\dimexpr\fboxsep+\fboxrule\relax,
    xrightmargin=\dimexpr\fboxsep+\fboxrule\relax,
    breaklines=true,
    basicstyle=\small\tt,
    keywordstyle=\color{blue},
    commentstyle=\color[rgb]{0.13,0.54,0.13},
    backgroundcolor=\color{yellow!10},
    tabsize=2,
    columns=flexible,
    morekeywords={maketitle},
}

\begin{document}

\begin{lstlisting}
\documentclass{article}
\usepackage{listings}
\title{Sample Document}
\author{John Smith}
\date{\today}
\begin{document}
\maketitle
Hello World!
% This is a comment.
\end{document}
\end{lstlisting}

\end{document}