# \apptocmd into a conditional—why it does not work?

Why the following MWE does not work while if I comment the conditional it works?

\documentclass{beamer}

\makeatletter

\usepackage{bookmark}
\usepackage{etoolbox}

\apptocmd{\beamer@@frametitle}{\only<1>{\bookmark[page=\the\c@page,level=3]{#1}}}%
{\message{** patching of \string\beamer@@frametitle succeeded **}}%
{\message{** patching of \string\beamer@@frametitle failed **}}%

}{}

\makeatother

\begin{document}

\begin{frame}{Title}
Hello \pause world
\end{frame}
\end{document}

-
You can't use \apptocmd in the argument of another command. –  egreg Mar 22 '14 at 17:54
@egreg thank you, so it's impossible to make any kind of if cycle with that command? –  FormlessCloud Mar 22 '14 at 17:57

In general, patching commands when # is involved can't happen in the argument to another command. One can do some tricks with category codes, but another approach can be easier:

\documentclass{beamer}

\makeatletter
\if@tempswa
\usepackage{bookmark}
\usepackage{etoolbox}
\apptocmd{\beamer@@frametitle}
{\only<1>{\bookmark[page=\the\c@page,level=3]{#1}}}%
{\message{** patching of \noexpand\beamer@@frametitle succeeded **}}%
{\message{** patching of \noexpand\beamer@@frametitle failed **}}%
\fi
\makeatother

\begin{document}

\begin{frame}{Title}
Hello \pause world
\end{frame}
\end{document}


The \if@tempswa conditional is a scratch conditional provided by the kernel.

Here's what's written in the .log file:

** patching of \beamer@@frametitle succeeded **


A similar approach without using \@tempswa and that can be used for other LaTeX pseudoconditionals such as \@ifpackageloaded or \@ifundefined:

\makeatletter
\newcommand{\latex@conditional}[1]{#1{11}{01}}

\usepackage{bookmark}
\usepackage{etoolbox}
\apptocmd{\beamer@@frametitle}
{\only<1>{\bookmark[page=\the\c@page,level=3]{#1}}}%
{\message{** patching of \noexpand\beamer@@frametitle succeeded **}}%
{\message{** patching of \noexpand\beamer@@frametitle failed **}}%
%\else
% code for the false branch
\fi
\makeatother


This relies on the facts that \if expands tokens and that LaTeX pseudoconditionals are fully expandable; so in the end \if finds either 11 if the condition is true, otherwise 01 and so it follows the true and false branches accordingly. Note that such constructions can be nested in other TeX style conditionals. Code for the false branch can be specified, too.

## Alternative method

Alternatively, use the regexpatch package:

\documentclass{beamer}

\makeatletter
\usepackage{bookmark}
\usepackage{regexpatch}
\xapptocmd{\beamer@@frametitle}
{\only<1>{\bookmark[page=\the\c@page,level=3]{#1}}}%
{\message{** patching of \noexpand\beamer@@frametitle succeeded **}}%
{\message{** patching of \noexpand\beamer@@frametitle failed **}}%
}{}
\makeatother

\begin{document}

\begin{frame}{Title}
Hello \pause world
\end{frame}
\end{document}

-