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}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}$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}$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}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}Pitfalls
\newcommandwith a name that exists stops with the error "Command ... already defined", see Command \vec already defined. Pick another name or use\renewcommand.- A command without arguments swallows the space after it. Write
\project{}or\project\when a space should follow. - A command name consists of letters only. Digits and underscores are not allowed, so
\vec2is read as\vecfollowed by the digit 2.
Compiled with pdfLaTeX from TeX Live 2023.
Related pages
- How-to Define your own environments in LaTeX
- How-to Define a math operator in LaTeX
- Package
xparse - Error Command \vec already defined
- Error Illegal parameter number in definition of \pair
- Package
amsmath - Package
amssymb - Package
xcolor