About
Shop
LaTeX
Software
Books
Gallery
News
Contact
Blog
Settings
Account


8. Defining Commands

It's possible to define your own commands or redefine existing ones. Be very careful about redefining existing commands; don't redefine a command simply because you want to use the name, only redefine it if you are making a modification. For example, if you want to change the format of the current date, you would redefine \today, but if you want to define a command to display a specific date, you should define a new command with a different name.

There are several reasons why you might want to define a new command:

  1. Reduce typing:

    Suppose you have a series of commands or text that you find yourself frequently using, then you could define a command to do all these other commands for you.

    Example:

    Suppose you want a lot of large bold slanted sans-serif portions of text within your document. Every time you type those portions of text, you will have to do something like:

    It would be much easier if you could use just one command to do all that, called, say, \largeboldsfsl:

    \largeboldsfsl{Some text}
    

    or you could call it, say, \lbsfsl which is shorter, but slightly less memorable:

    \lbsfsl{Some text}
    

  2. Ensure consistency:

    You may find that you want to format an object a certain way.

    Example:

    Recall near the end of §7.4. Sub-Floats, I suggested the following to reference a subfigure (when using \subref instead of \ref):

    (\emph{\subref{fig:circle}})

    For consistency, you might want to define a command, say,

    \formattedsubref{<label>}
    that was the same as (\emph{\subref{<label>}}).

    Another Example

    Suppose your document has a lot of keywords in it, and you want to format these keywords in a different font, say sans-serif, so that they stand out. You could just do:

    A \textsf{command} usually begins with a backslash.

    however, it is better to define a new command called, say, \keyword that will typeset its argument in a sans-serif font. That way it becomes a lot easier to change the format at some later date. For example, you may decide to splash out and have your keywords typed in a particular colour. In which case, all you need to do is simply change the definition of the command \keyword, otherwise you'll have to go through your entire document looking for keywords and changing each one which could be very time consuming if you have a large document. You might also decide at some later date to make an index for your document. Indexing all the keywords then becomes much simpler, as again all you'll need to do is modify the \keyword command.

New commands are defined using the command:

\newcommand{<cmd>}[<n-args>][<default>]{<text>}

The first mandatory argument <cmd> is the name of your new command, which must start with a backslash. The optional argument <n-args> specifies how many arguments your new command must take. The next optional argument <default> will be discussed later. The final mandatory argument <text> specifies what LaTeX should do every time it encounters this command.

Example (No Parameters):

Let's begin with a trivial example. Suppose I wanted to write a document about a particular course, say “Programming — Languages and Software Construction”, and I had to keep writing the course title, then I might decide to define a command that prints the course title rather than having to laboriously type it out every time. Let's call our new command \coursetitle. We want the following code:

The course \emph{\coursetitle} is an undergraduate course.

to produce the following output:

Image showing typeset output (click here for a more detailed description).

Clearly this command doesn't need any arguments, so we don't need to worry about the optional argument <n-args> to \newcommand, and the only thing our new command needs to do is print:

Programming --- Languages and Software Construction
so we would define our new command as follows:

\newcommand{\coursetitle}{Programming --- Languages and Software Construction}

Commands must always be defined before they are used. The best place to define commands is in the preamble:

\documentclass{scrartcl}

\newcommand{\coursetitle}{Programming --- Languages
and Software Construction}


\begin{document}

\section{\coursetitle}

The course \emph{\coursetitle} is an undergraduate course.

\end{document}

Example (One Mandatory Argument):

Now let's try defining a command that takes an argument (or parameter). Let's go back to our \keyword example. This command needs to take one argument that is the keyword. Let's suppose we want keywords to come out in sans-serif, then we could do:

