The xparse package
Defines commands with stars, several optional arguments and default values through \NewDocumentCommand. Since the LaTeX release of October 2020 these commands work without the package.
Loading the package
\usepackage{xparse}\newcommand allows one optional argument, and it has to be the first. \NewDocumentCommand describes the arguments with one letter each: m is a mandatory argument in braces, o an optional one in square brackets, O{default} an optional one with a default value, and s an optional star.
Inside the definition, \IfBooleanTF{#1}{...}{...} tests the star and \IfNoValueTF{#2}{...}{...} tests whether an o argument was given.
Since the release of October 2020, \NewDocumentCommand, \RenewDocumentCommand, \NewDocumentEnvironment and the tests are part of the LaTeX kernel. Loading xparse is only needed for older installations and for the argument types that stayed in the package, such as g, l and u, which new code should not use.
Main commands
\NewDocumentCommand{\name}{m o}{definition} | New command with one mandatory and one optional argument; an existing name is an error. |
\RenewDocumentCommand{\name}{m}{definition} | Redefines an existing command. |
\NewDocumentEnvironment{name}{O{Note}}{begin code}{end code} | New environment with the same kind of argument description. |
s | Argument type: an optional star. In the definition it is tested with \IfBooleanTF. |
O{default} | Argument type: optional argument in square brackets with a default value. |
\IfNoValueTF{#1}{missing}{given} | Tests whether an o argument was left out; \IfValueTF has the branches in the other order. |
+m | A plus sign in front of a type allows paragraph breaks in that argument. |
v | Argument type: verbatim text, as in \verb. |
Complete example
\documentclass{article}
\usepackage{xparse} % only needed for LaTeX before October 2020
\NewDocumentCommand{\quantity}{s O{m} m}{%
#3\,\IfBooleanTF{#1}{\textbf{#2}}{#2}}
\NewDocumentCommand{\remark}{o m}{%
\IfNoValueTF{#1}{Note: #2}{#1: #2}}
\NewDocumentEnvironment{hint}{O{Hint}}
{\par\medskip\noindent\textbf{#1.}\ \itshape}
{\par\medskip}
\begin{document}
\quantity{5}, \quantity[kg]{5} and \quantity*[s]{5}.
\remark{without a label} \remark[Warning]{with a label}
\begin{hint}[Tip]
The optional argument replaces the word in bold.
\end{hint}
\end{document}Compiled with pdfLaTeX from TeX Live 2023.
Pitfalls
- A command defined this way is robust: it can be used in headings and captions without
\protect. - Spaces and line ends in the argument description are ignored, but those in the definition are printed. End a line of the definition with
%when it must not produce a space. - An argument type that only the package knows gives, without the package, the error
Invalid argument typewith the hint that it requiresxparse.
Related pages
- How-to Define your own commands in LaTeX
- How-to Define your own environments in LaTeX
- Package
etoolbox - Error Command \vec already defined