Replace and add a/to a specific sequence of tokens

Is there a way to find a specific sequence of tokens and add after it a command? Or is there a way to find a specific sequence of tokens and replace it with another one? And do it only if the sequence of tokens is in the input file, otherwise don't leave any error message.

For example the command \AtBeginDocument{\bfseries} finds the string \begin{document} and add to it \bfseries. Is there a way to get a more general command that find any kind of string and add to it another one? Something like this:

\if@tokensequenceisgivenadd{<String to find>}% or more shortly \if@tokenadd

\fi


and I would another command like the following:

\if@tokensequenceisgivenreplace{<String to find>}% or more shortly \if@tokenreplace

<Replace it with this string>

\fi

-
Take a look at the etoolbox package, namely the \patchcmd command. –  Daniel Jun 19 '13 at 9:00

Note that AtBeginDocument does not in any sense find \begin{document}. the code for \begin{document} executes the command \@begindocumenthook if that is defined and \AtBeginDocument{...} just appends ... to the end of the hook macro so it gets executed when \@begindocumenthook is run.

However if your list of tokens does not include {} groups you can use a delimited macro.

\def\foo#1String to find#2!!{\def\zz{#1\bfseries#2}}


adds \bfseries after the string and defines \zz, usually used as

\def\zz{1 2 3 String to find 4 5 6}

\expandafter\def\expandafter\foo\zz!!


which leaves \zz defined as 1 2 3 String to find\bfseries 4 5 6

This is the basis of several patch macros you will find, but you have to take care over dropping brace groups. If \zz was initially

\def\zz{{1 2 3 }String to find 4 5 6}


Then the result of patching via \foo would again be 1 2 3 String to find\bfseries 4 5 6 as an argument that consists just of a top level {} TeX removes one level of grouping. Robust patch macros have to add extra tokens and remove them again to avoid this effect.

-

The \AtBeginDocument command doesn't work by searching: it adds code to a hook macro that is part of the internal code used to implement \begin{document} (actually the \document macro). What you need to do is set up appropriate hooks or simply append directly to the code you are using. The etoolbox package makes this easy

\RequirePackage{etoolbox}

If all you want to do is change the definition entirely, then assuming we are talking about a macro you can simply \def/\renewcommand it.