The etoolbox package
Programming tools for the preamble: flags with \newtoggle and \iftoggle, tests such as \ifstrequal and \ifdef, hooks such as \AtBeginEnvironment, and \patchcmd for changing existing commands.
Loading the package
\usepackage{etoolbox}Conditions in plain TeX are written with \if...\else...\fi, which breaks in many places inside LaTeX arguments. The tests of etoolbox all have the form \test{...}{true}{false} and can be used like any other command.
The second use is changing code that you did not write. \AtBeginEnvironment adds code to an environment, \apptocmd and \pretocmd add code to the end or the start of a command, and \patchcmd replaces a piece of its definition. That avoids copying a whole definition from a class to change one detail.
Main commands
\newtoggle{draft}, \toggletrue{draft}, \togglefalse{draft} | Creates and sets a flag. |
\iftoggle{draft}{true}{false} | Runs one of the two branches depending on the flag. |
\ifstrequal{#1}{ok}{true}{false} | Compares two strings without expanding them. |
\ifblank{#1}{true}{false} | Tests whether an argument is empty or consists of spaces. |
\ifdef{\command}{true}{false} | Tests whether a command is defined; \ifundef is the opposite. |
\AtBeginEnvironment{quote}{\itshape} | Runs code at the start of every environment of this name. |
\patchcmd{\command}{search}{replace}{success}{failure} | Replaces the first occurrence of the search text in the definition of a command and runs one of the two last arguments. |
\apptocmd{\command}{code}{success}{failure} | Appends code to a command; \pretocmd puts it at the start. |
Complete example
\documentclass{article}
\usepackage{etoolbox}
\newtoggle{draft}
\toggletrue{draft}
\AtBeginEnvironment{quote}{\itshape}
\newcommand{\greeting}{Hello world}
\patchcmd{\greeting}{world}{reader}{}{\PackageError{example}{Patch failed}{}}
\newcommand{\result}[1]{\ifstrequal{#1}{ok}{passed}{failed}}
\begin{document}
\iftoggle{draft}{Draft version.}{Final version.}
\greeting! The first test \result{ok}, the second one \result{error}.
\begin{quote}
Every quote is set in italics.
\end{quote}
\end{document}Compiled with pdfLaTeX from TeX Live 2023.
Pitfalls
\patchcmdruns its failure branch when the search text does not occur in the definition. Put an error message there, as in the example, so an update of the patched package does not go unnoticed.- A command with an optional argument keeps its real definition in an internal command.
\patchcmdthen does not find the text and fails; the packagexpatchoffers\xpatchcmdfor this case. - Since the LaTeX release of October 2020 the kernel has its own hooks, for example
\AddToHook{env/quote/begin}{...}.\AtBeginEnvironmentstill works and is the choice for documents that have to compile on older installations.
Related pages
- How-to Define your own commands in LaTeX
- How-to Define your own environments in LaTeX
- Package
ifthen - Package
xparse