\newcommand{\keyword}[1]{\textsf{#1}}

In this case we have used the optional argument <n-args> to \newcommand. We want our command \keyword to have one argument, so we have [1]. In \textsf{#1} the #1 represents the first argument. (If we had more than one argument, #2 would represent the second argument, #3 would represent the third argument etc. up to a maximum of 9[How to break the 9-argument limit].) So

\keyword{commands}
will be equivalent to
\textsf{commands}
and
\keyword{environment}
will be equivalent to
\textsf{environment}
and so on. Again, it's best to put the command definition in the preamble to ensure the command won't be used before it's defined.

\documentclass{scrartcl}

\newcommand{\keyword}[1]{\textsf{#1}}

\begin{document}

A \keyword{command} usually begins with a backslash.

\end{document}

Now if we want to change the way the keywords are formatted, we can simply change the definition of \keyword. Let's modify our code so that the keyword is now in a slanted sans-serif font:

\documentclass{scrartcl}

\newcommand{\keyword}[1]{\textsf{\slshape #1}}

\begin{document}

A \keyword{command} usually begins with a backslash.

\end{document}

Let's go one stage further. The color package provides the declaration:

\color{<col-name>}

which switches the foreground colour to <col-name>. It also provides the text-block command:

\textcolor{<col-name>}{<text>}

which sets <text> in the colour given by <col-name>.

So let's use the color package to make our keywords blue:

\documentclass{scrartcl}

\usepackage{color}

\newcommand{\keyword}[1]{\textsf{\slshape\color{blue}#1}}

\begin{document}

A \keyword{command} usually begins with a backslash.

\end{document}

Or we could index the keywords. To do this we need the makeidx package and the commands \makeindex, \index{<text>}and \printindex:

\documentclass{scrartcl}

\usepackage{makeidx}

\makeindex

\newcommand{\keyword}[1]{\textsf{\slshape #1}\index{#1}}

\begin{document}

A \keyword{command} usually begins with a backslash.

\printindex

\end{document}

For further information about how to create an index, see A Guide to LaTeX [7] or The LaTeX Companion [3]. Alternatively, if you want a brief overview, try Using LaTeX to Write a PhD Thesis.

Since it is unlikely that the keyword will contain a paragraph break, we should indicate that this is a short command using the starred form:

\newcommand*{\keyword}[1]{\textsf{\slshape #1}\index{#1}}

Now if you forget to add the closing brace, for example, \keyword{command, then TeX's error checking mechanism will pick up the error sooner. This will give an error message that looks like:

! Paragraph ended before \keyword was complete.
<to be read again>
                   \par
l.604
This at least gives you the line number (604 in this example) of the end of the paragraph where the error has occurred.

If you don't used the starred form of \newcommand, then you will get the somewhat less than helpful error:

! File ended while scanning use of \keyword.
If you have a very large document, it may take a while to track down where exactly you have missed a brace.

Exercise 19: Defining a New Command

Try typing up the following code:


\documentclass{scrartcl}

\newcommand*{\keyword}[1]{\textsf{#1}}

\begin{document}

A \keyword{command} usually begins with a backslash.

Segments of code may be \keyword{grouped}.

Some \keyword{commands} take one or more \keyword{arguments}.
\end{document}

Then modify your code so that the keywords are in a slanted sans-serif font or modify your code so that the keywords come out in blue (using the color package as in the example earlier). Again you can download or view the result.

For the more adventurous:

If you want to create an index as in the previous example, you will need to use the application makeindex. If you used latexmk back in §5.5. Cross-Referencing, you can just carry on using that as before. If not you need to do the following in TeXworks:

  1. Create the PDF as described in §3.1. TeXWorks.

  2. Select MakeIndex from the drop-down list next to the build (typeset) button (see Figure 8.1).

  3. Click on the build button. If all goes well, you won't see anything different. If you see something like the following:
    Couldn't find input index file exercise19 nor exercise19.idx.
    then you probably forgot to add the command \makeindex to the preamble. Add it in and go back to Step 1.

  4. Select pdfLaTeX from the drop-down list and build the PDF file again. Move to the last page of the PDF, and you should see the index.

Figure 8.1: Selecting MakeIndex in TeXWorks
 


This book is also available as A4 PDF or 12.8cm x 9.6cm PDF or paperback (ISBN 978-1-909440-00-5).

© 2012 Dickimaw Books. "Dickimaw", "Dickimaw Books" and the Dickimaw parrot logo are trademarks. The Dickimaw parrot was painted by Magdalene Pritchett.

Terms of Use Privacy Policy Cookies Site Map FAQs