[Tex/LaTex] Attach listing to PDF

embeddinglistingspdf

I would like to add listings source as attachment to a PDF (created by pdflatex). For \lstinputlisting this is pretty easy:

\RequirePackage{listings}
\RequirePackage{embedfile}

\let\lstinputlistingO=\lstinputlisting
\renewcommand{\lstinputlisting}[2][]{\embedfile{\detokenize{#2}}\lstinputlistingO[#1]{#2}}

but how can I do the same with \begin{listing} ... \end{listing}? (referenced filename should be the something like listing 12)

Best Answer

As embedfile can only embed external files, you have to write the content of the environment to a file first. To do this, the capabilities of the listings package, namely the \lst@BeginAlsoWriteFile macro, can be used:

\usepackage{listings}
\usepackage{embedfile}

\makeatletter
\lst@RequireAspects{writefile}

\lstnewenvironment{lstembedlisting}[2][]{%
\bgroup%
\lstset{#1}%
\lst@BeginAlsoWriteFile{#2}%
}
{%
\lst@EndWriteFile%
\embedfile{#2}%
\egroup%
}
\makeatother

This code snippet creates a new environment called lstembedlisting, which can be used like the normal lstlisting, except that it expects an additional filename as a mandatory argument. The code inside the environment is typeset and written to that file at the same time. Afterwards, \embedfile is called to attach it to the PDF.

Full MWE:

\documentclass{article}

\usepackage{listings}
\usepackage{embedfile}

\makeatletter
\lst@RequireAspects{writefile}

\lstnewenvironment{lstembedlisting}[2][]{%
\bgroup%
\lstset{#1}%
\lst@BeginAlsoWriteFile{#2}%
}
{%
\lst@EndWriteFile%
\embedfile{#2}%
\egroup%
}
\makeatother

\begin{document}
\begin{lstembedlisting}[language=TeX]{listing_12.tex}
Hello world!
\bye
\end{lstembedlisting}
\end{document}