# You can't use macro parameter character #' in restricted horizontal mode. [duplicate]

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.


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}


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}


The hash character can be escaped it seems:

\footnote{No really, it doesn't \Verb!S\#Var!}

• You can not use verb in a macro argument that is just \texttt(S\#Var} – David Carlisle Oct 19 '13 at 20:18
• @DavidCarlisle Actually \Verb doesn't throw an error, but I believe the result will be unpredictable, in general. – egreg Oct 19 '13 at 20:19