[Tex/LaTex] You can’t use `macro parameter character #’ in restricted horizontal mode.

fancyvrbfootnotes

I get a strange error with a \Verb escape in a footnote:

\documentclass{article} 
\usepackage{fancyvrb}
\begin{document}
Works inline \Verb!S#Var! but doesn't in footnote.
% \footnote{No really, it doesn't \Verb!S#Var! you see.}
\end{document}

When I uncomment the footnote line, the complaint is:

You can't use `macro parameter character #' in restricted horizontal mode.

Best Answer

Fun exercise. ;-)

\documentclass{article}
\usepackage{regexpatch,fancyvrb,xparse}
\makeatletter
\let\do@footnotetext\@footnotetext
\regexpatchcmd{\do@footnotetext}
  {\c{insert}\c{footins}\cB.(.*)\cE.}
  {\1\c{egroup}}
  {}{}
\def\@footnotetext{\insert\footins\bgroup\@makeother\#\do@footnotetext}
\newcommand{\ttvar}{\begingroup\@makeother\#\@ttvar}
\newcommand{\@ttvar}[1]{\ttfamily\detokenize{#1}\endgroup}
\makeatother

\setlength{\textheight}{3cm} % just to shorten the height for the example

\begin{document}
Works inline \ttvar{S#Var} and also in footnote.%
\footnote{Yes, \ttvar{S#Var}, as you see.}
\end{document}

enter image description here

With \detokenize you can print all characters, except backslashes and % (actually backslashes are allowed, but they might produce unwanted spaces), so long as braces are balanced.

The trick is to modify \@footnotetext not to absorb its argument, but just doing \insert\footins\bgroup, changing the category code of # (you quite certainly won't be defining commands in a footnote) and calling \do@footnotetext that will absorb the argument. Somebody might enjoy looking how \regexpatch does its work on a copy of the original \@footnotetext.

The command \ttvar will locally change the category code of #.


Alternative solution.

\documentclass{article} 
\usepackage{fancyvrb,cprotect}
\begin{document}
Works inline \Verb!S#Var! and also in footnote.%
\cprotect\footnote{Yes, \Verb!S#Var!, as you see.}
\end{document}
Related Question