Custom Macros
Learn how to define your own LaTeX commands and environments to save time and reduce code repetition.
If you find yourself typing the exact same complex block of LaTeX code repeatedly, you can create a custom macro using the \newcommand directive. This allows you to define your own commands.
Basic Macros (Shorthand)
The simplest use of a macro is to create a shorthand for a long command. You define macros in the preamble (before \begin{document}).
% Define the macro in the preamble
\newcommand{\R}{\mathbb{R}}
\begin{document}
% Use the macro in the text
Let $x \in \R$.
\end{document}In this example, every time the compiler sees \R, it replaces it with \mathbb{R}.
Macros with Arguments
You can make your macros dynamic by allowing them to accept arguments. You specify the number of arguments in square brackets [n], and reference them inside the definition using #1, #2, etc.
% Define a macro that takes 2 arguments
\newcommand{\vector}[2]{\begin{pmatrix} #1 \\ #2 \end{pmatrix}}
\begin{document}
% Use the macro
The vector is $\vector{x}{y}$.
\end{document}This significantly reduces the amount of typing required for repetitive mathematical structures.
Redefining Existing Commands
LaTeX will throw an error if you try to use \newcommand to define a command that already exists.
If you explicitly want to overwrite a built-in LaTeX command, you must use \renewcommand.
% Change the default bullet point in itemize to a dash
\renewcommand{\labelitemi}{$-$}Creating Custom Environments
Just as you can define custom commands, you can define custom environments (like \begin{myenv} ... \end{myenv}) using the \newenvironment directive.
This requires two code blocks: one for the code that should execute at the \begin statement, and one for the code at the \end statement.
% \newenvironment{name}{begin code}{end code}
\newenvironment{warningbox}
{
\begin{center}
\bfseries \color{red} WARNING:
}
{
\end{center}
}
\begin{document}
\begin{warningbox}
Do not touch the red button.
\end{warningbox}
\end{document}If you have dozens of custom macros, your main .tex file can become cluttered. A best practice is to put all your \newcommand directives into a separate file called macros.tex, and then import it into your main file using \input{macros.tex}.