Define your own commands in LaTeX (newcommand)

\newcommand{\name}{text} defines the command \name, which LaTeX replaces with the text. With a number in brackets, \newcommand{\name}[2]{...}, the command takes arguments, and #1 and #2 mark where they are inserted.

Preamble

The snippets on this page need these lines before \begin{document}:

\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{xcolor}

A command without arguments

Definitions usually stand in the preamble. A command works in text and in formulas; \mathbb in this one needs math mode and the amssymb package.

Complete document:

\documentclass{article}
\usepackage{amssymb}
\newcommand{\R}{\mathbb{R}}
\newcommand{\project}{Wind Tunnel Study}
\begin{document}
The set $\R$ contains all real numbers.
The \project{} started in 2024.
\end{document}
Result
The compiled example

Open in the editor

A command with arguments

The number in brackets is the number of arguments, at most 9. Each argument is given in its own pair of braces.

\newcommand{\norm}[1]{\lVert #1 \rVert}
\newcommand{\pair}[2]{\langle #1, #2 \rangle}

$\norm{x}^2 = \pair{x}{x}$
Result
The compiled example

Open in the editor

An optional argument with a default

A second pair of brackets makes the first argument optional and sets its default. Here \seq{x} uses n, and \seq[k]{y} replaces it with k.

\newcommand{\seq}[2][n]{#2_1, \dots, #2_{#1}}

$\seq{x}$ and $\seq[k]{y}$
Result
The compiled example

Open in the editor

Change an existing command

\renewcommand replaces a command that exists, with the same syntax as \newcommand. \providecommand defines a command only if it does not exist yet and does nothing otherwise.

\renewcommand{\labelitemi}{--}
\providecommand{\R}{\mathbb{R}}

\begin{itemize}
\item Every item starts with a dash now.
\item $\R$ is defined unless a package defined it before.
\end{itemize}
Result
The compiled example

Open in the editor

Star forms and several optional arguments

\NewDocumentCommand describes the arguments with letters: m is a mandatory argument, O{red} an optional one with a default, o an optional one without, and s a star. \IfBooleanTF{#1}{...}{...} tests the star. The command is part of LaTeX since 2020; older installations load the xparse package for it.

\NewDocumentCommand{\note}{s O{red} m}{%
  \IfBooleanTF{#1}{\textcolor{#2}{\textbf{#3}}}{\textcolor{#2}{#3}}}

\note{red}, \note[blue]{blue} and \note*{bold red}
Result
The compiled example

Open in the editor

Pitfalls

Compiled with pdfLaTeX from TeX Live 2023.

Related pages