# listings in a footnote

This code won't compile:

\documentclass{article}
\usepackage{listings}
\lstset{
language=C,
basicstyle=\small
}

\begin{document}
lorem ipsum\footnote{%
\begin{lstlisting}
// some C code or whatever...
printf("Blah blah\n");
\end{lstlisting}}
\end{document}


It says Illegal parameter number in definition of \lst@insertargs. I know listings is really picky about where it goes, but there must be a way to cram a listing into a footnote, right?

(This is a MWE and my tex files are a bit more complex; my actual error is Paragraph ended before \lst@next was complete. but they are hopefully related; I couldn't get this error with the MWE.)

## 4 Answers

Another option is to use the cprotect package, and replace \footnote by \cprotect\footnote.

\documentclass{article}
\usepackage{cprotect}
\usepackage{listings}
\lstset{
language=C,
basicstyle=\small
}

\begin{document}
lorem ipsum\cprotect\footnote{%
\begin{lstlisting}
// some C code or whatever...
printf("Blah blah\n");
\end{lstlisting}}
\end{document}


The main advantage is that many macros can be \cprotect-ed in the same way as footnote. The main disadvantage is that it will (currently) produce one auxiliary file per \cprotect-ed command.

You can find this package on CTAN (it is rather new).

\usepackage{bigfoot} should do the trick. It does a lot more than that, but making footnote texts be parsed only once (like plain TeX does with its own \footnote macro) is among them.

If you want more lightweight answers (most requiring more manual work, but not meddling with LaTeX's internals all that much), http://www.tex.ac.uk/cgi-bin/texfaq2html?label=verbwithin gives some.

A fail-proof way for passing around listings (and other verbatim material) that furthermore works without any extra packages or experimental features is to employ a box:

\documentclass{article}
\usepackage{listings}
\lstset{
language=C,
basicstyle=\small
}

\newsavebox{\LstBox}

\begin{document}
\begin{lrbox}{\LstBox}
\begin{lstlisting}
// some C code or whatever...
printf("Blah blah\n");
\end{lstlisting}
\end{lrbox}
%
lorem ipsum\footnote{\usebox{\LstBox}}
\end{document}

• This works great! – Thomas Ahle May 9 '13 at 16:26

The listings author describes the difficulties in using listings in arguments and offers an "experimental" way of handling it (see page 46 of the user manual).

\documentclass{article}
\usepackage{listings}
\lstset{
language=C,
basicstyle=\small
}
\usepackage{fancyvrb}
\begin{document}
lorem\footnote{\lstinline{var i:integer;} and
\lstinline!protected\ \ spaces! and
\fbox{\lstinline!\\\{\}\%!}}
ipsum  \VerbatimFootnotes
We can put verbatim\footnote{\verb+_Yes!_+} text in footnotes
\end{document}


You can also use the package fancyvrb, which offers a \VerbatimFootnote, as shown in the minimal above.