Feeds:
Posts
Comments

Archive for September, 2011

To create a new custom command in LaTeX, the command \newcommand is well-known. Its full usage is:

\newcommand{\commandname}[n][d]{definition}

where

  • \commandname is the name of the new command, with backslash; this name must have never been defined.
  • n is the number of arguments of the new command; if ignored, there will be no argument.
  • d is the default value of the first argument; if not provided, the first argument will be required.
  • definition is the definition of the new command.

If the command name has already been defined, the above command will cause an error. To re-define a command, use \renewcommand instead.

Conditioning

In the definition of the new command (or in your LaTeX document in general), you may want to generate content differently based on certain conditions. For example, if the first argument of the command is empty, you want to do “this”, otherwise you want to do “that.” You can use standard TeX commands (TeX programming) for this task, but it is easier to use the package xifthen (an extended version of the package ifthen, you can also use the latter if you want). These packages define commands like


\ifthenelse{condition}{code if true}{code if false}

and commands for checking conditions, for example \isempty{} to check if something is empty.

As an example, the following command generates content differently based on its optional first argument:


\newcommand{\mycommand}[2][]{%

\ifthenelse{\isempty{#1}}%

{\ensuremath{{#2}_{\mathrm{on}}}}%

{\ensuremath{{#2}_{\mathrm{on}, {#1}}}}%

}

Usafe examples:

  • \mycommand{f} produces f_{\mathrm{on}}
  • \mycommand[i]{f} produces f_{\mathrm{on}, i}

Read Full Post »