Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
LaTeX Beginner's Guide

You're reading from   LaTeX Beginner's Guide Create visually appealing texts, articles, and books for business and science using LaTeX

Arrow left icon
Product type Paperback
Published in Oct 2021
Publisher Packt
ISBN-13 9781801078658
Length 354 pages
Edition 2nd Edition
Tools
Arrow right icon
Author (1):
Arrow left icon
Stefan Kottwitz Stefan Kottwitz
Author Profile Icon Stefan Kottwitz
Stefan Kottwitz
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

Preface 1. Chapter 1: Getting Started with LaTeX 2. Chapter 2: Formatting Text and Creating Macros FREE CHAPTER 3. Chapter 3: Designing Pages 4. Chapter 4: Creating Lists 5. Chapter 5: Including Images 6. Chapter 6: Creating Tables 7. Chapter 7: Using Cross-References 8. Chapter 8: Listing Contents and References 9. Chapter 9: Writing Math Formulas 10. Chapter 10: Using Fonts 11. Chapter 11: Developing Large Documents 12. Chapter 12: Enhancing Your Documents Further 13. Chapter 13: Troubleshooting 14. Chapter 14: Using Online Resources 15. Other Books You May Enjoy

Creating our own commands

If you're frequently using the same term in your document, it would be annoying to type it again and again. What if you later decide to change that term or its formatting? To avoid searching and replacing the term in the whole document, LaTeX allows you to define your own commands in your preamble.

Remember: a command that consists of other commands is called a macro, and that's what we will define now. Basically, we choose a new macro name and define the sequence of text or commands to be used in that macro. Then, when we want to perform an action, we just need to use the macro's name.

We will start with simple macros that are basically abbreviations.

Using macros for simple text

Macros can save us from repeating long words or phrases and can act as placeholders. We can change the content of the macro to update the whole document with a different version of that phrase.

Here, we will define a short command that prints out the name of the TeX Users Group (TUG):

  1. Type this code into a new document:
    \documentclass{article}
    \newcommand{\TUG}{\TeX\ Users Group}
    \begin{document}
    \section{The \TUG}
    The \TUG\ is an organization for people who use
    \TeX\ or \LaTeX.
    \end{document}
  2. Click on Typeset and look at the result:
Figure 2.9 – Using our first macro

Figure 2.9 – Using our first macro

\newcommand in the highlighted line defines our command. The first argument is the name we chose for the command, and the second argument is the text we want it to print out in the document.

Now, whenever we type \TUG in our document, the complete name will appear. If we later decide to change the name or its formatting, we just need to change this \newcommand line. Then, the change will be applied to the whole document.

You may use formatting commands inside your command definition. Let's say you would like to change the formatting of all occurrences of this name to be typeset in small caps; just change the definition to the following:

\newcommand{\TUG}{\textsc{TeX Users Group}}

You have also seen that we've used the \TeX command. This abbreviation command just prints out the name of the typesetting system, formatted in the same way as its logo. \LaTeX works similarly.

Note that we used a backslash after \TeX. The following space would just separate the command from the following text; it wouldn't produce a space in the output. Using the backslash followed by a space forces the output of a space that would otherwise be ignored. That also applies to the command we just created.

Now we will see how to avoid that manual spacing.

Proper spacing after commands

A backslash following a command could easily be forgotten. Can't we modify the command in order to automate that? Tasks like this, which aren't supported by LaTeX directly, could be solved by using packages, which are collections of styles and commands.

Here, we will load the xspace package; its only purpose is to adjust the spacing after printed output:

  1. Insert this line into your preamble, that is, before \begin{document}:
    \usepackage{xspace}
  2. Add the \xspace command to your macro definition:
    \newcommand{\TUG}{\TeX\ Users Group\xspace}

\usepackage{xspace} tells LaTeX to load the xspace package and to import all of its definitions. From now on, we can use all commands contained in that package.

This package provides the \xspace command, which inserts a space depending on the following character:

  • If a normal letter follows, then it will print a space after the macro content.
  • If a dot, a comma, an exclamation mark, or a quotation mark follows, it won't insert a space.

