[Tex/LaTex] Include a footnote in verbatim text

footnoteslistingsverbatim

I have seen how to add verbatim text to a footnote: How to obtain verbatim text in a footnote?

What I would like to do is the opposite, include a footnote in a verbatim section. I am using the memoir class, listings for verbatim sections, and perpage footnotes. The footnote should appear at the bottom of the page just as a regular footnote would. I don't mind if the footnote symbol/superscript (not sure of technical term) is texttt vs the normal style.

Best Answer

listings provides the possibility to escape to LaTeX inside a listing, see section 5.12 Escaping to LaTeX of the manual for details. The basic idea is to set an escapechar which switches to LateX and back:

\documentclass{article}
\usepackage{listings}
\begin{document}
\begin{lstlisting}[basicstyle=\ttfamily,columns=fullflexible,gobble=2,escapechar=ß]
  helloß\footnote{test}ß world
\end{lstlisting}
\end{document}

enter image description here

enter image description here

Instead of escapechar=<tokens> which sets one or more characters <tokens> for starting and ending the escape you can also use escapeinside={<tokens1>}{<tokens2>} or escapebegin=<tokens1>,escapeend=<tokens2> if you want two different characters/strings <tokens1> and <tokens2> for begin and end. <tokens1> and <tokens2> also can be the same tokenlist. (Tests suggest that if <tokens> is longer than one token it cannot only contain the same token – I haven't determined a definite pattern behind this behaviour, though, and the manual doesn't seem to say anything about it.)