LaTeX/Macros

Documents produced with the commands you have learned up to this point will look acceptable to a large audience. While they are not fancy-looking, they obey all the established rules of good typesetting, which will make them easy to read and pleasant to look at. However, there are situations where LaTeX does not provide a command or environment that matches your needs, or the output produced by some existing command may not meet your requirements.

In this chapter, we will try to give some hints on how to teach LaTeX new tricks and how to make it produce output that looks different from what is provided by default.

LaTeX is a fairly high-level language compared to Plain TeX and thus is more limited. The next chapter will focus on Plain TeX and will explain advanced techniques for programming.

New commands
To add your own commands, use the

command. Basically, the command requires two arguments: the name of the command you want to create (preceded by a backslash), and the definition of the command. Note that the command name can but need not be enclosed in braces, as you like. The num argument in square brackets is optional and specifies the number of arguments the new command takes (up to 9 are possible). If missing it defaults to 0, i.e. no argument allowed.

The following two examples should help you to get the idea. The first example defines a new command called \wbal that will print “The Wikibook about LaTeX”. Such a command could come in handy if you had to write the title of this book over and over again.

The next example illustrates how to define a new command that takes one argument. The tag gets replaced by the argument you specify. If you wanted to use more than one argument, use and so on, these arguments are added in an extra set of brackets.

Name your new command and not  as digits cannot be used to name macros &mdash; invalid characters will error out at compile-time.

LaTeX will not allow you to create a new command that would overwrite an existing one. But there is a special command in case you explicitly want this:. It uses the same syntax as the command.

In certain cases you might also want to use the command. It works like, but if the command is already defined, LaTeX will silently ignore the new command.

With LaTex2e, it is also possible to add a default parameter to a command with the following syntax:

If the default parameter of is present, then the first of the number of arguments specified by  is optional with a default value of ; if absent, then all of the arguments are required.


 * Note: When the command is used with an explicit first parameter it is given enclosed with brackets (here "").

Here is a common example: if you are writing a book about Mathematics and you have to use vectors, you have to decide how they will look. There are several different standards, used in many books. If a is a vector, some people like to add an arrow over it ($$\vec{a}$$), other people write it underlined ( a ); another common version is to write it bold (a). Let us assume you want to write your vectors with an arrow over them; then add the following line in your mystyle.sty.

and write your vectors inside the new command. You can call it as you wish, but you'd better choose a short name because you will probably write it very often. Then, if you change your mind and you want your vectors to look differently you just have to change the definition of your. Use this approach whenever you can: this will save you a lot of time and increase the consistency of your document.

DeclareRobustCommand
Some commands are fragile, that is they fail in some environments. If a macro works in body text but not in (for example) a figure caption, it's worth trying to replace the declaration with  in the preamble. This is especially true for macros which, when expanded, produce text that is written to a .aux file.

New command to work in both paragraph and math mode

Suppose you want to declare some variable which you want to use in paragraph as well as in math mode. It can be achieved with the help of  command in Latex2e as follows Space after  the \newcommand

It is a common problem to having nonconforming spacing after a newly defined command.

Consider : "The momentum is calculated using p= mv." Note there is no space after the formula.

On the other hand "The formula p=mv calculates the momentum.",  have space after the formula.

For this spacing problem one may use xspace package which will automatically decide if there should be any space after it or not.

New environments
Just as with the command, there is a command to create your own environments. The command uses the following syntax:

Again can have an optional argument. When the command (which starts the environment) is encountered, the material specified in the  argument is processed before the text in the environment gets processed. The material in the argument gets processed when the  command (which ends the environment) is encountered.

The optional and  arguments are used the same way as in the  command. LaTeX makes sure that you do not define an environment that already exists. If you ever want to change an existing environment, you can use the command. It uses the same syntax as the command.

The example below illustrates the usage of the command:

Extra space
When creating a new environment you may easily get bitten by extra spaces creeping in, which can potentially have fatal effects. One example is when you want to create a title environment which suppresses its own indentation as well as the one on the following paragraph. The command in the begin block of the environment will make it ignore any space after executing the begin block. The end block is a bit more tricky as special processing occurs at the end of an environment. With the LaTeX will issue an after the special ‘end’ processing has occurred.

Also, if you're still having problems with extra space being appended at the end of your environment when using the \input for external source, make sure there is no space between the beginning, sourcing, and end of the environment, such as:

or

Declare commands within new environment
New commands can be declared within newenvironment. Commands declared within the newenvironment refer to their arguments by doubling the # character. In the following example, a new environment is declared along with a nested command:

If, by mistake, the arguments passed to the \topics macro are defined with a single # character, the following error message will be thrown:

! Illegal parameter number in definition of \topics.

Environment contents as a macro argument
Some commands (for example,, , and ) expect the text to be modified to be passed as an argument, and thus cannot be placed in the "header" or "footer" of an environment definition. In some cases, a workaround is a corresponding environment, such as for. When no corresponding environment exists, an alternative is the  package, which places the environment contents inside the local macro. In the following example, the  environment bolds its contents:

Extending the number of arguments
The packages will let you define key/value options for commands.

The package is quite complete and documentation is exhaustive. We recommend that package developers read it. 

Let's provide a simple example :

Arithmetic
LaTeX can manipulate numbers.

The package provides the common infix notation.

For high-precision computations, you can use the package.

Conditionals
LaTeX can use conditionals thanks to the package.

FYI: For newer projects e-TeX is recommended, available in LaTeX from etoolbox. See section 3.6 of their manual.

Following a short example, a bool that switches its state every time it is used.

Loops
The extension provides the  command.

If you are only using  and not drawing graphics, you may instead use the   package directly.

Alternatively you can check out the package.

Strings
provides a lot of features. From CTAN:
 * testing a string’s contents
 * extracting substrings
 * substitution of substrings
 * string length
 * position of a substring
 * number of recurrences of a substring

Examples:

LaTeX Hooks
LaTeX provides two hooks:
 * will let you specify a set of commands that will be executed when is met.
 * does the same for.

This gives you some more flexibility for macros. It can be useful to override settings that get executed after the preamble. These hooks can be called several times. The commands will be executed in the order they were set.

For instance, let's replace the page numbers with oldstylenums:

There are also hooks for classes and packages. See Creating Packages.

Command-line LaTeX
If you work on a Unix-like OS, you might be using Makefiles or any kind of script to build your LaTeX projects. In that connection it might be interesting to produce different versions of the same document by calling LaTeX with command-line parameters. If you add the following structure to your document:

Now you can call LaTeX like this: latex '\providecommand{\blackandwhite}{true}\input{test.tex}'

First the command gets defined and then the actual file is read with input. By setting to false the color version of the document would be produced.