I want to test whether a macro is (a) outside or (b) inside a \footnote command, similar to what's asked in (i) How to test if I'm currently in a footnote or not, (ii) Detect whether I'm in a \footnote?, (iii) footnote boolean: how to check whether currently in a footnote, and (iv) same command with output X in main body and Y in footnote.
The general technique is (1) define a boolean, defaulted to false; (2) redefine \footnote so that it sets the boolean to true upon entry and resets it to false when exiting. This requires a prepending and an appending to the original \footnote command.
Where my question differs from the answers given for (i)–(iii) above is that they all do the redefinition with a \let. However, though it's often forgotten, the \footnote command takes an optional argument (for the number of the footnote). (E.g., see "\footnote" of LaTeX2e unofficial reference manual (October 2018).) This fact should make using \let inappropriate. (E.g., "Remember that one must never use the old trick \let\ORIxyz\xzy… if \xyz has been defined with an optional argument." xpatch documentation)
(The answer in (iv) redefines \footnotetext rather than \footnote, which I don't understand.)
Thus, I want to redefine \footnote using the commands \xpretocmd and \xapptocmd from the xpatch package (to prepend and append, respectively). (See Enrico's helpful explanation.)
The below MWE is my attempt to solve this problem.
If I comment out the appending \xapptocmd{\footnote}{\togglefalse{inFootnoteCommand}}{}{} command, it works well (except for the obvious problem that it doesn't reset the boolean to false and, hence, thinks it's in the \footnote even after it's exited). See this output:
But when I leave the appending command uncommented, (a) it fails to reset the boolean and (b) the output falls apart both in the body text and in the footnote text, and (c) I get the error, associated with the \footnote commands itself:
Missing \endcsname inserted.
\unskip I.38 \footnote [Here's the footnote:\amIInAFootnote] The control sequence marked should not appear between \csname and \endcsname.
Where am I going wrong?
Here's the MWE:
\documentclass{article}
\usepackage{xcolor}
\usepackage{xpatch}
\usepackage{etoolbox}
\newtoggle{inFootnoteCommand}
\togglefalse{inFootnoteCommand}
\newcommand{\amIInAFootnote}{%
\iftoggle{inFootnoteCommand}{%
\textcolor{blue}{You are in a footnote.}
}{%
\textcolor{red}{You are NOT in a footnote.}
}%
}
\parindent=0pt
\begin{document}
This line intentionally left blank %To move the text closer to the footnote
\vspace{400pt}
\xpretocmd{\footnote}{\toggletrue{inFootnoteCommand}}{SUCCESS\\}{FAIL\\}
\xapptocmd{\footnote}{\togglefalse{inFootnoteCommand}}{SUCCESS\\}{FAIL\\}
Before a footnote: \amIInAFootnote.
At the end of this sentence is a footnote:%
\footnote{Here’s the footnote: \amIInAFootnote}
Now, I'm back from the footnote: \amIInAFootnote
\end{document}