That automation is the defining reason for using the xspace package.

Creating more universal commands and using arguments

Imagine that your text contains a lot of keywords that you want to be printed in bold. If you use the \textbf command on all the keywords, what will happen if you later decide to use an italic shape instead, or a typewriter font? You would have to change that formatting for each keyword. There's a better way: defining your own macro and using \textbf only inside that macro definition.

Creating a macro with arguments

In this section, we will use \newcommand again, but this time we will introduce a parameter that will contain our keyword. For the example, we will use it on some terms that we've got to know in this chapter.

Let's get started:

  1. Type the following code example in your editor. The highlighted line will be our own macro definition, as shown here:
    \documentclass{article}
    \newcommand{\keyword}[1]{\textbf{#1}}
    \begin{document}
    \keyword{Grouping} by curly braces limits the
    \keyword{scope} of \keyword{declarations}.
    \end{document}
  2. Click on Typeset and observe the look of the keywords in the output:
Figure 2.10 – Formatting keywords

Figure 2.10 – Formatting keywords

Let's look at the highlighted \newcommand line in the code. The number 1 in the square brackets marks the number of arguments that we want to use in the command. #1 will be replaced by the value of the first argument; #2 will be replaced by the value of the second argument, and so on. Now, if you want to modify the appearance of all keywords to be italic, just modify the definition of \keyword and the change will be global.

The first time we used \newcommand, in the Creating our own commands section, we used it with two arguments: the macro name and the macro commands. In the previous example, there were three arguments; the additional argument has been put in square brackets, which is how we mark optional arguments (those arguments may be given or may be omitted). If omitted, they would have a default value.

Previously, we've already worked with the \documentclass command, but how can we define a command with optional arguments ourselves?

Creating a macro with optional arguments

We will use \newcommand another time, but this time with an optional formatting parameter and a mandatory argument for the keyword:

  1. Modify the previous example to get this code:
    \documentclass{article}
    \newcommand{\keyword}[2][\bfseries]{{#1#2}}
    \begin{document}
    \keyword{Grouping} by curly braces limits the
    \keyword{scope} of \keyword[\itshape]{declarations}.
    \end{document}
  2. Click on Typeset and check out the result:
Figure 2.11 – Optional arguments

Figure 2.11 – Optional arguments

Let's look again at the highlighted \newcommand line in the code. By using [\bfseries], we introduced an optional parameter; we refer to it by #1 and its default value is \bfseries. Since we used a declaration this time, we added a pair of braces to ensure that only the keyword is affected by the declaration. Later in the document, we gave [\itshape] to \keyword, changing the default formatting to italic.

Here's the definition of \newcommand:

\newcommand{command}[arguments][optional]{definition}

These are the meanings of the parameters to \newcommand:

  • command: The name of the new command, starting with a backslash followed by lowercase and/or uppercase letters, or a backslash followed by a single non-letter symbol. The name must not be already defined and is not allowed to begin with \end.
  • arguments: An integer from 1 to 9, representing the number of arguments of the new command. If omitted, the command will have no arguments.
  • optional: If this is present, then the first of the arguments would be optional with a default value given here. Otherwise, all arguments are mandatory.
  • definition: Every occurrence of command will be replaced by definition and every occurrence of the form #n will then be replaced by the nth argument.

Use \newcommand to create styles for keywords, code snippets, web addresses, names, notes, information boxes, or differently emphasized text. How did we achieve the consistent structure of this book? Defining styles with \newcommand is the key. We should use font commands within our macro definitions, rather than in the document body text.

General good practice

As often as possible, create your own macros to achieve a logical structure. You will be rewarded with consistent formatting and changes could easily be applied to the whole document. By defining and using commands, you can ensure that the formatting remains consistent throughout your whole document.

Now that we have seen how to format words and phrases, let's look at whole paragraphs.

You have been reading a chapter from
LaTeX Beginner's Guide - Second Edition
Published in: Oct 2021
Publisher: Packt
ISBN-13: 9781801078658
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime