Stage 6 · Production, macros and packages 41 / 48 ≈ 22 min read

Custom Commands in LaTeX: newcommand, def and Macros

Macros with up to nine arguments, the TeX primitive layer underneath \newcommand — \def, \edef, \xdef and scope — when expansion happens and why that makes a command fragile in a heading, what catcodes have to do with \verb, and the look-ahead that turns a star into a branch.

    One definition, everywhere it matters

    A macro is a name you teach LaTeX: \newcommand{\name}{replacement}. From then on \name expands to the replacement everywhere. The payoff is semantic: if your vectors are bold today and bold-italic next month, you change one line — not four hundred occurrences.

    It is worth being exact about what actually happens, because the popular description — search and replace — is wrong in ways that cost people hours. Defining a command is an assignment: TeX stores a control sequence in memory whose meaning is a fixed token list. Nothing is substituted in your file, no pass over the text is made, and the replacement is performed again at every use, by the same machinery that reads the input. That is why a definition costs nothing to reuse a thousand times, why it takes effect from the moment it is executed rather than throughout the file, and why a macro can do things a text editor never could: take arguments, look at what follows it, and consult a counter while it expands.

    x \in \mathbb{R}^n \qquad f\colon \mathbb{R} \to \mathbb{R}
    x \in \mathbb{R}^n \qquad f\colon \mathbb{R} \to \mathbb{R}
    Macros live in the preamble so the whole document sees them — and so that nothing writes a half-expanded reading of the name into the .aux file before the definition exists.
    Custom Commands in LaTeX: newcommand, def and Macros — One definition, everywhere it matters
    Rendered output — typeset from the source shown on this page.

    Arguments: #1 to #9

    A macro can take up to nine arguments. The second, optional, argument of \newcommand is the count; the body then refers to the arguments as #1, #2, … Numbers and delimiters stay part of the definition, so \norm{\mathbf{x}}^2 sizes the bars automatically.

    Each slot receives exactly one balanced group, and that single rule explains most macro bugs people bring to a forum. \deriv y x hands y to slot one and x to slot two. \deriv \frac{a}{b} x hands \frac to slot one, then {a} becomes slot two, and {b} x is left behind to be typeset in the wrong place — which is why the symptom is "it worked until I passed it a fraction". Braces are not emphasis in an argument, they are the delimiters; the fix is \deriv{\frac{a}{b}}{x}, never a change to the definition.

    Between two slots, spaces are skipped, and that convenience has a known cost: an optional-argument macro looks ahead past a space, so the sentence "let \norm [1]" really does feed [1] to the macro instead of leaving it as punctuation. Write \norm{}[1] to break the look-ahead, or make the argument mandatory. And because a slot is grabbed before the body is typeset, whatever you pass in is re-read from scratch inside the definition — a reason to keep argument contents plain.

    \lVert \mathbf{x} \rVert = \sqrt{x_1^2 + \cdots + x_n^2}
    \lVert \mathbf{x} \rVert = \sqrt{x_1^2 + \cdots + x_n^2}
    Optional argument syntax: \newcommand{\cmd}[n][default]{…} — if the user omits it, the default fills #1.
    \lVert \mathbf{x} \rVert
    \lVert \mathbf{x} \rVert

    Operators, not just text

    Function names like sin are set upright and get proper spacing before the parenthesis. Your own operators need the same treatment: \DeclareMathOperator{\rank}{rank} — never \text{rank}(x), which gets spacing and limits wrong.

    The difference shows in two places. Spacing: \rank is declared as a math operator, so TeX inserts the correct space around relations and after an opening parenthesis, while \text{rank} is a text box inside maths and leaves the gap to chance. Limits: an operator declared with the starred form, \DeclareMathOperator*{\argmax}{arg\,max}, takes its subscript underneath in a display the way \sum does, which is what readers expect from a named optimisation operator; the unstarred declaration keeps it to the side, and a bare \text{…} refuses to move at all. The command lives in amsmath, so load the package first — without it you get Undefined control sequence on the very line defining your notation.

    There is a use-time alternative, \operatorname{rank}, and it is genuinely good at the job: it applies the same operator treatment to whatever you type, so it fits the operator you mention once and do not want to reserve a name for. The declared form wins for notation used throughout a paper for the same reason any macro wins — the spelling lives in one place — plus one practical edge: a control sequence can be re-pointed by a package or by your own preamble, while four hundred \operatorname{rank} calls have to be found and edited.

    \frac{\mathrm{d} f}{\mathrm{d} t}
    \frac{\mathrm{d} f}{\mathrm{d} t}

    A worked example

    Three definitions cover a whole paper's notation: the real numbers, a norm, and a derivative. Each is used dozens of times but defined once.

    Notice what the listing does not do: it does not define one macro in terms of another's name at the point of use, and it does not spread definitions into the body. The \normdef line is the one real design choice in the block — a defaulted first argument that reads as "the norm with respect to x, unless told otherwise" — and the whole block is four lines long, which is roughly the size at which keeping notation in the preamble stops being a habit and starts being obvious. The moment a project needs a second chapter-private set of names, the block moves into an included file with a one-line comment at its top, and the discipline is the same.

    \frac{\mathrm{d} y}{\mathrm{d} x}
    \frac{\mathrm{d} y}{\mathrm{d} x}
    The derivative macro renders as this — argument order is yours to choose: \deriv{y}{x} or \deriv{f}{t}.
    % Preamble:
    \newcommand{\R}{\mathbb{R}}
    \newcommand{\norm}[1]{\left\lVert #1 \right\rVert}
    \newcommand{\deriv}[2]{\frac{\mathrm{d}#1}{\mathrm{d}#2}}
    % optional argument = default value of #1:
    \newcommand{\normdef}[2][\mathbf{x}]{\norm{#2}_{#1}}
    
    % Body:
    Let $x \in \R^n$ and $p \in \R$.
    Then $\deriv{y}{x}$, $\norm{x}^2$ and $\normdef{v}$ all
    come from single definitions above.

    The four errors macros actually produce

    ! LaTeX Error: Command \R already defined. is \newcommand doing its job: something already owns that name, usually a package you loaded without reading its list of definitions. Decide on purpose — \renewcommand if you genuinely want to replace it, \providecommand if you only want a fallback when nobody else defined it, or rename your macro, which is almost always the right answer for a one-letter name like \R that several packages claim.

    ! Illegal parameter number in definition of \norm. means the body mentions #3 but the declaration said [2]. The count and the highest #n have to agree, and TeX checks this while scanning the definition, not when you call it — so the line number in the message points at the definition in your preamble even though you triggered it by typing in section four.

    ! Paragraph ended before \deriv was complete. is the blank-line trap: an empty line inside a macro argument closes the paragraph, and TeX never finds the closing brace. The same message appears when an argument straddles a \par or a list item boundary. The fix is unspectacular — delete the blank line or move the text out of the argument, because ordinary \newcommand arguments are not allowed to contain paragraphs.

    One more failure has no message to guide you, which makes it worse: a macro defined after its first use expands in half the places you expect, because LaTeX had already met the name as undefined text and written that reading into the .aux file. Keep every definition above every use — in the preamble, or at the very top of an included chapter file for private notation — and never define an argument-taking command inside another command's body, where the # levels silently double to ##1.

    The primitive layer: \def, \edef, \xdef and scope

    Under every LaTeX definer there is exactly one TeX primitive, \def. Its syntax is the shape LaTeX hides: a parameter text — \def\norm#1#2{...}, everything between the name and the opening brace — followed by the replacement tokens, matched literally against the input when the macro is called. Nothing else. \def does not check whether the name already meant something, does not count arguments for you, and does not warn: the previous meaning is simply gone.

    \newcommand is a thin wrapper over that primitive, and it adds three things and no magic: the \@ifdefinable existence test, the parsing of the argument count and default, and the \long switch that decides whether an argument may contain a paragraph. Reading package sources without \def is impossible; writing your documents with it is a bad trade, because a later \def from a package erases your notation with no message and the difference surfaces as a wrong glyph forty pages away.

    Scope is where the wrapper and the primitive really part company. A \def executed inside a group is local: at the closing brace the name reverts to whatever it meant before, or to undefined. That is the mechanism behind a hundred "my macro works on the first page only" reports, and it is why a \def tucked inside an \if branch, inside a table cell or inside an environment body quietly never happened.

    LaTeX's definers globalize instead — a \newcommand inside a group does survive the group — which is why an included file that gets read twice fails on the second pass with Command \notation already defined and not on the first. \gdef is the global TeX form, and \xdef is its \edef twin: \global\edef. Of the four verbs, only \xdef both expands and leaves the group.

    Expansion is the second axis, and it is the one people actually need. A plain \def stores the tokens as they stand, so \def\today{the value is \the\mycount} stores the instruction to look the count up every time \today is used. An \edef performs that instruction while assigning and stores the result — the only way to freeze a moving value, and the reason LaTeX's own internals are full of \edef wherever they capture a label, a counter or a name.

    The cost is that \edef does not stop at things you wanted preserved: it expands whatever it can reach. An \edef over material containing \par, a \protected command, or one half of a \left…\right pair fails at the definition line with ! Undefined control sequence., ! Missing } inserted. or the paragraph error, even though the same tokens typeset perfectly a line later. \string and \noexpand are the two brakes, and LaTeX's \protected@edef is the practical one: it does the \edef with \protect neutralised, so robust commands are stored rather than exploded.

    In a document you write, \edef should be rare — the listing below covers everything a notation block legitimately needs it for. But the distinction is not optional knowledge, because it explains the whole of the next section: the table of contents, the .aux file and a PDF bookmark are all places where LaTeX performs an \edef-like expansion on material you wrote for the typesetter. Once you know that a write expands and a heading does not, the error messages stop looking arbitrary.

    \underbrace{\backslash\texttt{def}}_{\text{store the tokens}} \;\ne\; \underbrace{\backslash\texttt{edef}}_{\text{expand while assigning}} \;\ne\; \underbrace{\backslash\texttt{xdef}}_{\text{expand, then global}}
    \underbrace{\backslash\texttt{def}}_{\text{store the tokens}} \;\ne\; \underbrace{\backslash\texttt{edef}}_{\text{expand while assigning}} \;\ne\; \underbrace{\backslash\texttt{xdef}}_{\text{expand, then global}}
    \edef inside a group is still local; if a frozen value has to outlive the braces, the verb you need is \xdef.
    \documentclass{article}
    \begin{document}
    
    % --- 1. \def is LOCAL: \inside stops existing at the closing brace.
    \begingroup
      \def\inside{readable only here}
      \inside            % fine
    \endgroup
    % \inside            % uncomment: ! Undefined control sequence.
    
    % --- 2. LaTeX's definers globalize, so the name outlives the group.
    %        That is exactly why a file \input twice dies on the SECOND pass
    %        with "Command \notation already defined" rather than the first.
    \begingroup
      \newcommand{\outlives}{still defined after \endgroup}
    \endgroup
    \outlives
    
    % --- 3. \def stores the instruction; \edef performs it while assigning.
    \newcount\mycount \mycount=7
    \def\lazily{the value is \the\mycount}     % looks \mycount up at USE time
    \edef\frozen{the value is \the\mycount}    % looks it up NOW
    \mycount=9
    \noindent \lazily \quad \frozen      % -> "the value is 9" and "the value is 7"
    
    % --- 4. \xdef = \global\edef: the only one of the three that leaves a group.
    \begingroup
      \xdef\alsive{captured \the\mycount}
    \endgroup
    \noindent \alsive                    % -> "captured 9"
    \end{document}

    Why the heading is fine and the contents line is not

    The argument of \section is used three times, in three different economies. It is typeset as a heading now; it is written to the .toc file to be read back by the next run; and, with hyperref loaded, it is converted to a PDF bookmark string. Typesetting is the forgiving case: macros expand as they meet the typesetter, in exactly the context you wrote them for, and everything works.

    A write is not typesetting. \write expands the token list it is carrying out, and the tokens that land in the file are then re-read as if you had typed them, in a context where headings, boxes and maths mean something else. Any command that cannot survive that premature expansion is called fragile — and every macro you have ever defined with \newcommand or \def is fragile by default, because the plain \def layer has no notion of the difference.

    So \section{Norms on $\RR$} prints a perfect heading and then, on the next compile, fails somewhere inside the .toc reading, with an error line pointing at a file you never opened. The two-run delay is what makes this class of bug so expensive: the change you made was to the title, and the message arrives from ./myfile.toc.

    LaTeX's patch is \protect. In normal typesetting \protect is essentially nothing, so the heading comes out right; during a write, \protect\foo is stored as the literal characters \protect \foo, and the macro is expanded later, at use time, when the context is right again.

    \DeclareRobustCommand automates that bookkeeping: it defines the command so that expanding it yields \protect plus its own name, which means the macro can wander into a caption, a heading or a running header without anybody remembering to guard the call site. That is the practical difference between the two definers you might reach for: \newcommand{\dd}{\,\mathrm{d}} is a definition with a debt attached, and \DeclareRobustCommand{\dd}{\,\mathrm{d}} has the debt paid in advance.

    Above robustness sits a stronger, engine-level answer: e-TeX's \protected prefix, which makes a command refuse to expand inside \edef and inside \write at all. Commands built by \NewDocumentCommand are protected this way, which is the real reason the modern definers stopped needing \protect in titles — not a style preference but a different guarantee.

    It cuts both ways, though: a protected macro is not expandable, so it cannot be used where expansion is required — in an \edef, in an \ifnum test, or in a tabular preamble. Three words are worth keeping straight, because the error messages do not say which one you are missing: fragile says "expand me whenever you like" and is the default; robust says "expand me into a guarded form"; protected says "do not expand me at all".

    hyperref adds a fourth budget: a PDF string holds characters, not boxes, so maths, font switches and colour commands are all out of its reach. What hyperref can expand, it expands; what it cannot, it discards while logging Token not allowed in a PDF string (Unicode) — a warning, not an error, which is why bookmarks silently lose your notation.

    \texorpdfstring{math}{replacement} is the surgical fix, and it is worth reaching for before the blunt one: the optional short argument, \section[Plain text]{Long heading with maths}, which settles heading, contents line and bookmark in one stroke and is the right answer whenever the long form is only long because of display machinery. Captions, footnotes, running heads and index entries are the same machine with different file extensions.

    \underbrace{\backslash\texttt{section}\{\cdots\}}_{\text{one argument}} \;\longrightarrow\; \underbrace{\text{page heading}}_{\text{typeset now}} \;+\; \underbrace{\text{.toc line}}_{\text{written, re-read}} \;+\; \underbrace{\text{bookmark}}_{\text{expanded to a string}}
    \underbrace{\backslash\texttt{section}\{\cdots\}}_{\text{one argument}} \;\longrightarrow\; \underbrace{\text{page heading}}_{\text{typeset now}} \;+\; \underbrace{\text{.toc line}}_{\text{written, re-read}} \;+\; \underbrace{\text{bookmark}}_{\text{expanded to a string}}
    If a heading is only there to be typeset, any definition works; the moment it must be written, robust or protected is not decoration but the thing that makes the second pass succeed.
    \documentclass{article}
    \usepackage{amsmath}
    \usepackage{hyperref}       % bookmarks are the third destination
    
    \newcommand{\RR}{\mathbb{R}}                 % fragile: expands inside the write
    \DeclareRobustCommand{\dd}{\,\mathrm{d}}     % robust: expands to \protect\dd
    % protected by construction, no \protect bookkeeping at the call site:
    \NewDocumentCommand{\absv}{m}{\left\lvert #1 \right\rvert}
    
    \begin{document}
    \tableofcontents
    
    \section{Functions on \protect\RR}                          % 1. guard by hand
    \section{Rates \texorpdfstring{$\RR^n$}{R(n)}}              % 2. bookmark-safe text
    \section[Short line for TOC and bookmark]
            {A long heading with \absv{f} and \dd x in it}       % 3. the escape hatch
    \section{Integrals with \dd x}                              % 4. robust: nothing to do
    
    A norm \absv{x} and a differential \dd t in running text, where plain
    expansion would also be fine -- and where \emph{this} macro would not:
    \newcommand{\badline}{first line\par second line}
    % \section{About \badline}   % \par during a write: the heading breaks, the body does not.
    \end{document}

    Catcodes, verbatim, and looking ahead

    One layer below expansion sits the layer that decides what a character is. When TeX reads a file it converts raw bytes into tokens by consulting category codes — catcodes — and the code is attached at that moment, permanently: 1 and 2 are group open and close, 6 is the parameter marker, 8 and 7 are subscript and superscript, 11 is a letter, 12 is "other", 13 is active. Nothing you do later changes a token already in memory, so \catcode changes only text that has not been read yet. \makeatletter and \makeatother are exactly this mechanism, and no more: they promote @ from "other" to "letter" so a name such as \norm@aux parses as one control sequence, which is why package code wraps its internals in them and why writing \def\foo@bar in a document without \makeatletter gives you a name that ends at foo and a stray @bar after it.

    Catcodes explain the whole of verbatim material, and one very specific failure mode. A normal command cannot print a #, a _ or a backslash, because by the time your macro runs those characters are already tokens of the wrong category; and an argument is collected before the macro that receives it executes. So \verb and the verbatim environment cannot be macros taking an argument — they work by changing catcodes and reading the remaining characters of the line directly, which is why the environment form has to start on a line of its own and why \verb inside the argument of another command fails. The tell is the error text: it names an internal control sequence beginning \verb@, not \verb, because the machinery broke halfway through. Same reason a literal # inside a definition body has to be written \#, and why writing to a file doubles every #: at both moments you are dealing with characters that have already been read as parameters.

    The last primitive worth owning is the one no LaTeX wrapper shows you: \futurelet, which copies the meaning of the next token without consuming it, so your macro can branch on what it sees and then let the input carry on as if nothing had happened. It is the pair \futurelet plus \let that implements a look-ahead, and every familiar behaviour is built on it. The star of \newcommand* is not an argument — it is a look-ahead test, which is why a star must sit flush against the name. The optional bracket of \cmd[opt]{arg} is a look-ahead for [, performed by a routine that skips spaces, which is exactly why \norm [1] in running text grabs a bracket that belonged to the prose. Write your own command that accepts either shape and \futurelet is the tool, together with the knowledge that skipping is a choice you can decline.

    Now the boundaries of this page, deliberately marked. \newcommand versus \def is a question about who is allowed to own the name and about when expansion happens, and both are answered above; the argument grammar that xparse exposes — m, o, O{...}, s, t+, v, b, the doubled ## in a nested definition, key-value option lists on a command — is the subject of the lesson on \newcommand mechanics, and naming a structure rather than a piece of notation is \newenvironment, whose begin and end hooks obey a scoping rule with nothing in common with #1. Numbering schemes are counters, not definitions. And expl3 is the language that generalises everything on this page — fully expandable functions, protected functions, key-value interfaces — which is what package authors reach for once they need the machinery itself rather than a name for a symbol. For a norm, a derivative and a set of number systems, define once in the preamble with \newcommand, keep the definitions above every use, and know that \def, expansion and catcodes are what is running underneath when it misbehaves.

    \text{reading fixes meaning:}\quad \underbrace{\#}_{\text{parameter}} \quad \underbrace{\_}_{\text{subscript}} \quad \underbrace{\backslash\texttt{makeatletter}}_{\text{@ becomes a letter}}
    \text{reading fixes meaning:}\quad \underbrace{\#}_{\text{parameter}} \quad \underbrace{\_}_{\text{subscript}} \quad \underbrace{\backslash\texttt{makeatletter}}_{\text{@ becomes a letter}}
    Test a heading macro the way a reader will meet it: compile twice with \tableofcontents and hyperref loaded, because a fragile definition shows its damage only on the pass that reads the file back.

    Lesson cheat sheet

    One key line of code from each section — jump to it or copy it straight from here.

    Section Key code
    x \in \mathbb{R}^n \qquad f\colon \mathbb{R} \to \mathbb{R}
    \lVert \mathbf{x} \rVert = \sqrt{x_1^2 + \cdots + x_n^2}
    \frac{\mathrm{d} f}{\mathrm{d} t}
    \newcommand{\R}{\mathbb{R}}
    \documentclass{article}
    \text{reading fixes meaning:}\quad \underbrace{\#}_{\text{parameter}} \quad \underbrace{\_}_{\text{subscript}} \quad \underbrace{\backslash\texttt{makeatletter}}_{\text{@ becomes a letter}}

    Common mistakes

    • Redefining an existing name: \newcommand fails loudly if \R already exists — that is a feature. Override on purpose with \renewcommand, and only when you know what you are replacing.
    • Naming a macro after digits or using spaces: names are letters only, and \my cmd is two tokens.
    • Forgetting the #1 in the body. The macro then takes an argument and silently throws it away.
    • Hard-coding \left( inside macros that may nest. Use \left…\right pairs matched within one macro, or \DeclarePairedDelimiter from mathtools.
    • Using the macro before its definition, then keeping the stale number or text a failed pass wrote into the .aux file. Definitions belong at the top of the preamble; delete .aux when a document starts quoting references you have already edited out.
    • Putting \verb, a verbatim environment or an unguarded fragile macro inside the argument of another command — a heading, a caption, a footnote. The argument is tokenised before the outer command runs, so the failure names an internal \verb@ sequence, or arrives on the next compile from the .toc. Guard with \protect, give the sectioning command its short optional form, or for a single character write the escape — \#, \_, \&.
    • Reaching for \edef or \xdef where \def was meant, then wondering why a \par, a \protected command or half a \left…\right pair explodes at the definition line. If you do not need the value frozen now, you do not need expansion.

    Questions about this lesson

    What is the difference between \newcommand and \def?
    \def is the TeX primitive: it takes a parameter text, silently overwrites whatever the name already meant, performs no arity or existence check, and defines locally — the meaning ends with the enclosing group. \newcommand is the LaTeX layer over it: it adds the \@ifdefinable test that refuses to overwrite, parses the argument count and default, makes the definition \long unless you star it, and globalizes the name so it survives the group it was defined in. There is a third layer, \edef and \xdef, which differ from \def by expanding the replacement text while assigning — that is how you freeze a counter or a computed value, and also how you blow up on a \par or a fragile command. Use \newcommand in documents; \def belongs to low-level package code and to private locals inside a group you control.
    How do I make a macro work in both text and math mode?
    Keep the math parts in the macro guarded: \newcommand{\ohm}{$\Omega$} works but is fragile; better, define math-only macros and wrap with \ensuremath where genuinely needed: \newcommand{\ohm}{\ensuremath{\Omega}}.
    Can macros take delimited arguments, like \frac{a}{b}?
    Plain \newcommand arguments are brace groups, but mathtools' \DeclarePairedDelimiter and lower-level TeX parsing allow true delimited macros — usually unnecessary in documents, essential in packages.
    Can a LaTeX macro take an optional argument in square brackets?
    Yes, in two flavours. \newcommand{\norm}[2][\mathbf{x}]{...} gives the first argument a default, and you call it as \norm{v} or \norm[C]{v}. The bracket is syntax, not content: an empty pair \norm[]{v} still passes an empty group rather than the default. For more than one optional argument, or keys instead of positions, xkeyval or the expl3 \NewDocumentCommand interface is the right tool.
    Is it safe to define a command inside another command or inside an if-block?
    It compiles, but the scope depends on the definer you used, and that asymmetry surprises people. A \def inside a group is local: it disappears at the closing brace, so a helper defined in one branch of an \ifthenelse or inside a table cell is simply gone afterwards — \gdef is what you need if the name has to leave the group. \newcommand, by contrast, globalizes, so a definition buried inside \textbf{...} or inside an environment body does survive, and the damage shows up on the second pass as "Command \foo already defined" when the file is read again. Neither is a good practice in a document: package authors use \providecommand or \@ifundefined so a name is created only when missing, and in your own preamble keep definitions flat at top level and put the conditional logic inside the macro body.
    Why does my LaTeX command work in the text but break in the table of contents or a PDF bookmark?
    Because a heading, caption or running head is a moving argument: the same tokens are typeset once and written to a file once, and the write expands them while typesetting does not. A macro defined with \newcommand or \def is fragile — it expands into something that cannot be written or cannot be re-read, and you get an error on the next compile or a garbled contents line. Three fixes, in increasing order of comfort: guard the call with \protect; define the macro with \DeclareRobustCommand, which emits \protect plus its own name when expanded; or define it with \NewDocumentCommand, which makes it protected at the engine level so \edef and \write refuse to expand it. For hyperref bookmarks, which keep characters rather than boxes, add \texorpdfstring{math}{plain} or give the sectioning command its optional short form; without that you get the warning "Token not allowed in a PDF string" and a silently truncated bookmark.

    Live playground: edit the LaTeX, see it render

    The preview updates as you type — break it on purpose to see how errors look.

    KaTeX error
    Try an example

    Keep reading

    Three ways into the same idea: the notation itself, the lesson that teaches it, and an article that applies it.