TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

<Add after it this string>


and I would another command like the following:

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

<Replace it with this string>

share|improve this question
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}


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.

share|improve this answer

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


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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.