Stage 6 · Production, macros and packages 43 / 48 ≈ 19 min read

LaTeX newcommand: Macros with Arguments, Optional Defaults

A macro definition is not a string substitution: TeX grabs arguments with a parameter text, LaTeX wraps that in a small family of definers, and each choice — arity, defaults, \long, expandability — has an observable consequence in the output or the error log. This page walks the mechanics from the kernel source outward, then shows the xparse syntax that replaces most of the guessing.

    Five commands that define commands, and the gate they share

    The family looks bigger than it is. At the bottom sits the TeX primitive \def: it takes a parameter text, overwrites whatever the name already meant, and never complains. Above it LaTeX builds \newcommand, \renewcommand and \providecommand, which differ only in what they do when the name is already taken — error, overwrite, and keep the old definition respectively — plus \DeclareRobustCommand, which defines a command and simultaneously makes it safe in moving arguments.

    The check \newcommand performs lives in the kernel macro \@ifdefinable. It looks up the control sequence name; if the name already exists it stops with ! LaTeX Error: Command \deriv already defined. It applies one more rule that surprises people: any name whose first three letters are end is rejected even if undefined, because LaTeX reserves \end–name pairs for environment terminators. So \newcommand{\endnote}{…} fails, and \def is not a workaround — it is a footgun in a document.

    Why the noise is worth it: a package or the class may already own the name you chose. \R is a real example in some fonts and packages, and \deg, \norm, \arg are claimed by common bundles. \newcommand turns a silent layout difference forty pages later into an error message with a line number at the definition. \renewcommand is the deliberate override, and it is strict in the mirror image: it errors with Command \foo undefined if the name was never defined, so a typo cannot quietly create a command nobody asked for.

    \providecommand is the one to reach for in a shared file: it defines only if the name is free, and silently throws the new body away otherwise. That makes it right for defaults that a later package is allowed to override, and wrong for anything whose meaning is load-bearing — the silent discard is exactly the failure mode \newcommand exists to prevent.

    Choosing between newcommand, renewcommand, providecommand, def and NewDocumentCommand THE GATE: IS THE NAME ALREADY TAKEN? \@ifdefinable also blocks any name starting with “end” free → define taken → error ! LaTeX Error: Command \R already defined. the failure is the feature: a clash with a package or the kernel is caught at definition time, not three hundred pages later WHAT EACH DEFINER DOES WHEN THE NAME EXISTS \newcommand errors out, keeps the old [arity][default] positional \renewcommand errors if the name is NOT yet defined — the mirror image \providecommand silently throws the new body away — safe defaults in .sty files \def TeX primitive: overwrites without asking, no arity check, package code only \NewDocumentCommand (kernel since LaTeX 2024-11-01) \NewDocumentCommand{\deriv}{ s O{#3} m m }{ ... } argument types instead of a count · nested optionals allowed · protected by construction · Renew/Provide/Declare siblings Default in new documents: \NewDocumentCommand. Reach for \renewcommand only to patch a name you did not define, and never \def at document level.
    The definer family, with the one question each one answers: is the name already taken?

    Arity and defaults: what a numbered argument really is

    The signature is positional: \newcommand{\cmd}[2][default]{…} means "this macro takes two arguments, and if no bracket is present the first one is default". The count is the first optional argument of \newcommand, which is why the syntax reads badly and why \NewDocumentCommand replaces it with a declarative string. Nine slots maximum, numbered from 1, and the number must survive \number — LaTeX reads it as a count, so [2] is fine, [\tw@] is not something to rely on.

    Each slot receives exactly one balanced group. \deriv y t puts y in one slot and t in the other; \deriv \frac{a}{b} t puts \frac alone in slot 1 and then fails, because {a} is the second group and {b} is left over. That is the single most common cause of "my macro works until I pass it a fraction": braces are not decoration, they are the argument delimiters.

    Because a slot holds a group rather than raw tokens, superscripts attach to what you expect: \norm{\mathbf{x}}^{2} raises after the closing brace of the macro, and the \left…\right pair inside the definition sizes itself to the content. That pairing rule bites when a macro emits only one half: \newcommand{\open}{\left(} followed later by \close{\right)} gives Missing \right inserted, because \left and \right must be in the same list and both visible to the math reader.

    A defaulted macro is secretly two macros: the wrapper that looks ahead for a bracket, and a hidden helper that does the work. The wrapper is why such a macro is robust by construction, why a space before the bracket still counts as the bracket, and why the default cannot refer to a later argument — see the next diagram.

    \left(\sum_{k=1}^{n} a_k\right)^{2} \le n \sum_{k=1}^{n} a_k^{2}
    \left(\sum_{k=1}^{n} a_k\right)^{2} \le n \sum_{k=1}^{n} a_k^{2}
    Nested paired delimiters are the case where \left/\right inside a macro pays off: the outer pair resizes to the whole sum, the inner one to its own group.
    How a two-argument newcommand macro expands: definition slots, call site and the resulting tokens 1 · THE DEFINITION (PREAMBLE) \newcommand{\deriv}[2]{% \frac{\mathrm{d}^{##2}#1}{\mathrm{d}##2^{##2}}% } 1st optional = arity (2) slots #1, #2 are the parameters of the macro 2 · THE CALL SITE (BODY) $\deriv{y}{x} + \deriv{f}{t}$ braces are mandatory here: \deriv y x is an error 3 · WHAT TEX ACTUALLY SETS replacement text, slots filled \frac{\mathrm{d}^{x}... → \frac{\mathrm{d}^{2}y}{...} #1 ← {y} #2 ← {x} #1 ← {f} #2 ← {t} Each slot is one balanced group. A slot holding \frac{a}{b} keeps its braces, so superscripts attach to the whole group; nine slots maximum, numbered from 1. 4 · THE TWO THINGS THAT BREAK \newcommand{\a}{\def\b##1{...}} nested definitions double every slot number: ##1 ! LaTeX Error: Command \deriv already defined \newcommand checks the name first — that is the point
    Definition, call site and the token list TeX actually sets, with the two failure modes labelled.

    The hidden helper macro a defaulted newcommand builds

    Here is the kernel definition, in words. Given \newcommand{\norm}[1][2]{…}, LaTeX makes \norm expand to \@protected@testopt\norm\\norm{2} and defines a second macro whose name is the string \norm — backslash included, built with \csname\string#1\endcsname so it cannot collide with a real command — which carries the actual parameter text #1.

    Three consequences follow, and each one has been the cause of a bug somebody has debugged. First, the look-ahead is LaTeX's \@ifnextchar, which skips spaces: the sentence "the value \norm [1]" really does hand [1] to the macro as its optional argument. Break the look-ahead with an empty group — \norm{}[1] — when the bracket is punctuation. Second, the optional-argument wrapper is protected, so such a macro survives being written into the .toc; a \def-style macro with the same behaviour would not. Third, the default is stored as a fixed token list in the wrapper, so it cannot depend on the other arguments.

    xparse removes all three oddities: \NewDocumentCommand{\norm}{ O{2} m }{…} uses the o/O{…} types, and there the default can reference a later slot — \NewDocumentCommand{\deriv}{O{#3} m m} is legal and reads naturally. Its optional arguments also nest properly, so \foo[\bar[x]]{y} parses; with \newcommand the inner bracket closes the outer one and the argument arrives mangled.

    If you ever need to see which of the two shapes you are holding, \show\norm prints the definition: the \@protected@testopt line is the giveaway that you are looking at a defaulted LaTeX macro rather than a plain \def.

    A newcommand with an optional argument becomes two macros: a look-ahead wrapper plus a hidden helper whose name contains a backslash WHAT YOU WRITE \newcommand{\norm}[1][2]{% \left\lVert #1 \right\rVert_{#1}} WHAT THE KERNEL MAKES (2 MACROS) \def\norm{\@protected@testopt \norm \\norm {2}} wrapper: look-ahead for an opening bracket hidden helper is named backslash + “norm” PATH A · BRACKET PRESENT \norm{\mathbf{v}} no bracket found, so the default 2 is used for #1 — the helper then grabs 1 slot PATH B · BRACKET SUPPLIED \norm[\infty]{\mathbf{v}} the bracketed group becomes #1, the brace group becomes #2 of the helper THREE CONSEQUENCES YOU CAN ONLY PREDICT IF YOU KNOW THE SHAPE ABOVE 1 · The look-ahead skips spaces, so “the value \norm [1]” really does feed [1] to the macro — write \norm{} [1] to stop it eating your bracket. 2 · The wrapper is why such a macro is robust in a moving argument, and 3 · why the default cannot refer to a later argument the way xparse’s O{#2} can.
    A defaulted newcommand becomes a wrapper plus a hidden helper, which explains space-skipping, robustness, and the fixed default.

    Why the hash doubles: parameters inside parameters

    When the body of a definition contains another definition, every parameter number belonging to the inner macro must be written doubled: ##1. The reason is mechanical rather than mystical — TeX reads the replacement text as an argument, and one layer of # is consumed when that argument is collected. Whatever survives the collection is what the inner \def then sees, so #1 in the source becomes #1 in the stored text only when you write ##1.

    The places this shows up are exactly the places where you are writing a definition inside something else: inside \newcommand and \NewDocumentCommand bodies, inside the begin and end code of \newenvironment, inside \AtBeginDocument/\AtEndOfPackage code, inside \fancyhead and \patchcmd arguments, and inside \addtocontents. If a nested definition gives Illegal parameter number in definition of \foo, the fix is doubling; if it gives You can't use `#1' in this position, an inner parameter has leaked out of the macro that owns it.

    The flip side is that ## inside a plain \edef or \xdef is a different question — there you are not nesting a definition, you are expanding one, and # handling follows expansion rules instead. The practical rule that keeps people out of trouble: do not write nested definitions at document level at all. Define the helper first with \newcommand, then use it.

    One more family of mistakes lives in \csname: building a name from a macro argument, as in the src listing, is powerful and totally legitimate, but the doubled hash rule still applies to the body being defined. This is how packages generate a family of related commands from one loop, and it is why reading a package source sometimes looks like reading a compiler.

    \frac{\partial^{2} f}{\partial x\,\partial y} = \frac{\partial^{2} f}{\partial y\,\partial x}
    \frac{\partial^{2} f}{\partial x\,\partial y} = \frac{\partial^{2} f}{\partial y\,\partial x}
    The mixed partial derivative above is a typical macro output — \pdv{2}{f}{x}{y}-style tools exist precisely so this line is typed once.
    \documentclass{article}
    \begin{document}
    
    % A \newcommand whose body itself defines a macro: every parameter number of
    % the INNER definition must be doubled, because the whole body is already the
    % replacement text of a parameterised macro.
    \newcommand{\mkmul}[1]{%
      \expandafter\newcommand\csname #1squared\endcsname[1]{##1^{2}\times ##1}%
    }
    \mkmul{mov}              % defines \movsquared with one argument
    $\movsquared{a}$         % -> a^{2}\times a
    
    % The same rule inside \NewDocumentCommand, and inside \AtBeginDocument,
    % \addtocontents, \fancyhead or any other place that stores a definition.
    \newcommand{\report}[1]{%
      \typeout{--- \string#1 \space starts here ---}%
      \textbf{#1}%
    }
    \report{Lemma 1.2}
    
    % Wrong: \newcommand{\a}{\def\b#1{#1}}  -> "Illegal parameter number"
    % Right: \newcommand{\a}{\def\b##1{##1}}
    \end{document}

    long versus short: the blank line that breaks a macro

    TeX distinguishes parameters that may contain a \par token from those that may not. A \long\def macro accepts a paragraph in its argument; a plain \def sees the blank line, panics and reports ! Paragraph ended before \foo was complete. LaTeX sides with the permissive version: \newcommand defines a \long macro, and the starred \newcommand* is the restricted one. The switch is a single kernel token, \l@ngrel@x, set to \long or \relax depending on whether \@ifstar saw a star.

    So \newcommand*{\citep}[1]{…} is the version that catches you out when somebody writes a blank line inside the argument, and \newcommand{\state}[1]{…} is the version that lets a whole multi-paragraph environment body through. Since the 2025 LaTeX release, an argument-free \newcommand is defined short even without the star, because \long is only meaningful for parameters — a small change that removes a false sense of safety.

    xparse made the decision per argument instead of per macro: +m makes that one argument long, + before b lets an environment body contain paragraphs, and the optional types are short unless you mark them. That is strictly more precise than "star or no star", and it is why a modern definition of something like \NewDocumentEnvironment{law}{+b} reads as an explicit contract with the reader.

    Two adjacent behaviours clear up once \long is understood. The end code of a \newenvironment is \long in the unstarred form and may contain \pars — but it takes no parameters, which is a separate kernel decision. And a blank line before \end{…} is not a "paragraph ended" error for a long macro; it becomes an empty paragraph with vertical space you then hunt through the source.

    \chi_{\mathbb{Q}}(x) = \begin{cases} 1 & x \in \mathbb{Q} \\ 0 & x \notin \mathbb{Q} \end{cases}
    \chi_{\mathbb{Q}}(x) = \begin{cases} 1 & x \in \mathbb{Q} \\ 0 & x \notin \mathbb{Q} \end{cases}
    A macro that has to swallow a body like this one — cases, alignment, several paragraphs — is a long-macro job, or an environment.

    Argument types: describing arguments instead of counting them

    The xparse specification is a string of letters, one per argument, and it is worth memorising as a table rather than looking up weekly. Mandatory: m a braced group, r/R delimited by tokens you specify, v read verbatim between two identical characters, b the body of an environment, c the body collected verbatim. Optional: o a bracket or \NoValue, O{def} a bracket with a default, d()/D(){} for other delimiters, s a star giving \BooleanTrue/\BooleanFalse, t+ any single optional token, e{}/E{} for embellishments that each carry a value.

    The values are not strings but markers, and there are dedicated tests: \IfNoValueTF{#1}, \IfValueTF{#1} and \IfBooleanTF{#1}. Comparing an o-type argument with \ifx against an empty group is a bug, because an absent optional argument is \NoValue, not {}[]-empty — \foo[]{x} supplies an empty value, \foo{x} supplies \NoValue, and those are different things you may want to distinguish.

    Three modifiers carry most of the remaining power. + makes that argument long (paragraphs allowed). ! stops spaces being skipped before an optional argument — \NewDocumentCommand\\{!s !o} is exactly how amsmath keeps \\[3pt] working while \\ [3pt] does not grab. = declares that the following optional argument is a keyval list with a named default key, which is how a modern \caption-style command accepts both free text and key=value in the same brackets.

    Finally >{\processor} attaches an argument processor: the grabbed tokens are passed through your function before the body sees them, so validation, upper-casing or defaulting happens at the boundary instead of inside the logic. Processors apply to defaults too, but deliberately not to \NoValue.

    \def\xto#1{\xrightarrow{\;#1\;}} \quad A \xto{\varphi} B
    \def\xto#1{\xrightarrow{\;#1\;}} \quad A \xto{\varphi} B
    A star-bearing macro reads better as { s O{#4} m m } than as [4][…], and the reader of the file can tell the shape without running it.
    \documentclass[11pt,a4paper]{article}
    \usepackage{amsmath,amssymb}
    \usepackage{mathtools}   % \DeclarePairedDelimiter, \coloneqq, ...
    \usepackage{xparse}      % kernel since LaTeX 2024-11-01; harmless shim today
    
    \begin{document}
    % --- 1. plain, no arguments: an abbreviation with a fixed spelling
    \NewDocumentCommand{\R}{}{\mathbb{R}}
    
    % --- 2. star + optional + mandatory: one signature, readable at a glance
    %     s = star, O{#4} = optional whose default is the 4th argument, m, m
    \NewDocumentCommand{\deriv}{ s O{#4} m m }{%
      \IfBooleanTF{#1}
        {\frac{\mathrm{d}^{#2}\,#3}{\mathrm{d}#4^{#2}}}   % * : plain d
        {\frac{\partial^{#2}\,#3}{\partial #4^{#2}}}%      %   : partial
    }
    
    % --- 3. paired delimiters that scale, from mathtools
    \DeclarePairedDelimiter{\abs}{\lvert}{\rvert}
    \DeclarePairedDelimiterX{\norm}[1]{\lVert}{\rVert}{#1}
    \DeclarePairedDelimiterX{\iprod}[2]{\langle}{\rangle}{#1,#2}
    
    % --- 4. operators: never \text{rank}, which loses spacing and limits
    \DeclareMathOperator{\supp}{supp}
    \DeclareMathOperator*{\esssup}{ess\,sup}
    
    % --- 5. a default that another package may already have set
    \providecommand{\dd}{\,\mathrm{d}}
    
    Body: $\deriv{f}{t}$, $\deriv*{y}{x}$, $\deriv[3]{y}{x}$,
    $\abs{\frac{z_1}{z_2}}$, $\norm{\mathbf{v}}$, $\iprod{u}{v}$,
    $\supp f$, $\esssup f$, $x\in\R^n$.
    \end{document}

    Expansion: where macros get eaten before they run

    A macro is data in three of the places a document lives: the .aux and .toc files (written during one run, read in the next), \edef/\xdef (which expand while assigning), and PDF bookmark strings written by hyperref. In all three, the tokens are expanded now rather than typeset later, and an ordinary macro that calls something fragile — \parskip changes, \protected commands, a \par — either dies or writes nonsense.

    LaTeX's answer was \protect: a command is prevented from expanding at write time and re-expanded at use time. \newcommand with an optional argument and \DeclareRobustCommand are robust by construction; xparse commands are protected, which is stronger and engine-level — a protected macro simply refuses to expand inside \edef and inside the \write, so it survives a moving argument without you remembering to guard it.

    The cost of protection is that the macro is not expandable, and there are real places that need the opposite: a \MyMultiCol used inside a tabular preamble, a conditional evaluated by \ifnum, a value fed to \setlength. For those, xparse provides \NewExpandableDocumentCommand, with strict limits — the argument types must be grabbable by pure expansion (roughly m, l, u, and short arguments), and the code must not perform assignments or change catcodes. The legacy name \DeclareExpandableDocumentCommand still appears in old documents.

    Symptoms worth recognising on sight: ! Undefined control sequence pointing at \protect, a table-of-contents line that prints the wrong thing while the section heading itself is right (the write expanded too early), and ! Argument of \foo has an extra }, which usually means an \edef chewed a token that was supposed to survive.

    \bigl|\,\lvert z \rvert - \lvert w \rvert\,\bigr| \le \lvert z + w \rvert
    \bigl|\,\lvert z \rvert - \lvert w \rvert\,\bigr| \le \lvert z + w \rvert
    Manual sizing like \bigl…\bigr is what a \DeclarePairedDelimiter emits in its starred form, and unlike \left…\right it can be split across two macros safely.

    Option lists on a command, and the package file that carries all this

    Once a notation block passes a dozen definitions, the bracket syntax stops being enough and you want names: \plot[color=red, width=6cm]{2}. The mechanism underneath every package that offers this is the same: an optional argument is grabbed as one token list and handed to a key parser. With keyval you declare \define@key{family}{color}{\def\plot@color{#1}} per key and call \setkeys{family}{#1} in the begin code; xkeyval adds families, \define@cmdkeys for string keys, \define@boolkeys for flags and \presetkeys for defaults. An unknown key surfaces as Package keyval Error: framewidth not allowed — a typo in a key name, always.

    The constraint that trips authors is timing: keys set in the begin code can only influence what is typeset after that point, so anything decided by an option has to be deferred rather than executed at definition time. If the option must change a length that a box was already built with, the box has to be rebuilt.

    New code should skip the hand-rolled dance and use ltcmd's = modifier with LaTeX3 keys (\keys_define:nn, \keys_set:nn, .code:n and .initial:n), which gives unknown-key handling, sub-families and documentation structure for free. That is what tcolorbox, mdframed and KOMA are built on, which is why their option sets behave consistently across commands and environments.

    When the block stabilises, move it out of the preamble into a one-file package: \NeedsTeXFormat, \ProvidesPackage{mynotation}[date version note], \RequirePackage for what you depend on, \DeclareOption/\ProcessOptions for your own switches, then the definitions. The version line in \ProvidesPackage is not decoration — \@ifpackagelater{mynotation}{2026/01/01}{…}{…} lets a document adapt when the notation changes, and the .log lists every package with its date, so a broken build on a colleague's machine becomes a version comparison instead of a rumour. The listing below is the whole shape of it.

    \argmax_{\theta} \sum_{i=1}^{n} \log p(y_i \mid x_i;\theta)
    \argmax_{\theta} \sum_{i=1}^{n} \log p(y_i \mid x_i;\theta)
    \DeclareMathOperator*{\esssup} puts limits underneath in display style — one of the few things a plain \text{...} macro can never imitate.
    % mynotation.sty — put it next to the .tex file, or in the project tree.
    \NeedsTeXFormat{LaTeX2e}[2021-11-15]
    \ProvidesPackage{mynotation}[2026-01-15 v1.2 project notation]
    
    \RequirePackage{amsmath}
    \RequirePackage{mathtools}
    \RequirePackage{xparse}
    
    \newif\ifmynot@uprightdiff
    \DeclareOption{uprightdiff}{\mynot@uprightdifftrue}
    \DeclareOption*{\PassOptionsToPackage{\CurrentOption}{amsmath}}
    \ProcessOptions\relax
    
    \DeclareDocumentCommand{\dif}{}{%
      \ifmynot@uprightdiff\,\mathrm{d}\else\,\mathrm{D}\fi}   % \DeclareDocumentCommand: no "already defined" test
    
    \NewDocumentCommand{\pdv}{ s O{#4} m m }{%
      \IfBooleanTF{#1}
        {\frac{\mathrm{d}^{#2}\,#3}{\mathrm{d}#4^{#2}}}
        {\frac{\partial^{#2}\,#3}{\partial #4^{#2}}}}
    
    \AtEndOfPackage{\typeout{mynotation: notation block loaded}}
    \endinput

    Lesson cheat sheet

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

    Section Key code
    \left(\sum_{k=1}^{n} a_k\right)^{2} \le n \sum_{k=1}^{n} a_k^{2}
    \documentclass{article}
    \chi_{\mathbb{Q}}(x) = \begin{cases} 1 & x \in \mathbb{Q} \\ 0 & x \notin \mathbb{Q} \end{cases}
    \documentclass[11pt,a4paper]{article}
    \bigl|\,\lvert z \rvert - \lvert w \rvert\,\bigr| \le \lvert z + w \rvert
    \NeedsTeXFormat{LaTeX2e}[2021-11-15]

    Common mistakes

    • Illegal parameter number in definition of \foo — a definition nested inside a definition without doubling the inner slots. Write ##1, or split the helper out of the macro.
    • Passing \frac{a}{b} to a one-argument macro as \cmd \frac{a}{b}: slot 1 receives \frac, the rest of the line receives the leftovers. Braces are the argument delimiter, not a style choice.
    • "Paragraph ended before \myem was complete" — a blank line inside the argument of a \newcommand* or of a short xparse argument. Use the unstarred form or mark the argument +m.
    • Relying on \providecommand for notation that must exist: if a package already owns the name your definition is discarded silently. Choose \renewcommand and read what you are replacing.
    • Letting a defaulted macro eat a bracket that belongs to the prose — "the value \norm [1]" — because the look-ahead skips spaces. Write \norm{}[1], or make the argument mandatory.
    • Using a protected xparse macro where expansion is required, inside a tabular preamble or an \ifnum test. That is the case for \NewExpandableDocumentCommand, not for \newcommand.
    • Comparing an o-type argument with \ifx against \@empty: an omitted optional argument is \NoValue, so the test never fires. Use \IfNoValueTF.

    Questions about this lesson

    Should I use newcommand or NewDocumentCommand in a new LaTeX document?
    NewDocumentCommand. It declares each argument by type instead of by position, it lets an optional argument's default depend on another argument, its nested optional arguments parse correctly, and the macros it creates are protected, so they survive the table of contents and PDF bookmarks without extra work. Since the LaTeX 2024-11-01 release it is a kernel command; on older installations load xparse. Use plain newcommand when you want the shortest possible line for a two-argument math abbreviation, and \renewcommand or \providecommand when the name is not yours.
    Why does my newcommand say the command is already defined?
    Because it is: \newcommand checks with the kernel macro \@ifdefinable and refuses to overwrite, which is the safety feature that catches clashes with packages and with the format. Either rename the macro, use \renewcommand deliberately after checking what the old meaning was, or use \providecommand in shared code where a package is allowed to win. Note that names beginning with end are rejected even when undefined, because LaTeX reserves \end pairs for environments.
    What does a double hash mean in a LaTeX macro definition?
    It is an escaped parameter number. When your definition contains another definition — a \def or \newcommand inside a \newcommand, or code inside \AtBeginDocument, \fancyhead or an environment — TeX consumes one layer of # while collecting the outer body, so the inner macro's slots must be written ##1, ##2. Single #1 still refers to the outer macro's own argument.
    How do I give a LaTeX command an optional argument with a default value?
    With \newcommand{\norm}[1][2]{...} the second bracket is the default for #1, or with \NewDocumentCommand{\norm}{O{2} m}{...}. The xparse form is safer: optional arguments nest, spaces can be made significant with the ! modifier, and the default may reference a later argument. Either way, remember the look-ahead skips spaces, so a bracket in the following text can be grabbed; {\cmd}{}[1] stops it.
    Why does my macro fail only in the table of contents or in a PDF bookmark?
    Because those are written to a file and expanded at write time rather than typeset. A fragile macro expands into something that cannot be written, and you get an error or a garbled heading. Make the macro robust with \DeclareRobustCommand, or define it with \NewDocumentCommand, which is protected by construction; alternatively give the sectioning command its optional short form.
    Can a LaTeX macro take a key-value option list like color=red, width=2cm?
    Yes, and the plumbing is always the same: grab one optional argument and pass it to a key parser. keyval provides \define@key plus \setkeys, xkeyval adds families, string and boolean keys and \presetkeys defaults, and ltcmd has an = argument modifier that turns an optional argument into a keyval list with a named default key. LaTeX3 keys (\keys_define:nn, .code:n, .initial:n) are the modern route and what tcolorbox and KOMA expose.

    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.