TeX/def

SynopsisEdit

\def <command> <parameter-text>{<replacement-text>}

DescriptionEdit

\def allows you to define new macros. The command must begin with an escape character (category code 0) and be composed of a series of letters (category code 11) or one single non-letter, following the escape character. (For instance \delta or \{.) Alternatively, <command> can be an active character (category code 13). Then, the parameter text tells TeX the valid syntax of the command being defined; furthermore, in the parameter text, one can include arguments (denoted by #1, etc., up to #9) which can be reused in the replacement text. For example, in

\def \foo [#1]#2{The first argument is ``#1'', the second one is ``#2''}

The first argument must be delimited by two square brackets while the second may be a single character (strictly speaking, a single token having a category code distinct from 1 or 2) or any balanced text surrounded by braces {...}. Finally, the replacement text tells TeX what the command is supposed to expand to and how to deal with the arguments if any (see example above).

Note that there should not be any space after parameter text. You can use % character if your command definition takes up multiple lines, for example

\def \foo [#1]#2%
  {The first argument is ``#1''.

  The second one is ``#2''}

Contrarily to LaTeX (with \newcommand), TeX doesn't check whether the command to be defined is important or not. You might well say \def \def etc., except that the most probable is that you encounter some problems quite quickly. One way to be safe in this respect is to write

\ifx <command> \undefined
  \def <command> . . .
\fi

\def can be preceded by \global (the redefinition isn't confined to the current group, also controlled by \globaldefs), \long (the command admits long arguments), \outer (the command is not tolerated in parts of the code which are read at high speed).

See also the commands \let, \edef, \xdef.

ExamplesEdit

This defines a simple shortcut:

\def \NAS {National Academy of Science}
\def \author {William {\sc Smith}}

This defines a quotation environment

\def \beginquote {\par \begingroup \narrower}
\def \endquote {\par \endgroup}
Last modified on 23 May 2013, at 18:51