Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 38 ยท Packages and Templates

Custom Commands and Environments

Define your own commands and environments with \newcommand, \renewcommand, \newenvironment and \DeclareMathOperator, and keep them tidy in a style file.

If you type the same long expression ten times, you will mistype it once. LaTeX lets you give it a name. A command (also called a macro) replaces a name with text or formatting; an environment wraps a block of text between \begin and \end with set-up and clean-up. Used well, they make your source shorter and let you change the look of a whole document in one place.

\newcommand

LATEX
\newcommand{\name}[number of args][default for first arg]{definition}

Examples:

LATEX
\newcommand{\R}{\mathbb{R}}                        % no arguments
\newcommand{\vect}[1]{\mathbf{#1}}                 % one argument: #1
\newcommand{\pair}[2]{\left(#1,\,#2\right)}        % two arguments
\newcommand{\term}[2][important]{\textbf{#2} (#1)} % optional first argument

The set $\R$ contains $\vect{x}$ and the point $\pair{a}{b}$.
\term{entropy}            % entropy (important)
\term[physics]{entropy}   % entropy (physics)

Rules to remember:

  • A command name made of letters starts with a backslash and may use only letters (no digits or underscores): \myCmdTwo, not \my_cmd2.
  • #1 to #9 are placeholders for arguments; at most nine.
  • \newcommand refuses to redefine an existing command, which protects you from accidentally breaking LaTeX. Use \renewcommand if you intend to override, and \providecommand to define only if not already defined.
  • In text, a command without arguments swallows the space after it: \LaTeX is prints "LaTeXis". Write \LaTeX{} is or use the xspace package: \newcommand{\proj}{ProjectX\xspace}.

The stand-in below models the substitution process with #1, #2 and a default argument, so you can see what LaTeX does when it expands a macro.

JS A tiny macro expander

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Commands in math: \DeclareMathOperator

Functions such as \sin are upright, with proper spacing. To make your own, use amsmath:

LATEX
\usepackage{amsmath}
\DeclareMathOperator{\argmax}{arg\,max}
\DeclareMathOperator*{\Var}{Var}   % * lets limits sit below in display style

$\argmax_{x} f(x)$

Typing $arg max$ gives italic letters with wrong spacing; the operator command is both shorter and correct.

Environments

LATEX
\newenvironment{name}[args][default]{begin code}{end code}
LATEX
\usepackage{xcolor}
\newenvironment{warning}
  {\par\medskip\noindent\textbf{\color{red}Warning.}\itshape\ }
  {\par\medskip}

\begin{warning}
Back up your files before upgrading.
\end{warning}

An environment with an argument:

LATEX
\newenvironment{boxedtext}[1]
  {\begin{center}\begin{minipage}{#1}\hrule\smallskip}
  {\smallskip\hrule\end{minipage}\end{center}}

\begin{boxedtext}{0.8\textwidth}
Some text inside a box.
\end{boxedtext}

Arguments such as #1 can be used only in the begin part; the end code cannot see them. If it needs them, store the value in a command during the begin code. Use \renewenvironment to change an existing one (for example quote or itemize).

Theorems

Theorem-like environments have their own tool in amsthm:

LATEX
\usepackage{amsthm}
\newtheorem{theorem}{Theorem}[section]    % numbered within sections
\newtheorem{lemma}[theorem]{Lemma}        % shares the theorem counter
\theoremstyle{definition}
\newtheorem{definition}{Definition}[section]
\theoremstyle{remark}
\newtheorem*{note}{Note}                  % * = unnumbered

\begin{theorem}[Pythagoras]\label{thm:pyth} ... \end{theorem}

Counters, lengths and conditionals

LATEX
\newcounter{exercise}
\newcommand{\exer}{\stepcounter{exercise}\textbf{Exercise \theexercise.}\ }

\newlength{\gap}
\setlength{\gap}{1.5em}

\usepackage{etoolbox}
\newtoggle{solutions}
\toggletrue{solutions}
\iftoggle{solutions}{Answer shown}{}

Counters can be reset (\setcounter{exercise}{0}) or tied to a parent counter with \newcounter{x}[section].

Keeping definitions in a style file

Move all your definitions into mymacros.sty (or preamble.tex):

LATEX
% mymacros.sty
\ProvidesPackage{mymacros}
\RequirePackage{amsmath, amssymb}
\newcommand{\R}{\mathbb{R}}

then \usepackage{mymacros} in every document. For a one-off file, \input{preamble} does the same. Reusing a single file keeps notation consistent across a thesis or a series of papers.

Good practice

  • Name macros by meaning (\vect, \keyword), not by appearance (\boldx). Then changing how keywords look is one edit.
  • Put macros in the preamble, never in the middle of the text.
  • Do not redefine core commands such as \section or \item casually.
  • Check for errors: "Command already defined" means use \renewcommand deliberately; "Illegal parameter number" means # appears where it should be ## (inside nested definitions).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does \newcommand{\pair}[2]{(#1,#2)} define?

    The number in square brackets is the count of arguments; #1 and #2 are placeholders.
  2. 2. Which command redefines an existing command on purpose?

    \renewcommand overrides; \newcommand errors if the name exists.
  3. 3. Why is \DeclareMathOperator{\argmax}{arg,max} better than $arg max$?

    Operators are typeset upright and spaced like \sin and \log.
  4. 4. In \newenvironment, where can #1 be used?

    Environment arguments are available only in the opening code; the closing code cannot read them.

Summary

  • \newcommand defines macros with up to nine arguments and an optional default for the first; \renewcommand overrides.
  • \DeclareMathOperator and \newenvironment handle operators and block-level structures; amsthm handles theorems.
  • Counters, lengths and etoolbox toggles add state and conditions.
  • Name macros by meaning and collect them in a .sty or \input file.
  • Mind spaces after commands: use {} or xspace.

Next: Page Layout, Headers and Fonts