LaTeX Commands and Macros: \newcommand, \renewcommand and \def
Quick answer
- A shortcut:
\newcommand{\R}{\mathbb{R}}in the preamble, then$x \in \R$. - With arguments:
\newcommand{\norm}[1]{\lVert #1 \rVert}, used as\norm{x}. - Optional first argument:
\newcommand{\vecnorm}[2][2]{\lVert #2 \rVert_{#1}}—[2]arguments, the first defaults to2. - Change an existing command:
\renewcommand; define only if missing:\providecommand. - Operator names:
\DeclareMathOperator{\tr}{tr}(amsmath) for upright names with correct spacing. - Avoid
\defin documents: it overwrites any command without warning. For complex signatures use\NewDocumentCommand{\name}{O{2} m}{...}.
\documentclass{article}
\usepackage{amsmath,amssymb}
\newcommand{\R}{\mathbb{R}} % no arguments
\newcommand{\norm}[1]{\lVert #1 \rVert} % one argument
\newcommand{\vecnorm}[2][2]{\lVert #2 \rVert_{#1}} % optional first argument
\DeclareMathOperator{\tr}{tr} % operator name
\renewcommand{\vec}[1]{\mathbf{#1}} % change an existing command
\begin{document}
Let $\vec{x} \in \R^n$ with $\norm{\vec{x}} \le 1$.
Then $\vecnorm{\vec{x}} \le \vecnorm[1]{\vec{x}}$ and $\tr(A) = \sum_i a_{ii}$.
\end{document}Everything you type in LaTeX that starts with a backslash is a command, and a macro is simply a command you define yourself. Defining macros is how you keep notation consistent (change \R once and every occurrence follows), shorten long constructions and give meaning to markup. This guide covers how to define commands with \newcommand, with and without arguments, how to change existing ones with \renewcommand, when \def and \NewDocumentCommand are the right tool, and lists the 40 LaTeX commands (the “LaTeX codes” people search for) you will use most.
How to Define a Command in LaTeX with \newcommand
The full syntax is \newcommand{\name}[number of arguments][default]{definition}. Only the name and the definition are required. Put the definitions in the preamble, after the packages they use, so that they apply to the whole document:
| Part | Example | Meaning |
|---|---|---|
| Name | {\R} | Backslash plus letters only; no digits, no underscores |
| Number of arguments | [1] | 0 to 9; omit it for a command without arguments |
| Default | [2] | Makes argument 1 optional, with this default |
| Definition | {\lVert #1 \rVert} | What the command expands to; #1 to #9 are the arguments |
\documentclass{article}
\usepackage{amssymb}
\newcommand{\R}{\mathbb{R}}
\newcommand{\N}{\mathbb{N}}
\newcommand{\eps}{\varepsilon}
\newcommand{\octree}{\textsc{Octree}}
\begin{document}
For every $\eps > 0$ there is $n \in \N$ with $x_n \in \R$.
This guide was compiled with \octree{} in seconds.
\end{document}A command without arguments swallows the space after it, so \octree is prints “Octreeis”. Write \octree{} is, or load the xspace package and end the definition with \xspace, which adds a space unless punctuation follows. In math mode the space does not matter, because math ignores spaces anyway.
\newcommand with Arguments
Give the number of arguments in brackets and refer to them as #1, #2 and so on. Each argument is passed in its own pair of braces:
\documentclass{article}
\usepackage{amsmath}
\newcommand{\norm}[1]{\left\lVert #1 \right\rVert}
\newcommand{\abs}[1]{\left\lvert #1 \right\rvert}
\newcommand{\inner}[2]{\langle #1, #2 \rangle}
\newcommand{\pd}[2]{\frac{\partial #1}{\partial #2}}
\newcommand{\keyword}[1]{\textbf{\emph{#1}}}
\begin{document}
A \keyword{norm} satisfies $\norm{x + y} \le \norm{x} + \norm{y}$ and
$\abs{\inner{x}{y}} \le \norm{x}\,\norm{y}$.
\[ \pd{f}{x} + \pd{f}{y} = 0 \]
\end{document}An argument can be used several times or not at all, and the definition can call other macros. If an argument is a single token you can leave out the braces (\norm x works), but always bracing them avoids surprises.
Optional Arguments in \newcommand
A second pair of brackets after the argument count gives the first argument a default value and makes it optional. The optional argument is written in square brackets when the command is used:
\documentclass{article}
\usepackage{amsmath}
% [2][2]: two arguments, the first is optional with default 2
\newcommand{\vecnorm}[2][2]{\lVert #2 \rVert_{#1}}
% [1][Note]: one argument, optional, default "Note"
\newcommand{\remark}[1][Note]{\textbf{#1:}\ }
\begin{document}
$\vecnorm{x}$, $\vecnorm[1]{x}$, $\vecnorm[\infty]{x}$
\remark Optional arguments are in brackets.
\remark[Warning] Only the first argument can be optional.
\end{document}\newcommand allows exactly one optional argument and it is always #1. For an optional argument in another position, several optional arguments or a starred variant, use \NewDocumentCommand (below).
\renewcommand and \providecommand
\renewcommand has the same syntax but only works on a command that already exists. Use it to change the names LaTeX prints, adjust class settings or redefine a symbol:
\documentclass{article}
\usepackage{amsmath,amssymb}
\renewcommand{\abstractname}{Summary} % heading of the abstract
\renewcommand{\contentsname}{Overview} % heading of the table of contents
\renewcommand{\vec}[1]{\boldsymbol{#1}} % bold vectors instead of arrows
\renewcommand{\arraystretch}{1.3} % taller table rows
\providecommand{\R}{\mathbb{R}} % only if no package defined it
\begin{document}
\tableofcontents
\begin{abstract}
The vector $\vec{v}$ is bold.
\end{abstract}
\section{Introduction}
Text.
\end{document}\providecommand defines the command only when it does not exist yet and quietly does nothing otherwise. It is handy in a file that is \input into several documents, or for a macro that a package or class might also define.
Math Operators with \DeclareMathOperator
For a function name such as tr, rank or argmax, do not define \newcommand{\tr}{\text{tr}}. \DeclareMathOperator from amsmath sets the name upright and adds the same spacing as \sin or \log. The starred form puts limits under the name in display math:
\documentclass{article}
\usepackage{amsmath}
\DeclareMathOperator{\tr}{tr}
\DeclareMathOperator{\rank}{rank}
\DeclareMathOperator*{\argmax}{arg\,max}
\begin{document}
$\tr A + \rank B$
\[ \hat\theta = \argmax_{\theta \in \Theta} L(\theta) \]
\end{document}\DeclareMathOperator only works in the preamble. For a one-off use \operatorname{rank} in the body. More on operator names in math functions.
\def vs \newcommand
\def is the TeX primitive underneath \newcommand. It defines a macro with no safety checks: \def\end{...} silently replaces the command that closes every environment, and the document breaks with errors far from the cause. \newcommand refuses the same name with “Command \end already defined”.
\newcommand | \def | |
|---|---|---|
| Existing name | Error, nothing overwritten | Silently overwritten |
| Arguments | [2], then #1 #2 | \def\pair#1#2{(#1, #2)} |
| Optional argument | Yes, one | No |
| Delimited arguments | No | Yes: \def\pt(#1,#2){...} |
| Multi-paragraph arguments | Yes (\newcommand* forbids them) | Only with \long\def |
\documentclass{article}
% Delimited arguments: something \newcommand cannot do
\def\point(#1,#2){\ensuremath{(#1;\,#2)}}
% \let copies the current meaning of a command
\let\oldemph\emph
\renewcommand{\emph}[1]{\textbf{\oldemph{#1}}}
\begin{document}
The \emph{point} \point(3,4) lies on the circle.
\end{document}Use \def for delimited arguments and in package code, and \let to save a command before redefining it. In a document, prefer \newcommand and \renewcommand.
\NewDocumentCommand (xparse)
\NewDocumentCommand describes every argument with a letter, so it can handle what \newcommand cannot: several optional arguments, an optional argument after a mandatory one, and starred variants. It came with the xparse package and has been part of the LaTeX kernel since 2020, so no package is needed on a current TeX distribution.
| Letter | Argument type |
|---|---|
m | Mandatory, in braces |
o | Optional in brackets, no default; test with \IfValueTF{#1}{...}{...} |
O{default} | Optional in brackets, with a default |
s | An optional star; test with \IfBooleanTF{#1}{...}{...} |
\documentclass{article}
\usepackage{amsmath}
% s = optional star, m = mandatory, O{2} = optional with default 2
\NewDocumentCommand{\pnorm}{s m O{2}}{%
\IfBooleanTF{#1}
{\left\lVert #2 \right\rVert_{#3}}
{\lVert #2 \rVert_{#3}}%
}
\RenewDocumentCommand{\vec}{m}{\mathbf{#1}}
\begin{document}
$\pnorm{\vec{x}}$, $\pnorm{\vec{x}}[\infty]$, $\pnorm*{\frac{\vec{x}}{2}}[1]$
\end{document}Defining Environments with \newenvironment
Environments work the same way, with code for the beginning and code for the end. Arguments can only be used in the beginning code:
\documentclass{article}
\newenvironment{note}[1][Note]
{\par\medskip\noindent\textbf{#1.}\ \itshape}
{\par\medskip}
\begin{document}
\begin{note}
Environments group their content.
\end{note}
\begin{note}[Tip]
Use \verb|\renewenvironment| to change an existing one.
\end{note}
\end{document}For numbered theorem-like environments use \newtheorem instead; see theorems and proofs.
The 40 Most Used LaTeX Commands (LaTeX Codes)
These are the commands that appear in almost every LaTeX document. The package column says what to load; an empty cell means the command is built in.
| Command | What it does | Package |
|---|---|---|
| Document setup | ||
\documentclass{article} | Sets the document type (article, report, book, beamer) | |
\usepackage{amsmath} | Loads a package | |
\begin{env} ... \end{env} | Opens and closes an environment | |
\title{...} | Document title | |
\author{...} | Author names | |
\date{...} | Date (\today for today) | |
\maketitle | Prints the title block | |
\tableofcontents | Prints the table of contents | |
| Structure and references | ||
\section{...} | Numbered section; \section* for unnumbered | |
\subsection{...} | Numbered subsection | |
\chapter{...} | Chapter (report and book only) | |
\label{key} | Marks a place to refer to | |
\ref{key} | Number of a labelled section, figure or equation | |
\cite{key} | Citation from the bibliography | |
\footnote{...} | Footnote | |
\href{url}{text} | Clickable link | hyperref |
| Text formatting | ||
\textbf{...} | Bold | |
\textit{...} | Italic | |
\emph{...} | Emphasis (italic, or upright inside italic) | |
\underline{...} | Underline | |
\texttt{...} | Monospaced (typewriter) text | |
\small, \large | Font size from here on | |
| Layout | ||
\\ | Line break | |
\newpage | Page break | |
\noindent | No indent for this paragraph | |
\vspace{1em} | Vertical space | |
\hspace{1em} | Horizontal space | |
\centering | Centers the rest of the group or float | |
\item | Entry in itemize, enumerate or description | |
\includegraphics{file} | Inserts an image | graphicx |
\caption{...} | Caption of a figure or table | |
| Math | ||
\frac{a}{b} | Fraction | |
\sqrt{x} | Square root; \sqrt[3]{x} for cube root | |
\sum_{i=1}^{n} | Sum with limits | |
\int_a^b | Integral with limits | |
\alpha, \beta, … | Greek letters | |
\cdot, \times | Multiplication dot and cross | |
\left( ... \right) | Brackets that grow with their content | |
\text{...} | Upright text inside math | amsmath |
\mathbb{R} | Blackboard bold letters | amssymb |
\documentclass{article}
\usepackage{amsmath,amssymb,graphicx,hyperref}
\title{A Short Example}
\author{Ada Lovelace}
\date{\today}
\begin{document}
\maketitle
\tableofcontents
\section{Introduction}\label{sec:intro}
This is \textbf{bold}, \textit{italic}, \emph{emphasised}, \underline{underlined}
and \texttt{monospaced} text.\footnote{A footnote.} See \href{https://useoctree.com}{Octree}.
\subsection{Math}
\begin{itemize}
\item $\frac{a}{b} + \sqrt{x} + \sum_{i=1}^{n} i^2 + \int_0^1 f(x)\,dx$
\item $\alpha \in \mathbb{R}$ and $\left( \frac{1}{2} \right) \cdot 2 = 1 \text{ exactly}$
\end{itemize}
Section~\ref{sec:intro} is the one you are reading.
\end{document}For symbols beyond these, see Greek letters and math symbols and special characters; for the basics of how a document is put together, start with Learn LaTeX.
Common Errors and Fixes
| Message or symptom | Cause | Fix |
|---|---|---|
| LaTeX Error: Command \R already defined | \newcommand on a name that exists, often defined by a package or class | Pick another name, or use \renewcommand if you mean to replace it |
| LaTeX Error: Command \foo undefined | \renewcommand on a name that does not exist | Use \newcommand (or \providecommand) |
| Illegal parameter number in definition of \norm | #2 in a command declared with [1], or #1 without any [n] | Make [n] match the highest #n |
| File ended while scanning use of \@argdef | A missing closing brace in the definition: \newcommand{\R}{\mathbb{R} | Count the braces; every { needs a } |
| LaTeX Error: \mathbb allowed only in math mode or Missing $ inserted | A math macro such as \R used in running text | Write $\R$, or wrap the definition in \ensuremath{...} |
| LaTeX Error: Can be used only in preamble | \DeclareMathOperator after \begin{document} | Move it to the preamble, or use \operatorname{...} |
| Undefined control sequence | A typo in the command name, or a command from a package that is not loaded | Check the spelling; load the package (see the table above) |
| Text runs together after a macro | A command without arguments eats the following space | \octree{} is, or \xspace at the end of the definition |
Missing braces are the most common cause of strange output with macros that take arguments. Without braces only the next single token is the argument:
\documentclass{article}
\newcommand{\keyword}[1]{\textbf{#1}}
\begin{document}
\keyword important % only the "i" is bold
\keyword{important} % the whole word is bold
\end{document}Frequently Asked Questions
How do I define a new command in LaTeX?
Put \newcommand{\name}{definition} in the preamble, for example \newcommand{\R}{\mathbb{R}}, and then write \R wherever you want the definition. For arguments, give their number in brackets and use #1, #2 in the definition: \newcommand{\norm}[1]{\lVert #1 \rVert} turns \norm{x} into ‖x‖.
What is the difference between \newcommand and \renewcommand?
\newcommand defines a command that does not exist yet and stops with “Command \x already defined” if it does. \renewcommand changes a command that already exists and stops with “Command \x undefined” if it does not. \providecommand defines the command only when it is missing and otherwise does nothing.
How do I give a LaTeX command an optional argument?
Add the default value as a second bracket: \newcommand{\vecnorm}[2][2]{\lVert #2 \rVert_{#1}}. The first argument (#1) is now optional and defaults to 2, so \vecnorm{x} gives the 2-norm and \vecnorm[\infty]{x} the infinity norm. \newcommand allows only one optional argument, and it must come first; use \NewDocumentCommand for anything more.
Should I use \def or \newcommand in LaTeX?
Use \newcommand in documents. \def is the underlying TeX primitive: it silently overwrites any existing command, including essential ones such as \end or \section, and has no syntax for optional arguments. \newcommand checks the name first and reports an error instead. \def is still useful in package code and for delimited arguments.
What are LaTeX codes?
People often call LaTeX commands “LaTeX codes”. Each starts with a backslash, such as \section, \textbf or \frac, and takes its arguments in braces. The most used ones set up the document (\documentclass, \usepackage), structure it (\section, \label, \ref), format text (\textbf, \emph) and write math (\frac, \sqrt, \sum).
Why do I get “Illegal parameter number in definition”?
The definition uses a #n that the command does not have: #2 in a command declared with [1], or #1 in a command declared with no argument count at all. Make the number in brackets match the highest #n in the definition. Inside the definition of a new environment, the arguments can only be used in the begin code, not in the end code.
Next Steps
- Math Functions – \operatorname and built-in operator names
- Theorems and Proofs – \newtheorem for numbered environments
- Greek Letters and Math Symbols – The symbols to build macros from
- Blackboard Bold – \mathbb for \R, \N and \Z shortcuts
- Underbrace and Overbrace – Annotating parts of an equation
- Learn LaTeX: Tutorial for Beginners – The basics, from the first document up
Free LaTeX Tools
- LaTeX Preview – Test your macros with a live PDF preview
- AI LaTeX Generator – Generate LaTeX from text descriptions
- LaTeX Symbols Reference – Look up the command for any symbol
Related Articles
Angle Brackets ⟨ ⟩: Symbol, Copy and Paste, and LaTeX
Compile LaTeX from Claude Code or Cursor with the Octree MCP Server
Diameter Symbol (⌀): Meaning, ⌀ vs Ø, and How to Type It on Windows, Mac, Word, LaTeX
LaTeX on iPad: How to Write and Compile LaTeX on a Tablet
Write and debug LaTeX macros with AI
Octree's AI editor writes \newcommand definitions for your notation, explains “already defined” and “illegal parameter” errors, and compiles your document in seconds.
Try Octree Free →