Defining commands
In LaTeX, you can define a new command, override an existing command or, in LaTeX2e only, provide a new command if it doesn’t already exist, using the following commands:
- newcommand{cmd}[args][opt]{def}
- renewcommand{cmd}[args][opt]{def}
- providecommand{cmd}[args][opt]{def} – LaTeX2e
The arguments of these are as follows:
- cmd
- The name of the new or redefined command. A followed by a string of lower and/or uppercase letters or a followed by a single nonletter. For newcommand the name must not be already defined and must not begin with end; for renewcommand it must already be defined. The providecommand command is identical to the newcommand command if a command with this name does not exist; if it does already exist, the providecommand does nothing and the old definition remains in effect.
- args
- An integer from 1 to 9 denoting the number of arguments of the command being defined. The default is for the command to have no arguments.
- opt (LaTeX2e only)
- If present, then the first of the number of arguments specified by args is optional with a default value of opt; if absent, then all of the arguments are required.
- def
- The text to be substituted for every occurrence of cmd; a parameter of the form #n in cmd is replaced by the text of the nth argument when this substitution takes place.
For example:
% Write a macro
\newcommand{\super}{supercalifragilisticexpialidocious}
Renewing the command overwrites the behaviour of a previously defined command. If you attempt to renew a command that hasn’t been defined yet, you will get an error.
% Redefine the macro
\renewcommand{\super}{superman}
If you provide a command, the command is created if it doesn’t already exist. If the command does already exist, there will be no effect. The original command’s behaviour will not be affected.
% Provide a macro
\providecommand{\super}{supercalifragilisticexpialidocious}
categories: Nature and Science and Tech
tags: computing, latex, top tips
last modified: 20th Feb 2012


