0

How do \newcommand, \newcommand*, \renewcommand, \renewcommand*, \newenvironment, \newenvironment*, \renewenvironment, \newenvironment* work and what is difference between them?

Sigur
  • 37,330
Giorgi
  • 1,069
  • \newcommand{\foo}{This prints the text here} simply define the command \foo which is a kind of shortcut for This prints the text here. So you can use and so \foo\ says that... – Sigur May 03 '15 at 09:43
  • 2
    Open a console or command window and type texdoc latex2e then check section 13 – percusse May 03 '15 at 09:44
  • 2
    http://tex.stackexchange.com/questions/1050/whats-the-difference-between-newcommand-and-newcommand – MattAllegro May 03 '15 at 09:50
  • http://en.wikibooks.org/wiki/LaTeX/Macros#New_commands – Fran May 03 '15 at 11:01

1 Answers1

2

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 \foo but does not allow for parbreaks in the arguments.
  • \renewcommand{\foo} redefines an already existing command \foo

  • \renewcommand*{\foo} redefines \foo, with the no-parbreak limitation.

  • \DeclareRobustCommand with the same syntax as \newcommand etc. 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 etoolbox package establishes the \(re)newrobustcmd* for making robust commands.

  • xparse package: \NewDocumentCommand, \RenewDocumentCommand, \ProvideDocumentCommand, \NewDocumentEnvironment and \ProvideDocumentEnvironment and \DeclareDocumentEnvironment are robust versions with a better argument handling than \newcommand etc. There is an expandable \DeclareExpandableDocumentCommand too, which should be used with care (as stated in the xparse manual)