Why Custom Commands Transform Your LaTeX Workflow
You've spent hours perfecting the formatting of your thesis, only to realize you have to repeat similar formatting throughout your document. Frustrating, right? You're not alone. Many academics face this repetitive task, which is where custom LaTeX commands become invaluable.
Custom commands let you:
- Save time by replacing complex code with short commands
- Ensure consistency across your entire document
- Make global changes by editing one definition instead of hundreds of instances
- Reduce errors by eliminating repeated typing of complex syntax
- Create semantic markup that makes your source code more readable
In this comprehensive guide, you'll learn everything from basic command creation to advanced techniques used by professional LaTeX users.
Understanding the Basics: \newcommand
The fundamental building block of custom commands is \newcommand. Here's its syntax:
\newcommand{\commandname}[number_of_arguments]{definition}Your First Custom Command
Let's start with the simplest possible command—one with no arguments:
\documentclass{article}
% Define a custom command for your university name
\newcommand{\myuniversity}{Massachusetts Institute of Technology}
\begin{document}
I am a student at \myuniversity. The research facilities at \myuniversity{}
are world-class.
\end{document}Notice the {} after the second \myuniversity. This prevents the command from "eating" the following space. Without it, "are" would run directly into the university name.
Commands with Arguments
Most useful commands accept arguments—pieces of text that get inserted into the output:
\documentclass{article}
% Command with one argument
\newcommand{\important}[1]{\textbf{\underline{#1}}}
% Command with two arguments
\newcommand{\definition}[2]{\textbf{#1}: \textit{#2}}
\begin{document}
This is \important{very important} information.
\definition{Algorithm}{A step-by-step procedure for solving a problem.}
\end{document}The [1] specifies one argument, [2] specifies two arguments, and so on. Inside the definition, #1 refers to the first argument, #2 to the second, etc.
Commands with Optional Arguments
You can define one optional argument with a default value:
\newcommand{\highlight}[2][yellow]{%
\colorbox{#1}{#2}%
}
% Usage:
\highlight{Important text} % Uses yellow (default)
\highlight[cyan]{Also important} % Uses cyanThe optional argument is specified in square brackets and must always be the first argument.
Real-World Examples for Academics
Let's look at practical commands that solve real problems.
Mathematical Notation
For mathematical writing, custom commands ensure consistent notation:
% Vector notation (bold)
\newcommand{\vect}[1]{\mathbf{#1}}
% Matrix notation (bold uppercase)
\newcommand{\mat}[1]{\mathbf{#1}}
% Probability
\newcommand{\prob}[1]{\mathbb{P}\left(#1\right)}
% Expected value
\newcommand{\expect}[1]{\mathbb{E}\left[#1\right]}
% Partial derivative
\newcommand{\pderiv}[2]{\frac{\partial #1}{\partial #2}}
% Usage in your document:
The vector \vect{x} is transformed by matrix \mat{A}.
The probability is \prob{X > 5} and the expected value is \expect{X^2}.
The partial derivative is \pderiv{f}{x}.Physical Constants and Units
Scientists often need consistent formatting for constants:
% Speed of light
\newcommand{\clight}{2.998 \times 10^{8}\,\text{m/s}}
% Planck's constant
\newcommand{\hbar}{\hslash}
% Boltzmann constant
\newcommand{\kb}{1.381 \times 10^{-23}\,\text{J/K}}
% Generic unit formatting
\newcommand{\unit}[1]{\,\text{#1}}
% Usage:
The speed of light is \clight.
Energy is measured in \unit{eV}.Document-Specific Terminology
When writing about specific topics, consistent terminology matters:
% Software name with consistent styling
\newcommand{\tensorflow}{\textsc{TensorFlow}}
\newcommand{\pytorch}{\textsc{PyTorch}}
% Your tool/method name
\newcommand{\ourmethod}{DeepLearn\textsuperscript{+}}
% Consistent abbreviations
\newcommand{\eg}{\textit{e.g.},\xspace}
\newcommand{\ie}{\textit{i.e.},\xspace}
\newcommand{\cf}{\textit{cf.}\xspace}
\newcommand{\etal}{\textit{et al.}\xspace}
% Usage:
We compared \ourmethod{} against \tensorflow{} and \pytorch{}.
Several methods exist, \eg random forests and neural networks.Note: The \xspace command (from the xspace package) intelligently adds a space after the command unless followed by punctuation.
Theorems and Environments
Create shortcuts for theorem-like environments:
\usepackage{amsthm}
\newtheorem{theorem}{Theorem}[section]
\newtheorem{lemma}[theorem]{Lemma}
\newtheorem{corollary}[theorem]{Corollary}
% Custom command for quick theorem insertion
\newcommand{\quicktheorem}[2]{%
\begin{theorem}[#1]
#2
\end{theorem}
}
% Usage:
\quicktheorem{Main Result}{
For all $n > 0$, the function $f(n)$ converges.
}Advanced Techniques with xparse
The xparse package provides much more powerful command definition capabilities than basic \newcommand.
Installation and Basic Usage
\usepackage{xparse}
% Define a command with xparse
\NewDocumentCommand{\mycommand}{m}{%
% m = mandatory argument
\textbf{#1}%
}Argument Types in xparse
| Specifier | Meaning | Example Input |
|-----------|---------|---------------|
| m | Mandatory argument in braces | {text} |
| o | Optional argument in brackets | [text] |
| O{default} | Optional with default value | [text] or nothing |
| s | Optional star (*) | * or nothing |
| d() | Delimited by parentheses | (text) |
| r<> | Required, delimited by angle brackets | <text> |
Practical xparse Examples
Command with multiple optional arguments:
\NewDocumentCommand{\figure}{O{htbp} O{0.8\textwidth} m m}{%
\begin{figure}[#1]
\centering
\includegraphics[width=#2]{#3}
\caption{#4}
\end{figure}
}
% Usage:
\figure{image.png}{A beautiful image} % Default placement and width
\figure[t]{image.png}{A beautiful image} % Top of page
\figure[h][0.5\textwidth]{image.png}{A smaller image} % Custom widthStar variant for different behavior:
\NewDocumentCommand{\important}{s m}{%
\IfBooleanTF{#1}
{\textbf{\textcolor{red}{#2}}} % Starred version: red and bold
{\textbf{#2}} % Normal version: just bold
}
% Usage:
\important{This is important} % Bold only
\important*{This is critical} % Bold and redConditional processing:
\NewDocumentCommand{\reference}{o m}{%
\IfNoValueTF{#1}
{\textit{#2}} % No optional: just italics
{\textit{#2} (\textbf{#1})} % With optional: add bold note
}
% Usage:
\reference{Some Book} % Outputs: Some Book (italics)
\reference[required reading]{The Manual} % Outputs: The Manual (required reading)Building a Personal Command Library
As you develop custom commands, organize them for reuse across projects.
Creating a Personal Style File
Save your commands in a .sty file:
% mycommands.sty
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{mycommands}[2024/01/01 My Custom Commands]
\RequirePackage{xspace}
\RequirePackage{xcolor}
\RequirePackage{amsmath}
\RequirePackage{amssymb}
% Mathematical notation
\newcommand{\vect}[1]{\mathbf{#1}}
\newcommand{\mat}[1]{\mathbf{#1}}
\newcommand{\prob}[1]{\mathbb{P}\left(#1\right)}
% Text shortcuts
\newcommand{\eg}{\textit{e.g.},\xspace}
\newcommand{\ie}{\textit{i.e.},\xspace}
\newcommand{\etal}{\textit{et al.}\xspace}
% Highlighting
\newcommand{\todo}[1]{\textcolor{red}{\textbf{TODO: #1}}}
\newcommand{\note}[1]{\textcolor{blue}{\textbf{Note: #1}}}
\endinputUse it in your documents:
\documentclass{article}
\usepackage{mycommands}
\begin{document}
The vector \vect{x} is important, \ie it determines the outcome.
\todo{Add more explanation here}
\end{document}Organizing Commands by Category
For larger collections, consider multiple style files:
mymath.sty— Mathematical notationmytext.sty— Text shortcuts and formattingmythesis.sty— Document-specific commandsmydraft.sty— Commands for draft mode (todos, notes, etc.)
Common Pitfalls and How to Avoid Them
1. Command Name Conflicts
If your command name already exists, LaTeX will error:
% This will fail if \section already exists
\newcommand{\section}[1]{...} % Error!
% Use \renewcommand to override existing commands
\renewcommand{\section}[1]{...} % Works
% Or use \providecommand (only defines if not already defined)
\providecommand{\mycommand}[1]{...}2. Fragile Commands in Moving Arguments
Some commands break when used in section titles or captions:
% This might cause problems
\section{The \vect{x} vector}
% Solution 1: Use \protect
\section{The \protect\vect{x} vector}
% Solution 2: Define as robust with etoolbox
\usepackage{etoolbox}
\robustify{\vect}3. Spacing Issues
Commands eat the space after them:
\newcommand{\LaTeX}{LaTeX} % Simplified example
The \LaTeX system is great. % Produces "LaTeXsystem"
% Solutions:
The \LaTeX{} system is great. % Add empty braces
The \LaTeX\ system is great. % Add explicit space
% Better: use xspace package
\newcommand{\LaTeX}{LaTeX\xspace}
The \LaTeX system is great. % Works correctly4. Debugging Complex Commands
When commands don't work as expected:
% Show what LaTeX sees after expansion
\show\mycommand
% Write to log file
\typeout{Debug: The value is \myvalue}
% Visual debugging with draft mode
\newcommand{\debug}[1]{\fbox{#1}} % Puts boxes around contentPerformance Considerations
Custom commands have minimal performance impact, but keep these tips in mind:
- Define commands in the preamble — Commands defined in the document body are re-read each compilation pass
- Avoid deep nesting — Commands that call commands that call commands can slow compilation
- Use
\letfor simple aliases —\let\V\vectis faster than\newcommand{\V}[1]{\vect{#1}}
Quick Reference Cheatsheet
| Task | Syntax |
|------|--------|
| Basic command | \newcommand{\name}{content} |
| With arguments | \newcommand{\name}[n]{...#1...#2...} |
| Optional argument | \newcommand{\name}[2][default]{...#1...#2...} |
| Override existing | \renewcommand{\name}{content} |
| Define if not exists | \providecommand{\name}{content} |
| xparse mandatory | \NewDocumentCommand{\name}{m}{...#1...} |
| xparse optional | \NewDocumentCommand{\name}{o m}{...} |
| xparse with default | \NewDocumentCommand{\name}{O{default} m}{...} |
| xparse star variant | \NewDocumentCommand{\name}{s m}{...} |
Conclusion
Custom LaTeX commands are one of the most powerful tools for improving your writing efficiency. By investing time upfront to create a library of well-designed commands, you'll:
- Write faster with less repetitive typing
- Maintain consistency across your entire document
- Make global changes with single edits
- Produce cleaner, more semantic source code
Start small with a few commonly-used patterns, then gradually expand your command library as you identify repetitive tasks in your workflow. Before long, you'll wonder how you ever worked without them.
Ready to put your custom commands to use? Try them in Thetapad's editor with instant preview and client-side compilation.