Defining macros

The best reason to define your own LaTeX command — a macro — is not that it saves typing. Picture a thesis in which every vector is set as \mathbf{v}, four hundred times over, and a supervisor who now wants arrows instead. If those vectors had been written \vect{v}, backed by a single \newcommand, the whole change is one line in the preamble; otherwise it is four hundred careful edits. A macro is the place where you keep the right to change your mind later. This page starts from \newcommand and its arguments, sorts out \renewcommand and \providecommand, explains where the space after a macro name disappears to, and ends with fragile commands, \protect, and the modern \NewDocumentCommand.

Defining your own command with \newcommand

The whole syntax is one line: \newcommand{\name}{definition}. The first argument is the name you want, the second is what it stands for, and from then on every \name you type is replaced by definition. The natural home for it is the preamble, before \begin{document}. This is where the vector story pays off: the name \vect refers to a meaning, not an appearance. Writing “this is a vector” instead of “this is bold” leaves the decision — bold, or an arrow on top — in exactly one place. It is the same bargain LaTeX itself offers: you write \section rather than setting 14pt bold by hand for precisely this reason.

latex
% preamble: one line decides how every vector in the document looks
\usepackage{amsmath,amssymb}
\newcommand{\vect}[1]{\mathbf{#1}}
% \newcommand{\vect}[1]{\vec{#1}}   % swap this line, the whole thesis follows

% semantic names for things you refer to constantly
\newcommand{\R}{\mathbb{R}}
\newcommand{\dd}{\mathrm{d}}

% body
\[ \vect{v} \cdot \vect{w} = \lvert \vect{v} \rvert \, \lvert \vect{w} \rvert \cos\theta \]
\[ \int_{\R} f(x) \, \dd x \]

Macros that take arguments, and the optional one

To vary the contents at each call, put the number of arguments in square brackets after the name and pick them up inside the definition as #1, #2, and so on: \newcommand{\name}[⟨nargs⟩]{... #1 #2 ...}. There is exactly one hard ceiling — parameters run #1 through #9, nine at most. What makes it interesting is that asking for a tenth produces ! You already have nine parameters., and that message comes from the TeX engine, not from LaTeX. The limit belongs to the \def primitive underneath, so \newcommand has no way to lift it. Needing more than nine is usually a sign to switch the design to key–value options rather than positional arguments.

latex
% two mandatory arguments: a number and a unit
\newcommand{\unit}[2]{#1\,\mathrm{#2}}

$a = \unit{9.8}{m/s^2}$

You can go one step further and make the first argument optional, with a default value. That is the doubled-bracket form, \newcommand{\name}[⟨nargs⟩][⟨default⟩]{...}: #1 becomes the optional argument, and calling without it substitutes ⟨default⟩. You then write \name{...} to take the default or \name[x]{...} to set #1 to x; any remaining mandatory arguments are counted from #2. The counting is the trap here — [⟨nargs⟩] is the total number of arguments, the optional one included. In the example below, [2][2] means “two arguments, the first optional with default 2”.

latex
% two arguments in total; the first is optional and defaults to 2
\newcommand{\pow}[2][2]{(x + y)^{#1}_{#2}}

$\pow{n}$      % -> (x + y)^2_n
$\pow[3]{n}$   % -> (x + y)^3_n

% starred form: the argument may not contain a blank line
\newcommand*{\keyword}[1]{\textsf{#1}}

Two details are worth adding. First, omitting [⟨default⟩] is not the same as writing empty brackets []: the latter gives an optional argument whose default is the empty string. Second, the starred \newcommand* builds a “short” macro whose argument may not contain a blank line (a \par). That looks like a restriction but is really a diagnostic: forget a closing brace and you get ! Paragraph ended before \keyword was complete. near the mistake. Without the star, TeX happily reads the next paragraph, and the one after it, as part of the argument, and the error surfaces pages later. Adding * to any macro that has no business spanning paragraphs is a kindness to your future self.

The difference between \newcommand, \renewcommand and \providecommand

All three take arguments in exactly the same way; what differs is how each reacts to a name that is already taken. \newcommand refuses and stops, \renewcommand overwrites, and \providecommand quietly stands down and keeps the existing definition. So pointing \newcommand at an existing name halts with ! LaTeX Error: Command \emph already defined., while pointing \renewcommand at an undefined one halts with ! LaTeX Error: Command \foo undefined. The two errors are a matched pair, guarding from opposite sides against clobbering something by accident and against thinking you clobbered something when you did not.

Here is an oddity: writing \newcommand{\endnotes}{...} stops with Command \endnotes already defined. even though no command of that name exists anywhere. The error’s second line gives the game away — it continues Or name \end... illegal, see p.192 of the manual. The name check inside latex.ltx first confirms the name is undefined and then additionally demands that its first three letters not be end, and that the name not be relax. Since \end{itemize} works by calling an internal \enditemize, letting anyone invent names beginning with end would break the matching of environments, so the whole prefix is reserved. The wording “already defined” is simply a blunt message covering both cases.

CommandOn an existing nameUse it for
\newcommandStops with an errorCreating a new command safely
\renewcommandOverwrites it (errors if undefined)Reworking an existing command
\providecommandDoes nothing (keeps the old one)Style files that may load twice
\DeclareRobustCommandOverwrites it and logs a noteRobust commands for moving arguments

The practical division of labour is clear. \renewcommand is the door marked “replace something LaTeX already provides”, and changing a list bullet with \renewcommand{\labelitemi}{--} is the classic case. \providecommand declares “supply this if nobody else has”, so that your own style file survives being read twice from two different places. In the example below \vect already exists, so \providecommand does nothing at all and the bold definition survives. And \DeclareRobustCommand is the star of the next section: it does not stop on an existing name, it simply leaves a line like LaTeX Info: Redefining \emph on input line 2. in the .log. Recording the overwrite rather than performing it silently is its real difference from \renewcommand.

latex
% replace something the class already defines
\renewcommand{\labelitemi}{--}

% define only if nobody else did; here \vect exists, so this line is a no-op
\providecommand{\vect}[1]{\vec{#1}}

% redefine on purpose, and say so in the log
\DeclareRobustCommand{\emph}[1]{\textbf{#1}}

Why the space after a macro disappears, and what \xspace fixes

A command name made only of letters ends at the first non-letter, and the spaces that follow are swallowed as the marker that ends the name. So with \newcommand{\lab}{Knuth Lab} in the preamble, typing \lab was founded. prints “Knuth Labwas founded.” The space did not vanish; TeX ate it while working out where the name \lab stops. The revealing part is the exception: \$ de keeps its space and prints “$ de”. \$ is a one-character control symbol made of a non-letter, so its name is complete after that single character and there is no reason to read ahead. The trap therefore applies only to command names spelled with letters.

latex
\usepackage{xspace}
\newcommand{\lab}{Knuth Lab}
\newcommand{\labx}{Knuth Lab\xspace}

\lab was founded.     % -> Knuth Labwas founded.
\lab{} was founded.   % -> Knuth Lab was founded.
\lab\ was founded.    % -> Knuth Lab was founded.
\labx was founded.    % -> Knuth Lab was founded.
\labx, and a comma.   % -> Knuth Lab, and a comma.

There are three fixes. The standard one is an empty pair of braces, \lab{}, marking where the name ends; next is the control space \lab\ ; and third is \xspace from the xspace package. What makes \xspace clever is that it does not add a space unconditionally — it peeks at the next token first. The exception list in xspace.sty holds , . ' / ? ; : ! ~ - ) and closing braces, along with \footnote and friends, and no space is inserted before any of them. That is why \labx, and sets correctly as “Knuth Lab, and”. The package is part of the LaTeX tools bundle and was originally written by David Carlisle; \xspaceaddexceptions lets you extend the list. Note the cost, though: \xspace is a lookahead trick, unnecessary for macros that take arguments (they end in } anyway) and occasionally surprising inside another macro’s argument. When in doubt, {} is the safest of the three.

Fragile commands, moving arguments, \protect and \DeclareRobustCommand

A macro of your own can break suddenly inside a section heading or a caption. The cause is the moving argument. The text of \section{...} is not only typeset in the body: it is also written out to the .aux file for the table of contents and passed along to the running head. The same material “moves” to other places. \caption{...}, \thanks{...}, and the @{...} expressions of tabular and array behave the same way. A command containing code that loses its meaning when expanded at the moment of writing-out is called a fragile command; one that survives being written out as-is is a robust command.

The classic remedy is \protect, placed immediately before a fragile command to say “do not expand this here — write it out as it stands”. It shields exactly one command at a time. There is good news, though: since the October 2019 LaTeX release, a great many formerly fragile commands were made robust. The change is recorded in LaTeX News 30 under “Making more user commands robust”, and it went as far as \begin and \end, so whole environments now work inside headings. The stubborn holdout is \verb: put it in a section title and the run stops with ! LaTeX Error: \verb illegal in argument. (usually dragging ! Paragraph ended before \@sect was complete. along with it). \protect cannot rescue that one, so in a heading or caption the practical move is to rewrite it as \texttt{...}.

latex
% \verb cannot go here at all -- rewrite it
\section{The \texttt{\textbackslash par} primitive}

% a macro that is robust from the start, even though \ifmmode is fragile
\DeclareRobustCommand{\seq}[2][n]{%
  \ifmmode #2_{1}\ldots #2_{#1}\else\textbf{??}\fi
}
\section{Sequences $\seq{x}$}   % works without \protect

For your own macros, defining them robustly from the outset with \DeclareRobustCommand is more reliable than remembering \protect every time. It takes arguments exactly like \newcommand, and even if the body mixes in fragile code such as \ifmmode, the resulting command survives a moving argument. The \seq above is the example from LaTeX’s own clsguide, written to demonstrate precisely this. The cost is a slight inefficiency, so there is no need to make every macro robust when it will never appear in a heading or caption. The single question worth asking is whether the macro could ever end up in the table of contents.

\NewDocumentCommand: the modern way to define commands

\newcommand can only build one shape: at most one bracketed optional argument, followed by mandatory ones. \NewDocumentCommand{\name}{⟨arg-spec⟩}{...} removes that ceiling. Instead of a number of arguments you hand it an argument specification (arg-spec): a string of letters naming the kind of each argument. It began as a feature of the xparse package, but the 2020-10-01 release folded it into the LaTeX kernel (the ltcmd module), so it now works without \usepackage{xparse}. LaTeX News 32 records the move.

SpecifierMeaningHow it arrives in the body
mA mandatory argumentAn ordinary #1 and so on
oAn optional [...] argumentA no-value marker if absent
O{default}Optional, with a defaultThe default if absent
sAn optional star *Tested with \IfBooleanTF

This is where it decisively beats \newcommand: it can take several optional arguments, and it handles starred variants as a first-class feature. Write s and #1 arrives as a boolean saying whether the star was there, which you branch on with \IfBooleanTF{#1}{starred}{plain}. Swapping the prefix among New, Renew, Provide and Declare gives you the counterparts of \newcommand, \renewcommand, \providecommand and an unconditional overwrite. For new code this interface can be the default — though \newcommand has neither gone away nor gone stale, and for a short definition with one or two arguments it remains perfectly good.

latex
% s = optional star, m = mandatory argument
\NewDocumentCommand{\diff}{s m}{%
  \IfBooleanTF{#1}%
    {\frac{\mathrm{d}}{\mathrm{d}#2}}%   starred: d/dx
    {\mathrm{d}#2}%                      plain:   dx
}

$\diff{x}$    % -> dx
$\diff*{x}$   % -> d/dx

% O{...} gives an optional argument with a default
\NewDocumentCommand{\note}{O{note} m}{\textbf{#1:} #2}

Naming macros without clashes, and where to keep the definitions

The best tool for avoiding a name clash is \newcommand itself. Overwrite first with \renewcommand or \def and you never learn what you destroyed; define with \newcommand first and an already defined error tells you immediately that somebody is using the name. That is exactly why you should not casually flatten kernel or package commands with \renewcommand. For your own names, avoid anything too short and prefer a project-specific prefix (\myR, \bookTitle). Short mathematical operator names in particular are already taken — \ker, \deg, \arg, \Re — so if you want \R, it is worth one trial run through \newcommand to find out.

Too many macros are as unreadable as too few. An extreme abbreviation like \newcommand{\x}{\xi} is a cipher to your future self and to a co-author. Reserve macros for what is repeated often, likely to change in bulk, or worth naming by meaning, and write the rest out plainly — it usually reads better. The test is simple: can the name be understood on sight? \vect can; \x cannot.

Finally, placement. One paper is fine with definitions in the preamble, but a book split into per-chapter files, or several papers sharing one notation, is easier to manage if the definitions live in their own file loaded with \usepackage. There is a small bonus to that: inside a .sty or .cls, @ counts as a letter, so internal names such as \mybook@vecfont work without writing \makeatletter at all. Since a name containing @ cannot be called from the document body, you get a naming distinction between the commands you expose and the ones that are private. Doing the same in a preamble means fencing the code between \makeatletter and \makeatother, which is one more thing to get wrong.

latex
% ---- mynotation.sty --------------------------------------------
\ProvidesPackage{mynotation}[2024/01/01 shared notation]
\RequirePackage{amsmath,amssymb}

% private: the @ makes it uncallable from the document body
\newcommand{\mynot@vecfont}[1]{\mathbf{#1}}

% public
\newcommand{\vect}[1]{\mynot@vecfont{#1}}
\newcommand{\R}{\mathbb{R}}

% ---- thesis.tex ------------------------------------------------
% \usepackage{mynotation}