How do \newcommand, \newcommand*, \renewcommand, \renewcommand*, \newenvironment, \newenvironment*, \renewenvironment, \newenvironment* work and what is difference between them?
1 Answers
To answer this to satisfy the OP ...
The whole bunch of macro definition commands are quite connected:
\newcommand{\foo}[num_of_args][opt first arg value]{% definition}defines\foo\newcommand*{\foo}[num_of_args][opt first arg value]{% definition}defines\foobut does not allow for parbreaks in the arguments.\renewcommand{\foo}redefines an already existing command\foo\renewcommand*{\foo}redefines\foo, with theno-parbreaklimitation.\DeclareRobustCommandwith the same syntax as\newcommandetc. which makes the command robust (i.e. protected/not expandable).
In addition (hidden) \newcommand and it's relatives define automatically \endfoo, so it's not possible to say \newcommand{\endfoo} itself. For more on this see my question Are \end.... macro names reserved in LaTeX2e?
The environment commands:
- \newenvironment{fooenv}[num_of_args]{first opt arg]{%
startcode}{endcode} defines an environment named fooenv, i.e. it can be used with \begin{fooenv}...\end{fooenv}. The content between this pair is grouped, i.e. \(re)newcommand etc, length changes are applied only within this pair and not visible outside, i.e. safe (unless \global is not used
- \renewenvironment redefines an existing environment
- \newenvironment* and \renewenvironment* are applied with the no-parbreak limit.
In addition, there is \providecommand (same syntax as \newcommand) which can used to be sure that some command is really defined. If it's already defined, then \providecommand does nothing.
The machine behind all is the basic TeX \def command.
In addition, see Difference between \newcommand and \newcommand*
Alternatives from etoolbox and xparse
The
etoolboxpackage establishes the\(re)newrobustcmd*for making robust commands.xparsepackage:\NewDocumentCommand,\RenewDocumentCommand,\ProvideDocumentCommand,\NewDocumentEnvironmentand\ProvideDocumentEnvironmentand\DeclareDocumentEnvironmentare robust versions with a better argument handling than\newcommandetc. There is an expandable\DeclareExpandableDocumentCommandtoo, which should be used with care (as stated in thexparsemanual)
\newcommand{\foo}{This prints the text here}simply define the command\foowhich is a kind of shortcut for This prints the text here. So you can useand so \foo\ says that...– Sigur May 03 '15 at 09:43texdoc latex2ethen check section 13 – percusse May 03 '15 at 09:44