La Te X Beginner's Guide

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 336

DownloadLa Te X Beginner's Guide
Open PDF In BrowserView PDF
LaTeX

Beginner's Guide

Create high-quality and professional-looking texts, articles,
and books for business and science using LaTeX

Stefan Kottwitz

BIRMINGHAM - MUMBAI

LaTeX

Beginner's Guide
Copyright © 2011 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system,
or transmitted in any form or by any means, without the prior written permission of the
publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the
information presented. However, the information contained in this book is sold without
warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers
and distributors will be held liable for any damages caused or alleged to be caused directly or
indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

First published: March 2011

Production Reference: 1150311

Published by Packt Publishing Ltd.
32 Lincoln Road
Olton
Birmingham, B27 6PA, UK.
ISBN 978-1-847199-86-7

www.packtpub.com

Cover Image by Asher Wishkerman (a.wishkerman@mpic.de)

Credits
Author
Stefan Kottwitz
Reviewers
Kevin C. Klement
Joseph Wright
Acquisition Editor
Eleanor Duffy
Development Editor
Hyacintha D'Souza
Technical Editor
Sakina Kaydawala
Copy Editor
Leonard D'Silva
Indexer
Hemangini Bari

Editorial Team Leader
Mithun Sehgal
Project Team Leader
Lata Basantani
Project Coordinator
Vishal Bodwani
Proofreader
Aaron Nash
Graphics
Nilesh Mohite
Production Coordinator
Adline Swetha Jesuthas
Cover Work
Adline Swetha Jesuthas

About the Author
Stefan Kottwitz studied mathematics in Jena and Hamburg. Afterwards, he worked as an

IT Administrator and Communication Officer onboard cruise ships for AIDA Cruises and for
Hapag-Lloyd Cruises. Following 10 years of sailing around the world, he is now employed as
a Network & IT Security Engineer for AIDA Cruises, focusing on network infrastructure and
security such as managing firewall systems for headquarters and fleet.
In between contracts, he worked as a freelance programmer and typography designer. For
many years he has been providing LaTeX support in online forums. He became a moderator
of the web forum http://latex-community.org/ and of the site http://golatex.
de/. Recently, he began supporting the newly established Q&A site http://tex.
stackexchange.com/ as a moderator.
He publishes ideas and news from the TeX world on his blog at http://texblog.net.
I would like to thank Joseph Wright and Kevin C. Klement for reviewing
this book. Special thanks go to Markus Kohm for his great valuable input. I
would also like to thank the people of Packt Publishing, who worked with
me on this book, in particular my development editor Hyacintha D'Souza.

About the Reviewers
Kevin C. Klement is an Associate Professor of Philosophy at the University of

Massachusetts, Amherst. Besides using LaTeX in his academic work in the history of logic and
analytic philosophy, he is a maintainer of the PhilTeX blog, and an active participant in many
online LaTeX communities, including PhilTeX, LaTeX Community, and TeX.SE.

Joseph Wright is a research assistant at the University of East Anglia. As well as using

LaTeX for his academic work as a chemist, he is a member of the LaTeX3 Project, runs the
blog Some TeX Developments and is one of the moderators on the TeX.SE site.

www.PacktPub.com
Support files, eBooks, discount offers, and more
You might want to visit www.PacktPub.com for support files and downloads related to your
book.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub
files available? You can upgrade to the eBook version at www.PacktPub.com and as a print
book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
service@packtpub.com for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for
a range of free newsletters, and receive exclusive discounts and offers on Packt books and
eBooks.

http://PacktLib.PacktPub.com

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book
library. Here, you can access, read, and search across Packt's entire library of books.

Why Subscribe?
‹‹

Fully searchable across every book published by Packt

‹‹

Copy and paste, print, and bookmark content

‹‹

On demand and accessible via web browser

Free Access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view nine entirely free books. Simply use your login credentials for
immediate access.

Table of Contents
Preface
Chapter 1: Getting Started with LaTeX

What is LaTeX?
How we can benefit
The virtues of open source
Separation of form and content
Portability
Protection for your work
Comparing it to word processor software
What are the challenges?
Installing LaTeX
Time for action – installing TeX Live using the net installer wizard
Time for action – installing TeX Live offline
Installation on other operating systems
Creating our first document
Time for action – writing our first document with TeXworks
Summary

Chapter 2: Formatting Words, Lines, and Paragraphs

Understanding logical formatting
Time for action – titling your document
Exploring the document structure
Understanding LaTeX commands
How LaTeX reads your input
Time for action – trying out the effect of spaces, line breaks, and empty lines
Commenting your source text
Printing out special symbols
Time for action – writing special characters in our text
Formatting text – fonts, shapes, and styles

1
9

9
10
10
11
11
11
12
12
12
14
20
20
21
21
23

25

25
26
27
28
28
29
30
30
31
31

Table of Contents

Time for action – tuning the font shape
Choosing the font family
Time for action – switching to sans-serif and to typewriter fonts
Switching fonts
Time for action – switching the font family
Summarizing font commands and declarations
Delimiting the effect of commands
Time for action – exploring grouping by braces
Time for action – exploring font sizes
Using environments
Time for action – using an environment to adjust the font size
Saving time and effort – creating your own commands
Time for action – creating our first command using it as an abbreviation
Gentle spacing after commands
Time for action – adding intelligent spacing to command output
Creating more universal commands – using arguments
Time for action – creating a macro for formatting keywords
Using optional arguments
Time for action – marking keywords with optional formatting
Using boxes to limit the width of paragraphs
Time for action – creating a narrow text column
Common paragraph boxes
Boxes containing more text
Time for action – using the minipage environment
Understanding environments
Breaking lines and paragraphs
Improving hyphenation
Time for action – stating division points for words
Improving the justification further
Time for action – using microtype
Breaking lines manually
Time for action – using line breaks
Preventing line breaks
Managing line breaks wisely
Exploring the fine details
Time for action – exploring ligatures
Understanding ligatures
Choosing the right dash
Setting dots
Time for action – using differently spaced dots
[ ii ]

32
33
33
34
35
36
36
36
37
38
38
39
40
41
41
42
42
43
43
45
46
46
48
48
49
50
50
51
52
52
53
53
54
55
55
56
57
57
57
58

Table of Contents

Time for action – comparing dots to ellipsis
Setting accents
Time for action – experimenting with accents
Using special characters directly in the editor
Time for action – using accents directly
Turning off full justification
Time for action – justifying a paragraph to the left
Creating ragged-left text
Time for action – centering a title
Using environments for justification
Time for action – centering verses
Displaying quotes
Time for action – quoting a scientist
Quoting longer text
Time for action – quoting TeX's benefits
Time for action – spacing between paragraphs instead of indentation
Summary

59
60
60
61
61
62
62
62
63
63
64
65
65
66
66
67
69

Chapter 3: Designing Pages

71

Choosing the paper size
Specifying the text area
Setting the margins

76
76
77

Defining the overall layout
Time for action – writing a book with chapters
Reviewing LaTeX's default page layout
Defining the margins yourself
Time for action – specifying margins
Using the geometry package

Obtaining package documentation
Time for action – finding the geometry package manual
Changing the line spacing
Time for action – increasing line spacing
Using class options to configure the document style
Time for action – creating a two-column landscape document
Creating a table of contents
Time for action – adding a table of contents
Sectioning and the contents
Time for action – shortening the table of content entries
Designing headers and footers
Time for action – customizing headers with the fancyhdr package
Understanding page styles
Customizing header and footer
[ iii ]

71
72
73
74
74
75

78
78
79
80
82
82
84
85
86
86
88
88
90
90

Table of Contents

Using decorative lines in header or footer
Changing LaTeX's header marks
Breaking pages
Time for action – inserting page breaks
Enlarging a page
Time for action – sparing an almost empty page
Using footnotes
Time for action – using footnotes in text and in headings
Modifying the dividing line
Time for action – redefining the footnote line
Using packages to expand footnote styles
Summary

91
92
92
92
95
96
98
98
100
101
102
103

Chapter 4: Creating Lists

105

Chapter 5: Creating Tables and Inserting Pictures

121

Building a bulleted list
Time for action – listing LaTeX packages
Nesting lists
Time for action – listing packages by topic
Creating a numbered list
Time for action – writing a step-by-step tutorial
Customizing lists
Saving space with compact lists
Time for action – shrinking our tutorial
Choosing bullets and numbering format
Time for action – modifying lists using enumitem
Suspending and continuing lists
Producing a definition list
Time for action – explaining capabilities of packages
Summary
Writing in columns
Time for action – lining up information using the tabbing environment
Time for action – lining up font commands
Typesetting tables
Time for action – building a table of font family commands
Drawing lines in tables
Understanding formatting arguments
Increasing the row height
Beautifying tables
Time for action – adding nicer horizontal lines with the booktabs package
Spanning entries over multiple columns
[ iv ]

105
105
106
106
107
108
109
109
109
111
112
115
115
116
119
121
122
123
125
125
126
126
128
129
129
131

Table of Contents

Time for action – merging cells
Inserting code column-wise
Time for action – using the array package
Spanning entries over multiple rows
Time for action – merging cells using the multirow package
Adding captions to tables
Time for action – adding a caption to our font table
Placing captions above
Auto-fitting columns to the table width
Generating multi-page tables
Coloring tables
Using landscape orientation
Aligning columns at the decimal point
Handling narrow columns
Inserting pictures
Time for action – including a picture
Scaling pictures
Choosing the optimal file type
Including whole pages
Putting images behind the text
Managing floating environments
Time for action – letting a figure float
Understanding float placement options
Forcing the output of floats
Limiting floating
Avoiding floating at all
Spanning figures and tables over text columns
Letting text flow around figures
Time for action – embedding a picture within text
Breaking figures and tables into pieces
Summary

Chapter 6: Cross-Referencing

Setting labels and referencing
Time for action – referencing items of a top list
Assigning a key
Referring to a key
Referring to a page
Producing intelligent page references
Time for action – introducing variable references
Fine-tuning page references
[v]

131
132
132
133
134
134
135
136
137
138
139
139
139
139
140
140
142
143
144
144
144
144
145
146
146
147
148
148
148
150
150

153

154
154
155
156
156
157
157
158

Table of Contents

Referring to page ranges
Using automatic reference names
Time for action – referring cleverly
Combing cleveref and varioref
Referring to labels in other documents
Summary

159
160
160
162
162
163

Chapter 7: Listing Content and References

165

Chapter 8: Typing Math Formulas

189

Customizing the table of contents
Time for action – refining an extensive table of contents
Adjusting the depth of the TOC
Shortening entries
Adding entries manually
Creating and customizing lists of figures
Time for action – creating a list of diagrams
Creating a list of tables
Using packages for customization
Generating an index
Time for action – marking words and building the index
Defining index entries and subentries
Specifying page ranges
Using symbols and macros in the index
Referring to other index entries
Fine-tuning page numbers
Designing the index layout
Creating a bibliography
Time for action – citing texts and listing the references
Using the standard bibliography environment
Using bibliography databases with BibTeX
Time for action – creating and using a BibTeX database
Looking at the BibTeX entry fields
Understanding BibTeX entry types
Choosing the bibliography style
Listing references without citing
Changing the headings
Summary
Writing basic formulas
Time for action – discussing quadratic equations and roots
Embedding math expressions within text
Displaying formulas
[ vi ]

165
166
168
168
169
170
170
171
171
172
172
174
174
174
175
175
176
177
177
178
179
179
181
182
184
184
185
187
190
190
192
193

Table of Contents

Numbering equations
Adding subscripts and superscripts
Extracting roots
Writing fractions
Greek letters
Script letters
Producing an ellipsis
Comparing in-line formulas to displayed formulas
Changing the font, style, and size
Customizing displayed formulas
Time for action – typesetting multi-line formulas
Aligning multi-line equations
Numbering rows in multi-line formulas
Inserting text into formulas
Fine-tuning formulas
Using operators
Exploring the wealth of math symbols

193
194
194
194
195
196
196
196
196
198
199
200
201
201
201
202
202

Writing units
Building math structures
Creating arrays
Writing binomial coefficients:
Typesetting matrices
Stacking expressions
Underlining and overlining
Setting accents
Putting a symbol above another
Writing theorems and definitions
Summary

206
206
207
207
207
208
208
209
209
209
212

Binary operation symbols
Binary relation symbols
Inequality relation symbols
Subset and superset symbols
Variable sized operators
Arrows
Harpoons
Symbols derived from letters
Variable sized delimiters
Miscellaneous symbols

Chapter 9: Using Fonts

Preparing the encoding
Time for action – directly using special characters
Installing additional fonts
[ vii ]

202
203
203
203
204
204
204
205
205
206

213

214
214
216

Table of Contents

Choosing the main font
Time for action – comparing Computer Modern to Latin Modern
Loading font packages
Latin Modern – a replacement for the standard font
Kp-fonts – a full set of fonts

217
217
218
218
218

Serif fonts

219

Sans-serif fonts

221

Typewriter fonts

223

Times Roman
Charter
Palatino
Bookman
New Century Schoolbook
Concrete Roman

219
220
220
221
221
221

Helvetica
Bera Sans
Computer Modern Bright
Kurier

222
222
222
222

Courier
Inconsolata
Bera Mono

223
223
223

Exploring the world of LaTeX fonts
Summary

224
225

Chapter 10: Developing Large Documents

227

Chapter 11: Enhancing Your Documents Further

243

Splitting the input
Time for action – swapping out preamble and chapter contents
Including small pieces of code
Including bigger parts of a document
Compiling parts of a document
Creating front and back matter
Time for action – adding a dedication and an appendix
Designing a title page
Time for action – creating a title page
Working with templates
Time for action – starting with a template
Summary
Using hyperlinks and bookmarks
Time for action – adding hyperlinks
Time for action – customizing the hyperlink appearance
Time for action – editing PDF metadata
Creating hyperlinks manually
Creating bookmarks manually
[ viii ]

228
228
230
231
232
232
233
235
235
237
238
242
243
244
246
248
250
250

Table of Contents
Math formulas and special symbols in bookmarks

Benefitting from other packages
Time for action – visiting the TeX Catalogue Online
Time for action – installing a LaTeX package
Designing headings
Time for action – designing chapter and section headings
Coloring your document
Summary

251

251
252
255
256
257
260
264

Chapter 12: Troubleshooting

265

Chapter 13: Using Online Resources

281

Understanding and fixing errors
Time for action – interpreting and fixing an error
Using commands and environments
Writing math formulas
Handling the preamble and document body
Working with files
Creating tables and arrays
Working with lists
Working with floating figures and tables
General syntax errors
Handling warnings
Time for action – emphasizing on a sans-serif font
Justifying text
Referencing
Choosing fonts
Placing figures and tables
Customizing the document class
Avoiding obsolete classes and packages
General troubleshooting
Summary
Web forums, discussion boards, and Q&A sites
Usenet groups
comp.text.tex
Newsgroups in other languages

Web forums

265
266
267
268
268
269
270
270
271
271
272
272
273
274
274
274
275
275
277
279
281
282
282
282

282

LaTeX-Community.org
TeX and LaTeX on Stack Exchange

Time for action – asking a question online
Frequently Asked Questions
UK TeX FAQ
Visual LaTeX FAQ
[ ix ]

282
283

284
287
287
287

Table of Contents

MacTeX FAQ
AMS-Math FAQ
LaTeX Picture FAQ
Mailing lists
texhax
tex-live
texworks
List collections
TeX user group sites
TUG – the TeX users group
The LaTeX project
UK TUG – TeX in the United Kingdom
Local user groups
Homepages of LaTeX software and editors
LaTeX distributions
LaTeX editors

287
288
288
288
288
288
289
289
289
289
289
290
290
290
290
290

LaTeX archives and catalogs
CTAN – the Comprehensive TeX Archive Network
The TeX Catalogue Online
The LaTeX Font Catalogue
TeX Resources on the Web
Friends of LaTeX
XeTeX
LuaTeX
ConTeXt
LyX
LaTeX blogs
The TeXblog
Some TeX Developments
LaTeX Alive
LaTeX for Humans
The TeX community aggregator
Summary

292
292
292
292
293
293
293
293
293
294
294
294
294
294
294
295
295

Cross-platform
Windows
Linux
Mac OS X

Appendix: Pop Quiz Answers

Chapter 2: Formatting Words, Lines, and Paragraphs
Commands
Lines and paragraphs
[x]

291
291
291
292

297

297
297
297

Table of Contents

Chapter 3: Designing Pages
Chapter 4: Creating Lists
Chapter 5: Creating Tables and Inserting Pictures
Tables
Pictures and floats
Chapter 6: Cross-Referencing
Chapter 7: Listing Content and References
Chapter 8: Typing Math Formulas
Chapter 9: Using Fonts
Chapter 10: Developing Large Documents
Chapter 11: Enhancing Your Documents Further
Chapter 12: Troubleshooting
Chapter 13: Using Online Resources

Index

297
298
298
298
298
298
298
299
299
299
299
299
300

301

[ xi ]

Preface
LaTeX is a high-quality open source typesetting software that produces professional prints
and PDF files. However, as LaTeX is a powerful and complex tool, getting started can be
intimidating. There is no official support and certain aspects such as layout modifications can
seem rather complicated. It may seem more straightforward to use Word or other WYSIWG
programs, but once you've become acquainted, LaTeX's capabilities far outweigh any initial
difficulties. This book guides you through these challenges and makes beginning with LaTeX
easy. If you are writing mathematical, scientific, or business papers, then this is the perfect
book for you.
LaTeX Beginner's Guide offers you a practical introduction to LaTeX. Beginning with the
installation and basic usage, you will learn to typeset documents containing tables, figures,
formulas, and common book elements like bibliographies, glossaries, and indexes. Lots of
step-by-step examples start with fine-tuning text, formulas and page layout and go on to
managing complex documents and using modern PDF features. It's easy to use LaTeX, when
you have LaTeX Beginner's Guide at hand.
This practical book will guide you through the essential steps of Latex, from installing LaTeX,
formatting, and justification, to page design. Finally, you will learn how to manage complex
documents and how to benefit from modern PDF features. Right from the beginning, you
will learn to use macros and styles to maintain a consistent document structure while saving
typing work. This book will help you learn to create professional looking tables as well
as include figures and write complex mathematic formulas. You will see how to generate
bibliographies and indexes with ease. Detailed information about online resources like
software archives, web forums, and online compilers complement this introductory guide.

Preface

What this book covers

Chapter 1, Getting Started with LaTeX, introduces LaTeX and explains its benefits. It guides
you through the download and installation of a comprehensive LaTeX distribution and
shows you how to create your first LaTeX document.
Chapter 2, Formatting Words, Lines, and Paragraphs, explains how to vary font, shape, and
style of text. It deals with centering and justification of paragraphs and how you can improve
line breaks and hyphenation. It introduces the concept of logical formatting and teaches you
how to define macros and how to use environments and packages.
Chapter 3, Designing Pages, shows how you can adjust the margins and change the line
spacing. It demonstrates portrait, landscape, and two-column layout. In this chapter, we will
create dynamic headers and footers and learn how to control page breaking and how to use
footnotes. Along the way, you will also learn about redefining existing commands and using
class options. Furthermore, you will get familiar with accessing package documentation.
Chapter 4, Creating Lists, deals with arranging text in bulleted, numbered, and definition
lists. We will learn how to choose bullets and numbering style and how to design the overall
layout of lists.
Chapter 5, Creating Tables and Inserting Pictures, shows you how to create
professional-looking tables and how to include external pictures in your documents.
It deals with typesetting captions to tables and figures. We will learn how to benefit
from LaTeX's automated tables and figures placement and how to fine-tune it.
Chapter 6, Cross-Referencing, introduces means of intelligent referencing to sections,
footnotes, tables, figures, and numbered environments in general.
Chapter 7, Listing Content and References, deals with creating and customizing of a table of
contents and lists of figures and tables. Furthermore, it teaches how to cite books, how to
create bibliographies, and how to generate an index.
Chapter 8, Typing Math Formulas, explains mathematical typesetting in depth. It starts with
basic formulas and continues with centered and numbered equations. It shows how to align
multi-line equations. In detail, it shows how to typeset math symbols such as roots, arrows,
Greek letters, and operators. Moreover, you will learn how to build complex math structures
such as fractions, stacked expressions, and matrices.
Chapter 9, Using Fonts, takes us into the world of fonts and demonstrates various fonts for
Roman, sans-serif, and typewriter fonts in different shapes. By the way, you will learn about
character encoding and font encoding.

[2]

Preface

Chapter 10, Developing Large Documents, helps in managing large documents by splitting
them into several files. It shows how to swap out settings, how to reuse code, and how to
compile just parts of a bigger documents. After reading this chapter, you will be able to
create complex projects building upon sub-files. Furthermore, we deal with front matter
and back matter with different page numbering and separate title pages. We will work it
out by creating an example book. By doing this, you will get familiar with using document
templates, finally being able to write our own thesis, book, or report.
Chapter 11, Enhancing Your Documents Further, brings color into your documents. It shows
you how to modify headings of chapters and all kinds of sections. We will learn how to
create feature-rich PDF documents with bookmarks, hyperlinks, and meta-data. While doing
this, we visit the TeX Catalogue Online to look out for further useful LaTeX packages and we
will go through a package installation.
Chapter 12, Troubleshooting, provides us with tools for problem-solving. We will learn
about different kinds of LaTeX's errors and warnings and how to deal with them. After
reading this chapter, you will understand LaTeX's messages and you will know how to
use them for fixing errors.
Chapter 13, Using Online Resources, guides you through the vast amount of LaTeX
information on the Internet. We will visit a LaTeX online forum and a LaTeX Question &
Answer site. This chapter points the way to huge LaTeX software archives, to homepages of
TeX user groups, to mailing lists, Usenet groups, and LaTeX blogs. It tells you where you can
download LaTeX capable editors and where you can find enhanced versions of TeX, such
as XeTeX, LuaTeX, and ConTeXt. Finally, you will know how to access the knowledge of the
world-wide LaTeX community and how to become a part of it.

What you need for this book

You need access to a computer with LaTeX on it. An online connection would be helpful
regarding installation and updates. LaTeX can be installed on most operating systems, so
you can use Windows, Linux, Mac OS X, or Unix.
This book uses the freely available TeX Live distribution, which runs on all mentioned
platforms. You just need an online connection or the TeX Live DVD to install it. In the book,
we work with the cross-platform editor TeXworks, but you could use any editor you like.

[3]

Preface

Who this book is for

If you are about to write mathematical or scientific papers, seminar handouts, or even
plan to write a thesis, then this book offers you a fast-paced and practical introduction.
Particularly when studying in school and university you will benefit a lot, as a mathematician
and a physicist as well as an engineer or a humanist. Everybody with high expectations who
plans to write a paper or a book may be delighted by this stable software.

Conventions

In this book, you will find several headings appearing frequently. To give clear instructions of
how to complete a procedure or task, we use:

Time for action - heading
1.

Action 1

2.

Action 2

3.

Action 3

Instructions often need some extra explanation so that they make sense, so they are
followed with:

What just happened?
This heading explains the working of tasks or instructions that you have just completed.
You will also find some other learning aids in the book, including:

Pop quiz
These are short multiple choice questions intended to help you test your own understanding.

Have a go hero - heading
These set practical challenges and give you ideas for experimenting with what you have
learned.
You will also find a number of styles of text that distinguish between different kinds of
information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text are shown as follows: "The command \chapter produced a large
heading. This command will always begin on a new page."
[4]

Preface

A block of code is set as follows:
\documentclass[a4paper,12pt]{book}
\usepackage[english]{babel}
\usepackage{blindtext}
\begin{document}
\chapter{Exploring the page layout}
In this chapter we will study the layout of pages.
\section{Some filler text}
\blindtext
\section{A lot more filler text}
More dummy text will follow.
\subsection{Plenty of filler text}
\blindtext[10]
\end{document}

When we wish to draw your attention to a particular part of a code block, the relevant lines
or items are set in bold:
\documentclass[a4paper,11pt]{book}
\usepackage[english]{babel}
\usepackage{blindtext}
\usepackage[a4paper, inner=1.5cm, outer=3cm, top=2cm,
bottom=3cm, bindingoffset=1cm]{geometry}
\begin{document}
\chapter{Exploring the page layout}
In this chapter we will study the layout of pages.
\section{Some filler text}
\blindtext
\section{A lot more filler text}
More dummy text will follow.
\subsection{Plenty of filler text}
\blindtext[3]
\end{document}

Any command-line input or output is written as follows:
texdoc geometry

New terms and important words are shown in bold. Words that you see on the screen, in
menus or dialog boxes for example, appear in the text like this: "Save the document and
Typeset it."

[5]

Preface

Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this
book—what you liked or may have disliked. Reader feedback is important for us to
develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to feedback@packtpub.com, and
mention the book title via the subject of your message.
If there is a book that you need and would like to see us publish, please send us a note in
the SUGGEST A TITLE form on www.packtpub.com or e-mail suggest@packtpub.com.
If there is a topic that you have expertise in and you are interested in either writing or
contributing to a book on, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you
to get the most from your purchase.

Downloading the example code

You can download the example code files for all Packt books you have purchased from your
account at http://www.PacktPub.com. If you purchased this book elsewhere, you can
visit http://www.PacktPub.com/support and register to have the files e-mailed directly
to you.

[6]

Preface

Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do
happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—
we would be grateful if you would report this to us. By doing so, you can save other readers
from frustration and help us improve subsequent versions of this book. If you find any
errata, please report them by visiting http://www.packtpub.com/support, selecting
your book, clicking on the errata submission form link, and entering the details of your
errata. Once your errata are verified, your submission will be accepted and the errata will
be uploaded on our website, or added to any list of existing errata, under the Errata section
of that title. Any existing errata can be viewed by selecting your title from http://www.
packtpub.com/support.

Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt,
we take the protection of our copyright and licenses very seriously. If you come across any
illegal copies of our works, in any form, on the Internet, please provide us with the location
address or website name immediately so that we can pursue a remedy.
Please contact us at copyright@packtpub.com with a link to the suspected
pirated material.
We appreciate your help in protecting our authors, and our ability to bring you
valuable content.

Questions
You can contact us at questions@packtpub.com if you are having a problem with any
aspect of the book, and we will do our best to address it.

[7]

1

Getting Started with LaTeX
Are you ready to leave those "what you see is what you get" word processors
behind and to enter the world of real, reliable, and high-quality typesetting?
Then let's go together!

It's great that you decided to learn LaTeX. This book will guide you along the way to help you
get the most out of it. Let's speak briefly about LaTeX's benefits and the challenges, and then
we shall prepare our tools.
In this chapter, we will:
‹‹

Get to know LaTeX and talk about the pros and cons compared to word processors

‹‹

Install a complete LaTeX software bundle, including an editor

‹‹

Write our first LaTeX document

So, let's get started.

What is LaTeX?
LaTeX is a software for typesetting documents. In other words, it's a document preparation
system. LaTeX is not a word processor, but is used as a document markup language.
LaTeX is a free, open source software. It was originally written by Leslie Lamport and is based
on the TeX typesetting engine by Donald Knuth. People often refer to it as just TeX, meaning
LaTeX. It has a long history; you can read about it at http://www.tug.org/whatis.html.
For now, let's continue by looking at how we can make the best use of it.

Getting Started with LaTeX

How we can benefit
LaTeX is especially well-suited for scientific and technical documents. Its superior typesetting
of mathematical formulas is legendary. If you are a student or a scientist, then LaTeX is by far
the best choice, and even if you don't need its scientific capabilities, there are other uses —
it produces very high quality output, it is extremely stable, and handles complex documents
easily no matter how large they are.
Further remarkable strengths of LaTeX are its cross-referencing capabilities, its automatic
numbering and generation of lists of contents, figures and tables, indexes, glossaries,
and bibliographies. It is multilingual with language-specific features, and it is able to use
PostScript and PDF features.
Apart from being perfect for scientists, LaTeX is incredibly flexible—there are templates for
letters, presentations, bills, philosophy books, law texts, music scores, and even for chess
game notations. Hundreds of LaTeX users have written thousands of templates, styles, and
tools useful for every possible purpose. It is collected and categorized online on archiving
servers.
You could benefit from its impressive high quality by starting with its default styles relying
on its intelligent formatting, but you are free to customize and to modify everything. People
of the TeX community have already written a lot of extensions addressing nearly every
formatting need.

The virtues of open source
The sources of LaTeX are completely free and readable for everyone. This enables you to
study and to change everything, from the core of LaTeX to the latest extension packages.
But what does this mean for you as a beginner? There's a huge LaTeX community with a lot
of friendly, helpful people. Even if you cannot benefit from the open source code directly,
they can read the sources and assist you. Just join a LaTeX web forum and ask your questions
there. Helpers will, if necessary, dig into LaTeX sources and in all probability find a solution
for you, sometimes by recommending a suitable package, often providing a redefinition of a
default command.
Today, we're already profiting from about 30 years of development by the TeX community.
The open source philosophy made it possible, as every user is invited to study and improve
the software and develop it further. Chapter 13, Using Online Resources, will point the way
to the community.

[ 10 ]

Chapter 1

Separation of form and content
A basic principle of LaTeX is that the author should not be distracted too much by the
formatting issues. Usually, the author focuses on the content and formats logically, for
example, instead of writing a chapter title in big bold letters, you just tell LaTeX that it's a
chapter heading—you could let LaTeX design the heading or you decide in the document's
settings what the headings will look like—just once for the whole document.
LaTeX uses style files extensively called classes and packages, making it easy to design
and to modify the appearance of the whole document and all of its details.

Portability
LaTeX is available for nearly every operating system, like Windows, Linux, Mac OS X, and
many more. Its file format is plain text—readable and editable, on all operating systems.
LaTeX will produce the same output on all systems. Though there are different LaTeX
software packages, so called TeX distributions, we will focus on TeX Live, because this
distribution is available for Windows, Linux, and Mac OS X.
LaTeX itself doesn't have a graphical user interface; that's one of the reasons why it's so
portable. You can choose any text editor. There are many editors, even specialized in LaTeX,
for every operating system. Some editors are available for several systems. For instance,
TeXworks runs on Windows, Linux, and Mac OS X; that's one of the reasons why we will use
it in our book. Another very important reason is that it's probably best-suited for beginners.
LaTeX generates PDF output—printable and readable, on most computers and looks identical
regardless of the operating system. Besides PDF, it supports DVI, PostScript, and HTML
output, preparing the ground for distribution both in print and online, on screen, electronic
book readers, or smart phones.
To sum up, LaTeX is portable in three ways—source, its implementation, and output.

Protection for your work
LaTeX documents are stored in human readable text format, not in some obscure word
processing format, that may be altered in a different version of the same software. Try to
open a 20 year old document written with a commercial word processor. What might your
modern software show? Even if you can read the file, its visual appearance would certainly
be different than before. LaTeX promises that the document will always be readable and
will result in the same output. Though it's being further developed, it will remain backwards
compatible.
Word processor documents could be infected with viruses, malicious macros could
destroy the data. Did you ever hear of a virus "hiding" in a text file? LaTeX is not
threatened by viruses.
[ 11 ]

Getting Started with LaTeX

Comparing it to word processor software
We've already described some advantages of the typesetting system LaTeX compared
to word processing software. While LaTeX encourages structured writing, other word
processors may compel you to work inconsistently. They might hide the real formatting
structure and encrypt your document in some proprietary file format. Compatibility is a big
problem, even between versions of the same software.
There are some interesting articles available online comparing LaTeX to other software. Of
course, they are expressions of opinion. Some are years old and therefore do not cover the
most recent software, but they discuss important points that are still valid today. You will find
them listed in Chapter 13, Using Online Resources.

What are the challenges?
The learning curve could be steep, but this book will to help you master it.
Though writing LaTeX looks like programming, don't be afraid. Soon you will know the
frequently used commands. Text editors with auto completion and keyword highlighting
will support you. They might even provide menus and dialogs with commands for you.
Do you now think it will take a long time until you would learn to achieve creditable results?
Don't worry; this book will give you a quick start. You will learn by practicing with a lot
of examples. Many more examples can be read and downloaded from the Internet. In
Chapter 13, we will explore the Internet resources.
We shall continue with the setup of LaTeX on our computer.

Installing LaTeX
Let's start off with the installation of the LaTeX distribution–TeX Live. This distribution is
available for Windows, Linux, Mac OS X, and other Unix-like operating systems. TeX Live is
well maintained and it is being actively developed.
Another very good and user-friendly LaTeX distribution for Windows is
MiKTeX. It's easy to install like any other Windows application, but it's not
available for other systems like Linux or Mac OS X. You can download it
from http://miktex.org.

At first, we will visit the TeX Live homepage and take a survey of the installation possibilities.
Feel free to explore the homepage in depth to study the information offered there.
Open the TeX Live homepage at http://tug.org/texlive.
[ 12 ]

Chapter 1

We will cover two ways of installation. The first will be online and requires an Internet
connection. The other method starts with a huge download, but may be finished offline.
Let's check out the two installation methods.

[ 13 ]

Getting Started with LaTeX

Time for action – installing TeX Live using the net
installer wizard
We will download the TeX Live net installer and install the complete TeX Live distribution on
our computer.

1.

Click on downloading over the net or navigate to http://
tug.org/texlive/acquire-netinstall.

2.

Download the net installer for Windows by clicking on install-tl.zip.

3.

Extract the file install-tl.zip using your favorite archiving program.
For example, WinZip, WinRar, or 7-Zip can do it for you.

4.

Open the folder install-tl-*and double-click the Windows
batch file install-tl:

[ 14 ]

Chapter 1

5.

The net installer will automatically detect your language. If it's showing the
wrong language, you can force the choice of the language using the lang
option at the command prompt such as install-tl –lang=en:

[ 15 ]

Getting Started with LaTeX

6.

The installation wizard will pop up, as shown in the following screenshot:

7.

Click on the Next button, now it offers to change the installation folder, but
it's fine to retain it. In our book, we will refer to this default location:

[ 16 ]

Chapter 1

8.

Click on the Next button. As shown in the following screenshot, choose
one of the options, for example, for the creation of shortcuts:

9.

Click on the Next button. You can then confirm the settings and
actually start the installation by clicking on the Install button:

[ 17 ]

Getting Started with LaTeX

10.

The next screenshot shows how you can monitor the installation progress:

11.

Finally, click on the Finish button and you're done.

What just happened?
You have completed the installation of TeX Live 2010. Now your Start menu contains
a folder called TeX Live 2010 containing six programs:

‹‹

DVIOUT DVI viewer—a viewer program for the classic LaTeX output format DVI.
Today, most people choose PDF output, so you probably won't need it.

[ 18 ]

Chapter 1
‹‹

PS_VIEW—a viewer program for the PostScript format; again you probably
won't need it, except if you would like to use the PostScript language or read
such documents.

‹‹

TeX Live documentation—well, that's useful regarding setup and use of your
software!

‹‹

TeX Live Manager—that's your tool for package management, for example,
installation and update of LaTeX packages.

‹‹

TeXdoc GUI—it's a graphical user interface offering access to a huge amount of
LaTeX-related information. There's a lot of it stored in your computer by now. Use it
to gather information whenever needed; it could be quicker than searching online.

‹‹

TeXworks editor—this is an editor developed to create LaTeX documents
comfortably. We will make extensive use of it.
TeXworks is also shipped with MiKTeX 2.8 and higher.

If you would like to stay in control over what should be installed on your computer, start the
install-tl-advanced batch file instead of install-tl:

[ 19 ]

Getting Started with LaTeX

The TeX documentation available online contains more information for advanced users.
Now, we will go through the offline installation of TeX Live 2010.

Time for action – installing TeX Live offline
We will download a compressed ISO image of TeX Live 2010 with a size of about 1.2
gigabytes. After extraction, we can choose to burn it on DVD or to extract it to our hard
disk drive and run the installation from there:

1.

Visit the download area at http://www.tug.org/texlive/acquire-iso.html.

2.

Download texlive2010.xz. If possible, use a download manager,
especially if your Internet connection is not stable.

3.

Extract texlive2010.xz and you will get the file texlive2010.iso. If your
archiving program doesn't support the .xz file format, obtain, for instance, the
program 7-Zip version 9 or later from http://7zip.org and use it for extraction.

4.

Either burn the ISO file on a DVD using a burning software supporting the ISO format
or extract it to your hard disk drive. 7-Zip is also capable of doing that for you.

5.

Among the extracted files or on your DVD, you will find the installer batch files
install-tl and install-tl-advanced that we've already seen. Choose
one, start it, and go through the installation like in the previous installation.

What just happened?
It was similar to the first installation, but this time you've got all the data and you won't
need an Internet connection. This complete download is especially recommended if it's
foreseeable that you will do another installation of TeX Live later or if you would like to
give it to friends or colleagues.
After an offline installation, it's recommended to run an update of TeX Live soon,
because packages on a DVD or within an image could already be outdated. Use
the TeX Live Manager to keep your system up-to-date if you are connected to
the Internet.

Installation on other operating systems
If you work on Mac OS X, you may download a customized version of TeX Live at http://
www.tug.org/mactex/. Download the huge .zip file and double-click on it to install.

[ 20 ]

Chapter 1

On most Linux systems, installation is easy. Use your system's package manager. With
Ubuntu, you may use Synaptic, on SUSE systems use YaST, with Red Hat a RPM frontend, and
on Debian systems use Aptitude. In the respective package manager, look out for texlive.
If you want to stay on the edge, you could download and install the most current version of
TeX Live from its homepage, instead of the version from the operating system's repositories.
But be aware that installing third party sources may harm the integrity of your system.
Now that we've prepared the ground, let's start to write LaTeX!

Creating our first document
We have installed TeX and launched the editor; now let's jump in at the deep end by writing
our first LaTeX document.

Time for action – writing our first document with TeXworks
Our first goal is to create a document that's printing out just one sentence. We want to use it
to understand the basic structure of a LaTeX document.

1.

Launch the TeXworks editor by clicking on the desktop icon or open it in the
Start menu.

2.

Click on the New button.

3.

Enter the following lines:
\documentclass{article}
\begin{document}
This is our first document.
\end{document}

4.

Click on the Save button and save the document. Choose a location where
you want to store your LaTeX documents, ideally in its own folder.

[ 21 ]

Getting Started with LaTeX

5.

In the drop-down field in the TeXworks toolbar, choose pdfLaTeX:

6.

Click the Typeset button

7.

The output window will automatically open. Have a look at it:

.

What just happened?
You have just seen the first few minutes of the life of a LaTeX document. Its following hours
and days will be determined by editing, typesetting, and so on. Don't forget to save your
document frequently.
As announced in contrary to the classic word processor software, you cannot see the effect
of changes immediately—but the result is just one click away.

[ 22 ]

Chapter 1

Have a go hero – checking out advanced LaTeX editors
Do you have experience in working with complex programs? Do you like using a feature-rich
and powerful editor? Then have a look at these LaTeX editors. Visit their websites to find
screenshots and to read about their features:
‹‹

TeXnicCenter— a very powerful editor for Windows, http://texniccenter.
org/

‹‹

Kile— a user-friendly editor for operating systems with KDE, such as Linux,
http://kile.sourceforge.net/

‹‹

TeXShop—an easy-to-use and very popular editor for Mac OS X, http://pages.
uoregon.edu/koch/texshop/

‹‹

Texmaker—a cross-platform editor running on Linux, Mac OS X, Unix, and
Windows systems, http://www.xm1math.net/texmaker/

The mentioned editors are free open source software.

Summary
We learned in this chapter about the benefits of LaTeX. It will be our turn to use the virtues
of LaTeX to achieve the best possible results.
Furthermore, we covered:
‹‹

Installation of TeX Live

‹‹

Using the editor TeXworks

‹‹

Creation of a LaTeX document and generation of output

Now that we've got a functional and tested LaTeX system, we're ready to write our own
LaTeX documents. In the next chapter, we will work out the formatting of text in detail.

[ 23 ]

2

Formatting Words, Lines, and
Paragraphs
In the last chapter, we installed LaTeX and used the TeXworks editor to write our
first document. Now we will speak about the structure of a document and we
will focus on the text details and its formatting.

In this chapter, we shall:
‹‹

Speak about logical formatting

‹‹

Learn how to modify font, shape, and style of text

‹‹

Use boxes to limit the text width

‹‹

See how to break lines and how to improve hyphenation

‹‹

Explore justification and formatting of paragraphs

By working with examples and trying out new features, we shall learn some basic concepts
of LaTeX. By the end of this chapter, we will be familiar with commands and environments.
You will even be able to define your own commands.

Understanding logical formatting
In the previous chapter, we wrote a small example document. Let's extend it a bit to get an
illustrative example for understanding the typical document structure.

Formatting Words, Lines, and Paragraphs

Time for action – titling your document
We will take the first example and insert some commands that will produce a
nice-looking title.

1.

Type the following code in the editor; modify the previous example if you like:
\documentclass[a4paper,11pt]{article}
\begin{document}
\title{Example 2}
\author{My name}
\date{January 5, 2011}
\maketitle
\section{What's this?}
This is our second document. It contains a title and a section
with text.
\end{document}

2.

Click the Typeset button.

3.

View the output:

What just happened?
In the first chapter, we talked about logical formatting. First, let's look at this example
from that point of view. We told LaTeX that:
‹‹

Our document is of the type article. It will be printed on A4 paper using a size
of 11 points for the base font.

‹‹

The title is "Example 2".

‹‹

You are the author.

‹‹

The document was written on January 5, 2011.
[ 26 ]

Chapter 2
‹‹

Concerning the content of the document:
‰‰

It begins with a title.

‰‰

The first section shall have the heading "What's this?"

‰‰

The following text is "This is our second document."

Note, we did not choose the font size of the title or heading; neither did we make something
bold or centered. Such formatting is done by LaTeX but nevertheless you're free to tell LaTeX
how it actually should look.
We did not need to press the Save button. TeXworks automatically saves
the document if we click the Typeset button.

Exploring the document structure
Let's look at the details. A LaTeX document doesn't stand alone—commonly the document
is based on a versatile template. Such a fundamental template is called a class. It provides
customizable features, usually built for a certain purpose. There are classes for books, for
journal articles, for letters, for presentations, for posters, and many more; hundreds of
reliable classes can be found in Internet archives but also on your computer now, after
you've installed TeX Live. Here we have chosen the article class, a standard LaTeX class
suitable for smaller documents.
The first line starts with \documentclass. This word begins with a backslash; such a
word is called a command. We used commands to specify the class and to state document
properties: title, author, and date.
This first part of the document is called the preamble of the document. This is where we
choose the class, specify properties, and in general, make document-wide definitions.
\begin{document} marks the end of the preamble and the beginning of the actual
document. \end{document} marks the end of it. Everything that follows would be
ignored by LaTeX. Such a piece of code, framed by a \begin … \end command pair,

is called an environment.

In the actual document, we've used the command \maketitle that prints the title, author,
and date in a nicely formatted manner. By the \section command, we produced a heading,
bigger and bolder than normal text. Then we let some text follow. What we wrote here, in
the document environment, will be printed out. On the contrary, the preamble will never
produce any output.
Let's look at commands in detail.

[ 27 ]

Formatting Words, Lines, and Paragraphs

Understanding LaTeX commands
LaTeX commands begin with a backslash, followed by big or small letters. LaTeX commands
are usually named with small letters and in a descriptive way. There are exceptions: you will
see some commands consisting of a backslash and just one special character.
Commands may have arguments, given in curly braces or in square brackets.
Calling a command looks like the following:
\command

Or:
\command{argument}

Or:
\command[optional argument]{argument}

There could be several arguments, each of them in braces or brackets. Arguments in curly
braces are mandatory. If a command is defined to require an argument, one has to be given.
For example, calling \documentclass would be futile if we hadn't stated a class name.
Arguments in square brackets are optional; they may be given but it's not a
must. If no optional argument is provided, the command will use a default
one. For instance, in the first example in Chapter 1, Getting Started with LaTeX,
we wrote \documentclass{article}. This document has been typeset
with a base font size of 10pt, because this is the class default base font size.
In the second document, we wrote \documentclass[a4paper,11pt]
{article}; this way, we replaced default values with the given values, so now
the document will be adjusted for A4 paper using a base font size of 11pt.

There are commands generating output—try \LaTeX—and commands setting properties,
changing fonts or layout. Generally, the names of commands are chosen according to their
purpose. We will have a more detailed look in this chapter, but first let's see how LaTeX
treats what we type.

How LaTeX reads your input
Before we continue writing, let's look at how LaTeX understands what you've written in
the editor.

[ 28 ]

Chapter 2

Time for action – trying out the effect of spaces, line
breaks, and empty lines
We will take the first example and insert spaces and line breaks.

1.

Modify the previous example as follows:
\documentclass[a4paper,11pt]{article}
\begin{document}
\title{Example 3}
\author{My name}
\date{January 5, 2011}
\maketitle
\section{What's this?}
This
is
our
second document.
It contains two paragraphs. The first line of a paragraph will be
indented, but not when it follows a heading.
% Here's a comment.
\end{document}

2.

Typeset.

3.

View the output:

[ 29 ]

Formatting Words, Lines, and Paragraphs

What just happened?
Though we've inserted some spaces, the distances between the words in the output
remained the same. The reason is that LaTeX treats multiple spaces just like a single space.
Also, a single line break has the same effect like a single space. It doesn't matter how you
arrange your text in the editor using spaces or breaks, the output will stay the same.
A blank line denotes a paragraph break. Like spaces, multiple empty lines are treated as one.
Briefly said, spaces separate words, empty lines separate paragraphs.

Commenting your source text
You've seen that the last line seems to be missing in the output. That's because the percent
sign introduces a comment. Everything following a percent sign until the end of the line
will be ignored by LaTeX and won't be printed out. This enables you to insert notes into
your document. It's often used in templates to inform the user what the template does at
that certain place. Note also that the end of the line, normally behaving like a space, will be
ignored after a percent sign.
Easing experimenting by trial and error
If you want to disable a command temporarily, it may be favorable to insert a
percent sign instead of deleting the command. That way, you're able to undo this
change easily by removing the %.

If the percent sign behaves that way, what should we do if we want to write 100% in our
text? Let's figure out how to do it.

Printing out special symbols
Common text mostly contains upper and lowercase letters, digits, and punctuation
characters. Simply type them with your editor. However, some characters are reserved for
LaTeX commands; they cannot be used directly. We already encountered such characters,
and besides the percent sign, there are the curly braces and so on. There are LaTeX
commands to print such symbols.

[ 30 ]

Chapter 2

Time for action – writing special characters in our text
We will write a very short example printing out an amount of dollars and a percent number,
then we shall try more symbols:

1.

Create a new document and enter the following lines:
\documentclass{article}
\begin{document}
Statement \#1:
50\% of \$100 makes \$50.
More special symbols are \&, \_, \{ and \}.
\end{document}

2.

Typeset and view the output:

What just happened?
By putting a backslash before such a special symbol, we turned it into a LaTeX command.
This command has the only purpose of printing out that symbol.
The command for printing a backslash is \textbackslash. If you would
like to know what \\ might be used for, it is used as a shortcut for a line break
command. That's a bit odd, but line breaks occur frequently whereas backslashes
are rarely needed in the output, therefore this shortcut has been chosen.

There's a wealth of symbols that we can use for math formulas, chess notation, zodiac signs,
music scores, and more. We don't need to deal with those symbols for now, but we shall
return to that subject in Chapter 8, Typing Math Formulas, when we will need symbols to
typeset math formulas.
Now that we know how to enter pure text, let's find out how we can format it.

Formatting text – fonts, shapes, and styles
LaTeX already does some formatting. For example, we've seen that section headings are
bigger than normal text and bold faced. Now we will learn how to modify the appearance
of the text ourselves.
[ 31 ]

Formatting Words, Lines, and Paragraphs

Time for action – tuning the font shape
We will emphasize an important word in a text and we will see how to make words appear
bold, italic, or slanted. We shall figure out how to highlight words in a part of some text
that's already emphasized:

1.

Create a new document containing the following code:
\documentclass{article}
\begin{document}
Text can be \emph{emphasized}.
Besides being \textit{italic} words could be \textbf{bold},
\textsl{slanted} or typeset in \textsc{Small Caps}.
Such commands can be \textit{\textbf{nested}}.
\emph{See how \emph{emphasizing} looks when nested.}
\end{document}

2.

Typeset and have a look at the output:

What just happened?
At first, we used the command \emph, giving one word as an argument to this command.
This argument will be typeset in italic shape, because this is the default way how LaTeX
emphasizes text.
Text-formatting commands usually look like \text**{argument}, where ** stands for a
two letter abbreviation like bf for bold face, it for italic, and sl for slanted. The argument
will then be formatted accordingly like we've seen. After the command, the subsequent
text will be typeset as it was before the command—precisely after the closing curly brace
marking the end of the argument. We checked it out.
We've nested the commands \textit and \textbf, which allowed us to achieve a
combination of those styles, and the text appears both italic and bold.

[ 32 ]

Chapter 2

Most font commands will show the same effect if they are applied twice like
\textbf{\textbf{words}}: the words won't become bolder. Only \emph behaves
differently. We've seen that emphasized text will be italic, but if we use \emph onto a
piece of this text again, it will change from italic to normal font. Imagine an important
theorem completely typeset in italics—you should still have the opportunity to highlight
words inside this theorem.
\emph is so called semantic markup, because it refers to the meaning, not just to the

appearance of text.

Emphasizing twice, such as marking bold and italic at the same
time, might be considered to be a questionable style. Change
the font shape wisely—and consistently.

Choosing the font family
Compare the font of our examples and the standard font you see in this book. While the
LaTeX font has a decorative appearance, the text font of this book looks simple and clean.
Our code examples are different in another way: every letter has the same width. Let's see
how we can implement this in our writings.

Time for action – switching to sans-serif and to typewriter fonts
Imagine that we start to write an article about LaTeX's Internet resources. To get a clearly
readable heading, we shall use a font without frills. The body text will contain a web address;
we choose a typewriter font to stress it:

1.

Create a LaTeX document with the following code:
\documentclass{article}
\begin{document}
\section{\textsf{\LaTeX\ resources on the internet}}
The best place for downloading LaTeX related software is CTAN.
Its address is \texttt{http://www.ctan.org}.
\end{document}

[ 33 ]

Formatting Words, Lines, and Paragraphs

2.

Typeset and look at the result:

What just happened?
We encountered more font commands. By using\textsf, we've chosen the sans-serif font in
the section heading. We used the command \texttt to get the typewriter font for the web
address. Those commands can be used just like the font commands we've learned before.
The letters in the LaTeX standard font have so-called serifs, those small decorative details
at the end of a letter's strokes. Serifs shall improve readability by leading the reader's eyes
along the line. Therefore, they are widely used in body text. Such fonts are also called
Roman fonts. This name led to the command \textrm for the Roman text—the default
font with serifs.
Headings are often done without serifs; the used font is called a sans-serif font. Such fonts
are also a good choice for screen text because of the better readability on lower resolutions.
So you might want to choose a sans-serif font when you produce an e-book.
If every letter of a font has the same width, the font is called monospaced or a typewriter
font. Besides, on typewriters, such fonts were used with early computers; today they are still
preferred for writing source code of computer programs, both in print and in text editors.
So if you want to typeset a program listing or LaTeX source code, consider using a typewriter
font. Like we did in the previous example, this book is using a typewriter font to distinguish
code and web addresses from the normal text.

Switching fonts
Putting too much text into a command's argument could be unhandy. Sometimes we would
like to set font properties of longer passages of text. LaTeX provides other commands, which
work like switches.

[ 34 ]

Chapter 2

Time for action – switching the font family
We will modify the previous example using font family switching commands:

1.

Modify the example to get the following code:
\documentclass{article}
\begin{document}
\section{\sffamily\LaTeX\ resources in the internet}
The best place for downloading LaTeX related software is CTAN.
Its address is \ttfamily http://www.ctan.org\rmfamily.
\end{document}

2.

Typeset and compare the output to the previous one; it's the same.

What just happened?
By using the command \sffamily, we switched over to sans serif font. This change has
been made inside an argument, so it's valid only there.
We used the command \ttfamily to switch to a typewriter font. The typewriter font will
be used from this point onwards. By using\rmfamily, we returned to Roman font.
These commands don't produce any output, but they will affect the following text. We will
call such a command a declaration.
Now have a closer look at the section number: it's a digit with serifs, which doesn't match
the remaining sans-serif heading. Moreover, changing the font within a\section command
feels wrong—and rightly so! The better way is to declare the section heading font once for
the complete document. We will learn how to globally modify heading fonts in Chapter 11,
Enhancing Your Documents Further, after we prepared some more tools.

[ 35 ]

Formatting Words, Lines, and Paragraphs

Summarizing font commands and declarations
Let's list the font commands and their corresponding declarations together with
their meanings:

The corresponding declaration to \emph is \em.

Delimiting the effect of commands
In the previous example, we've reversed the effect of \ttfamily by writing \rmfamily. To
be safe, we could write \normalfont to switch back to the base font. However, there's an
easier way.

Time for action – exploring grouping by braces
We shall use curly braces to tell LaTeX where to apply a command and where to stop that:

1.

Modify our first font shape example to get this code:
\documentclass{article}
\begin{document}
{\sffamily
Text can be {\em emphasized}.
Besides being {\itshape italic} words could be {\bfseries bold},
{\slshape slanted} or typeset in {\scshape Small Caps}.
Such commands can be {\itshape\bfseries nested}.}
{\em See how {\em emphasizing} looks when nested.}
\end{document}
[ 36 ]

Chapter 2

2.

Typeset and check out the output:

What just happened?
We started with an opening curly brace. The effect of the following command \sffamily
lasted until we stopped it with the corresponding closing brace. That closing brace came
at the end of the highlighted code. This highlighting shows the area of the code where
\sffamily is valid.
We replaced every font command by the corresponding declaration. Remember, \em is
the declaration version of \emph. Further, we surrounded every declaration and the
affected text by curly braces.
An opening curly brace tells LaTeX to begin a so called group. The following commands
are valid for the subsequent text until a closing curly brace appears causing LaTeX to stop
using the commands or declarations written in this group. Till a command is valid, that's
called its scope.
Groups can be nested as follows:
Normal text, {\sffamily sans serif text {\bfseries and bold}}.

We have to be careful to close each group; opening and closing braces should match.
Braces which enclose an argument of a command don't form a group. Together
with the argument, these braces are gobbled by the command. If necessary, use
additional braces.

Time for action – exploring font sizes
We will try out every font size available by LaTeX's default font size commands. For testing,
we exceptionally use them in the body text—their main use is in the macro definitions:

1.

Create a document with the following code:
\documentclass{article}
\begin{document}
\noindent\tiny We \scriptsize start \footnotesize \small small,
\normalsize get \large big \Large and \LARGE bigger,
[ 37 ]

Formatting Words, Lines, and Paragraphs
\huge huge and \Huge gigantic!
\end{document}

2.

Typeset and observe the output:

What just happened?
At first, we used \noindent. This command suppresses the paragraph indentation. Then we
used all 10 available size declarations, starting small with \tiny and ending really big with
\Huge. There are no corresponding commands taking arguments, so we would have to use
curly braces to delimit their scope, as we learned to before.
The actual resulting font size depends on the base font. If your document has a base font
of 12 pt, then \tiny would result in text bigger than with a base font of 10 pt. We have to
see it in relation. Use \footnotesize, if you wish to get the same size like LaTeX uses for
footnotes; use \scriptsize, if you create a style with a size matching LaTeX subscripts and
superscripts. It's still a kind of logical formatting though they are quite low-level commands.
Normally, font size declarations are used only in definitions of macros in the preamble, just
as it does apply to the other font commands. You will rarely encounter font size or shape
commands in good body texts, except freely designed passages like title pages—and test
examples like the ones here.

Using environments
When you use several declarations and you group them by curly braces, will you always
know which closing brace matches which of the previously entered declarations? An
environment forms a group. Using an environment instead of just curly braces improves
the readability of your code.

Time for action – using an environment to adjust the font size
We will produce a title with a larger and bigger font:

1.

Create another small document with this code:
\documentclass{article}
\begin{document}
\begin{huge}
\bfseries
A small example
[ 38 ]

Chapter 2
\end{huge}
\bigskip
This is just another small illustrative example.
\end{document}

2.

Typeset to see the result:

What just happened?
By writing \begin{huge}, we told LaTeX to switch to a huge font size just like with the
\huge command. \end{huge} informs LaTeX that this size change should end now.
From this point onwards, the font size is the same as before \begin{huge}.
Inside this environment, we use the declaration \bfseries. Note that the effect of this
declaration ended together with the end of the environment.
The empty line before \end{huge} denotes a paragraph break. Using the command
\bigskip, we skipped some space vertically.
For every declaration there's a corresponding environment carrying the same name except
the backslash. Using environments instead of braces might make complex code easily
understandable.
Commonly it's advisable to end the paragraph before a font size change, not
after it. That's because TeX calculates the interline spacing depending on the
current font size when it reaches the end of the paragraph. That's the reason we
used the blank line before \end{huge} instead of afterwards.

Saving time and effort – creating your 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 decided to change that term or its formatting? To
avoid searching and replacing in the whole document, LaTeX allows you to define your
own commands in your preamble. They are also called macros. Give it a name. Later in the
document you just need to use this name whenever you want to change this term. We need
to do it just once in the macro definition. This will affect the whole document. Let's see how
it works.
[ 39 ]

Formatting Words, Lines, and Paragraphs

Time for action – creating our first command using it as an
abbreviation
We will define a short command printing out the name of the TeX Users Group:

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 are interested in
\TeX\ or \LaTeX.
\end{document}

2.

Typeset and look at the result:

What just happened?
\newcommand in the highlighted line defines our command. The first argument is the name

we chose for it, and the second argument is the text we want it to put 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 it will be applied for the complete 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 command \TeX. This command just prints out the
name of the basic typesetting system formatted like in its logo. It's an abbreviation command
like we've written now and \LaTeX works similarly. Note that we had to use a backslash
after \TeX! The following space would just separate the command from the following text;
it won't produce a space in the output. Using the backslash followed by a space forces the
output of the space that would otherwise be ignored. You may try omitting that backslash to
be convinced.

[ 40 ]

Chapter 2

Gentle 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. These are collections of styles and commands.

Time for action – adding intelligent spacing to command output
We will load the package xspace. Its only purpose is to fulfill this need.

1.

Modify the previous example to get the following code:
\documentclass{article}
\usepackage{xspace}
\newcommand{\TUG}{\textsc{TeX Users Group}\xspace}
\begin{document}
\section{The \TUG}
The \TUG is an organization for people who are interested in \TeX\
or \LaTeX.
\end{document}

2.

Typeset, see that the spacing between the words is correct, even without
the backslash:

What just happened?
\usepackage{xspace} tells LaTeX to load the package called xspace and to read in all

of its definitions. From now on we may use all commands contained in that package. This
package provides the command \xspace that inserts a space depending on the following
character: If a dot, a comma, an exclamation, or a quotation mark follows, it won't insert a
space, but if a normal letter follows, then it will. Usually, that's exactly what we want.

[ 41 ]

Formatting Words, Lines, and Paragraphs

Imagine you've mentioned the TUG several times in your document and now you've got
the idea to use the TeX logo style in its name. There's no need for changes in the document.
Now only the command in the preamble needs adjustment:
\newcommand{\TUG}{\textsc{\TeX\ Users Group}\xspace}

The heading in our last example doesn't contain small caps—have you seen it?
Not all font properties can be combined, depending on the chosen font. For
instance, fonts with small caps together with variations like bold and italic are
rare. Therefore, some people even fake small caps if they don't want to change
to a more complex font.

By defining and using commands, you can ensure that the formatting remains consistent
throughout your whole document.

Creating more universal commands – 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 would 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.

Time for action – creating a macro for formatting keywords
We will use \newcommand again, but this time we will introduce a parameter that will
contain our keyword. Let's just use it on some terms that we've got to know in this chapter:

1.

Type this code example:
\documentclass{article}
\newcommand{\keyword}[1]{\textbf{#1}}
\begin{document}
\keyword{Grouping} by curly braces limits the
\keyword{scope} of \keyword{declarations}.
\end{document}

[ 42 ]

Chapter 2

2.

Typeset and notice the look of the keywords in the output:

What just happened?
Let's look at the highlighted 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 would refer to a 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.

Using optional arguments
In one preceding example, we've used \newcommand with two arguments. In the previous
example, there were three arguments. The additional argument has been put in square
brackets. That's the way we mark optional arguments: those arguments may be given or
may be omitted. If omitted, they would have a default value. We've already noticed that
with the \documentclass command. But how can we define a command with optional
arguments ourselves?

Time for action – marking keywords with optional formatting
We will use \newcommand another time, this time with an optional parameter concerning
the formatting 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.

Typeset and check out the result:

[ 43 ]

Formatting Words, Lines, and Paragraphs

What just happened?
Let's look again at the bold marked line in the code. By using [\bfseries], we introduced
an optional parameter. We refer to it with #1. 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 italics.
Here's the definition of the\newcommand:
\newcommand{command}[arguments][optional]{definition}
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.
That name must not be already defined and is not allowed to begin with \end.

arguments

An integer from 1 to 9, 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 the command will be replaced by definition and every
occurrence of the form #n will then be replaced by the nth argument.

\newcommand is our key to introduce logical formatting. We should avoid using LaTeX

font commands inside the document—you are on the right track if they appear only in the
preamble of the document. 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? Using styles is the key!

Pop quiz – commands
1. Imagine your document contains some addresses of websites. Let's say we want
them to be typeset in typewriter font. According to this book, which of the following
possibilities would be the best way to print out, for instance, http://ctan.org?
a. \texttt{http://ctan.org}
b. {\ttfamilyhttp://ctan.org}
c.

\newcommand{\CTAN}{\texttt{http://ctan.org}} in the preamble
and \CTAN in the body text

d. \newcommand{\site}[1]{\texttt{#1}} and \newcommand{\CTAN}
{http://ctan.org} in the preamble and \site{\CTAN} in the body text

[ 44 ]

Chapter 2

2. Which kind of punctuation marks are used to enclose optional arguments?
a. Parentheses: ()
b. Square brackets: []
c.

Curly braces: {}

Have a go hero – saving effort using optional arguments
Most website addresses begin with http://. But there are sites that differ—some may
start with ftp://, so called FTP server, some sites begin with https://, so called secure
web server. Visit, for instance, ftp://ctan.org, and you will enter a file server instead
of a web server.
Extend the definition of \site of our last pop quiz. Introduce an optional argument
denoting the protocol of the site, that is, how the address starts. Default should start with
http://. It shall work like the following:
‹‹

\site{www.tug.org} prints out http://www.tug.org in typewriter font

‹‹

\site[ftp]{ctan.org} prints out ftp://ctan.org in typewriter font
Web addresses in texts
There's a package called url designed for typesetting web addresses.
Write \usepackage{url} in your preamble; this will provide the
command \url. This command takes an address for the argument and
will print it out with typewriter font. Furthermore, it is able to handle
special characters in addresses like underscores and percent signs. It even
enables hyphenation in addresses, which is useful for websites with a very
long name.

Using boxes to limit the width of paragraphs
We won't always write the text just from left to right over the complete text width.
Sometimes, we'd like a paragraph to have a smaller width, for instance, when we would
like to put text and a picture side-by-side.

[ 45 ]

Formatting Words, Lines, and Paragraphs

Time for action – creating a narrow text column
We would like to explain the acronym TUG in a text column of only 3 cm width:

1.

Create a new document containing these four lines:
\documentclass{article}
\begin{document}
\parbox{3cm}{TUG is an acronym. It means \TeX\ Users Group.}
\end{document}

2.

Typeset and take a critical look at the output:

What just happened?
We used the command \parbox to create a column. We stated the width of 3 cm in the
first argument and the contained text in the second argument to \parbox.
\parbox takes the argument text and formats the output to fit the specified width. We

see that the text is fully justified. Our example shows an obvious problem: insisting on full
justification could lead to undesirable big gaps in the text. Possible solutions are:
‹‹

Introducing hyphenation: the word acronym could easily be divided

‹‹

Improving justification: LaTeX could do better

‹‹

Giving up full justification: narrow text could look better when it's only left justified

We will check out all of these options. But first, let's see how \parbox is working.

Common paragraph boxes
Usually we just need a text box with a certain width; occasionally we would like to have
some additional alignment to the surrounding text. So the common definition of the
\parbox command is:
\parbox[alignment]{width}{text}

[ 46 ]

Chapter 2

alignment

Optional argument for the vertical alignment. State t to align at the top line of
the box; write b to align at its bottom line. The default behavior is to place the
box such that its center is in line with the center of the current text line.

width

The width of the box. It can be given for example in ISO units like 3 cm, 44 mm,
or 2 in.

text

The text that you want to put in that box. It should be a short piece of common
text. For complicated contents, we will get to know other methods.

Here's a demonstration of the effect of the alignment parameters:
\documentclass{article}
\begin{document}
Text line
\quad\parbox[b]{1.8cm}{this parbox is aligned at its bottom line}
\quad\parbox{1.5cm}{center-aligned parbox}
\quad\parbox[t]{2cm}{another parbox aligned at its top line}
\end{document}

The command \quad produces some space; we used it to separate the boxes a bit. Here's
the output:

From now on we will call such a box a parbox.

[ 47 ]

Formatting Words, Lines, and Paragraphs

Have a go hero – exploring further features of \parbox
\parbox is capable of doing even more. Here's the complete definition:
\parbox[alignment][height][inner alignment]{width}{text}

height

If this optional argument isn't given, the box will have just the natural
height of the text inside. Use this argument if you want to change the
height of the box to make it bigger or smaller.

inner alignment

Especially, if the height of the box is different to the natural height of
the contained text, you might want to adjust the text position. The
argument means:
‹‹

c—vertically center the text in the box

‹‹

t—place text at the top of the box

‹‹

b—place text at its bottom

‹‹

s—stretch the text vertically if possible

If you omit this argument, the alignment argument will be
used here as the default value.
Take our previous demonstration example and try the effect of the optional arguments. Use
the command \fbox that helps to visualize the effect; if you write \fbox{\parbox[...]
{...}{text}}, the complete parbox will be framed.

Boxes containing more text
Parboxes are suitable for boxes with only a little text inside. In case of a box containing
a large amount of text, the closing brace could easily be forgotten or overlooked. The
minipage environment would then be a better choice.

Time for action – using the minipage environment
We will use the minipage environment instead of \parbox to get a text with a width of just
3 cm.

1.

Modify the parbox example to get the following code:
\documentclass{article}
\begin{document}
\begin{minipage}{3cm}
TUG is an acronym. It means \TeX\ Users Group.
\end{minipage}
\end{document}
[ 48 ]

Chapter 2

2.

Typeset and look at the output:

What just happened?
By using\begin{minipage}, we started a "page in a page". We specified the width of 3cm
by the mandatory argument. From this point onwards, the text lines will have a width of
3cm. They will be automatically wrapped and fully justified. We ended this restriction with
\end{minipage}. Any text typed afterwards would run over the complete body text width.
Note: There won't be a page break in such a "minipage".
Have you been a hero struggling with the \parbox and all of its optional arguments? The
minipage environment accepts all those arguments as well with the same meaning.

Have a go hero – creating a footnote inside a minipage
Of course, LaTeX supports footnotes. You guessed it right—the corresponding command is
called \footnote{text}. Try it in one of our examples. You will get a footnote mark inside
the text and the text of the footnote will be put into the bottom of the page.
A minipage is like a small page inside a normal page. Think of using a footnote inside
such a "page"; do you want to see the footnote text inside this small page? The minipage
environment supports it, just try it—use \footnote inside the minipage in the previous
example.

Understanding environments
LaTeX environments are started with \begin and ended with \end. Both commands require
the name of the environment as their argument.
Simple environments look like the following:
\begin{name}
…
\end{name}

Such environments can be used for each declaration called \name.

[ 49 ]

Formatting Words, Lines, and Paragraphs

Like commands, environments may also have arguments. Exactly like in the case of
commands, mandatory arguments are written in curly braces and optional arguments in
square brackets. So you will encounter:
\begin{name}{argument}
…
\end{name}

And:
\begin{name}[optional argument]{argument}
…
\end{name}

Environments are like declarations with a built-in scope. With \begin, the environment
introduces a change in layout, font, or other properties. There must be an\end command,
where this change will be canceled. The effect of the environment name is delimited to the
piece of code between \begin{name} and \end{name}.
Furthermore, the effect of all local declarations used inside an environment will end together
with the surrounding environment.

Breaking lines and paragraphs
Generally, when you're writing text, you don't need to care about the line wrapping.
Just type the text with your editor; LaTeX will make it fit to the line and take care of the
justification. If you want to begin a new paragraph, in consequence of getting a line break
in the output, just insert an empty line before you continue with your text.
Now we will find out how to control the line wrapping. First we will see how to improve the
automatic line breaking. Then we will learn commands to insert breaks directly.

Improving hyphenation
If you look at longer texts, you will notice that it's outstanding how the text is fully justified
by LaTeX and how the spacing between words is evenly distributed on the lines. If necessary,
LaTeX will divide words and put hyphens at the end of the line in order to break the lines in a
better way. LaTeX already uses very good algorithms to hyphenate words, but it may happen
that it can't find an acceptable way to divide a word. The previous example pointed out this
problem: breaking the word acronym would improve the output, but LaTeX does not know
where to divide it. We shall find out how to solve that.

[ 50 ]

Chapter 2

Time for action – stating division points for words
No matter how good the justification skill is, text in very narrow columns is extremely hard
to justify. The previous example showed it pitiless. We will tell LaTeX how a word could be
divided:

1.

Insert the following line into the preamble of the previous example:
\hyphenation{acro-nym}

2.

Typeset and look at the output:

What just happened?
We've told LaTeX that the word acronym may have a division point between acro and nym.
That means a hyphen might be put after acro at the end of the line and nym goes to the
following line.
The \hyphenation command tells LaTeX where the division points of a word may be. Its
argument may contain several words separated by spaces. For each word, we can indicate
several points. For instance we could extend the argument by more division points and more
word variants like this:
\hyphenation{ac-ro-nym ac-ro-nym-ic a-cro-nym-i-cal-ly}

You could also indicate division points in the body text by inserting a backslash followed
by a hyphen, like ac\-ro\-nym. But if you do it in the preamble, you'll collect all rules
there and they will be used consistently. Use it especially in the rare cases when LaTeX's
automation fails.
Preventing hyphenation
If you want to prevent the hyphenation of a certain word at all, there are two
ways: either declare it in the preamble by using it in the \hyphenation
argument without any division points, like \hyphenation{indivisible},
or you protect it inside the text using the \mbox command: The following
word is \mbox{indivisible}.

[ 51 ]

Formatting Words, Lines, and Paragraphs

Have a go hero – exploiting the hyphenat package
The hyphenat package extends the possibilities:
‹‹

\usepackage[none]{hyphenat} prevents hyphenation throughout the

document.
‹‹

\usepackage[htt]{hyphenat} enables hyphenation for typewriter text.

Otherwise such monospaced fonts won't be hyphenated by LaTeX.

Such optional arguments to \usepackage are called package options. They configure the
behavior of a package. The mentioned options may be combined, separated by commas.
Even if you don't use the option none, you can disable hyphenation for short pieces of text
using the command \nohyphens{text}. Try out these features if you want to profit from
them. The package documentation explains more features that you might need sometimes,
such as hyphenation after special characters like numerals and punctuation characters—TeX
would not break there.

Improving the justification further
Today's most popular TeX compiler is pdfTeX, which directly produces PDF output. When
Hàn Thế Thành developed pdfTeX, he extended TeX by micro-typographic capabilities. When
we typeset directly to PDF, we're actually using pdfLaTeX and we can benefit from the new
features by using the microtype package.

Time for action – using microtype
We will improve our previous example by loading the microtype package:

1.

Insert the following line into the preamble of the previous example:
\usepackage{microtype}

2.

Typeset and look at the output:

[ 52 ]

Chapter 2

What just happened?
We have loaded the microtype package without any options, relying on its default
behavior. It introduces font expansion to tweak the justification and uses hanging
punctuation to improve the optical appearance of the margins. This may reduce the need of
hyphenation and improves the "grayness" of the output. You've seen its effect on a narrow
column—imagine the improvement on wide text—keep that in mind and try it out later!
Though microtype provides powerful features and options for the advanced typesetter,
we usually won't need to do more than just load it to profit from it. There's an extensive
package documentation if you want to study it in depth.
microtype does nice tweaking, but it's not a cure-all; we should still take care of proper

hyphenation.

Breaking lines manually
We might choose to end a line overriding the automatism. There are several commands with
different effects.

Time for action – using line breaks
We will type the beginning of a famous poem by Edgar Allan Poe. As the author has specified
where a verse has to end, we shall insert line breaks there.

1.

Create a document containing these lines:
\documentclass{article}
\begin{document}
\emph{Annabel Lee}\\
It was many and many a year ago,\\
In a kingdom by the sea,\\
That a maiden there lived whom you may know\\
By the name of Annabel Lee
\end{document}

2.

Typeset and view the output:

[ 53 ]

Formatting Words, Lines, and Paragraphs

What just happened?
The very short command \\ ended a line; the following text was put to the next line.
That's different to a paragraph break: we're still in the same paragraph. The command
called \newline has the same effect.
There's another command called \linebreak, which tells LaTeX to end the line but to keep
the full justification. Therefore, the space between the words would be stretched to reach
the right margin. This could cause unpleasant gaps—that's why that command is rarely used.

Have a go hero – exploring line breaking options
Both introduced commands understand optional arguments.
‹‹

\\[value] would insert additional vertical space after the break depending on the
value, like \\[3mm].

‹‹

\\*[value] is a variation of the same but prevents a page break before the next

line of text.
‹‹

\linebreak[number] can be used to influence the line break slightly or strongly:
If number is 0, a line break is allowed, 1 means it's desired, 2 and 3 mark more

insistent requests, and 4 will force it. The latter is the default behavior if no number
was given.
Change the heading of our poem example to the following:
\emph{Annabel Lee}\\[3mm]

This will insert some space between our heading and the poem fragment. Try the options
further and check out their effects. If you're daring, try \linebreak instead of \\ to end a
poem line just to see its effect.

Preventing line breaks
The command \linebreak has a direct counterpart: \nolinebreak. This command
prevents a line break at the current position. Like its counterpart, it takes an optional
argument. If you write \nolinebreak[0], you recommend to not break the line there.
Using 1, 2, or even 3 makes the request stronger and \nolinebreak[4] forbids it
completely. The latter will be presumed if you don't provide an argument.
The already mentioned command, \mbox[text], does not only disable hyphenation
of a word, it will also prevent a line break for the complete text.

[ 54 ]

Chapter 2

LaTeX will break lines at spaces between words if meaningful. The symbol ~ stands for an
interword space where no break is allowed: if you would write Dr.~Watson, the title Dr.
would never stand lonely at the end of a line.

Managing line breaks wisely
Bad hyphenation could still disappear as the document grows, so stating some sensible
hyphenation rules would not do any harm but could prove to be useful.
But only use \\, \newline, and \linebreak for line adjustment when you're working
on the final version of your document! While you're still editing your text, you don't need
to worry about line breaks. They still may change during the writing process. Bad looking
justification could still change and become better without intervention. On the other hand,
if you break a line manually but later insert text before, the result could be an unwanted
short line.
So don't waste your energy on formatting while you're writing.

Exploring the fine details
Typographic conventions may require paying attention to small details; there are different
dashes, and the space around a dot may vary depending on the context. The space after
some letters may depend on the following one, so much so that some letters may even
be joined to a single one. Such constructions are called ligatures. Let's have a closer look
at them.

[ 55 ]

Formatting Words, Lines, and Paragraphs

Time for action – exploring ligatures
We will check out Example 3 to discover a ligature. Afterwards, we will have a close look at
the default ligatures:

1.

Open Example 3 in TeXworks, click the Typeset button. Move the mouse pointer into
the output window, right over the word first, and then click the left button.

2.

Go to the editor window, and then add a paragraph break by with empty line and
the following letter combinations: ff fi flffiffl -- ---

3.

Add a paragraph break, repeat the preceding line, but this time insert \/ between
the letters: f\/f f\/i f\/l f\/f\/i f\/f\/l -\/- -\/-\/-

4.

Typeset and compare the letters in the output:

What just happened?
By left-clicking the mouse in the output window, you activated TeXworks' magnifying glass. It
allows inspecting the output in detail as the area around the mouse pointer will be enlarged.
You can see that two or even three letters have been joined, but not in the last line: the
command \/ prevented this.

[ 56 ]

Chapter 2

Understanding ligatures
If the letter i follows the letter f, the dot of the letter i could collide with the head of the f. It
could be avoided in two ways: either by increasing the space between those two letters or by
combining them. The latter will result in a ligature. This will automatically be done by LaTeX
when the used font provides such ligatures.
Sometimes this behavior might be undesirable, for instance, in compound words like
"halflife". In this case, you can suppress this behavior by inserting \/ getting half\/life.
Curly braces can be used to achieve the same effect. For instance, in -{}- and {-}{-}, the
dashes cannot be joined because this would cross group boundaries.
If you don't like ligatures, for instance, because your PDF reader doesn't support
search or copy and paste of ligatures, completely suppressing ligatures could be
done easily by passing the option noligatures to the microtype package:
\usepackage[noligatures]{microtype}.

Choosing the right dash
We've seen several kinds of dashes up until now. Let's sort them out:
‹‹

A short dash is used to mark hyphenation or compound words. In LaTeX: -

‹‹

A longer dash is used to indicate a range of some values, such as 2-3 hours.
Generally this dash has the same width like a digit. In LaTeX: --

‹‹

Even wider is the dash commonly used to mark a parenthetical thought. In LaTeX:
---

Hyphenation is always done using the short dash. Regarding the wider dashes, it's a matter
of style which kind of dash should be used, and further whether there should be a space
around the dash or not. You decide—but now you know how to typeset those dashes.

Setting dots
How wide is the space following a dot? Some styles require additional space after the period
that ends a sentence, but not after the period marking an abbreviation. Furthermore, three
consecutive dots, forming an ellipsis, aren't usually written by just typing three dots. Let's
figure this out.

[ 57 ]

Formatting Words, Lines, and Paragraphs

Time for action – using differently spaced dots
We shall typeset a short text containing periods to see the default behavior. Afterwards, we
will create an example where LaTeX's automation fails; we shall see how to correct it. We will
learn how to simplify all this spacing using a different style.

1.

Create a new document in TeXworks:
\documentclass{article}
\begin{document}
\TeX\ was designed by Donald E. Knuth.
It has become a de facto standard in mathematics.
\end{document}

2.

Typeset to see the output:

3.

Now add a paragraph break followed by this line:
Look at the spacing etc. in LaTeX. See it?

4.

Check out the spacing after the two periods in the output:

5.

Correct the spacing by inserting a backslash and \@:
Look at the spacing etc.\ in LaTeX\@. See it?

6.

Now remove the extra \ and \@ we've added, insert the declaration
\frenchspacing into the preamble, and typeset to see the difference:

[ 58 ]

Chapter 2

What just happened?
The first step shows typical text and its output. As you can see, LaTeX adds a little space after
the period ending a sentence. But not following the letter E: in case of periods after capital
letters, LaTeX assumes that it's an abbreviation, therefore it doesn't add the extra space.
Generally, this automatism is helpful. However, you might encounter exceptions: in step 3,
we constructed such a situation where LaTeX's assumptions are wrong. We've got unwanted
extra space after etc. and missed a space after the last period.
In step 5, we corrected it: the backslash followed by a space (a "quoted space") produces the
normal interword space, the \@ before the dot states that the following dot stands at the
end of a sentence. Now the spacing is correct.
If you prefer to avoid this extra space or if the style you're following requires it, you could
switch off this default sentence spacing. We've done it in step 6 with the declaration
\frenchspacing. Now the spacing after sentences will be as it is between words.
The counterpart to \frenchspacing is \nonfrenchspacing, which is default.

Time for action – comparing dots to ellipsis
We will write an ellipsis in two ways: firstly by simply writing dots, secondly by using a
dedicated command. Let's compare!

1.

Create a new document in TeXworks:
\documentclass{article}
\begin{document}
Here are three dots... compare them to the ellipsis\ldots
\end{document}

2.

Check out the difference:

What just happened?
We used the command \ldots to print out an ellipsis—three consecutive dots with a wider
spacing. Such dots may indicate a pause, an unfinished thought, or an omitted word. When
we just accumulated dots, they were typeset tightly together. However, it's common to print
those dots wider.

[ 59 ]

Formatting Words, Lines, and Paragraphs

Setting accents
Some languages have letters with accents that you can't simply type with your editor. In case
you need to write such letters: let's see how to do it.

Time for action – experimenting with accents
We will write some words having letters with accents in Portuguese and in French.

1.

Create a new document:
\documentclass{article}
\begin{document}
N\~{a}o compreendo. H\'{a} aqui algu\'{e}mque fale ingl\^{e}s?
Comment \c{c}a va? O\`{u} se trouve l'a\'{e}roport?
\end{document}

2.

Typeset to see the generated accents:

What just happened?
LaTeX provides some special commands to produce a variety of accents. They may be
combined with any letter. Such a command consists of a backslash followed by one
character. The accent will be put above or below the letter that has to follow in curly
braces. The following table will list these commands and their effect:

[ 60 ]

Chapter 2

Using special characters directly in the editor
It might be a bit cumbersome to use those accent commands. There's a package that extends
LaTeX basic capabilities. It allows you to enter at least some commonly used accented and
other special characters directly.

Time for action – using accents directly
We will modify the previous example daring to enter accented letters directly in the editor.

1.

Create a new document:
\documentclass{article}
\usepackage[utf8]{inputenc}
\begin{document}
Não compreendo. Há aqui alguém que fale inglês?
Comment çava? Où se trouve l'aéroport?
\end{document}

2.

Typeset and compare to the previous output:

What just happened?
We loaded the inputenc package. The option utf8 tells the package to use Unicode input
encoding, which provides many more symbols than just the ASCII code. Now we just need
to find the symbol on the keyboard and to type it.
TeXworks supports Unicode/UTF-8. Depending on operating system and editor, you might
need to use another option when loading inputenc. A rule of thumb: utf8 works on most
Linux and Unix systems, like Mac OS X, and latin1 works with most Windows editors.
Today, many Windows editors move to UTF-8. This is seemingly
becoming the cross-platform standard.

[ 61 ]

Formatting Words, Lines, and Paragraphs

Turning off full justification
Though commonly your text will look fine if full justification is used, there may be occasions
when it's not the optimum. For instance, full justification could be displeasing if the text lines
are short. In such a case, it could be sufficient to justify only to the left side. We shall see
how to put this into practice, further how to right-justify, and how to get centered lines.

Time for action – justifying a paragraph to the left
Remember the first parbox example which was fully justified but had those big gaps between
the words. We shall give up justification to the right side to avoid such gaps.

1.

Create a new document containing these lines:
\documentclass{article}
\begin{document}
\parbox{3cm}{\raggedright
TUG is an acronym. It means \TeX\ Users Group.}
\end{document}

2.

Typeset and look at the output:

What just happened?
We inserted the declaration \raggedright. From this point onwards, the text will be
ragged-right. In other words, the text will be moved to the left margin - "flushed-left".
There won't be hyphenation.
Because we used this declaration inside a box, it's only valid there, like inside environments.
After the box, the text will be fully justified again.
If we want the whole document to be ragged-right, we just need to use \raggedright in
our preamble.

Creating ragged-left text
There might be occasions when we would like to achieve the opposite effect: flushing the
text to the right margin. We can do it similarly by inserting the declaration \raggedleft.
Remember, you're able to control where lines are broken by inserting \\.
[ 62 ]

Chapter 2

Time for action – centering a title
We shall create a nice looking title for our document. It should contain the title, the author,
and the date. All those lines have to be centered.

1.

Write a document containing this code:
\documentclass{article}
\pagestyle{empty}
\begin{document}
{\centering
\huge\bfseries Centered text \\
\Large\normalfont written by me \\
\normalsize\today
}
\end{document}

2.

Typeset to see the output:

What just happened?
Because only the title should be centered, we opened a group to limit the centering. Through
the declaration \centering, we made the remaining text of this group horizontally aligned
to the center. We inserted a paragraph break: it's always a good idea to do it before ending
the group when paragraph-affecting commands were used. By the brace after \today, we
ended the group. If you complement some following text, it will be typeset normally, not
centered.
\centering is commonly used when pictures or tables are inserted, further on title pages

and sometimes for headings.

Using environments for justification
As there's a corresponding environment for every declaration, as we learned, we could
have written \begin{centering} … \end{centering} in our previous example. It
could be done similarly for ragged-right and ragged-left text. There's a couple of predefined
environments acting similarly but starting a new paragraph at the same time.

[ 63 ]

Formatting Words, Lines, and Paragraphs

Time for action – centering verses
Let's reuse the fragment of the poem "Annabel Lee". This time we shall center all verses:

1.

Create a document containing these lines:
\documentclass{article}
\usepackage{url}
\begin{document}
\noindent This is the beginning of a poem
by Edgar Allan Poe:
\begin{center}
\emph{Annabel Lee}
\end{center}
\begin{center}
It was many and many a year ago,\\
In a kingdom by the sea,\\
That a maiden there lived whom you may know\\
By the name of Annabel Lee
\end{center}
The complete poem can be read on
\url{http://www.online-literature.com/poe/576/}.
\end{document}

2.

Typeset and see the output:

What just happened?
We began with \noindent avoiding the paragraph indentation. \begin{center} started
the center environment. It begins a new paragraph, leaving some space to the preceding
text. \end{center} ended this environment. We used the environment twice. In the
second one, we inserted \\ to end the verses.
[ 64 ]

Chapter 2

After the center environment ended, some space followed and the next paragraph began
at the left margin.
The corresponding environment for ragged-right text is called flushleft, and for ragged-left
text it's flushright.

Displaying quotes
Imagine your text contains a quotation of another author. It might be hard to read if it's just
embedded in your words. A common way to improve the readability is displaying: setting the
text off by indenting on both margins.

Time for action – quoting a scientist
We will quote thoughts of famous physicists.

1.

Create a new document containing these lines:
\documentclass{article}
\begin{document}
Niels Bohr said: ``An expert is a person who has made
all the mistakes that can be made in a very narrow field.''
Albert Einstein said:
\begin{quote}
Anyone who has never made a mistake has never tried anything new.
\end{quote}
Errors are inevitable. So, let's be brave trying something new.
\end{document}

2.

Typeset to see the result:

What just happened?
Firstly we quoted inline. `produced a left quotation mark; the character is also called a
backtick. 'gave a right quotation mark. We just typed two such symbols to get double
quotes.
[ 65 ]

Formatting Words, Lines, and Paragraphs

Then we used the quote environment to display a quotation. We did not begin a new
paragraph for it, because the quotation is already set a bit off. That's the reason we
don't use a blank line before and after the environment.

Quoting longer text
When writing short quotations, the quote environment looks very good. However, when
you would like to quote a text containing several paragraphs, you might wish to have the
same paragraph indentation like in your surrounding text. The quotation environment will
do it for you.

Time for action – quoting TeX's benefits
We will quote some of the benefits of TeX and LaTeX found on a web page on CTAN.

1.

Start a new document. This time, it will be a bit longer:
\documentclass{article}
\usepackage{url}
\begin{document}
The authors of the CTAN team listed ten good reasons
for using \TeX. Among them are:
\begin{quotation}
\TeX\ has the best output. What you end with,
the symbols on the page, is as useable, and beautiful,
as a non-professional can produce.
\TeX\ knows typesetting. As those plain text samples
show, \TeX's has more sophisticated typographical algorithms
such as those for making paragraphs and for hyphenating.
\TeX\ is fast. On today's machines \TeX\ is very fast.
It is easy on memory and disk space, too.
\TeX\ is stable. It is in wide use, with a long history.
It has been tested by millions of users, on demanding input.
It will never eat your document. Never.
\end{quotation}
The original text can be found on
\url{ http://www.ctan.org/what_is_tex.html}.
\end{document}

2.

Typeset and look at the output:

[ 66 ]

Chapter 2

What just happened?
This time, we used the quotation environment to display some paragraphs. As in normal
text, blank lines separate the paragraphs. They are left-indented at their beginning just like in
all our body text.
But what if we don't like that paragraph indentation? Let's check out an alternative.

Time for action – spacing between paragraphs instead of
indentation
We like to avoid the paragraph indentation. Instead, we shall separate the paragraphs by
some vertical space.

1.

Create copy of the previous example and reuse most of it this way:
\documentclass{article}
\usepackage{parskip}
\usepackage{url}
\begin{document}
The authors of the CTAN team listed ten good reasons
for using \TeX. Among them are:
\TeX\ has the best output. What you end with,
the symbols on the page, is as useable, and beautiful,
as a non-professional can produce\ldots
The original text can be found on
\url{ http://www.ctan.org/what_is_tex.html}.
\end{document}
[ 67 ]

Formatting Words, Lines, and Paragraphs

2.

See the effect:

What just happened?
The highlighted line shows that we've loaded the parskip package. Its only purpose is to
remove the paragraph indentation completely. At the same time, this package introduces
a skip between paragraphs. But this package doesn't affect the definition of the quotation
environment—you still could use the quote environment.
In order to distinguish paragraphs, there are two common ways. One is to indent the
beginning of each paragraph; this is the default LaTeX style. The other way is to insert vertical
space between paragraphs while omitting the indentation, which is suitable for narrow
columns where indenting would cost too much width.

Pop quiz – lines and paragraphs
1. Which of the following designates the end of a paragraph?
a. \newline
b. \\
c.

A blank line

2. How do the words in a \hyphenation command be separated?
a. By commas
b. By semicolons
c.

By spaces

3. Which command switches to left-aligned text?
a. \raggedleft
b. \raggedright
c.

\flushright

[ 68 ]

Chapter 2

Summary
In this chapter, we developed the basics: editing, arranging, and formatting of text.
Specifically, we covered:
‹‹

Modifying shape and style of text and its font

‹‹

Breaking lines and improving hyphenation

‹‹

Controlling justification of text

We got to know the basic LaTeX concepts:
‹‹

Commands and declarations, mandatory and optional arguments

‹‹

Definition of new commands

‹‹

Using environments

‹‹

Using packages, how they can be loaded and options to packages

Keep in mind that even though we've used formatting commands directly in the text when
exploring them, you should use them inside command definitions in the preamble to allow
easy changes for the future. During your learning and writing process, you probably will get
to know further useful commands and packages that could improve your previously written
commands.
We've learned general practices:
‹‹

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.

‹‹

Deal with line or page breaking issues at the earliest when you go for your final
version.

Now that we've learned about the detailed formatting of text, we're ready to enter the next
chapter that deals with formatting and layout of whole pages and documents.

[ 69 ]

3

Designing Pages
After the previous chapter, formatting text should be easy for us. So, let's turn
to whole pages!

In this chapter, we will learn how to:
‹‹

Adjust the margins

‹‹

Change the line spacing

‹‹

Section the document

‹‹

Create a table of contents

‹‹

Design headers and footers

‹‹

Control page breaking

‹‹

Set footnotes and modify their appearance

In learning this, we shall gain a deeper insight into classes and packages.

Defining the overall layout
We shall write an example document spanning over several pages. This will be our test
object for modifying margins, line spacing, headers, footers, and more.

Designing Pages

Time for action – writing a book with chapters
We will start to write a book. At first, we shall choose a class, further we will use some filler
text to work out the page layout.

1.

Create a new document with the following code:
\documentclass[a4paper,12pt]{book}
\usepackage[english]{babel}
\usepackage{blindtext}
\begin{document}
\chapter{Exploring the page layout}
In this chapter we will study the layout of pages.
\section{Some filler text}
\blindtext
\section{A lot more filler text}
More dummy text will follow.
\subsection{Plenty of filler text}
\blindtext[10]
\end{document}

2.

Save the document and Typeset it. Look at the first page:

[ 72 ]

Chapter 3

What just happened?
We have chosen the document class book. As the name implies, this class is suitable for
book-like documents. Books are commonly two-sided and consist of chapters which usually
start at right-hand pages. They may have a front matter with one or more title pages and a
back matter with bibliography, index, and so on. The book class supports all of this.
We loaded the babel package. This is useful especially for typesetting in other languages
than English regarding hyphenation, language-specific characters, and more.
Even for English language, there are several options: USenglish, american, english,
UKenglish, british, canadian, australian, and newzealand. Obviously, some mean
the same, such as UKenglish and british. However, there are differences in hyphenation
rules between USenglish (american, english) and UKenglish (british).
For now, we just need babel to load blindtext: this package has been developed to produce
filler text. It requires babel to detect the language of the document. We stated the language
English to babel, which means American English.
The command \chapter produced a large heading. This command will always begin on a
new page.
We've already seen the \section command. It's our second sectioning level and generates
a smaller heading than \chapter. It's automatically numbered per chapter. The command
\blindtext followed, printing some dummy text just to fill the space with some text.
At last, we refined the sectioning with a \subsection command followed by more dummy
text to fill up the page.
There's another popular package for generating dummy text. It's called lipsum
and it produces the famous LoremIpsum text which has been the typesetter's
dummy text for hundreds of years.

Reviewing LaTeX's default page layout
For the example in the current chapter, we used A4 paper and a font size of 12 pt. We let
LaTeX define the margins. Let's look at them:
‹‹

The right margin is the outer margin of the book, because the chapter starts on a
right-hand page. It might seem to be a bit wide—but good text isn't just intended to
fill as much space as possible: it should be well-readable for our eyes. Therefore the
lines shouldn't be too long.

[ 73 ]

Designing Pages
‹‹

The left margin is the inner margin on such a right-hand page. A user asked why the
inner margin is smaller than the outer, even further some space will get lost because
of the binding. The explanation is simple, if we imagine the book lies opened right
before us: the inner margins would look joined. It's a good idea to aim at equal
margins—left, middle, and right. In this sense, we could choose the inner margin to
be half of the size of the outer margin—plus some offset for the binding.

‹‹

The bottom margin contains the page number.

‹‹

The top margin looks very tall. It's caused by the chapter heading, there's always
more space left above. By looking at the second page, you will see that normal
pages have a smaller top margin.

If you ever doubt LaTeX's design, look at some books in your shelves and compare, whether
it's regarding margins, ligatures, numbering, or anything else.

Defining the margins yourself
A publisher or a supervisor may request you to follow his specifications. Besides font size,
interline spacing, and other style issues, this might also apply to the margins. In this case,
you would need to override LaTeX's recommendations specifying the margins precisely.
There's a package fulfilling these demands.

Time for action – specifying margins
We shall load the geometry package and state the exact width and height of all margins.

1.

Extend the preamble of the previous example with this command:
\usepackage[a4paper, inner=1.5cm, outer=3cm, top=2cm,
bottom=3cm, bindingoffset=1cm]{geometry}

2.

Typeset and examine the margins:

[ 74 ]

Chapter 3

What just happened?
We loaded another package with the name geometry. This package takes care of our layout
regarding the paper size, margins, and more dimensions. We chose A4 paper size, an outer
margin of 3 cm, and an inner margin of just 1.5 cm, remembering that the two inner margins
will be perceived as one space when the two-sided book is opened. We stated the top and
the bottom margin. At last, we specified a value of 1 cm for the binding correction. We need
the inner margins to be wider because we expect to lose this space later because of the
binding like gluing or stapling.

Using the geometry package
In the early days of LaTeX, it was common to manipulate the layout dimensions directly. This
approach had some disadvantages. We could easily make mistakes in calculating the lengths,
for instance left margin + right margin + text width might not fit to the paper width. The
geometry package comes to the rescue. It provides a comfortable interface for specifying
layout parameters. Further, it provides auto-completion. It calculates missing values to match
the paper size. It even adds missing lengths using a heuristic approach to achieve a good
layout. Let's look at it in detail.
[ 75 ]

Designing Pages

The geometry package understands arguments of the form "key=value", separated by
commas. If you load geometry without arguments, those arguments could alternatively
be used by calling \geometry{argument list}. We shall look at some of them.

Choosing the paper size
Geometry provides several options to set the paper size and orientation:
‹‹

paper=name states the paper name, for example, paper=a4paper. It may be

abbreviated like we did in our example. The package supports a lot of paper sizes,
such as letterpaper, executivepaper, legalpaper, a0paper, … ,a6paper,
b0paper, … , b6paper, and more.
‹‹

paperwidth, paperheight allow you to choose the paper dimensions freely,
like paperwidth=7in, paperheight=10in.

‹‹

papersize={width,height} sets width and height of the paper like
papersize={7in,10in}. This is an example of a double-valued argument.

‹‹

landscape changes the paper orientation to landscape mode.

‹‹

portrait switches to portrait mode. This is the default.
If you already specified the paper name to the document class, geometry will
inherit it. That's valid in general: all document class options will be automatically
given to the packages that recognize them.

Specifying the text area
The text area may be adjusted by these options:
‹‹

textwidth sets the width of the text area, like textwidth=140mm.

‹‹

textheight states the height of the text area, like textheight=180mm.

‹‹

lines gives another way to specify the text height by the number of lines, like
lines=25.

‹‹

includehead causes the header of the page to be included into the body area;
set false by default.

‹‹

includefoot causes the footer of the page to be included into the body area;
set false by default.

[ 76 ]

Chapter 3

Setting the margins
The size of the visible margins can be specified by these options:
‹‹

left, right set the width of the left and the right margin, like left=2cm.

Use it for one-sided documents.
‹‹

inner, outer set the width of the inner and the outer margin, like inner=2cm.

Use it for two-sided documents.
‹‹

top, bottom set the height of the top and the bottom margin, like top=25mm.

‹‹

twoside switches to two-sided mode. This means that left and right margins

would be swapped on left-hand pages, also called verso pages.
‹‹

bindingoffset reserves space on the left margin (one-side), respectively the

inner margin (two-sided) for the binding.

That's just a selection of commonly used options—there are many more. You could choose
and set some options intuitively—for instance, \usepackage[margin=3cm]{geometry}
will result in a 3 cm margin on each edge of the paper and the paper size comes from the
document class option.
The auto-completion works like this:
‹‹

paperwidth = left + width + right, where width=textwidth by default

‹‹

paperheight = top + height + bottom, where height=textheight by default

If you decide to include marginal notes within the text body when calculating, width could
get wider than textwidth. If two dimensions of the right side of each formula are given,
the missing dimension would be calculated. That's why it may be enough to specify left
and right, top and bottom, respectively. Even if just one margin is specified, the other
dimensions would be determined using default margin ratios:
‹‹

top:bottom = 2:3

‹‹

left:right = 1:1 for one-sided documents

‹‹

inner:outer = 2:3 for two-sided documents

Sounds complicated? That's just intended to help you to achieve practical dimensions even if
some values were missing.
In 2010, version 5 of geometry introduced the commands
\newgeometry{argument list} and \restoregeometry,
allowing users to change margin dimensions in the middle of a document.
Their auto-completion may also differ a bit from previous versions.

[ 77 ]

Designing Pages

The geometry package provides an extensive manual. Don't be worried by the amount of
documentation: it's an offer to guide you through the variety of features.

Obtaining package documentation
There are hundreds of LaTeX packages available. No book could ever explain all of their
features on its own. But most of those packages offer good documentation that you can read
for free. If you work your way through this book and supplement it with the documentation
of the mentioned packages, you're on the right track to become a LaTeX power user.

Time for action – finding the geometry package manual
We would like to examine the documentation of the geometry package. At first, we shall look
for it locally on our computer. Afterwards, we will see how to find the documentation online:

1.

Click the Start button and choose All Programs| Accessories |Command prompt

2.

Type the following:
texdoc geometry

3.

A PDF viewer should start and show the package manual. The same command works
at the command prompt on Linux/Unix computers.

4.

Hit the Start button again; this time, choose All Programs | TeX Live 2010 |TeXdoc
GUI. Click on Search texdoctk's database, enter the keyword geometry, and
press Enter:

5.

Have a look at the search result. Open it by double-clicking or hit the View button.
A viewer should open the documentation.
[ 78 ]

Chapter 3

6.

Open an Internet browser and visit the site http://ctan.org/pkg/geometry.
Scroll down to Documentation on CTAN and hit the link User's manual. Again, your
PDF viewer or a browser plug-in will show the documentation.

What just happened?
We've tried three ways of obtaining the documentation. At first, we used texdoc. This is a
tool to find and to view LaTeX documentation. It can be used at the command prompt; just
type texdoc followed by a keyword. For this, it's required to be in the operating system's
search path. The TeX distribution installer takes care of it. The argument to texdoc doesn't
have to be the package name, as texdoc understands aliases. Further, we used a GUI for
texdoc providing a search feature supplemented by a category classification. Perhaps
browse for a little while through the categories.
If texdoc doesn't help you, there's another opportunity: visit CTAN. You
just need to know the package name. Simply visit http://ctan.org/
pkg/packagename to get to the package homepage, there you may find
documentation.
In case you don't know the package name or you just have a vague idea what
you're looking for, visit the TeX Catalogue Online on http://texcatalogue.
sarovar.org/bytopic.html. It lists hundreds of packages sorted by topic.
Note: The online documentation might match a different package version than
the one on your computer.

Have a go hero – constructing the page layout with typearea
Now that you know how to open package documentation, you could figure out if you want
to benefit from the typearea package. While the geometry package allows you to control
all margins yourself, typearea provides a different approach. It supports you in creating
a page layout based on proven typography standards. typearea is explained within the
KOMA-Script manual, so the keywords for texdoc and CTAN would be koma-script or
typearea. Reading Chapter 2 of the manual on Page Layout could give you an insight into
typography, even if you decide not to use typearea.

Changing the line spacing
Without some vertical space between the lines, the readability of a text could suffer.
Adding such space would help lead the eye along the line.

[ 79 ]

Designing Pages

Time for action – increasing line spacing
Though LaTeX already takes care of good readability by choosing a meaningful interline
spacing, publishers might require different spacing. We shall modify our example by adding
half of a line height to the line spacing.

1.

Extend the preamble of our example with this command:
\usepackage[onehalfspacing]{setspace}

2.

Typeset to see the change:

What just happened?
We loaded the setspace package. Its only purpose is to adjust the line spacing. We provided
the option onehalfspacing. This increases the spacing by half of a line height for the
whole document.
[ 80 ]

Chapter 3

setspace understands three options:
‹‹

singlespacing is the default. No additional space will be inserted. The text will

be typeset with LaTeX's default interline spacing, which is about 20 percent of the
line height.
‹‹

onehalfspacing means one-and-a-half spacing like in our example.

‹‹

doublespacing can be used for even more spacing: the distance between the

baselines of successive text lines would be twice as high as a single line.

Commonly, we choose the spacing for the complete document. In that case, such an option
would be sufficient. For each of the options, there's a corresponding environment. They are
called singlespace, onehalfspace, and doublespace. Those environments may be
used to adjust the spacing within the document. They shouldn't be nested. For the need of
a different stretching factor, the spacing environment is provided. It may be used like the
following:
\begin{spacing}{2.4}
This text is stretched by a factor of 2.4.
\end{spacing}

In typesetter's jargon, the distance between the baselines of consecutive text
lines is called leading.

Have a go hero – examining a package source file
In some cases the documentation of a package is not easily accessible. This applies to
setspace: the explanation of the options, commands, and environments is contained in the
package source file itself. How can we obtain it? We could visit CTAN, as we described before,
or locate the file on our computer. A package filename usually ends with .sty, standing for
style file. TeX Live provides a tool for locating such source files. Try it: open the command
prompt, that is, hit the Start button and click All Programs |Accessories |Command prompt.
Then type the following:
kpsewhich setspace.sty

And press Enter. The program will print the location of the file, as follows:
c:/texlive/2010/texmf-dist/tex/latex/setspace/setspace.sty

Open the file using TeXworks or any text editor. There are a lot of comment lines explaining
the package features.

[ 81 ]

Designing Pages

The kpsewhich tool belongs to the kpathsea library. kpathsea's
fundamental purpose is filename lookup.

Using class options to configure the document style
We already know that a document class is the basis of our document. It provides commands
and environments extending the LaTeX standard features. Though the class provides a
default style, it's still customizable with options.

Time for action – creating a two-column landscape document
We shall change the orientation of our example to landscape. We would also like to typeset
our text in two columns:

1.

Add the options landscape and twocolumn to the \documentclass statement
of our example, as follows:
\documentclass[a4paper,12pt,landscape,twocolumn]{book}

2.

Typeset and see how the layout has changed:

[ 82 ]

Chapter 3

What just happened?
By using the landscape option, we switched the orientation. By stating the twocolumn
option, we caused the body text to be divided into two columns.
There's a command\twocolumn[opening text] starting a two-column
page with optional opening text over the whole width. \onecolumn begins a
one-column page.
If you'd like to balance the columns on the last page or if you wish to have
more than two columns, use the multicols package.

The LaTeX base classes are article, book, report, slides, and letter. As the name suggests, the
last one can be used to write letters, though there are further suitable classes like scrlttr2.
slides can be used to create presentations, but today there are more powerful and feature
rich classes like beamer and powerdot.
Let's sum up the options of the base classes:
‹‹

a4paper, a5paper, b5paper, letterpaper, legalpaper, or executivepaper:

The output will be formatted according to this paper size, that is, A4: 210 mm x 297
mm. letterpaper (8.5 in x 11 in) is the default. Loading the geometry package
allows more sizes.

‹‹

10pt, 11pt, or 12pt: The size of normal text in the document; the default is ten
points (10pt). The size of headings, footnotes, indexes, and so on, will be adjusted

accordingly.
‹‹

landscape: Switches to landscape format; width and height of the output size

will be interchanged.
‹‹

onecolumn or twocolumn: Decides whether the pages will be one-column

(default) or two-column. It's not supported by the letter class.
‹‹

oneside or twoside: Formatting for printing on one side or both sides of a page.
oneside is the default, except for the book class. twoside is not usable with the
slides class and the letter class.

‹‹

openright or openany: The first decides that chapters have to begin on a righthand page (the default for the book class), openany allows chapters to start on any
page (default for the report class). These options are only supported by the book

and the report class because the other classes don't provide chapters.
‹‹

titlepage or notitlepage: The first causes a separate title page when
\maketitle is used and is the default, except for the article class. The
default of article is notitlepage, which means that normal text may follow

the title on the same page.

[ 83 ]

Designing Pages
‹‹

final or draft: If draft is set, then LaTeX will mark overfull lines with a black

box, which is helpful in reviewing and improving the output. Some packages support
these option as well, behaving differently then, such as omitting embedding of
graphics and listings when draft has been chosen. final is the default.
‹‹

openbib: When this option is set, a bibliography would be formatted in open style

instead of compressed style.
‹‹

fleqn: Causes displayed formulas to be left-aligned.

‹‹

leqno: For numbered displayed formulas, the number would be put to the left side.

The right side is the default.

Many other classes support these options as well and even more. For
the need of an uncommon base font size, the classes extarticle,
extbook, extreport, and extletter provide base font sizes from
8 pts to 20 pts. The so called KOMA-Script classes allow arbitrary base
font sizes. They understand such a large amount of options that they're
additionally supporting a "key=value" interface like we've seen with the
geometry package.

Have a go hero – trying KOMA-Script classes
Have you been so brave to check out the typearea package documentation? Then you've
already seen the KOMA-Script manual accessible by texdoc koma-script. Open it again;
this time, read it with the idea of choosing KOMA classes for your documents. They may be
used like the base classes: for each base class, there's a corresponding KOMA class. They
differ in some meaningful presets; for instance, headings use a sans-serif font by default.
However, the presets can easily be changed. Those classes extend the base classes very
much, providing a huge amount of commands. Web forums frequently show user questions
being hard to solve using base classes, but being easily achievable by a single KOMA class
command.

Creating a table of contents
A book commonly begins with a table of contents, so let's create one.

[ 84 ]

Chapter 3

Time for action – adding a table of contents
We shall create a table of contents based on our numbered headings.

1.

Let's remove the options landscape and twocolumn. We also don't load
the setspace package. Add the command\tableofcontents right after
\begin{document}. Our code shall now be:
\documentclass[a4paper,12pt]{book}
\usepackage[english]{babel}
\usepackage{blindtext}
\usepackage[a4paper, inner=1.5cm, outer=3cm, top=2cm,
bottom=3cm, bindingoffset=1cm]{geometry}
\begin{document}
\tableofcontents
\chapter{Exploring the page layout}
In this chapter we will study the layout of pages.
\section{Some filler text}
\blindtext
\section{A lot more filler text}
More dummy text will follow.
\subsection{Plenty of filler text}
\blindtext[10]
\end{document}

2.

Typeset twice. Afterwards, the first page of your output will contain this table:

What just happened?
The command \tableofcontents tells LaTeX to produce a file with the extension .toc.
This file will be used to generate a table of contents. We had to typeset twice: in the first run,
the .toc file was written and in the second run, LaTeX read it and processed it.
The entries are created by the sectioning commands. We used \chapter, \section, and
\subsection, and we've got an entry for each.
[ 85 ]

Designing Pages

Sectioning and the contents
A heading might be very long; it could span over two or more lines. In that case, we might
wish to shorten its corresponding table of contents entry. Let's see how.

Time for action – shortening the table of content entries
We will use the optional argument of the sectioning commands to produce shorter entries,
different to the actual headings:

1.

Take our example and modify the sectioning commands as shown in the
highlighted lines:
\documentclass[a4paper,12pt]{book}
\usepackage[english]{babel}
\usepackage{blindtext}
\usepackage[a4paper, inner=1.5cm, outer=3cm, top=2cm,
bottom=3cm, bindingoffset=1cm]{geometry}
\begin{document}
\tableofcontents
\chapter[Page layout]{Exploring the page layout}
In this chapter we will study the layout of pages.
\section[Filler text]{Some filler text}
\blindtext
\section[More]{A lot more filler text}
More blindtext will follow.
\subsection[Plenty]{Plenty of filler text}
\blindtext[10]
\end{document}

2.

Typeset twice and look at the modified table of contents:

[ 86 ]

Chapter 3

What just happened?
Besides the mandatory argument producing the heading, each sectioning command
understands an optional argument. If this is given, it will be used instead of the mandatory
heading for the table of contents entry.
Again, we had to typeset twice to notice a change. This is not unusual. You will encounter
more situations when several LaTeX runs would be necessary, like creating an index or
a bibliography.
In Chapter 7, Listing Content and References, we shall take a further look and learn how
to customize the table of contents. Let's look again at the sectioning commands of book,
report, and article. There are seven levels in those base classes:
‹‹

\part: For dividing the document in major units. The numbering of other sectional
units is independent of \part. A part heading will use a whole page in book and
report documents.

‹‹

\chapter: A large heading that will start at a new page, available in the book and
report classes.

‹‹

\section, \subsection, \subsubsection: Bold headings available in all classes,

the following text comes below.
‹‹

\paragraph, \subparagraph: Available in all classes, produces a run-in heading.

Except \part, all sectioning commands reset the counter of the section that's one level
below in the hierarchy. For instance, \chapter resets the section counter. This way, the
sections will be numbered per chapter.
To sum up, though these commands are easy to use, they do a lot, such as:
‹‹

Cause a page break (\part and \chapter with book and report classes)

‹‹

Generate a number and a presentation for it, some depending on the higher-level
counters (like 2.1)

‹‹

Reset the counter of the next-level sectional unit (except \part)

‹‹

Produce a table of contents entry storing it in the .toc file

‹‹

Format the heading, usually bold-faced and the larger the higher in the hierarchy

‹‹

If needed, save the heading for use in a page header

All sectioning commands provide a starred form, as follows:
\section*{title}

[ 87 ]

Designing Pages

If you use this form, the numbering will be suppressed and there won't be an entry in the
table of contents or in a header. Look at the heading Contents in our example; this has
actually been typeset by \chapter* inside the \tableofcontents macro.
As page headers have been mentioned, let's explore them now.

Designing headers and footers
Already during testing of the first version of our example, you might have noticed that except
for the page where the chapter started, all pages already showed the page number, chapter
title, and section title in their header:

Though these standard headers are already quite useful, we shall see how to customize them
to meet our individual requirements.

Time for action – customizing headers with the
fancyhdr package
The default shape of the page headings is slanted. Furthermore, they are written in capital
letters. We shall use bold typeface instead and we will use capital letters only for the chapter
title. We will load the fancyhdr package and use its commands to achieve that:

1.

Load the first version of our example. Insert the highlighted lines:
\documentclass[a4paper,12pt]{book}
\usepackage[english]{babel}
\usepackage{blindtext}
\usepackage{fancyhdr}
\fancyhf{}
\fancyhead[LE]{\leftmark}
\fancyhead[RO]{\nouppercase{\rightmark}}
\fancyfoot[LE,RO]{\thepage}
\pagestyle{fancy}
\begin{document}
\chapter{Exploring the page layout}
In this chapter we will study the layout of pages.
\section{Some filler text}
[ 88 ]

Chapter 3
\blindtext
\section{A lot more filler text}
More dummy text will follow.
\subsection{Plenty of filler text}
\blindtext[10]
\end{document}

2.

Typeset—the footers will contain the page number on their outer side and the
headers should look like the following:

What just happened?
We loaded the fancyhdr package. Our first action was calling \fancyhf{}; this command
clears the headers and footers. Further, we used the following:
‹‹

\leftmark: Used by the book class to store the chapter title together with the

chapter number. Capital letters are used as default.
‹‹

\rightmark: Used by the book class to store the section title together with its

number. Capital letters are used as well.

We used the command \fancyhead with the optional argument LE to put the chapter title
into the header. LE stands for left-even and means that this chapter title will be put on the
left side of the header on even-numbered pages.
Analogous, we called the command \fancyhead with RO to put the section title into the
header. RO stands for right-odd and means that this section heading shall be displayed on
right side of the header on odd-numbered pages.
Afterwards, we used \fancyfoot to display the page number in the footer. This time, we
used LE and RO that showed the page number on even as well as on odd pages, always on
the outer side. The command \thepage prints the page number.
All those commands are used to modify a page style provided by fancyhdr; this
style is called fancy. We had to tell LaTeX to use this style and we did it through
\pagestyle{fancy}.

[ 89 ]

Designing Pages

Emphasizing by writing all letters capitalized, like fancyhdr does by default,
is called all caps. It is widely regarded as a questionable style. If it's used at
all, then it's recommended to slightly increase the spacing between the capital
letters. For adjusting this so called letterspacing, you can use the microtype
package or the soul package.

Understanding page styles
LaTeX and its base classes provide four page styles:
‹‹

empty: Neither a header nor a footer is shown.

‹‹

plain: No header. The page number will be printed and centered in the footer.

‹‹

headings: The header contains titles of chapters, sections, and/or subsections,

depending on the class and also the page number. The footer is empty.
‹‹

myheadings: The header contains a user-defined text and the page number;

the footer is empty.

fancyhdr adds one page style:
‹‹

fancy: Both the header and footer may be customized by the user.

Two commands may be used to choose the page style:
‹‹

\pagestyle{name}: Switches to the page style name from this point onwards.

‹‹

\thispagestyle{name}: Chooses the page style name only or the current page;

the following pages will have the style that's been used before.

You have seen that where a chapter starts, the page style is different to the style of other
pages. Such pages will have plain style. If you thought all pages should use the same style,
look into some books: it's very common that chapter beginnings differ in style. They usually
have a blank header. \thispagestyle could be used to override that.

Customizing header and footer
Let's divide the header and footer into six pieces: left, center, and right (l, c, r) both for the
header and footer. The commands to modify those areas are as follows:
‹‹

For the header: \lhead, \chead, \rhead

‹‹

For the footer: \lfoot, \cfoot, \rfoot

Each of these commands requires a mandatory argument, like \chead{User's guide}
or \cfoot{\thepage}. This argument will be put into the corresponding area of the page.
[ 90 ]

Chapter 3

Alternatively, you could use these versatile commands:
‹‹

For the header: \fancyhead[code]{text}

‹‹

For the footer: \fancyfoot[code]{text}

Here, code may consist of one or more letters:
Symbol

Meaning

L

left

C

center

R

right

E

even page

O

odd page

H

header

F

footer

It doesn't matter if we choose uppercase or lowercase letters. We already used such
combinations in our example.

Using decorative lines in header or footer
We can introduce or delete lines between header and body text and body text and footer,
respectively, with these two commands:
‹‹

\renewcommand{\headrulewidth}{width}

‹‹

\renewcommand{\footrulewidth}{width}

Where width may be a value like 1pt, 0.5mm, and so on. Just set it to 0pt if you don't like
such a line. The default is 0.4pt for the header line and 0pt for the footer line.
\renewcommand works exactly like \newcommand, except that the command must already

exist. It will get the new meaning. Incidentally, we've got to know a new concept: a lot of
LaTeX commands may be redefined in this way. We shall take advantage of it from now on.
There are starred versions-\newcommand, and \renewcommand,
respectively. They are called short commands. Their arguments must not contain
paragraph breaks. This limitation eases troubleshooting, as TeX would be able to
pick up an error earlier. That's why many people use them whenever possible.

[ 91 ]

Designing Pages

Changing LaTeX's header marks
As we already know, LaTeX classes and packages store sectioning numbers and headings
in the macros \leftmark and \rightmark automatically. It will be done when we call
\chapter, \section, or \subsection. So, we could just use \leftmark and
\rightmark in the arguments of the fancyhdr commands.
We will sometimes want to change those entries manually, even if we rely on this
automatism. For instance, the starred sectioning commands like \chapter* and
\section* won't produce a header entry, like indicated earlier. In such a case, two
commands will help us:
‹‹

\markright{right head} sets the right heading

‹‹

\markboth{left head}{right head} sets both left and right heading

The default style headings is easy-to-use and gives good results. myheadings can be
used together with \markright and \markboth. However, the most flexible way is
given by fancy, especially in combination with \markright and \markboth.
There's a very good alternative to fancyhdr, which is a package
called scrpage2. It belongs to KOMA-Script, but works with other
classes as well. It provides a similar functionality and offers even
more features.

Breaking pages
As you've seen in our example, LaTeX took care of the page breaking. There might be
occasions where we'd like to insert a page break ourselves. LaTeX offers several commands
to do it; with vertical balance or without.

Time for action – inserting page breaks
We will go back to the first version of our example and we shall manually insert a page break
right before the subsection 1.2.1.

1.

Insert the highlighted line into our example:
\documentclass[a4paper,12pt]{book}
\usepackage[english]{babel}
\usepackage{blindtext}
\begin{document}
\chapter{Exploring the page layout}
In this chapter we will study the layout of pages.
\section{Some filler text}
[ 92 ]

Chapter 3
\blindtext
\section{A lot more filler text}
More dummy text will follow.
\pagebreak
\subsection{Plenty of filler text}
\blindtext[10]
\end{document}

2.

Typeset and have a look:

3.

Replace \pagebreak by \newpage.

[ 93 ]

Designing Pages

4.

Typeset and compare:

What just happened?
At first, we inserted the command \pagebreak. Like its name suggests, it causes a page
break. Furthermore, the text has been stretched to fill the page down to the bottom.
Afterwards, because of the obviously unpleasant whitespace between the paragraphs and
the headings, we replaced \pagebreak with \newpage. This command breaks the page
as well, but it doesn't stretch the text: the remaining space of the page will stay empty.
So, \pagebreak behaves like \linebreak and \newpage works like \newline, for
pages instead of lines. There's even a command \nopagebreak that's analogous to
\nolinebreak and forbids page breaking.

[ 94 ]

Chapter 3

\pagebreak won't break a line. Furthermore, \nopagebreak doesn't refer to the middle

of a line: both commands apply at the end of the current line. Of course, they immediately
have effect when used between paragraphs.

If you use the two-column format, both \pagebreak and \newpage would begin on a new
column instead of a new page.
There are two further variants: \clearpage works like \newpage,
except that it will start on a new page, even in two-column mode.
\cleardoublepage does the same, but causes the following text to start
on a right-hand page, inserting a blank page if necessary. The latter is useful
for two-sided documents.
More importantly, both commands cause all figures and tables that LaTeX has
in its memory to be printed out immediately.

Sometimes you may notice large gaps between headings and paragraphs. Those could be
the result of a bad page break like in our example. In that case, you could assist LaTeX by
such a page break command or you switch off vertical justification by the command
\raggedbottom. Its counterpart \flushbottom will switch it on, which is the default
in the book class.
What we learned about line breaking is valid for page breaking as well: don't worry about it
while your work is still in progress. Only when you're done with your document and you're
preparing the final version, will it be time to tweak the page breaks.

Have a go hero – exploring page breaking options
Remember the optional arguments for \linebreak and \nolinebreak. \pagebreak and
\nopagebreak are able to take an optional argument as well, an integer between 0 and 4.
While 0 recommends, 4 demands. Again, try the previous example. This time use an optional
argument for \pagebreak. Test with 0, 1, 2, 3, 4. Only \pagebreak[4] will cause the page
break because the necessary stretching is so much that LaTeX doesn't like to follow either a
weak or a strong request.

Enlarging a page
LaTeX's rules are not set in stone; they also apply to page balancing. There may be occasions
where we want to put a little more text onto a page, even if the text would be squeezed a bit
or the text height increases. There's a command that will help us out: \enlargethispage.

[ 95 ]

Designing Pages

Time for action – sparing an almost empty page
We shall modify our example a bit. This time, we will try to avoid a nearly empty page by
squeezing their text to the preceding page.

1.

Remove the command \newpage from our example and switch to 11pt base font.
This time, use less filler text in the subsection:
\documentclass[a4paper,11pt]{book}
\usepackage[english]{babel}
\usepackage{blindtext}
\usepackage[a4paper, inner=1.5cm, outer=3cm, top=2cm,
bottom=3cm, bindingoffset=1cm]{geometry}
\begin{document}
\chapter{Exploring the page layout}
In this chapter we will study the layout of pages.
\section{Some filler text}
\blindtext
\section{A lot more filler text}
More dummy text will follow.
\subsection{Plenty of filler text}
\blindtext[3]
\end{document}

2.

Typeset, and the result will consist of two pages:

[ 96 ]

Chapter 3

3.

Insert this command right after the \subsection line:
\enlargethispage{\baselineskip}

4.

Typeset. Now our document fits in only one page:

[ 97 ]

Designing Pages

What just happened?
We used the command \enlargethispage to squeeze more text onto a page. This
command takes the additionally requested height as its argument. The command
\baselineskip returns the height of a text line that we used as the argument. So,
LaTeX could put one extra line onto the page, and even the remaining line fitted in as
well because LaTeX compressed some whitespace.
We could use factors: write \enlargethispage{2\baselineskip} to get two more lines
on a page. It doesn't even need to be an integer value. Like always, when you state a length,
you could use other units such as 10pt, 0.5in, 1cm, or 5mm, and even negative values.
Only the current page will be affected by this command.
There's a starred version: \enlargethispage* would
additionally shrink all vertical spaces on the page to their minimum.

Using footnotes
As briefly mentioned in Chapter 2, Formatting Words, Lines, and Paragraphs, LaTeX provides
a command to typeset footnotes. Let's see it in action.

Time for action – using footnotes in text and in headings
Let's go back to the very first example of this chapter. We shall insert one footnote in the
body text and one in a section heading:

1.

Modify the example inserting a footnote, as shown in the highlighted line:
\documentclass[a4paper,12pt]{book}
\usepackage[english]{babel}
\usepackage{blindtext}
\begin{document}
\chapter{Exploring the page layout}
In this chapter we will study the layout of pages.
\section{Some filler text}
\blindtext
\section{A lot more filler text}
More dummy text\footnote{serving as a placeholder} will follow.
\subsection{Plenty of filler text}
\blindtext[10]
\end{document}
[ 98 ]

Chapter 3

2.

Typeset to see how the footnote looks in print:

3.

Insert a footnote in the second section header. This time, put \protect right
before:
\section{A lot more filler text\protect\footnote{to fill the
page}}

4.

Typeset to check that it works:

[ 99 ]

Designing Pages

What just happened?
The command \footnote{text} placed a superscripted number at the current position.
Further, it prints its argument text into the bottom of the page, marked by the same
number. As we've seen, such notes are separated from the main text by a horizontal line.
The other \footnote command has been preceded by the command \protect. If we
omitted that, an error would be raised—try it. Such an error may occur when we use
\footnote inside an argument, where it's being further processed. \protect simply
prevents this processing error. As a rule of thumb, if a command causes an error when
it's used inside an argument, like in headings, try to fix it by putting \protect right
before that command. Cases where \protect would hurt instead of helping are rare.
Generally, a heading might not be a good place for footnotes. If you simply use \footnote in
headings, be aware that they would appear in the table of contents and perhaps also in page
headers. If you want to avoid that, use the optional parameter of the sectioning commands
without \footnote, that is, \section[title without footnote]{title with
footnote}. The same applies to \chapter, and so on, and even further to \caption.
The complete definition of \footnote is:
‹‹

\footnote[number]{text} produces a footnote marked by this optional
number, an integer. If we don't give the optional number, an internal counter would

be stepped and used. This would be done automatically; we don't need to worry.
Nevertheless, if we encounter difficulties in placing footnotes, there are two commands
that help us:
‹‹

\footnotemark[number] produces a superscripted number in the text as a

footnote mark. If the optional argument wasn't given, it's also stepping and using
the internal footnote counter. No footnote will be generated.
‹‹

\footnotetext[number]{text} generates a footnote without putting a

footnote mark into the text without stepping the internal footnote counter.

Both the commands may be used together in circumstances when \footnote would fail.
Set a footnote command right after the related text. Don't leave a space in-between.
Otherwise, you would get a gap between the text and the following footnote mark.

Modifying the dividing line
The line that separates footnotes from the text is produced by the command
\footnoterule. If we wish to omit that line or if we want to modify it, we must
redefine it. We learned about \renewcommand—so, let's use it.

[ 100 ]

Chapter 3

Time for action – redefining the footnote line
We will use \renewcommand to override the default \footnoterule command:

1.

Take the previous example and add the following lines to the preamble:
\renewcommand{\footnoterule}
{\noindent\smash{\rule[3pt]{\textwidth}{0.4pt}}}

2.

Typeset and see how the line has changed:

What just happened?
Remember the definition of \newcommand—here it's analogous. The existing command
\footnoterule will be replaced by a new definition that we wrote in the second line. The
command \rule[raising]{width}{height} draws a line, here 0.4 pt thick, and as
wide as the text, raised a bit by 3 pt. Through the command \smash, we let our line pretend
to have a height and a depth of zero, so it's occupying no vertical space at all. This way,
the page balancing will not be affected. You already know \noindent, which avoids the
paragraph indentation.
If you want to omit that line completely, you just need to write:
\renewcommand{\footnoterule}{}

Now the command is defined to do nothing.

[ 101 ]

Designing Pages

Using packages to expand footnote styles
There are different habits for setting footnotes. Some styles require footnotes numbered
per page, they might have to be placed in the document as so called endnotes, and symbols
instead of numbers may be used. More demands exist and therefore several packages have
been developed to comply with them. Here's a selection:
‹‹

endnotes: Places footnotes at the end of the document

‹‹

manyfoot: Allows nested footnotes

‹‹

bigfoot: Replaces and extends manyfoot, improves page break handling with
footnotes

‹‹

savefnmark: Useful when you need to use footnotes several times

‹‹

footmisc: All-round package; introduces numbering per page, is able to save space
when many short footnotes are used, offers symbols instead of numbers as footnote
marks, provides hanging indentation and other styles

Have a look at the respective package documentation to learn more—now you know how to
obtain it.

Pop quiz
1. According to the text, which of the following points should be the goal when
designing the page layout?
a.
b.
c.
d.

Fill the page as much as possible
Achieve an artistic design
Improve readability
Distinguish the work from other publications

2. Which options are preset by the book class?
a.
b.
c.
d.

openright and twoside
openany and twoside
openright and oneside
openany and oneside

3. Which page style is used as default on the first page of a chapter?
a. empty
b. plain
c.

headings

d. myheadings
e. fancy
[ 102 ]

Chapter 3

4. One of these page breaking commands is able to stretch the text to the bottom to
fill the page. Which one?
a. \newpage
b. \clearpage
c.

\cleardoublepage

d. \pagebreak
5. We would like to put a footnote into a chapter heading. Choose the best way!
a. \chapter{title\footnote{text}}
b. \chapter*{title\footnote{text}}
c.

\chapter{title\protect\footnote{text}}

d. \chapter[title]{title\footnote{text}}

Summary
In this chapter, we have worked out how to design the overall layout of a document.
Specifically, we learned about:
‹‹

Adjusting the page dimensions and margins

‹‹

Using landscape orientation and two-column layout

‹‹

Modifying the spacing between lines

‹‹

Breaking pages and paying attention to the vertical justification

‹‹

Designing headers and footers with titles and page numbers

‹‹

Using footnotes

Further, we covered some general topics:
‹‹

Obtaining documentation of packages in several ways

‹‹

Changing document properties by choosing class options

‹‹

Redefining existing commands

Now it's time to deal with further text structures. In the next chapter, we shall learn how to
create lists for presenting text in an easy-to-read way.

[ 103 ]

4

Creating Lists
Arranging text in the form of a list can be very reader-friendly. You can present
several ideas by a clear structure which is easy to survey. Commonly, three
types of lists are used:
1. Bulleted lists
2. Numbered lists
3. Definition lists

In this chapter, we shall learn how to create such lists.

Building a bulleted list
We shall start with the simplest kind of list. It contains just the items without numbers. Each
item is marked by a bullet.

Time for action – listing LaTeX packages
We shall create a list of packages that we got to know in the previous chapter:

1.

Begin a new document and enter the following code:
\documentclass{article}
\begin{document}
\section*{Useful packages}
LaTeX provides several packages for designing the layout:
\begin{itemize}
\item geometry

Creating Lists
\item typearea
\item fancyhdr
\item scrpage2
\item setspace
\end{itemize}
\end{document}

2.

Typeset and have a look at the output:

What just happened?
It was not necessary to load any package. We began with a heading followed by some
text. For the actual list, we used an environment called itemize. As we know about
environments, \begin{itemize} starts it and \end{itemize} ends it. The command
\item tells LaTeX that a new item to the list follows. Each item may contain text of any
length and even paragraph breaks. Well, that's pretty easy, isn't it?

Nesting lists
When a list gets longer, we could make it clearer by dividing it. We just create lists in a
list. It's advisable to use different bullets to keep the list levels apart easily. LaTeX does
it for us automatically.

Time for action – listing packages by topic
We shall refine the package list by introducing categories:

1.

Refine the aforementioned highlighted itemize environment of our
example in the following way:
\begin{itemize}
\item Page layout
\begin{itemize}
[ 106 ]

Chapter 4
\item geometry
\item typearea
\end{itemize}
\item Headers and footers
\begin{itemize}
\item fancyhdr
\item scrpage2
\end{itemize}
\item Line spacing
\begin{itemize}
\item setspace
\end{itemize}
\end{itemize}

2.

Typeset to see the new list:

What just happened?
We simply inserted another list inside the list. Up to four levels are possible, otherwise LaTeX
would stop and print out the error message ! LaTeX Error: Too deeply nested. As we saw, the
first level is marked by a bullet, and the second by an en dash. A third level item would start
with an asterisk symbol *. The fourth and last level would be marked by a centered dot.
Deeply nested lists can rarely be seen; such complicated structures might be hard to read.
In such cases, it could be a good idea to revise the text structure or at least split the list.

Creating a numbered list
Bulleted lists are useful if the order of the items doesn't matter. However, if the order is
important, we could organize the items by giving them numbers and creating a sorted list.
That would allow a reader to follow our thoughts easily.
[ 107 ]

Creating Lists

Time for action – writing a step-by-step tutorial
Let's prepare a tiny "how-to" about designing the page layout:

1.

Start with a new document and enter the following code:
\documentclass{article}
\begin{document}
\begin{enumerate}
\item State the paper size by an option to the document class
\item Determine the margin dimensions using one of these
packages:
\begin{itemize}
\item geometry
\item typearea
\end{itemize}
\item Customize header and footer by one of these packages:
\begin{itemize}
\item fancyhdr
\item scrpage2
\end{itemize}
\item Adjust the line spacing for the whole document
\begin{itemize}
\item by using the setspace package
\item or by the command \verb|\linespread{factor}|
\end{itemize}
\end{enumerate}
\end{document}

2.

Typeset to generate the «how-to»:

[ 108 ]

Chapter 4

What just happened?
We used an enumerate environment. Except for the name, we use it just like the itemize
environment; each list item is introduced by the command \item. Again, we nested two
lists, but this time the lists are of a different kind. As we saw, that's no problem. Even though
the unnumbered list is embedded within a numbered list, it's marked by bullets, because it's
the first unnumbered level. Mixed nesting could go further than four levels, but four is the
maximum for each kind and six in general.
The default numbering scheme for the enumerate environment is as follows:

\item understands an optional argument; if you write \item[text], then text will be

printed instead of a number or a bullet. This way, you could use any numbering and any
symbol for the bullet.

Customizing lists
The default appearance of lists is meaningful regarding spacing, indentation, and symbols.
Nevertheless, it may be required to use another scheme for the enumeration, for the bullets,
or to modify the line spacing or their indentation. There are packages helping us both to save
space and to customize the symbols; let's start with the spacing.

Saving space with compact lists
A frequently arising question is how to reduce the space. LaTeX's lists are often regarded as
being too spacious. We shall see how to implement that.

Time for action – shrinking our tutorial
We shall remove the white space around the list items and before and after the whole list
as well:

1.

In the previous example, load the package paralist and replace
enumerate with compactenum and itemize with compactitem:
\documentclass{article}
\usepackage{paralist}
\begin{document}
[ 109 ]

Creating Lists
\begin{compactenum}
\item State the paper size by an option to the document class
\item Determine the margin dimensions using one of these
packages:
\begin{compactitem}
\item geometry
\item typearea
\end{compactitem}
\item Customize header and footer by one of these packages:
\begin{compactitem}
\item fancyhdr
\item scrpage2
\end{compactitem}
\item Adjust the line spacing for the whole document
\begin{compactitem}
\item by using the setspace package
\item or by the command \verb|\linespread{factor}|
\end{compactitem}
\end{compactenum}
\end{document}

2.

Typeset and compare the spacing:

3.

Now extend the highlighted list item for setspace as follows:
\item by using the setspace package and one of its options:
\begin{inparaenum}
\item singlespacing
\item onehalfspacing
\item double spacing
\end{inparaenum}

[ 110 ]

Chapter 4

2.

Typeset and look at the change in the line spacing subject:

What just happened?
The used package paralist provides several new list environments designed to be
typeset within paragraphs or in a very compact look. We loaded this package and replaced
the standard environments with their compact counterparts. In step 3, we used a new
environment, where the items are enumerated but stay within the same paragraph.
For each standard environment, paralist adds three corresponding environments:
Numbered lists:
‹‹

compactenum: Compact version of the enumerate environment without any

vertical space before or after the list or its items
‹‹

inparaenum: An enumerated list typeset within a paragraph

‹‹

asparaenum: Every list item is formatted like a separate common LaTeX paragraph,

but numbered
Bulleted lists:
‹‹

compactitem: Compact version of the itemize environment like compactenum

‹‹

inparaitem: An itemized list typeset within a paragraph, rarely seen in print

‹‹

asparaitem: Like asparaenum, but with symbols instead of numbers

Choosing bullets and numbering format
To follow language specific habits or certain requirements, we might wish to enumerate
by Roman numbers or alphabetically; parentheses or dots might be required. Some may
prefer dashes instead of bullets. The package enumitem provides sophisticated features to
implement such requirements.

[ 111 ]

Creating Lists

Time for action – modifying lists using enumitem
Let's change the numbering scheme. We shall number alphabetically using circled letters.
Furthermore, we will replace bullets by dashes:

1.

We shall discard paralist and load the package enumitem instead. We will turn
away from the compact environments returning to the standard list notation:
\documentclass{article}
\usepackage{enumitem}
\setlist{nolistsep}
\setitemize[1]{label=---}
\setenumerate[1]{label=\textcircled{\scriptsize\Alph*},
font=\sffamily}
\begin{document}
\begin{enumerate}
\item State the paper size by an option to the document class
\item Determine the margin dimensions using one of these
packages:
\begin{itemize}
\item geometry
\item typearea
\end{itemize}
\item Customize header and footer by one of these packages:
\begin{itemize}
\item fancyhdr
\item scrpage2
\end{itemize}
\item Adjust the line spacing for the whole document
\begin{itemize}
\item by using the setspace package
\item or by the command \verb|\linespread{factor}|
\end{itemize}
\end{enumerate}
\end{document}

2.

Typeset and see the output:

[ 112 ]

Chapter 4

3.

Right above the highlighted line, insert the following lines:
\end{enumerate}
\subsubsection*{Tweaking the line spacing:}
\begin{enumerate}[resume*]

4.

Typeset to see the change:

What just happened?
We used the enumitem command to specify list properties. Let's take a closer look:
‹‹

\setlist{nolistsep}: \setlist sets properties valid for all types of lists. Here
we specified nolistsep to achieve very compact lists analogous to the compact
paralist environment.

‹‹

\setitemize[1]{label=–--}: \setitemize modifies properties of bulleted

lists. Here we chose an em dash as the label to get a leading wide dash.

[ 113 ]

Creating Lists
‹‹

\setenumerate[1]{label=\textcircled{\scriptsize\Alph*},font=\
sffamily}: \setenumerate sets properties valid for numbered lists. We used it
to set a label and a font for the label. The command \Alph* stands for enumeration

in capital letters.

All of those three commands allow arguments of the form key=value. Some useful
parameters are as follows:
Parameter
font

Meaning

Values

Modifies the label font Any font command

Example
font=\bfseries

label

Sets the label for the
current level

label=\emph\
alph*)

May contain
\arabic*,
\alph*, \Alph*, \
roman*, \Roman*

label*

Like label but
appended to the
current label

align

Alignment of the label left or right

align=right

start

Number of the first
item

start=10

resume,

Let's the counter
continue from the
previous lists value

resume

noitemsep

No extra space
between items and
paragraphs

noitemsep

nolistsep

No extra vertical
spacing at all

nolistsep

resume*

Like label

Integer

label*=\arabic)

These options may be set globally like \setenumerate[level]{key=value list}.
If the optional argument level is missing, this global command will apply to all levels.
Those options may be used locally like we did with resume*. Other examples are:
‹‹

\begin{itemize}[noitemsep] for a compact bulleted list

‹‹

\begin{enumerate}[label=\Roman*.,start=3] numbered by III., IV., ...

‹‹

\begin{enumerate}[label=\alph*)],nolistsep] for a very compact list

numbered a), b), c), ...

[ 114 ]

Chapter 4

The labeling commands would achieve a numbering as follows:
\arabic* 1, 2, 3, 4, …
\alph*
a, b, c, d, …
\Alph*

A, B, C, D, …

\roman*

i, ii, iii, iv, …

\Roman*

I, II, III, IV, …

The * has been added to distinguish those commands from LaTeX commands with the same
name. Parentheses and punctuation may be used as wished. Later in the book, you will learn
how to choose between thousands of symbols for labels and bullets.
There's even a short form: if you load enumitem with the option shortlabels, you may
use a compact syntax like \begin{enumerate}[(i)], \begin{enumerate}[(1)] where
1, a, A, i, I stand for \arabic*, \alph*, \Alph*, \roman*, \Roman* respectively. This
allows customization quickly and easily. However, consider using global commands to keep
formatting consistent.

Suspending and continuing lists
In step 3 of our example, we interrupted the list. We continued writing normal text until we
restarted the list by \begin{enumerate}[resume*]. The resume option tells enumitem
to continue the list with the next number. The starred variant resume* does it with the
same formatting like before. If you would like to complete the document, note that a \
subsubsection command should be preceded by a \subsection command. This should
follow a \section command. Just using a lower-level heading without a parent heading
could result in numbering like 0.0.1.

Producing a definition list
We shall proceed to the third kind of list, namely, definition lists, also called description lists.
Every list item consists of a term followed by its description.

[ 115 ]

Creating Lists

Time for action – explaining capabilities of packages
Now that we know some packages for creating lists, we shall write a short overview to show
their capabilities. Let's choose some additional packages listed on http://texcatalogue.
sarovar.org:

1.

We will use a description environment. Create a document with the following code:
\documentclass{article}
\begin{document}
\begin{description}
\item[paralist] provides compact lists and list versions that
can be used within paragraphs, helps to customize labels and
layout
\item[enumitem] gives control over labels and lengths
in all kind of lists
\item[mdwlist] is useful to customize description lists, it
even allows multi-line labels. It features compact lists and
the capability to suspend and resume.
\item[desclist] offers more flexibility in definition list
\item[multenum] produces vertical enumeration in multiple
columns
\end{description}
\end{document}

2.

Typeset to get the definition list:

[ 116 ]

Chapter 4

What just happened?
We used the description environment like the other lists, except that we used the optional
argument of \item. In the description environment, \item is defined such that the
optional parameter will be typeset in the bold typeface.
The package paralist supports the description environment as well; there are
the compactdesc, inparadesc, and asparadesc versions working analogous to
the other lists.
The same is valid for enumitem: there's the global command \setdescription{format}
working like \setitemize and \setenumerate. Furthermore, it also extends the
description environment to accept optional formatting arguments of the form key=value,
supporting the short form as well.

Have a go hero – adjusting the dimensions of lists
LaTeX's lists have a meaningful layout. However, there might be occasions when you would
like to modify this layout, for instance, to change the margins or the item indentation. All
layout dimensions are determined by LaTeX macros, so called lengths.
There's a package which is really great for visualizing layouts, which presents these length
macros. It's called layouts and it has been written by Peter Wilson. Let's use it to examine
LaTeX's list dimensions. We will use this small document:
\documentclass[12pt]{article}
\usepackage{layouts}
\begin{document}
\listdiagram
\end{document}

[ 117 ]

Creating Lists

By simply typesetting it, we will get the following diagram:

Isn't it fantastic? The layouts package can do even more, which you can read about in its
documentation. For now, we stay on topic regarding lists.
Though there are LaTeX commands for customizing those lengths, for example,
\setlength{\labelwidth}{2cm}, applying them to individual lists and certain
nesting depths is hard. If you need to modify the list layout, the enumitem package
comes handy again. Its commands like \setlist and its key=value interface may be
used also for adjusting the values of the lengths you could see in the previous diagram.
For example, if we would like to remove the space between list items in the
description environment and to reduce the left margin, we could load
enumitem and write the following:
\setdescription{itemsep=0cm,parsep=0cm,leftmargin=0.5cm}

Note, we don't use the backslash for keys. Similarly, \setitemize, \setenumerate, and
\setlist can be used for fine-tuning. Try assigning values by yourself, and test the effect on
our examples. If you would like to learn more, have a look at the enumitem documentation.
[ 118 ]

Chapter 4

Pop quiz
1. A list environment may be nested to up to how many levels?
a. Two
b. Three
c.

Four

d. Any number, just depending on the memory
2. All but one of these packages understand options in the form key=value. Which
does not?
a. geometry
b. paralist
c.

enumitem

3. In which environment should \item be used with an optional argument?
a. itemize
b. enumerate
c.

description

d. inparaenum

Summary
In this chapter, we got to know a new way to structure our text—lists. Specifically, we
learned to create:
‹‹

Bulleted lists using the itemize environment

‹‹

Numbered lists using the enumerate environment

‹‹

Definition lists using the description environment

Furthermore, we worked with compact versions of such lists provided by the packages
paralist and enumitem. Those packages allowed us to customize our lists at will.
You may regard those lists as an additional possibility to structure your text. Use it to clarify
your ideas. Though you may design the layout of lists as you wish, it's highly recommended
to use the same bullets and numbering scheme respectively for the same nesting level.

[ 119 ]

5

Creating Tables and Inserting
Pictures
Scientific documents and others do not just contain plain text; they also present
information and data in tables and use diagrams and drawings to visualize
them. We shall become familiar with that.

In this chapter, we will learn how to perform the following:
‹‹

Lining up text and data in columns

‹‹

Typesetting complex tables

‹‹

Including pictures in our documents

‹‹

Adding captions to pictures and tables

‹‹

Controlling the placement of figures and tables

Let's tackle these tasks!

Writing in columns
Remember the time of the typewriter and early word processing software? When we
needed to line up some text in columns, we could use tab stops. LaTeX provides a similar
way to easily align text in columns, namely, the tabbing environment.

Creating Tables and Inserting Pictures

Time for action – lining up information using the tabbing
environment
We would like to present a quick overview regarding LaTeX. We shall present one point on
each line, aligned at words and double colons:

1.

Begin a new document and open a tabbing environment:
\documentclass{article}
\begin{document}
\begin{tabbing}

2.

Write the text, set tab stops by \=, and end the line by \\:
\emph{Info:} \= Software \= : \= \LaTeX \\

3.

Add further lines, move to the next tab stop by \>, and again end lines by \\:
\> Author \> : \> Leslie Lamport \\
\> Website \> : \> www.latex-project.org

4.

Close the tabbing environment and end the document:
\end{tabbing}
\end{document}

5.

Typeset to get the output:

What just happened?
The tabbing environment that we used begins a new line. We used three simple tags
for markup:
‹‹

\= sets a tab stop. We could put several tab stops on a line. If we use \=

later, the next awaited tab stop would be reset to this position.
‹‹

\\ ends a row.

‹‹

\> goes to the next tab stop. This could also mean to go backwards.

This way, we can quickly produce columns containing left-aligned text. If the rows of the
tabbing environment would reach the end of a page, it could continue on the next page.
What if a column is too long, running over the tab stop? Let's see how to solve that.
[ 122 ]

Chapter 5

Time for action – lining up font commands
In Chapter 2, Formatting Words, Lines, and Paragraphs, we've got to know a lot of font
commands and declarations. We saw a table containing those commands and example
output. Now we shall create such a table ourselves:

1.

Begin a new document, like the one in step 1 of our previous example,
but define a command for setting the font of our header:
\documentclass{article}
\newcommand{\head}[1]{\textbf{#1}}
\begin{document}
\begin{tabbing}

2.

Write the first row set tab stops by \= and use \> to move to the tab stops.
Use the command \verb|…| to typeset the LaTeX commands:
\begin{tabbing}
Family \= \verb|\textrm{...}| \= \head{Declaration} \= \kill
\> \head{Command} \> \head{Declaration} \> \head{Example}\\
Family \> \verb|\textrm{...}| \> \verb|\rmfamily|
\> \rmfamily Example text\\
\> \verb|\textsf{...}| \> \verb|\sffamily|
\> \sffamily Example text\\
\> \verb|\texttt{...}| \> \verb|\ttfamily|
\> \ttfamily Example text
\end{tabbing}

3.

Typeset and examine:

4.

As we can see, the tab stops are too narrow. We shall correct it. Create a new head
row containing the tab stops; this time, we will mark the line by \kill to hide that
line. Use filler text to specify the width between the tab stops. Complete it with
further font commands:
\begin{tabbing}
Family \= \verb|\textrm{...}| \= \head{Declaration} \= \kill
\> \head{Command} \> \head{Declaration} \> \head{Example}\\
Family \> \verb|\textrm{...}| \> \verb|\rmfamily|
\> \rmfamily Example text\\
\> \verb|\textsf{...}| \> \verb|\sffamily|
\> \sffamily Example text\\
\> \verb|\texttt{...}| \> \verb|\ttfamily|
\> \ttfamily Example text
\end{tabbing}
[ 123 ]

Creating Tables and Inserting Pictures

5.

Typeset to get the result:

What just happened?
After we noticed that our tab stops have been set too narrow, we constructed a new first row
containing the tab stops. It consists of words representing the widest entries of each column.
To hide this auxiliary row, we used the command \kill right at the end of the line; \kill
at the end of a line causes this line to have no output.
Like in this example, the command \verb|code| typesets code "as it is",
without interpreting commands within. Instead of |, any character may be
chosen as the delimiter. \verb cannot be used in arguments of commands
including \section and \footnote, and not in table heads.
For longer, verbatim text, use the environment with the same name:
verbatim.

There are further useful commands:
‹‹

\+ at the end of a line causes each subsequent line to start at the first tab.
Use it twice \+\+ to start at the second tab and so on.

‹‹

\- cancels a preceding \+; also using multiply has cumulative effect.

‹‹

\< at the beginning of a line cancels the effect of one previous \+ command

for that line.

The mentioned commands already allow a good use of the tabbing environment. Even more
commands can be found in the reference manual: http://texblog.net/help/latex/
tabbing.html.
Inside tabbing environments, declarations are local to the
current item. A following \=, \>, \\, or \kill command
would stop the effect.
Tabbing environments cannot be nested.

[ 124 ]

Chapter 5

Typesetting tables
We might need more complicated structures and formatting, like centering in columns,
dividing lines, or even nested structures. LaTeX provides the tabular environment for
typesetting simple and complex tables which can be nested.

Time for action – building a table of font family commands
We shall create a table like in the previous example, but this time, we would like to make all
entries in a column horizontally centered to each other. We will also add some horizontal
lines to mark the border and the header of the table:

1.

Create a new document. Define a command for setting the font for the head row:
\documentclass{article}
\newcommand{\head}[1]{\textnormal{\textbf{#1}}}
\begin{document}

2.

Begin a tabular environment. As a mandatory argument, provide ccc standing
for three centered columns:
\begin{tabular}{ccc}

3.

Write the table head row, write & to separate column entries, and \\ to end rows.
Use \hline to insert horizontal lines:
\hline
\head{Command} & \head{Declaration} & \head{Output}\\
\hline

4.

Continue with the table body and end the environment and the document. For
typesetting LaTeX commands, write \verb|\command|:
\verb|\textrm| & \verb|\rmfamily| & \rmfamily Example text\\
\verb|\textsf| & \verb|\sffamily| & \sffamily Example text\\
\verb|\texttt| & \verb|\ttfamily| & \ttfamily Example text\\
\hline
\end{tabular}
\end{document}

5.

Typeset to see the table:

[ 125 ]

Creating Tables and Inserting Pictures

What just happened?
In the mandatory argument, we wrote a list of characters. Each character stands for a
formatting option. As we used three characters, we've got three columns. c stands for
centered alignment. Therefore, the entries of all columns have been centered.
Column entries are separated by &, while rows are terminated by \\. Don't end the last
line by \\ unless you further wish to write a line below. It's also a good idea to align the
ampersands in our source code to keep it readable.
Inside the entries, you may use ordinary text as well as LaTeX commands. As in the tabbing
environment, declarations are local to the entry, like if each entry was surrounded by curly
braces.
Furthermore, tabular has an optional alignment argument just like minipage. So, the
complete definition is:
\begin{tabular}[position]{column specifiers}
row 1 col 1 entry & row 1 col 2 entry ... & row 1 col n entry\\
...
\end{tabular}

In the optional argument, t means alignment at the top row and b means alignment at the
bottom row. The default is vertically centered alignment. This may come in handy if you
would like to place two tables next to each other or within further text.

Drawing lines in tables
Within tabular, three types of lines may be used:
‹‹

\hline draws a horizontal line over the whole width of the table

‹‹

\cline{m-n} draws a horizontal line starting at the beginning of column m and
ending at the end of column n

‹‹

\vline draws a vertical line over the full height and depth of the current row

Understanding formatting arguments
Of course, further formatting is possible. Have a look at this example table:
\begin{tabular}{|l|c|r|p{1.7cm}|}
\hline
left & centered & right & a fully justified paragraph cell\\
\hline
l & c & r & p\\
\hline
\end{tabular}
[ 126 ]

Chapter 5

This code would produce the following table:

The options understood by the tabular environment are as follows:
‹‹

l for left alignment.

‹‹

c for centered alignment.

‹‹

r for right alignment.

‹‹

p{width} for a "paragraph" cell of a certain width. . If you place several p cells

next to each other, they will be aligned at their top line. It's equivalent to using
\parbox[t]{width} within a cell.
‹‹

@{code} inserts code instead of empty space before or after a column. This might

also be some text or it could be left empty to avoid this space.
‹‹

| stands for a vertical line.

‹‹

*{n}{options} is equivalent to n copies of options, where n is a positive integer
and options may consist of one or more column specifiers including * as well.
It is very advisable to avoid vertical lines in tables. Lines should subtly support
your information but not make reading difficult.

After loading the array package by \usepackage{array} you may use some options,
such as:
‹‹

m{width} is similar to\parbox{width}: the base line is at the middle

‹‹

b{width} is like \parbox[b]{width}: the base line is at the bottom

‹‹

!{code} can be used like | but inserts code instead of a vertical line.

In contrast to @{…}, the space between columns will not be suppressed.

‹‹

>{code} can be used before an l, c, r, p, m, or b option and inserts code right at
the beginning of each entry of that column

‹‹

<{code} can be used after an l, c, r, p, m, or b option and inserts code at the end
of the entry of that column

[ 127 ]

Creating Tables and Inserting Pictures

This example shows the effect of @{} and the alignment arguments p, m, and b:
\begin{tabular}{@{}lp{1.2cm}m{1.2cm}b{1.2cm}@{}}
\hline
baseline & aligned at the top & aligned at the middle
& aligned at the bottom\\
\hline
\end{tabular}

The output table is as follows:

Increasing the row height
You may have noticed that horizontal lines nearly touch the letters in the cells, especially
capital letters. The array package introduces a length called \extrarowheight. If it has a
positive value, this will be added to the height of every row of the table.
The next example, following the very first example of this chapter, shows how to extend
the row height and shows the effect of the remaining array options:
\documentclass{article}
\usepackage{array}
\setlength{\extrarowheight}{4pt}
\begin{document}
\begin{tabular}{@{}>{\itshape}ll!{:}l<{.}@{}}
\hline
Info: & Software & \LaTeX\\
& Author & Leslie Lamport\\
& Website & www.latex-project.org\\
\hline
\end{tabular}
\end{document}

The output is as follows:

[ 128 ]

Chapter 5

Here, >{\itshape} has been used to change the font of a row to italic. >{} is often used
to insert an alignment declaration, but there's a pitfall: such declarations might change the
internal meaning of \\, which is a shortcut for \tabularnewline within tables. But the
array package offers a command to repair it; in such cases, just add \arraybackslash, for
example:
\begin{tabular}{>{\centering\arraybackslash}p{5cm}}

Otherwise, the content of paragraph cells stated by p, m, or b will be fully justified.
After a specific row, you can add vertical space by the optional argument of \\, such as
\\[10pt].
You may even stretch a whole table: the macro \arraystretch contains a stretching factor
with a default value of 1. Just redefine it. For example, \renewcommand{\arraystretch}
{1.5} will increase the height of the rows by 50 percent. You could use it inside a group or
an environment to keep the effect local.

Beautifying tables
Still our tables don't look as perfect as they look in good books. Especially, the lines and their
distances to the text might need improvement. The booktabs package comes to the rescue;
after loading it, you can enhance the quality of your tables by new line commands replacing
\hline and \cline.

Time for action – adding nicer horizontal lines with the
booktabs package
We shall use the new commands introduced by booktabs:

1.

In the previous example, load the package booktabs:
\usepackage{booktabs}

2.

Use \toprule, \midrule, and \bottomrule instead of \hline. Specify a
thickness as an optional argument:
\begin{tabular}{ccc}
\toprule[1.5pt]
\head{Command} & \head{Declaration}
\midrule
\verb|\textrm| & \verb|\rmfamily| &
\verb|\textsf| & \verb|\sffamily| &
\verb|\texttt| & \verb|\ttfamily| &
\bottomrule[1.5pt]
\end{tabular}
[ 129 ]

& \head{Output}\\
\rmfamily Example text\\
\sffamily Example text\\
\ttfamily Example text\\

Creating Tables and Inserting Pictures

3.

Typeset to see the difference:

What just happened?
British typesetters call a line a rule. The booktabs developer chose this terminology for
the new commands. We used three of them. These are their definitions:
‹‹

\toprule[thickness] may be used to draw a horizontal line at the top of the
table. If desired, a thickness may be specified, like 1pt or 0.5mm.

‹‹

\midrule[thickness] draws a horizontal dividing line between rows of a table.

‹‹

\bottomrule[thickness] draws a horizontal line to finish off a table.

‹‹

\cmidrule[thickness](trim){m–n} draws a horizontal line from column m to
column n. (trim) is optional like thickness, it could be (l) or (r) to trim the
line at its left or right end. Write (lr) to trim at both ends. Even adding {width},
like in (l{10pt}), is possible and specifies the trim width.

The package does not define vertical lines. They are not advisable anyway. The same applies
to double rules. Neither vertical nor double rules are recommended. They are even widely
considered to be bad typographic style.
Consider using \toprule and the other line commands without optional arguments—let's
figure out how.

Have a go hero – adjusting lengths
We briefly introduced the command \setlength. Instead of specifying a line thickness by
an optional argument to \toprule, \midrule, \cmidrule, or \bottomrule, always omit
it. Instead, specify it once for your whole document by \setlength in the preamble.
These are the lengths that may be adjusted:
‹‹

\heavyrulewidth for the thickness of the top and bottom lines

‹‹

\lightrulewidth for the thickness of the middle lines by \midrule

‹‹

\cmidrulewidth for the thickness of \cmidrule

‹‹

\cmidrulekern for the trimming in \cmidrule

‹‹

\abovetopsep is the space above the top rule; the default is 0pt
[ 130 ]

Chapter 5
‹‹

\belowbottomsep is the space below the bottom rule; the default is 0pt

‹‹

\aboverulesep specifies the space above \midrule, \cmidrule, and
\bottomrule

‹‹

\belowrulesep stands for the space below \midrule, \cmidrule, and
\toprule

Try to change the thickness of the lines. The lengths already have reasoned values, but
you may change them. So, the adjustment in your preamble would improve all tables in
your document.

Spanning entries over multiple columns
Columns concerning the same subject might be grouped by a common header. In such
a case, two cells in the header should be merged. The command \multicolumn does it
for us.

Time for action – merging cells
Regarding our example table, commands and declarations are both input, whereas, the
remaining column contains output. We shall emphasize that in our header:

1.

In our example, insert another header row. Use \multicolumn to merge cells. Alter
the column formatting argument and the middle rule. Changes are highlighted:
\begin{tabular}{@{}*3l@{}}
\toprule[1.5pt]
\multicolumn{2}{c}{\head{Input}} &
\multicolumn{1}{c}{\head{Output}}\\
\head{Command} & \head{Declaration}
\cmidrule(r){1-2}\cmidrule(l){3-3}
\verb|\textrm| & \verb|\rmfamily| &
\verb|\textsf| & \verb|\sffamily| &
\verb|\texttt| & \verb|\ttfamily| &
\bottomrule[1.5pt]
\end{tabular}

2.

Typeset and see the output:

[ 131 ]

& \\
\rmfamily Example text\\
\sffamily Example text\\
\ttfamily Example text\\

Creating Tables and Inserting Pictures

What just happened?
We used the command \multicolumn twice; once to merge two cells and surprisingly
another time just for one cell. Let's first look at its definition:
\multicolumn{number of columns}{formatting options}{entry text}

The number of columns to be spanned may be a positive integer or just 1. The formatting
options will be applied instead of the options specified in the tabular definition for this cell.
We took advantage of this when we used \multicolumn{1}{c}{…}, overriding the l
option of the column by a c option to get just this cell centered.
The other change we made concerns \cmidrule. We used it instead of \midrule together
with the trimming argument to get a gap between the input and the output column.

Inserting code column-wise
There are many more font commands that we would like to add to the table. Writing
\verb|…| in each cell is tiresome. We shall exploit the >{…} feature of the array package
to define the formatting of the entries once for the column.

Time for action – using the array package
We shall modify the table definition to set our input columns in the typewriter font. At the
same time, we will insert a column on the left, standing for our command type:

1.

Extend the preamble of our example by defining a command \normal. It shall use
\multicolumn to produce an l cell, no matter what the column formatting is:
\documentclass{article}
\usepackage{array}
\usepackage{booktabs}
\newcommand{\head}[1]{\textnormal{\textbf{#1}}}
\newcommand{\normal}[1]{\multicolumn{1}{l}{#1}}
\begin{document}

2.

As \verb cannot be used in table headers, we shall use \ttfamily. Preceding it
with \textbackslash is enough for our purposes. Use >{…} to insert it twice.
Then add <{Example text} to the last column to save typing work:
\begin{tabular}{@{}l*2{>{\textbackslash\ttfamily}l}l%
<{Example text}@{}}
\toprule[1.5pt]
& \multicolumn{2}{c}{\head{Input}} &
\multicolumn{1}{c}{\head{Output}}\\

[ 132 ]

Chapter 5

3.

We'll use the \normal command to avoid the typewriter formatting in the header:
& \normal{\head{Command}} & \normal{\head{Declaration}}
& \normal{}\\
\cmidrule(lr){2-3}\cmidrule(l){4-4}

4.

Now we may continue listing the font command names:
Family & textrm&rmfamily & \rmfamily\\
& textsf & sffamily & \sffamily\\
& texttt & ttfamily & \ttfamily\\
\bottomrule[1.5pt]
\end{tabular}
\end{document}

5.

Typeset and look at the result:

What just happened?
Using >{\textbackslash\ttfamily}l defines a left aligned row, where each entry is
preceded by a backslash and by switching to typewriter font. We wrote *2{…} to define two
columns of this style. Because the example text has been inserted according to our table
definition with <{…}, we just had to put the declarations into the last column without the
text.

Spanning entries over multiple rows
We already know how to span text over several columns. But what if text should cross over
several rows? LaTeX doesn't define a command for it. However, the package multirow does.

[ 133 ]

Creating Tables and Inserting Pictures

Time for action – merging cells using the multirow package
Before we complement the font table, we would like to center the command type "Family"
vertically, that is, span this cell over three columns. If we figured this out, we could use it
later on:

1.

In our previous example, additionally load multirow:
\usepackage{multirow}

2.

Replace the word «Family»:
\multirow{3}{*}{Family} & textrm & rmfamily & \rmfamily & \\

3.

Typeset to see the small change:

What just happened?
We used the command \multirow to span three rows. Its definition is:
\multirow{number of rows}{width}{entry text}

The entry will span that number of rows from the row on which \multirow has been used.
If the number is negative, it will span the rows above.
You can specify a width or just write * for the natural width. If a width has been specified,
the text would be wrapped accordingly.
multirow understands further optional arguments for fine tuning. They are described in

its documentation.

Adding captions to tables
Especially with longer text, we would like to add captions and numbers to our tables.
Numbering the tables allows referring to them, whereas captions are informative, if the
table is not exactly placed where we refer to it. LaTeX has built-in features to achieve that.

[ 134 ]

Chapter 5

Time for action – adding a caption to our font table
Now it's time to complete our table. We shall list the remaining font commands. We'll use
the first column to describe the category of the font commands: Family, Weight, Shape, and
so on. Then we will add another column to show the effect of combining font commands.
To finish, we shall center the table and provide a number and a caption:

1.

Put a table environment around our example table, use \centering inside, and
insert a \caption command at the end of the table environment. Add more font
commands and add another column at the right containing more examples:
\documentclass{article}
\usepackage{array}
\usepackage{booktabs}
\usepackage{multirow}
\newcommand{\head}[1]{\textnormal{\textbf{#1}}}
\newcommand{\normal}[1]{\multicolumn{1}{l}{#1}}
\pagestyle{empty}
\begin{document}
\begin{table}
\centering
\begin{tabular}{@{}l*2{>{\textbackslash\ttfamily}l}%
l<{Example text}l@{}}
\toprule[1.5pt]
& \multicolumn{2}{c}{\head{Input}}
& \multicolumn{2}{c}{\head{Output}}\\
& \normal{\head{Command}} & \normal{\head{Declaration}}
& \normal{\head{Single use}} & \head{Combined}\\
\cmidrule(lr){2-3}\cmidrule(l){4-5}
\multirow{3}{*}{Family} & textrm & rmfamily & \rmfamily & \\
& textsf & sffamily & \sffamily& \\
& texttt & ttfamily & \ttfamily& \\
\cmidrule(lr){2-3}\cmidrule(lr){4-4}
\multirow{2}{1.1cm}{Weight} & textbf & bfseries & \bfseries
& \multirow{2}{1.8cm}{\sffamily\bfseries Bold and sans-serif} \\
& textmd & mdseries & \mdseries & \\
\cmidrule(lr){2-3}\cmidrule(lr){4-4}
\multirow{4}{*}{Shape} & textit & itshape & \itshape & \\
& textsl & slshape & \slshape &
\multirow{2}{1.8cm}{\sffamily\slshape Slanted and sans-serif}\\
& textsc & scshape & \scshape & \\
& textup & upshape & \upshape & \\
\cmidrule(lr){2-3}\cmidrule(lr){4-4}
Default & textnormal & normalfont & \normalfont & \\
\bottomrule[1.5pt]
\end{tabular}
\caption{\LaTeX\ font selection}
\end{table}
\end{document}
[ 135 ]

Creating Tables and Inserting Pictures

2.

Typeset and our table is now ready:

What just happened?
We put the tabular environment in a table environment. It's used in this way together
with the \caption command:
\begin{table}[placement options]
table body
\caption{table title}
\end{table}

The table environment is a so-called floating environment. Unlike normal text, they might
appear somewhere else other than what is defined by their position in the source code. The
optional placement argument determines where the table might appear. However, LaTeX
decides it. We shall discuss this at the end of this chapter together with the placement of
graphics.
\caption understands an optional argument as well: if you write \caption[short
text]{long text}, then short text will appear in a list of tables and long text

in the document body. That's useful if you need very long descriptive captions.
Tables are automatically numbered.

Placing captions above
In typesetting, it's very common to place captions above the tables instead of below. This can
be achieved by writing \caption before the table body. However, LaTeX expects caption to
always be below, resulting in a cramped look to the table. There's too little space between
the caption and the following table. You might wish to add some space, for instance, by
entering \vspace{10pt} directly after a top caption.
[ 136 ]

Chapter 5

Remember booktabs? If you begin tables with \toprule, just specify the length
\abovetopskip, for example:
\setlength{\abovetopsep}{10pt}

By putting this line into your preamble, 10pt space would be added below the caption and
above the top line of the table.

Have a go hero – customizing captions
By default, the captions look like normal body text; there's no visual difference. Would you
like to have a slight change in font size, a different formatting of the label, some margins or
indentation, or any other customization? The caption package is the answer to most needs.
By using a few options, you could enhance the visual appearance of all of your captions. Try:
\usepackage[font=small,labelfont=bf,margin=1cm]{caption}

This way, your captions will be smaller than normal text, the label with number will be
bold, and it will not be as wide as normal text. The package offers a lot of features, both for
document wide settings and fine-tuning. It's very well documented. So, have a look at its
documentation.

Auto-fitting columns to the table width
l, c, and r columns have the width of their content. For p columns, you specify the width.

This way, it's hard to find out the actual width of the table. Wouldn't it be a good idea to
specify the table width and let LaTeX decide how wide the columns may be? The tabularx
package allows that. Using it looks like:
\usepackage{tabularx}
...
\begin{tabularx}{width}{column specifiers}
...
\end{tabularx}

The new environment tabularx requires an additional argument: the width of the table. It
introduces a new column type X. X columns behave like p columns, but they use all available
space. One X column would take all of the available space. If you use several X columns, they
would share the space equally. So you could write, for instance:
\begin{tabularx}{0.6\textwidth}{lcX}

This way you would get a table occupying 60 percent of the text width, a left aligned and a
centered column as wide as their content, and a paragraph column as wide as possible until
60 percent is reached.
[ 137 ]

Creating Tables and Inserting Pictures

Though it's easy to use, the tabularx documentation gives further examples, informs about
the derived types, and gives advice like this: don't let \multicolumn entries cross any X
column.
There are two similar approaches:
‹‹

LaTeX provides a starred version of the tabular environment:
\begin{tabular*}{width}[position]{column specifiers}

The table is set to width, but by modifying the inter-column space. tabularx has
been developed satisfying the need for a more useful way.
‹‹

The tabulary package provides another sophisticated tabular environment taking
the total width. It's weighting each column width according to the natural width of
the widest cell in the column.

Generating multi-page tables
All tabular environments we've got to know until now cannot cross page boundaries.
The tabbing environment is an exception due to its different nature.
As tables might contain a lot of data, we need a solution. There are several packages:
‹‹

longtable provides an environment with the same name that's like a multi-page
version of tabular. It provides commands to set table captions, continued
captions, and special headers and footers when a page break occurs. It's probably
the easiest way for multi-page tables and therefore the most popular. The package
documentation describes all you need. In combination with the booktabs package,
you will get very good results.

‹‹

ltxtable provides a combination of longtable and tabularx.

‹‹

ltablex is another approach to combine the features of longtable and tabularx.

‹‹

supertabular offers another multi-page extension of the internally used tabular
environment, providing optional table tails and heads where page breaks occur.

‹‹

xtab extends supertabular and reduces some of its weaknesses.

‹‹

stabular implements a simple way to use page breaks in tabular without
much ado.

Example tables and links to documentation can be found at
http://texblog.net/beginners-guide/tables/.

[ 138 ]

Chapter 5

Coloring tables
We didn't even color text yet, as this usually isn't what we do first with LaTeX. But of course,
this can be done with text as well as with tables. For coloring text, use the color package
or, better, the extension xcolor. For coloring tables, use the package colortbl. All can be
combined by using:
\usepackage[table]{xcolor}

The package allows coloring columns, rows, single entries, and lines in many ways. The
package documentation may tell you more.

Using landscape orientation
Very wide tables could be typeset in landscape orientation. The rotating package offers an
environment called sidewaystable that you could use instead of the table environment.
Both table and caption would be rotated +-90 degrees and placed on a separate page. The
package provides further rotation-related environments and commands.

Aligning columns at the decimal point
Columns containing numbers are more readable when the entries are aligned at the
decimal marker and perhaps at an exponent. Several packages support this:
‹‹

siunitx is primarily intended for typesetting values with units in a consistent way
according to scientific conventions. However, it provides a tabular column type
for such decimal alignment of numbers.

‹‹

dcolumn offers a column type for aligning at a comma, a period, or another single
character.

‹‹

rccol defines a column type where numbers are "right-centered", that is, they are
centered with respect to other entries but flushed right to each other. This way
corresponding digits are aligned along the column.

In contrast to dcolumn and rccol, the siunitx package is very new and powerful.

Handling narrow columns
Text in very narrow columns might require special attention because justification is difficult
if there's little space. Here's some advice:
‹‹

Have a look at the correct hyphenation. If necessary, improve it like we did in
Chapter 2.

[ 139 ]

Creating Tables and Inserting Pictures
‹‹

TeX doesn't hyphenate the first word of a line, a box, or a table entry. So, a long
word may cross the column boundary. To enable hyphenation, insert an empty
word: write \hspace{0pt} directly at the beginning.

‹‹

Load microtype to improve justification, it shows the best effect in narrow
columns.

‹‹

Full justification in p columns and the like may look bad because of big gaps.
Consider using >{\raggedright\arraybackslash} for such columns.

‹‹

From the ragged2e package, using the command \RaggedRight can do even
better and doesn't need \arraybackslash.

Pop quiz – tables
1. Which of these environments cannot cross page boundaries?
a. tabular
b. longtable
c.

tabbing

2. If you would like to format one entry different from the specification of its column,
which command may be used?
a. >{…}
b. @{…}
c.

\multirow

d. \multicolumn

Inserting pictures
Documents may not consist of just text and tables. You might wish to include pictures,
diagrams, or drawings made with other programs. The graphicx package is dedicated to this.

Time for action – including a picture
We shall create a short document. Between two paragraphs, we would like to insert a
picture. If there's no picture file available, we will use the demo mode of graphicx:

1.

Begin a new document and load babel and blindtext to print some filler text:
\documentclass[a5paper]{article}
\usepackage[english]{babel}
\usepackage{blindtext}
\usepackage[demo]{graphicx}
[ 140 ]

Chapter 5
\pagestyle{empty}
\begin{document}
\section{Including a picture}
\blindtext

2.

Open a figure environment and declare centering:
\begin{figure}
\centering

3.

Use the command \includegraphics with the filename as the argument:
\includegraphics{test}

4.

Declare a caption, close the figure environment, and end the document with
filler text:
\caption{Test figure}
\end{figure}
\blindtext
\end{document}

5.

Typeset and have a look at the output:

[ 141 ]

Creating Tables and Inserting Pictures

What just happened?
The most important command is \includegraphics. We specified a filename. This file
would be loaded if it exists. Otherwise an error would occur. LaTeX supports the following
file types:
‹‹

PNG, JPG, and PDF if you directly compile to PDF (pdfLaTeX)

‹‹

EPS if you compile to DVI and convert to PS and PDF (traditional LaTeX)

To clarify, PS means PostScript, EPS means Encapsulated PostScript, and DVI means Device
Independent Format. The latter was the first output format to be supported by TeX. You
definitely know the very popular picture formats PNG and JPG, often used for screenshots
or photos.
You don't need to specify a filename extension, it will be automatically added. Put the file
into the same directory as your document; otherwise specify a full or relative path name:
\includegraphics{appendix/figure1}

Don't use blanks in the filename or path! Blanks and special characters may cause problems
with \includegraphics. If such symbols in filenames are required, load the package
grffile to try to fix it. Also, in filenames, use slashes / instead of backslashes \, as the latter
begin a LaTeX command.
Because we specified the demo option, graphicx doesn't require a file test.png or any other
file; instead it's just printing a black filled rectangle. This is useful for testing or if you would like
to discuss a LaTeX problem in an online forum, but don't wish to publish your pictures.
Go ahead; copy a picture of your choice into your document directory, give
\includegraphics its filename, and compile. The picture will be embedded with
its original size.

Scaling pictures
You may choose a different size. For this, let's look at the definition of includegraphics:
\includegraphics[key=value list]{file name}

The graphicx documentation lists all keys and possible values. Here are the most
popular ones:
‹‹

width: The graphic would be resized to this width. Example: width=
0.9\textwidth.

‹‹

height: The graphic would be resized to this height. Example: height=3cm.

‹‹

scale: The graphic would be scaled by this factor. Example: scale=0.5.

‹‹

angle: The graphic would be turned by this angle. Example: angle=90.
[ 142 ]

Chapter 5

There are options for clipping, but such post processing can be easily done with any graphics
software.
Instead of turning a figure by 90 degrees, you could use the sidewaysfigure environment of
the rotating package. It's analogous to sidewaystable that has been mentioned before.

Choosing the optimal file type
If you've got the final picture, well, just use this format and include it. However, if you are
free to choose a file format, you could think about it for a moment.
EPS and PDF are both vector graphics format. They are scalable, also looking good at high
resolution or if you zoom in. So, whenever possible, PDF (or EPS) should be preferred, for

instance, when you export drawings or diagrams out of other office software. For such
graphics, vector formats are common.

PNG and JPG are bitmap formats, also called raster graphics, commonly used for photos. If
you zoom in, you would notice a loss of quality. PNG uses a lossless compression, whereas
JPG pictures may lose quality when they are saved. So, if you make screenshots, use PNG or
at least ensure that there's no loss compression if you choose JPG.

Besides supporting vector graphics, both EPS and PDF may contain bitmap
graphics. They are also called container formats.

There are a lot of tools to convert between graphic formats. These three are especially useful
and included in both TeX Live and MiKTeX:
‹‹

dvips converts DVI files to the PostScript format

‹‹

ps2pdf converts PostScript files to PDF

‹‹

epstopdf converts EPS files to PDF, a package with the same name does it on-the-fly

These are command line tools. Some editors like TeXnicCenter use them to automate the
way TEX => DVI => PS => PDF.
epstopdf is especially useful if you have to include Postscript pictures, but wish to benefit
from pdfLaTeX features like font expansion and character protrusion accessible by
microtype.
For further working with graphics, ImageMagick and GIMP are very capable open
source programs.

[ 143 ]

Creating Tables and Inserting Pictures

Including whole pages
How can we include pictures wider or higher than the text area? \includegraphics
could do it, but LaTeX would complain about width or size and might put it off to the next
page. Oversized images and even whole pages can be included using the pdfpages package.
It provides a command, \includepdf, which is able to include a complete page and
even a multi-page PDF document at once. Despite its name and not even mentioned in its
otherwise good documentation, it's capable of including PNG and JPG files, not just PDF.
pdfpages could also be used to resize several PDF pages and to arrange them on a

single sheet.

Putting images behind the text
Do you need watermarks? Background images? Textboxes positioned at arbitrary positions
on the page, preferably not interfering with the other text? The package eso-pic does it
for you.
Another approach is offered by the textpos package, developed for placing boxes with text
or graphics at absolute positions on a page.

Managing floating environments
When a page break occurs, normal text can be broken to continue on the next page.
However, pictures cannot be divided. Simple tables cannot be split either. That's why LaTeX
provides two floating environments, namely, figure and table. They are briefly called
floats. Their content may float to a place where it's the optimum for the page layout. Let's
figure out how to deal with it.

Time for action – letting a figure float
Both the figure and the table environment take an optional argument affecting the final
placement of the figure or the table. We shall test the effect in our graphics example:

1.

Go back to the previous example. This time, add the options h and t:
\begin{figure}[ht]
\centering
\includegraphics{test}
\caption{Test figure}
\end{figure}

[ 144 ]

Chapter 5

2.

Typeset, notice the change in the output.

3.

Change the options into !b:
\begin{figure}[!b]

4.

Typeset, the figure is now forced to float to the bottom. Compare both results:

What just happened?
Just by adding some characters standing for placement options, we could force the figure to
appear where we wanted it to.

Understanding float placement options
The optional argument of the figure and table environment tells LaTeX where it's allowed
to place the figure or the table. Four letters stand for four possible places:
‹‹

h stands for here. The float may appear where it's been written in the source code.

‹‹

t stands for top. Placing at the top of a page is permitted.

‹‹

b stands for bottom. The float may appear at the bottom of a page.

‹‹

p stands for page. The float is allowed to appear on a separate page, where only

floats may reside but no normal text.

[ 145 ]

Creating Tables and Inserting Pictures

A fifth option might come in handy:
‹‹

! tells LaTeX to try harder! Some constraints may be ignored, easing the placement.

If you don't specify any option, the float could be placed far away. New LaTeX users might
be surprised. Specifying more options would help to place it as near as possible. The most
flexible is using the placement [!htbp], allowing a float everywhere. You still could consider
removing a placement specifier if you don't like it.

Forcing the output of floats
If you would like to stop LaTeX from putting the floats, there's a way; the \clearpage
command ends the current page and causes all already defined figures and tables to be
printed out. You can use \cleardoublepage that does the same but in a two-sided layout
it ensures that the next non-float page is a right-hand page. . If necessary, a blank page
would be inserted.
Immediately ending the page might not be the best thing to do. It could leave a lot of empty
space on the current page. The afterpage package offers a clever possibility; this package
allows deferring the execution of \clearpage until the current page has ended:
\usepackage{afterpage}
...
body text
\afterpage{\clearpage}

Limiting floating
It may happen that tables and figures float far away, perhaps even into another section. The
placeins package provides a useful command to restrict the floating. If you load placeins
with \usepackage{placeins} and write \FloatBarrier somewhere in your document,
no table or figure could float past it. This macro keeps floats in their place.
A very convenient way to prevent floats from crossing section boundaries is stating the
section option:
\usepackage[section]{placeins}

This option causes an implicit \FloatBarrier to be used at the beginning of each section.
Two further options, namely, above and below, allow you to lower the restrictions,
preventing floats from appearing above the start of the current section or below the start
of the next section.
Figures don't float into the next chapter because \chapter implicitly uses \clearpage.
[ 146 ]

Chapter 5

Avoiding floating at all
Would you like to place a float exactly where you want it? The obvious answer is: don't use
a floating environment! Even a caption doesn't have the same importance if the table or
figure is placed at the current point. However, if you really need a caption, you may use the
\captionof command without a float. Both the caption package , KOMA-Script classes,
and the tiny capt-of package provide that command:
\usepackage{capt-of}% or caption
…
\begin{center}
\begin{minipage}{\linewidth}%
\centering%
\includegraphics{test}%
\captionof{figure}{Test figure}%
\end{minipage}
\end{center}

The minipage keeps a picture and caption together. Furthermore, it's centered. Use
\captionof within a group or environment like minipage or center. The definition is
the same as \caption, except there is the additional argument specifying the float type:
\captionof{figure}[short text]{long text}
\captionof{table}[short text]{long text}

Be aware that the numbering could get wrong if you mix real floats and fixed figures or
tables. As you don't benefit from LaTeX's positioning capabilities, you have to take care that
pages are still properly filled.
The float package provides a convenient and consistent looking approach. It introduces the
placement option H causing the float to appear right there:
\usepackage{float}
…
\begin{figure}[H]
\centering
\includegraphics{test}
\caption{Test figure}
\end{figure}

You may choose between these two options. If you wish to exploit further features of
the float package, load it. Otherwise, consider using the one-liner capt-of. Perhaps
not even that is necessary, assuming that you're already using the caption package or
a KOMA-Script class.

[ 147 ]

Creating Tables and Inserting Pictures

Spanning figures and tables over text columns
There are starred forms of floats, namely, figure* and table*. In a two-column layout,
they put the float into a single column. In one-column mode, there's no difference to the
non-starred form.

Letting text flow around figures
Though it's a bit playful, you might wish to let text flow around a table or a figure. This can
be achieved using the wrapfig package and its environments wrapfigure and wraptable.

Time for action – embedding a picture within text
We shall modify our picture embedding an example. We would like the picture to appear on
the left side, accompanied by the body text on the right side:

1.

In our example, additionally load the wrapfig package:
\documentclass[a5paper]{article}
\usepackage[english]{babel}
\usepackage{blindtext}
\usepackage[demo]{graphicx}
\usepackage{wrapfig}
\pagestyle{empty}
\begin{document}

2.

Begin an unnumbered section, place a wrapfig environment within some filler
text:
\section*{Text flowing around a picture}
\blindtext
\begin{wrapfigure}{l}{4.4cm}
\includegraphics[width=4.4cm]{test}
\caption{Test figure}
\end{wrapfigure}
\blindtext
\end{document}

[ 148 ]

Chapter 5

3.

Typeset and look:

What just happened?
The wrapfigure environment understands parameters other than the figure
environment. We used just two of them. If you need more, here's the complete definition:
\begin{wrapfigure}[number of lines]{placement}[overhang] {width}

The first optional argument states the number of wrapped text lines. If omitted, it would be
automatically calculated from the height. placement can be one of the characters r, l, i, o
for right, left, inner, or outer side or the corresponding uppercase letters R, L, I, O with the
same meaning, but allowing the figure to float. Only one character for specifying the option
is allowed. The other optional argument, overhang, may specify a width that the figure
might stick into the margin. The final and mandatory argument gives the width of the figure.
The wraptable environment works analogous.

[ 149 ]

Creating Tables and Inserting Pictures

Breaking figures and tables into pieces
For grouping several sub figures or sub tables with captions within a single figure or table,
there are several supporting packages you can choose from:
‹‹

subfig is a sophisticated package supporting inclusion of small figures and tables.
It takes care of positioning, labeling, and captioning within single floats.

‹‹

subcaption is another package for this purpose and belongs to the
caption package.

‹‹

subfigure is still available, but considered as obsolete since subfig has appeared.

Pop quiz – pictures and floats
1. This chapter listed all graphic formats supported by LaTeX. Now, identify from the
following file types which is not directly supported by LaTeX!
a. jpg
b. gif
c.

png

d. eps
e. pdf
2. If you would like a figure or a table to float but to appear as near as possible to its
source, which of the following float placement options would be appropriate?
a. h
b. H
c.

htbp

d. !htbp

Summary
In this chapter, we have learned to create tables and figures, and how to place them within
our document. Specifically, we dealt with:
‹‹

Putting text into columns

‹‹

Typesetting tables with captions

‹‹

Spanning columns and rows in tables

‹‹

Using packages to auto-fit columns and to create colored, landscape, and even
multi-page tables
[ 150 ]

Chapter 5
‹‹

Including pictures with captions

‹‹

Controlling and tuning placement of figures and tables

LaTeX is able to generate lists of tables and figures like a table of contents. We shall deal
with such lists in Chapter 7, Listing Contents and References.
As our figures and tables are numbered, we can use these numbers to refer to them within
the text. In the next chapter, we shall figure out how to do this, benefitting from LaTeX's
cross-referencing capabilities.

[ 151 ]

6

Cross-Referencing
Our documents contain a lot of numbered things such as pages, sections, list
items, figures, and tables. There's even more we have not covered yet. For
instance, if you would like to write a mathematical text, you may number
equations, theorems, definitions, and many more.
We number things not just to count them, but to refer to them in other places
of our document. If you want to point the reader to the ninth figure in the third
chapter, you might write "See figure 3.9". LaTeX automatically enumerates the
figures for you. If you insert another figure, LaTeX will automatically adjust the
numbering of all figures after it. But what's with the references?

LaTeX is able to take care of all of our cross-references. This is the subject of this chapter.
We shall learn how to:
‹‹

Set labels that we shall use to refer to

‹‹

Refer to sections, footnotes, list items, tables, and more

‹‹

Refer to page numbers and ranges

‹‹

Make LaTeX refer verbosely to adjacent pages

‹‹

Automate naming of references

‹‹

Create references to external documents

Let's figure out how to do all this.

Cross-Referencing

Setting labels and referencing
To be able to refer to a certain point, we have to mark it by a label. The name of that label
will serve us afterwards.

Time for action – referencing items of a top list
We shall typeset a list of the most used packages for papers on the e-print archive site
http://arXiv.org. Through the command \label, we will mark items that we can
later refer to with the command \ref.

1.

Create a new document with this code:
\documentclass{book}
\begin{document}
\chapter{Statistics}
\section{Most used packages on arXiv.org}\label{sec:packages}
The Top Five packages, used on arXiv.org\footnote{according
to the arXMLiv project\label{fn:project}}:
\begin{enumerate}
\item graphicx
\item amssymb \label{item:amssymb}
\item amsmath \label{item:amsmath}
\item epsfig
\item amsfonts
\end{enumerate}
\chapter{Mathematics}
\emph{amsmath}, on position \ref{item:amsmath} of the top list
in section~\ref{sec:packages} on page~\pageref{sec:packages},
is indispensable to high-quality mathematical typesetting in
\LaTeX.\emph{amssymb}, on position \ref{item:amssymb},
provides a huge amount of math symbols.
See also the footnote on page~\pageref{fn:project}.
\end{document}

2.

Typeset and have a look at the text on page 3:

[ 154 ]

Chapter 6

3.

Do you see the question marks? The references are still missing! Typeset again
and compare:

What just happened?
We created cross-references with just three commands: \label marks the position, \ref
prints the number of the element we refer to, and \pageref prints the page number of
that element. Each command takes the name of the element as argument. Any name may
be chosen by us.
We had to Typeset twice because LaTeX needs one run to produce the references that can
be read in during the next compiler run. If LaTeX cannot resolve a reference, it prints two
question marks instead.
Let's have a closer look.

Assigning a key
The command \label{name} assigns the current position to the key name. Specifically:
‹‹

If the \label command appeared in ordinary text, then the current sectional unit,
like the chapter or the section, would be assigned.

‹‹

If the \label would be placed within a numbered environment, that environment
would be assigned to the key.

So, we cannot mark a section within a table environment. To avoid any problem because of
a possible unsuitable positioning, a good rule of thumb is to place the \label command
right after the position we would like to mark. For instance, place it directly after the
corresponding \chapter or after \section—not before, of course.
In the figure or table environments, \caption is responsible for the numbering. That's
why \label has to be placed after \caption, not before. Therefore, typical floating
environments look like the following:
\begin{figure}[htp]
\centering
\includegraphics{filename}
\caption{Test figure}\label{fig:name}
\end{figure}

[ 155 ]

Cross-Referencing

Or as follows:
\begin{table}[hbp]
\centering
\caption{table descripion}\label{tab:name}
\begin{tabular}{cc}
…
\end{tabular}
\end{table}

A key may consist of letters, digits, or punctuation characters. Keys are case-sensitive.
If you write larger documents, the number of keys could become very high. Imagine, you
have a section dealing with fonts and a font table—how to distinguish their keys? We could
prefix them with the type of environment. It has become common practice to label figures
with fig:name, tables with tab:name, sections with sec:name, and similar in other cases.

Referring to a key
Once a label has been set and given a name, we may refer to that name. For this, we use
\ref{name}: this command prints the number that belongs to name. It could already be
used before the corresponding \label command appears in your code.
Even though it's that simple, it's powerful. Each time we Typeset a document, LaTeX checks
the keys and reassigns the numbers, responding to all changes. If LaTeX noticed that labels
have been changed, it would inform you that a second Typeset run would be required to
update the corresponding labels. If in doubt Typeset twice.

Referring to a page
The command \pageref{name} works analogous to \ref, except that it prints the
corresponding page number.
Would all the references stay correct if we changed the section and page numbers?
Let's put it to the test! Insert a section and a page break at the beginning:
\chapter{Statistics}
\section{Introduction}
\newpage
\section{Most used packages on arXiv.org}\label{sec:packages}

Typeset once. LaTeX will compile it, but it will show a message: LaTeX Warning: Label(s) may
have changed. Rerun to get cross-references right. That's what we shall do! Typeset a second
time, now all the numbers have been correctly adjusted:

[ 156 ]

Chapter 6

Using a reference together with the page number reference, you may write:
See figure~\ref{fig:name} on page~\pageref{fig:name}.

As you know how to define a command, you could make such referencing easier:
\newcommand{\fullref}[1]{\ref{#1} on page~\pageref{#1}}
…
See figure~\fullref{fig:name}.

This way, you would get a full reference like "See figure 4.2 on page 32". However, if the
reference appears on the same page, like the figure, writing out the page number looks
a bit odd. How can we avoid that? The varioref package provides a way.

Producing intelligent page references
The varioref package offers a command being able to add "on the preceding page", "on
the following page", or on the page number to a reference, depending on the context.

Time for action – introducing variable references
We will use the varioref commands, \vref and \vpageref, to achieve enhanced
reference texts:

1.

Open our current example. Add the package varioref to your preamble:
\usepackage{varioref}

2.

Edit the content of the second chapter:
\emph{amsmath}, on position \ref{item:amsmath} of the top list
in section~\vref{sec:packages}, is indispensable to high-quality
mathematical typesetting in \LaTeX. \emph{amssymb}, on position
\ref{item:amssymb}, provides a huge amount of math symbols.
See also the footnote \vpageref{fn:project}.

[ 157 ]

Cross-Referencing

3.

Typeset twice and look at the result:

What just happened?
The command \vref checked the distance to the referenced section. As it's on the facing
page, that is, on the preceding page in a two-sided layout, it wrote "1.2 on the facing page".
Similar for \vpageref, it refers to "the preceding page".
\vref{name} acts in the following way:
‹‹

If the reference and \label{name} are on the same page, it behaves exactly
like \ref. The page number will not be printed.

‹‹

If the reference and the corresponding \label are on two successive pages, \vref
prints the referred number and additionally "on the preceding page" or "on the
following page", or "on the facing page". The latter will be chosen if the document
is two-sided, that is, if \label and the reference fall onto a double-page spread.

‹‹

Otherwise it will print both \ref and \pageref.

\vpageref is equivalent to \pageref, but behaves like \vref concerning the page

reference.

Even though varioref defines new commands, you may still use the common \ref
and \pageref.

Fine-tuning page references
If label and reference are very close to each other, they would probably fall on the same
page, but not necessarily. In such cases, we usually know if the label comes before or after
the reference. It allows specifying an optional argument to \vpageref:
see the figure \vpageref[above]{fig:name}

This will print:
‹‹

"see the figure above" if the figure is on the same page

‹‹

"see the figure on the page before" if the figure is on the preceding page

[ 158 ]

Chapter 6

Whereas, with the following:
see the footnote \vpageref[below]{fn:name}

This will print:
‹‹

"see the footnote below" if the footnote is on the same page

‹‹

"see the footnote on the following page" if the footnote is on the next page

In fact, \vpageref understands two optional arguments. The second optional argument
would be used if the label and reference would fall on different pages. So, we could even
write:
see the figure \vpageref[above figure][figure]{fig:name}

This would print:
‹‹

"see the above figure" if the figure is on the same page

‹‹

"see the figure on the page before" if the figure is on the preceding page

Actually, reversing the word order to "above figure" if necessary.
Sounds complicated? Well, your demands might increase over time, requiring more
sophisticated features, so these features might come in handy some day.

Referring to page ranges
varioref offers two more commands:
‹‹

\vpagerefrange[opt]{key1}{key2}, where key1 and key2 denote a range
(like a sequence of figures from fig:a to fig:c). If both labels fall onto the same
page, the result is the same as with \vpageref. Otherwise, the output will be a
range like "on pages 32-36". opt would be used if both labels fall onto the current

page.
‹‹

\vpageref [opt]{key1}{key2}is analogous, but similar to \vref: see
figures \vpageref{fig:a}{fig:c} may result in "see figures 4.2 to 4.4 on

pages 36-37".

\vref, \vpageref, and \vpagerefrange have been implemented to remove any space to
their left before they insert space of their own. For example, \vref inserts a nonbreakable
space like we did before with ~. If this is not desired, use starred forms \vref*, \
vpageref*, or \vpagerefrange*.

More information regarding customization may be found in the package manual.

[ 159 ]

Cross-Referencing

Using automatic reference names
Tired of writing figure~\ref{fig:name} and table~\ref{fig:name}again and
again? Wouldn't it be great if LaTeX knew what type is meant by \ref{name} writing type
and number? What if we desire to abbreviate, say, fig.~\ref{fig:name}in the whole
document? The cleverev package eases the work: it automatically determines the type of
cross-reference and the context in which it's used.
Basically, you could just use \cref instead of \ref or \Cref if you wish to capitalize.
The corresponding range commands are \crefrange and \Crefrange.

Time for action – referring cleverly
We shall rewrite our first example using cleveref. To verify that the package acts cleverly,
we consciously omit prefixes in key names to \label and \cref.

1.

Modify our first example in this way:
\documentclass{book}
\usepackage{cleveref}
\crefname{enumi}{position}{positions}
\begin{document}
\chapter{Statistics}\label{stats}
\section{Most used packages on arXiv.org}\label{packages}
The Top Five packages, used on arXiv.org\footnote{according
to the arXMLiv project\label{project}}:
\begin{enumerate}
\item graphicx
\item amssymb \label{amssymb}
\item amsmath \label{amsmath}
\item epsfig
\item amsfonts
\end{enumerate}
\begin{table}[tp]
\centering
(Identify obsolete packages on CTAN)
\caption{Obsolete packages}\label{obsolete}
\end{table}
\chapter{Mathematics}
\emph{amsmath}, on \cref{amsmath} of the top list in
\cref{packages} of \cref{stats}, is indispensable to high-quality
Mathematical typesetting in \LaTeX. \emph{amssymb}, on
\cref{amssymb}, provides a huge amount of math symbols.
[ 160 ]

Chapter 6
\Cref{obsolete} shows obsolete and outdated packages that
should be avoided. See also the \cref{project}.
\end{document}

2.

Typeset twice and check the references for having the correct names:

What just happened?
As we can see, we never needed to specify which object we refer to. \cref always chooses
the right name and the correct number for us. That's really comfortable!
We used the command \crefname to tell cleveref which name it should use for
enumerated items. The definition of \crefname is:
\crefname{type}{singular}{plural}

type may be one of chapter, section, figure, table, enumi, equation, theorem,

or many other types we did not encounter yet. The singular version will be used for
single references and the plural version for multiple. If you need capitalized versions, use
\Crefname. So, a typical use may be:
\crefname{figure}{fig.}{figs.}
\Crefname{figure}{Fig.}{Figs.}

To sum up your benefits:
‹‹

You save much typing.

‹‹

You could use arbitrary labels. The package fancyref does a similar job but relies
on prefixes like chap, fig, tab, and so on.

‹‹

If you decide to change wordings, it could be done easily by doing this once in the
preamble, having the desired effect in the whole document.

However, it's recommended to use a prefix like fig: or sec: to distinguish the kind of
referenced object; your code would become more understandable—it's common.

[ 161 ]

Cross-Referencing

Combing cleveref and varioref
As cleveref fully supports varioref, you may use both to get the most out of them.
cleveref redefines the commands of varioref to use \cref internally. So, you could
use the good page referencing features of varioref together with the clever naming
automatism!
Just load varioref before cleveref:
\usepackage{varioref}
\usepackage{cleveref}

Now, you may use \vref, \cref, \ref, or the other commands—whichever seems
appropriate.

Referring to labels in other documents
If you write several related documents that refer to each other, you might want to
use references to labels of another document. The package with the short name
xr (standing for eXternal References) implements it. First load the package:
\usepackage{xr}

If you need to refer to sections or environments in an external document called, say,
doc.tex, insert this command into your preamble:
\externaldocument{doc}

This enables you to additionally refer to anything that has been given a label in doc.tex.
You may do this for several documents. If you need to avoid conflicts when an external
document uses the same \label like the main document, declare a prefix using the optional
argument of \externaldocument:
\externaldocument[D-]{doc}

This way, all references from doc.tex would be prefixed by D- and you could write
\ref{D-name} to refer to name in doc.tex. Instead of D- you may choose any prefix
that transforms your labels such that they become unique.

Have a go hero – turning references into hyperlinks
PDF documents offer bookmarks and hyperlink capabilities. How about exploiting that
ourselves? There's an outstanding package offering hyperlink support; it's called hyperref.
Try it: load hyperref right before cleveref. This order is important for the references to
work. Even without any options or commands, your document will be hyperlinked as much
as possible:
[ 162 ]

Chapter 6
‹‹

All references become hyperlinks. Click any of those numbers to jump to the
referred table, list item, section, or page.

‹‹

Each footnote marker is a hyperlink to the footnote text. Click it to jump down.

‹‹

If you insert \tableofcontents, you will get a bookmark list for the document,
chapters, and sections listed in a navigation bar of you PDF reader.

hyperref can do even more for you: linking index entries to text passages, back-referencing

of bibliography entries, and more. You can finely customize the behavior using options, for
instance, choosing color or frames for hyperlinks. So, you could keep that valuable package
in mind. In Chapter 11, Enhancing Your Documents Further, we shall return to this topic.

Pop quiz
1. For a reference to a table, at which position should the \label be placed?
a. Before \caption
b. After \caption
c.

After\end{table}

2. What should we do if we see two unexpected consecutive question marks in
the output?
a. Load the hyperref package.
b. Look out for an undefined command. Check the syntax at that point.
c.

Typeset again. If the question marks stay, check the key to the reference
at that point.

Summary
In this chapter, we learned how to reference chapters, sections, footnotes, and environments
by their number or by the number of the corresponding page.
We even got to know some ways of clever and context dependent referencing.
In the next chapter, we shall deal with lists, which consist mainly of references: table of
contents, lists of figures and tables, and bibliographies.

[ 163 ]

7

Listing Content and References
LaTeX makes it very easy to create lists for many purposes. For example, we've
seen that just the simple command \tableofcontents creates a nice looking
table of contents. Let's just call it the TOC from now on. It simply takes the
entries from the headings and from the numbers of the pages they fall on.

In this chapter, we will perform the following:
‹‹

Decide which headings at which numbering level go to the TOC

‹‹

Create and customize a list of figures (LOF) and a list of tables (LOT)

‹‹

Insert arbitrary text and commands into the TOC and into other lists

‹‹

Cite books and create a bibliography

‹‹

Create an index

‹‹

Modify the headings for all those lists

We shall start with the content.

Customizing the table of contents
Besides just calling \tableofcontents to get a pre-designed list of content, LaTeX provides
basic ways to modify it. Let's use some.

Listing Content and References

Time for action – refining an extensive table of contents
We shall build the frame of a document containing some headings. We will modify the
automatically created table of contents to be finer and to contain additional entries.
In Chapter 3, Designing Pages, we saw the effect of \tableofcontents. The entries have
been collected from the headings. We shall use this down to the subsubsection level.
Then we shall extend the TOC further. We will manually add entries for some headings:

1.

Create a new document with the following code:
\documentclass{book}
\setcounter{tocdepth}{3}
\begin{document}
\tableofcontents
\part{First Part}
\chapter*{Preface}
\addcontentsline{toc}{chapter}{Preface}
\chapter{First main chapter}
\section{A section}
\section{Another section}
\subsection{A smaller section}
\subsubsection[Deeper level]{This section has an even deeper
level}
\chapter{Second main chapter}
\part{Second part}
\chapter{Third main chapter}
\appendix
\cleardoublepage
\addtocontents{toc}{\bigskip}
\addcontentsline{toc}{part}{Appendix}
\chapter{Glossary}
\chapter{Symbols}
\end{document}

2.

Typeset. The first page will just show Contents but no entries.

3.

Typeset a second time. Now the table of contents will be displayed:

[ 166 ]

Chapter 7

What just happened?
We structured a document using several sectioning commands. In the first run, LaTeX read
all of our sectioning commands and created a file with the extension .toc. This file contains
the commands and the titles for all entries in the table of contents. During the first run, that
file didn't exist yet, thus the TOC remained empty.
During the second run, the command \tableofcontents read the .toc file and printed
the TOC.
In this example, we raised the depth of the TOC by one level. We added a chapter-like entry
for the preface and inserted a part-like heading showing the beginning of the appendix, using
\addcontentsline. Through \addtocontents, we inserted some space before the latter
heading. Let's look at these commands in detail.

[ 167 ]

Listing Content and References

Adjusting the depth of the TOC
These are the standard sectioning commands and their so called TOC level:
Command
\part

Level

\chapter

0 (not available in article class)

\section

1

\subsection

2

\subsubsection

3

\paragraph

4

\subparagraph

5

-1 (book and report class)

In the book and in the report class, LaTeX creates TOC entries until level 2, in the article
class until level 3. In a book, this means, for example, \subsubsection doesn't generate
a TOC entry. There's a variable representing the level, namely, \tocdepth. It's an integer
variable which we call a counter. To tell LaTeX to include subsubsections in the TOC, we
would have to raise this counter. There are two basic ways to adjust a counter value:
‹‹

\setcounter{name}{n} specifies an integer value of n for the counter name

‹‹

\addtocounter{name}{n} adds the integer value of n to value of the counter
name. n may be negative

Thus, the following command would ensure that even \subparagraph gives a TOC entry:
\setcounter{tocdepth}{5}

Using \addcounter instead you may raise or lower the level without knowing its number.
In contrast to commands, counter names don't begin with a backslash.

Shortening entries

As you have already learned in Chapter 3, you may choose a text for the TOC that's different
to the heading in the body text. Each sectioning command understands an optional
argument for the TOC entry, which is especially useful if you wish to use very long headings,
but a shorter TOC entry would be sufficient. In our example, we did this by:
\subsubsection[Deeper level]{This section has an even deeper level}

[ 168 ]

Chapter 7

The body text shows the long heading while the TOC shows the short one. Running titles in
the headings would use the short entry as well, as the space in headings is very limited.

Adding entries manually
Starred commands like \chapter* and \section* don't produce a TOC entry. In our
example, we did that manually using this command:
\addcontentsline{file extension}{sectional unit}{text}

This command can be used in several contexts: the file extension may be:
‹‹

toc for the table of contents file

‹‹

lof for the list of figures file

‹‹

lot for the list of tables file

Or, any another extension of such a file type known to LaTeX.
The sectional unit determines the formatting of the entry. Specify chapter to create
an entry that's formatted like normal chapter entries and similar for other sectional units like
part, section, or subsection.
The third argument contains the text for the entry. This text may contain commands. Do
you remember the \protect command? For a macro inside the entries, it's usually a good
idea to write \protect right before it.
You may insert text or commands more directly with:
\addtocontents{file extension}{entry}

In contrary to \addcontentsline, the argument entry is written directly to the file
without any additional formatting. You may choose any formatting you like.
This command may even be used for some customization, for example:
‹‹

\addtocontents{toc}{\protect\enlargethispage{\baselineskip}}

extends the text height such that one additional line fits to the contents page.
‹‹

\addtocontents{toc}{\protect\newpage} causes a page break in the TOC.

For instance, if the automatic page break happens after a chapter entry and before
the following section entries, you might wish to force a page break already before
the chapter entry.
‹‹

\addtocontents{toc}{\protect\thispagestyle{fancy}} changes the

page style of the current TOC page to fancy. As the first page of a chapter is of
plain style by default, the first page of the TOC would be plain as well, even if you
specified \pagestyle{fancy}. This command overrides it.
[ 169 ]

Listing Content and References

Place such commands where they should be effective. To affect the first TOC page, place it
at the beginning of your document. To cause a page break before a certain chapter, place it
right before the corresponding \chapter call.

Creating and customizing lists of figures
As briefly mentioned in the previous chapter, the two commands for creating lists of figures
and tables are \listoffigures and \listoftables. Depending on the class, they produce
a fine list of all captions together with the figure respectively the table number and the
corresponding page numbers. As with the TOC, all can be done automatically. However, we
may use the same techniques, like with the TOC, to customize the other lists. Let's try that.

Time for action – creating a list of diagrams
Suppose all of our figures are diagrams. We shall avoid the term figure and we will typeset a
list of diagrams:

1.

Open our current example. Add these lines to your preamble:
\renewcommand{\figurename}{Diagram}
\renewcommand{\listfigurename}{List of Diagrams}

2.

Right after \tableofcontents, add:
\listoffigures

3.

Add a diagram somewhere in Chapter 1:
\begin{figure}
\centering
\fbox{Diagram placeholder}
\caption{Enterprize Organizational Chart}
\end{figure}

4.

In the second part, in the third chapter, we'd like to add network design diagrams.
Let's mark that in the LOF and let the diagrams follow:
\addtocontents{lof}{Network Diagrams:}
\begin{figure}
\centering
\fbox{Diagram placeholder}
\caption{Network overview}
\end{figure}
\begin{figure}
\centering
[ 170 ]

Chapter 7
\fbox{Diagram placeholder}
\caption{WLAN Design}
\end{figure}

5.

Typeset twice to get the document and the list:

What just happened?
We renamed the figures and the list heading by redefining LaTeX macros. At the end of
the chapter, you will get a list of names used by LaTeX classes that you may redefine.
Like with the TOC, we used the command \addtocontents; this time to insert a bold
heading into the .lof file where LaTeX collects the captions. It works similar to the TOC.

Creating a list of tables
You already know all you need to create and customize a list of tables! The file, where LaTeX
collects the captions of the tables, has the extension .lot, and that's why the first argument
of \addtocontents would be lot. Everything works analogous, like \listoftables,
\tablename, and \listtablename.

Using packages for customization
Besides the described simple methods, there are packages providing sophisticated features
for customizing the table of contents and the lists of figures and tables:
‹‹

tocloft gives extensive control over the typography of TOC, LOF, and LOT. You may
even define new kinds of such lists.

‹‹

titletoc offers convenient handling of entries and is the companion to titlesec,
a very good package for customizing sectioning headings.

[ 171 ]

Listing Content and References
‹‹

multitoc offers a layout in two or more columns using the multicol package.

‹‹

minitoc can create small TOCs for each part, chapter, or section.

‹‹

tocbibind can automatically add bibliography, index, TOC, LOF, and LOT to the table
of contents. It's even capable of using numbered headings instead of the default
unnumbered ones.

Let's continue with the announced index and the bibliography.

Generating an index
Extensive documents often contain an index. It is a list of words or phrases and page
numbers pointing to where related material can be found in the document. In contrary
to a full-text search feature, the index provides selective pointers to relevant information.
While it's our turn to identify and to mark the words for the index, LaTeX will collect this
information and is able to typeset the index for us.

Time for action – marking words and building the index
Suppose our example would contain information about an enterprise and its structure and
further about its network structure and design. We shall mark places in the text where these
concepts occur. Finally, we will order LaTeX to typeset the index:

1.

Go back to our example. In the preamble, load the index package and add the
command to create the index:
\usepackage{index}
\makeindex

2.

In the caption of our enterprise diagram, index this point with the keyword
enterprise:
\caption{\index{enterprise}Enterprise Organizational Chart}

3.

In the third chapter, which contains our diagrams, index by the keyword network:
\index{network}

4.

Directly before \end{document}, create an entry for the index for the table of
contents. To ensure that it shows the correct page number, end the page before:
\clearpage
\addcontentsline{toc}{chapter}{Index}

[ 172 ]

Chapter 7

5.

In the next line, order LaTeX to typeset the index:
\printindex

6.

If you're using TeXworks, choose MakeIndex instead of pdfLaTeX in the drop-down
box next to the typeset button. Then click typeset. If you use another editor, use its
MakeIndex feature or type the following at the command prompt in the document
directory:
makeindex documentname

7.

Switch back to pdfLaTeX, Typeset, and look at the last page:

What just happened?
We loaded the index package, which improves LaTeX's built-in indexing capabilities.
Alternatively, you could use the makeidx package which is part of standard LaTeX. The
command \makeindex prepared the index. Both commands must be put into the preamble.
The command \index takes just one argument, namely, the word or the phrase to be
indexed. This will be written to a file with the extension .idx. If you look into this file,
you will find lines like the following:
\indexentry {enterprise}{9}
\indexentry {network}{15}

These stand for the index entries and the corresponding page numbers.
The external program makeindex takes that .idx file and produces an .ind file. The
latter consists of LaTeX code for the index creation. Specifically, it contains the index list
environment together with the items and looks like the following:
\begin{theindex}
\item enterprise, 9
\indexspace
\item network, 15
\end{theindex}
[ 173 ]

Listing Content and References

More complex indexes may contain subitems, page ranges, and references to other items.
Let's see how to produce such an index.

Defining index entries and subentries
We already created simple index entries with:
\index{phrase}

Subentries are produced by specifying the main entry followed by the subentry, separated
by an exclamation mark, for example:
\index{network!overview}

Also subentries may have subentries; just use another ! symbol, for example:
\index{enterprise!organization}
\index{enterprise!organization!sales}
\index{enterprise!organization!controlling}
\index{enterprise!organization!operation}

Up to three levels are possible.

Specifying page ranges
If several pages deal with the same concept, you may specify a page range for the index
entry. Suffix the entry with |( where the range starts and add |) where it ends, as follows:
\index{network|(}

at the beginning of the network chapter and:
\index{network|)}

at the end of this chapter. This results in an entry of the form Network, 15-17.

Using symbols and macros in the index
makeindex sorts the entries alphabetically. If you would like to include symbols in the index,

for example, Greek letters, chemical formulas, or math symbols, you could face the problem
of integrating them into the sorting. For this purpose, \index understands a sort key. Use
this key as prefix for the entry, separated by an @ symbol, for instance:
\index{Gamma@$\Gamma$}

[ 174 ]

Chapter 7

Using macros for index entries is generally not really recommended. Macros would be sorted
according to the macro name including the backslash, though it would be expanded when
the index is typeset. Imagine, you've got a macro \group standing for TeX Users Group. If
you write the following, then the entry TeX Users Group would be treated like \group in the
sorting and won't appear among the entries beginning with T:
\index{\group}

However, you could repair such issues by adding a sort key:
\index{TeX@\group}
\index{schon@sch\"{o}n}

What if you wish to use the symbols |, @, and ! within index entries? Quote them by using
a preceding ":
\index{exclamation ("!)!loud}

And don't worry, " itself may be used within verbatim text as follows:
\index{quote (\verb|""|)}

Referring to other index entries
Different words may stand for the same concept. For such cases, it's possible to add a crossreference to the main phrase without a page number. Adding the code |see{entry list}
achieves that, for example:
\index{network|see{WLAN}}
\index{WLAN}

As such references don't print a page number, their position in the text doesn't matter. You
could collect them in one place of your document.

Fine-tuning page numbers
If an index entry refers to several pages, you might want to emphasize one page number to
indicate it as the primary reference. You could define a command for emphasizing as follows:
\newcommand{\main}[1]{\emph{#1}}

And for the index entry, add a pipe symbol and the command name:
\index{WLAN|main}

[ 175 ]

Listing Content and References

Thus, the corresponding page number would be emphasized. Simply writing
\index{WLAN|emph} or \index{WLAN|texbf} is possible as well. However, defining
your own macro is more consistent—remember the concept of separating form and content.

Designing the index layout
If we extend our example document with the aforementioned example commands,
\printindex gives us this layout, containing subentries, ranges, references, and
emphasized entries:

LaTeX provides some index styles called latex (the default), gind, din, and iso. To use
another style, specify it using the –s option of the makeindex program, for example:
makeindex –s iso documentname

If you typeset after this call, the index layout would be changed to:

[ 176 ]

Chapter 7

You could even define your own styles. To learn more about indexing and makeindex, use
texdoc at the command prompt:
texdoc index
texdoc makeindex

Though it seems natural to generate the index while writing the
document, this might lead to inconsistencies in the index. It's
recommendable first to finish writing and afterwards to work out what
should appear in the index.

Creating a bibliography
Especially in scientific documents, a list of references or bibliography is very common.
We shall work out how to typeset a bibliography and how to refer to its entries.

Time for action – citing texts and listing the references
Using LaTeX's standard features, we shall create a small list of references containing a book
and an article by Donald E. Knuth, the creator of TeX. In our body text, we will refer to both:

1.

Create a new document as follows:
\documentclass{article}
\begin{document}
\section*{Recommended texts}
To study \TeX\ in depth, see \cite{DK86}. For writing math texts,
see \cite{DK89}.
\begin{thebibliography}{8}
\bibitem{DK86} D.E. Knuth, \emph{The {\TeX}book}, 1986
\bibitem{DK89} D.E. Knuth, \emph{Typesetting Concrete
Mathematics}, 1989
\end{thebibliography}
\end{document}

[ 177 ]

Listing Content and References

2.

Typeset and view the output:

What just happened?
We used an environment called thebibliography to typeset the list of references, which is
similar to a description list as we've seen in Chapter 4, Creating Lists. Each item of this list
has got a key. For citing in the body text, we referred to that key using the \cite command.
Let's look at these commands in detail.

Using the standard bibliography environment
LaTeX's standard environment for bibliographies has the following form:
\begin{thebibliography}{widest label}
\bibitem[label]{key} author, title, year etc.
\bibitem…
…
\end{thebibliography}

Each item is specified using the command \bibitem. This command requires a mandatory
argument determining the key. We may simply refer to this key by \cite{key} or
\cite{key1,key2}. \cite accepts an optional argument stating a page range, for
example, \cite[p.\,18--20]{key}. You may choose a label by the optional argument
of \bibitem. If no label has been given, LaTeX will number the items consecutively in
square brackets, as we've seen.
Using labels, the environment could look as follows:
\begin{thebibliography}{Knuth89}
\bibitem[Knuth86]{DK86} D.E. Knuth, \emph{The {\TeX}book}, 1986
\bibitem[Knuth89]{DK89} D.E. Knuth, \emph{Typesetting Concrete
Mathematics}, 1989
\end{thebibliography}

[ 178 ]

Chapter 7

And the output would then be as follows:

As you can see, the output of \cite has been automatically adjusted to the new labels.
The cite package offers compressed and sorted lists
of numerical citations, like [2,4-6], and further
formatting options for in-text citations.

The mandatory item of the environment should contain the widest label for the alignment
of the items. So, for instance, if you have more than 9 but fewer than a 100 items, you may
write two digits into the argument.

Using bibliography databases with BibTeX
Manually creating the bibliography is laborious. Especially, if you use references in
several documents, it would be beneficial to use a database and let a program create
the bibliography for you. This sounds more complicated than it really is. We will try this.

Time for action – creating and using a BibTeX database
We shall create a separate database file containing the references of our previous example.
We will modify our example to use that database. To make this database usable, we have to
call the external program BibTeX:

1.

Create a new document. Begin with writing the entry for the TeXbook:
@book{DK86,
author = "D.E. Knuth",
title = "The {\TeX}book",
publisher = "Addison Wesley",
year = 1986
}

[ 179 ]

Listing Content and References

2.

For the next entry, that is, the article, we will specify even more fields:
@article{DK89,
author = "D.E. Knuth",
title = "Typesetting Concrete Mathematics",
journal = "TUGboat",
volume = 10,
number = 1,
pages = "31--36",
month = apr,
year = 1989
}

3.

Save the file and give it the name tex.bib. Open our example tex document and
modify it as follows:
\documentclass{article}
\begin{document}
\section*{Recommended texts}
To study \TeX\ in depth, see \cite{DK86}. For writing math texts,
see \cite{DK89}.
\bibliographystyle{alpha}
\bibliography{tex}
\end{document}

4.

Typeset one time with pdfLaTeX.

5.

If you're using TeXworks, choose BibTeX instead of pdfLaTeX, present in the
drop-down box next to the Typeset button, and then click on Typeset. If you
write with another editor, use its BibTeX option or type at the command
prompt in the document directory as follows:
bibtex documentname

6.

Typeset twice with pdfLaTeX. Here's the result:

[ 180 ]

Chapter 7

What just happened?
We created a text file containing all bibliography entries. In the next section, we shall look
at its format in depth. In our document, we chose a style called alpha, which sorts entries
according to the author's name and uses a shortcut consisting of author and year as label.
Then we told LaTeX to load the bibliography file called tex. The extension .bib has been
automatically added.
Afterwards, we called the external program BibTeX. This program knows from the example
.tex file that tex.bib has to be translated. Thus out of this .bib file, it creates a .bbl
file, which contains a LaTeX thebibliography environment and the final entries.
Finally, we had to Typeset twice, to ensure that all cross-references are correct.
Though we need some more steps to generate the bibliography, there are benefits: we don't
need to fine-tune each entry. We can easily switch between styles. We can then reuse the
.bib file.
So, let's look at the .bib file format. It supports various entry types like book and article.
Furthermore, these entries contain fields like author, title, and year. Let's first look at
the supported fields, and afterwards we shall talk about the different kinds of entries.

Looking at the BibTeX entry fields
Here's a list of the standard fields. Some fields are common, some are rarely used—we just
list them in alphabetical order, following the BibTeX documentation:
address

Usually the address of the publisher. At least for small publishers, this
information might be useful.

annote

An annotation, not used by the standard bibliography styles. Other styles or
macros might use this.

author

The name(s) of the author(s).

booktitle

The title of a book, if you cite a part of that. For a book, use the title field
instead.

chapter

A chapter number.

crossref

The key of the database entry being cross referenced.

edition

The edition (First, Second, and alike) of a book. Commonly it's capitalized.

editor

The name(s) of the editor(s).

howpublished

The way of publishing, especially if it's unusual. Capitalize the first word.

institution

Could be a sponsoring institution.

journal

A journal name; you may use common abbreviations.

[ 181 ]

Listing Content and References

key

Used for alphabetizing, cross-referencing, and labeling if the author information
is missing. Don't confuse it with the key used in the \cite command which
corresponds to the beginning of the entry.

month

The month in which the work was published or written if it's not yet published.
Usually a three letter abbreviation is used.

note

Any additional useful information. Capitalize the first word.

number

The number of a journal or another kind of work in a series.

organization

Might be a sponsoring organization.

pages

A page number or range of page numbers, like 12-18 or 22+.

publisher

The name of the publisher.

school

Could be the name of the school where the document was written.

series

The name of a series of books or its number of a multi-volume set.

title

The title of the work.

type

The type of the publication.

volume

The volume of a journal or multi-volume book.

year

The year of the publication or the year when it was written if it hasn't been
published yet. Commonly four numerals are used, such as 2010.

You may use any fields possibly supported by other styles and ignored by standard styles.
Referring to Internet resources
Today we often refer to online sources. To put Internet addresses into BibTeX
fields, use the \url command of the url or hyperref package, for example,
howpublished = {\url{http://texblog.net}}. Some styles offer
a url field.

Understanding BibTeX entry types
Firstly, you decide which type of entry you want to add and then you fill in the fields.
Different types may support different fields. Some fields are required, some are optional
and may be omitted, and some are simply ignored.

[ 182 ]

Chapter 7

Usually the name of the entry tells you its meaning. These are the standard entry types and
their required and optional fields, according to the BibTeX reference:
Type

Required fields

Optional fields

article

author, title, journal,
year

volume, number, pages, month, note

book

author or editor,
title, publisher, year
title

volume or number, series, address,
edition, month, note

conference

author, title,
booktitle, year

editor, volume or number, series,
pages, address, month, organization,
publisher, note

manual

title

author, organization, address,
edition, month, year, note

mastersthesis

author, title, school,
year

type, address, month, note

misc

none

author, title, howpublished, month,
year, note

phdthesis

author, title, school,
year

type, address, month, note

proceedings

title, year

editor, volume or number, series,
address, month, organization,
publisher, note

techreport

author, title,
institution, year

type, number, address, month, note

unpublished

author, title, note

month, year

booklet

author, howpublished, address,
month, year, note

Have a look at the BibTeX reference for more details:
texdoc bibtex

If no other entry fits, choose misc. It doesn't matter if you use capitals or small letters;
@ARTICLE is understood the same as @article. As the example showed, entries have
the following form:
@entrytype{keyword,
fieldname = {field text},
fieldname = {field text},
…
}

[ 183 ]

Listing Content and References

Use braces around the field text. Straight quotes instead like in "field text" are
supported as well. For numbers, you may omit the braces.
Some styles change the capitalization, which might lead to undesired
lowercase letters. To protect letters or words from becoming lowercase, put
additional braces around them. Preferably around a word instead of just the
letter to keep ligatures and kerning improvement, that is, {WAL} looks better
than {W}AL as TeX moves an A closer to a preceding W. Separating braces
hampers TeX's micro-typographic improvements.

Choosing the bibliography style
Standard styles are as follows:
plain

Arabic numbers for the labels, sorted according to the names of the authors. The number
is written in square brackets, which also appear with \cite.

unsrt

No sorting. All entries appear like they were cited in the text, otherwise it looks like
plain.

alpha

Sorting is according to the names of the authors, the labels are shortcuts made of the
authors name and the year of publication. Also here, square brackets are used.

abbrv

Like plain, but first names and other field entries are abbreviated.

The style should be chosen after \begin{document} and before \bibliography. You
may write \bibliographystyle right before \bibliography to keep it together.
There are more styles available in TeX distributions and on the Internet. For instance, the
natbib package provides styles and the capability to cite in a nice author-year scheme. This
package further adds some fields, like ISBN, ISSN, and URL.
The package biblatex provides a complete reimplementation of the
bibliographic features offered by BibTeX and LaTeX. Without learning the BibTeX
language, you could create new styles just by using your LaTeX knowledge.

Listing references without citing
BibTeX takes only those references from the database that are cited in the text, and prints
them out. However, you may specify keys for references, which should appear nevertheless
the following for a single reference. Just write the following for a single reference:
\nocite{key}
[ 184 ]

Chapter 7

Or write the following to list the complete database
\nocite{*}

Changing the headings
Like in our diagram example, if you don't like the heading Contents, you could easily change
it. The text of the heading is stored in the text macro \contentsname. So, just redefine it
as follows:
\renewcommand{\contentsname}{Table of Contents}

Here's a list of all those headings:
List

Default heading

Table of contents

Heading command
\contentsname

List of figures

\listfigurename

List of figures

List of tables

\listtablename

List of tables

Bibliography

\bibname in book and report

Bibliography in book and report
References in article

Index

\refname in article
\indexname

Contents

Index

Furthermore, as promised, here's a list of further macros for names used by LaTeX:
Name

Default value

figure

Command
\figurename

table

\tablename

Table

part

\partname

Part

chapter

\chaptername

Chapter

abstract

\abstractname

Abstract

appendix

\appendixname

Appendix

Figure

Not really surprising! Using name macros is especially useful when another language will be
used. For instance, the babel package takes a language option and redefines all those name
macros according to those languages.
However, they are also useful to choose abbreviations like Fig. or Appendices instead
of Appendix.

[ 185 ]

Listing Content and References

Have a go hero – using natbib
Load the already mentioned natbib package and try its new styles plainnat, abbrvnat, and
unsrtnat, for instance:
\usepackage{natbib}
\bibliographystyle{plainnat}

Our example would change as follows:

natbib reimplemented the \cite command and offers variations to it, with the main

purpose of supporting author-year citations. It works with most other available styles.
natbib introduces the citation command \citet for textual citations and the command
\citep for parenthetical citations. There are starred variants printing the full author list,
and optional arguments allow adding text before and after.
Check out the documentation if you would like to benefit from this fine package.

Pop quiz
1. Which of these commands should be used for adding unnumbered headings to the
table of contents?
a. \addtocontents
b. \addcontentsline
c.

\contentsname

2. Which of the following indexing commands has to come before \begin{document}?
a. \index
b. \printindex
c.

\makeindex
[ 186 ]

Chapter 7

3. Which command generates the bibliography?
a. \bibliography
b. \bibliographystyle
c.

\bibitem

Summary
In this chapter, we dealt with many kinds of lists. Specifically, we learned about:
‹‹

Generating and customizing the table of contents and lists of figures and tables

‹‹

Producing an index pointing to relevant information for keywords and phrases

‹‹

Creating bibliographies, both manually and using a bibliography database

These lists are intended to guide the reader to the information he's/she's looking for; they
aren't just for listing and summarizing. That's why the headings of the list of figures and the
list of tables usually don't appear in the TOC, as they commonly directly follow the TOC.
Sometimes there's even the strange requirement to list the table of contents within itself. If
you are not sure with a design or a requirement, have a look at a good book in your special
field, to see how exemplary tables of contents, lists, and indexes might look.
In the next chapter, we shall look at scientific writing in depth.

[ 187 ]

8

Typing Math Formulas
Chapter 1, Getting started with LaTeX, claimed that LaTeX offers excellent
quality for mathematical typesetting. Now it's time to prove this.

To make the most of LaTeX's capabilities, we shall learn how to perform the following:
‹‹

Writing basic formulas

‹‹

Embedding formulas within text and text within formulas

‹‹

Centering and numbering equations

‹‹

Aligning multi-line equations

‹‹

Typesetting math symbols such as roots, operators, Greek letters, and arrows

‹‹

Building fractions

‹‹

Stacking expressions

‹‹

Building matrices

That's a great undertaking—let's tackle it!

Typing Math Formulas

Writing basic formulas
LaTeX knows three general modes:
‹‹

The paragraph mode: The text is typeset as a sequence of words in lines,
paragraphs, and pages. That's what we used until now.

‹‹

The left-to-right mode: The text is also considered to be a sequence of words,
but LaTeX typesets it from left to right without breaking the line. For instance,
the argument of \mbox will be typeset in this mode; that's why \mbox prevents
hyphenation.

‹‹

The math mode: Letters are treated as math symbols. That's why they're typeset
in italic shape, which is common for variables. A lot of symbols can be used, most
of them exclusively in this mode. Such symbols are roots, sum signs, relation
signs, math accents, arrows, and various delimiters like brackets and braces. Space
characters between letters and symbols are ignored. Instead, the spacing depends
on the type of symbols—distances to relation signs are different from distances to
opening or closing delimiters. This mode is required for all math expressions.

Now we shall enter the math mode for the first time.

Time for action – discussing quadratic equations and roots
Our first small math text shall deal with the solutions of quadratic equations. We need to
typeset formulas with constants, variables, superscripts for the square, and subscripts for
the solutions. The solution itself needs a root symbol. Finally, we will use cross-references to
formulas.

1.

Start a new document. For now, we don't need any package:
\documentclass{article}
\begin{document}
\section*{Quadratic equations}

2.

State the quadratic equation with its conditions. Use an equation environment
for it. Surround small pieces of math within text by \( … \):
The quadratic equation
\begin{equation}
\label{quad}
ax^2 + bx + c = 0,
\end{equation}
where \( a, b \) and \( c \) are constants and \( a \neq 0 \),
has two solutions for the variable \( x \):
[ 190 ]

Chapter 8

3.

Use another equation for the solutions. The command for the square root is
\sqrt. The command for a fraction is \frac:
\begin{equation}
\label{root}
x_{1,2} = \frac{-b \pm \sqrt{b^2-4ac}}{2a}.
\end{equation}

4.

Let's introduce the discriminant and discuss the case zero. To get an
unnumbered displayed equation, we surround the formula with \[ … \]:
If the \emph{discrimimant} \( \Delta \) with
\[
\Delta = b^2 - 4ac
\]
is zero, then the equation (\ref{quad}) has a double solution:
(\ref{root}) becomes
\[
x = - \frac{b}{2a}.
\]
\end{document}

5.

Typeset twice and look at the result:

[ 191 ]

Typing Math Formulas

What just happened?
Just as we said in Chapter 1, writing formulas also looks a lot like programming. However,
this chapter will help you master it, and the results are worth the effort. The formulas have
been built with commands: there are commands with arguments, like for roots and fractions,
and simple commands for symbols, like for the Greek letter. Most symbols have to be within
a math environment and don't simply work within normal text.
The equation environment created a displayed formula; that formula has been horizontally
centered, some vertical space has been added before and after, further these formulas are
consecutively numbered.
However, \[ … \] and \( … \) are also, in truth, environments. Let's sort this out.

Embedding math expressions within text
LaTeX provides the math environment in-text formulas:
\begin{math}
expression
\end{math}

Since it's very laborious to write this environment for each small expression or symbol, LaTeX
offers an alias that's doing the same:
\(
expression
\)

You may write it without line breaks, such as \(expression\).
A third way is by using a shortcut, coming from TeX:
$expression$

A disadvantage of the latter is that the commands for beginning and ending the math
environment are the same, which may easily lead to errors. However, it's much easier to
type, which may be the reason why it's still popular among LaTeX users.
\( … \) might cause problems in moving arguments like in headings. To
prevent any such problems, just load the package fixltx2e, which fixes this as
well as other issues.

[ 192 ]

Chapter 8

Displaying formulas
For displayed formulas, which have to be centered, LaTeX offers the displaymath
environment:
\begin{displaymath}
expression
\end{displaymath}

The effect of this environment is that the paragraph will be ended, some vertical space
follows, then the centered formula plus the following vertical space. As this math
environment takes care of the spacing, don't leave empty lines before and after it! This
would cause additional vertical space because of the superfluous paragraph breaks.
Also for this environment there's a shortcut. We already used it:
\[
expression
\]

In this case, putting the shortcuts \[ and \] on separate lines commonly improves the
readability as the formula is also kind of displayed in the source code.
There's also a TeX low level command:
$$
expression
$$

However, it's strongly recommended to use\[ … \], because this LaTeX environment
handles vertical spacing better.
For the rest of this chapter, all pieces of code use math mode. Either we explicitly use a math
environment or we imagine that we are already in math mode, for short pieces of code.

Numbering equations
Equations and formulas in general may be numbered. However, this applies only to displayed
formulas. The equation environment is responsible for this:
\begin{equation}
\label{key}
expression
\end{equation}

It looks similar to displaymath but numbered this time. The number will be displayed in
parentheses on the right side of the equation.
[ 193 ]

Typing Math Formulas

Adding subscripts and superscripts
As exponents and indexes are frequently used, there are very short commands for
typesetting them, for example, _ gives an index or subscript, ^ produces an exponent
or superscript. Use braces to mark the concerned expression. So, the common forms are
as follows:
{expression}_{subscript}

And:
{expression}^{superscript}

This may be nested. If you use subscripts and superscripts to the same expression, the order
of ^ and _ is not important. In the case of single letters, numerals, or symbols, you can omit
the braces. Let's look at an example:
\[ x_1^2 + x_2^2 = 1, \quad 2^{2^x} = 64 \]

Extracting roots
Our example contained a square root: \sqrt{value}. As there are roots of higher order,
this command accepts an optional argument for the order. The complete definition is:
\sqrt[order]{value}

The size of the root symbol will be automatically adjusted to the height and the width of
the value expression. Roots may be nested. Both can be seen in this example:
\sqrt[64]{x} = \sqrt{\sqrt{\sqrt{\sqrt{\sqrt{\sqrt{x}}}}}}

Writing fractions
Within text formulas, you may just write / to denote fractions, such as \( (a+b)/2 \).
For larger fractions, there's the \frac command:
\frac{numerator}{denumerator}
[ 194 ]

Chapter 8

This command may also be used for in-text formulas. However, the line spacing could
increase.
\[ \frac{n(n+1)}{2}, \quad \frac{\frac{\sqrt{x}+1}{2}-x}{y^2} \]

Greek letters
Mathematicians like to use Greek letters, for instance, to denote constants. To get a
lowercase Greek letter, just write the name with a backslash for the command. Here
are the lowercase Greek letters with their corresponding LaTeX commands:

For some letters, variants are available:

As the omicron just looks like an o, there's no command for it. It's similar for most uppercase
Greek letters, which are equal to Roman letters. The remaining uppercase Greek letters are
produced as follows:

For upright Greek letters, you may use the upgreek package.

[ 195 ]

Typing Math Formulas

Script letters
For the twenty-six uppercase letters A, B, C, … , Z, there's a calligraphic shape, produced
by \mathcal:
\[ \mathcal{A}, \mathcal{B}, \mathcal{C}, \ldots, \mathcal{Z} \]

There are packages offering different calligraphic fonts, such as zapfino and xits.

Producing an ellipsis
You already know \ldots for a low ellipsis. It also works in math mode. We use the low
ellipsis mainly between letters and commas. Between operation and relation symbols, a
centered ellipsis is commonly used. Furthermore, a matrix may require a vertical ellipsis.
Here's how all of them may be produced:

Comparing in-line formulas to displayed formulas
Writing formulas in-line saves space and allows fluent explanations. This is recommendable
for short math expressions within text.
Formulas in the displayed style are outstanding; they are centered and require more space.
Furthermore, they can be numbered and you may refer to them using the \label and \ref
techniques that you learned in Chapter 5, Creating Tables and Inserting Pictures.
Choose the style that is optimal for the readability of your text.

Changing the font, style, and size

In Chapter 2, Formatting Words, Lines, and Paragraphs, we learned how to modify the font
of common text. There are further commands changing the font style in math mode:
[ 196 ]

Chapter 8

Though letters in math mode are italic, they are considered to be separate symbols, which
results in a different spacing than that of an italic word. For instance, in math mode, fi may
be the product of the variables f and i, but not the ligature fi. Compare:
\textit{Definition}, \(Definition\)

Also, \mathit treats the argument as text in italic math font. So, for text within formulas,
use a text or math font command, or even better: use \text{…} of amsmath—we will
return to this very soon.
If you wish to switch to bold typeface for a complete math expression, you can use the
declaration \boldmath before the expression, that is, already outside math mode. The
declaration \unboldmath switches back to the normal typeface. The latter has to be used
outside math mode as well.
To make parts of a formula bold, you can switch to the left-to-right mode by \mbox and by
using \boldmath in its argument.
Four math styles are available, determining the way of typesetting and the font size:
Style

Command
\displaystyle

Meaning

display
text

\textstyle

Default for letters and symbols within in-text
formulas

script

\scriptstyle

Smaller font size, used for subscripts and for
superscripts

scriptscript

\scriptscriptstyle

Even smaller font size, for nested script style

Default for letters and symbols in displayed
formulas

[ 197 ]

Typing Math Formulas

The textstyle differs from the displaystyle in mainly two ways; in textstyle,
variable sized symbols are smaller and subscripts and superscripts are usually placed beside
the expression instead of below and above, respectively. Otherwise the font size is the same.
LaTeX switches the style automatically; if you write a simple exponent, it will be typeset in
script style, that is, with a smaller font size.
You may force a desired style using one of the commands in the aforementioned table.
This allows you, for instance, to:
‹‹

Type formulas within the text exactly like they would appear in a displayed formula:
bigger fraction, bigger sum signs, further subscripts are set below, and superscripts
are set above. Note, all of this increases the line spacing.

‹‹

Write exponents or indexes with bigger symbols.

Customizing displayed formulas
There are two options that modify the way the formulas are displayed:
fleqn

"left equation numbers"

This causes all displayed formulas to be aligned at
the left margin.

leqno

"left equation numbers"

All numbered formulas would get the numbers on
the left side instead of the right.

Often, formulas are not displayed just standalone. We may encounter situations where:
‹‹

A formula is too long to fit on one line

‹‹

Several formulas are listed row-by-row

‹‹

An equation shall be transformed step-by-step

‹‹

A chain of inequalities spans over more than one line

‹‹

Several formulas shall be aligned at relation symbols

We may also encounter similar situations, where we have to write multi-line formulas, often
with some kind of alignment. The amsmath package offers specialized environments for
nearly every such need.

[ 198 ]

Chapter 8

Time for action – typesetting multi-line formulas
We shall use the amsmath package to experiment with a very long formula and with a
system of equations:

1.

Start a new document on an A6 paper and load the amsmath package.
\documentclass{article}
\usepackage[a6paper]{geometry}
\usepackage{amsmath}
\begin{document}

2.

Use the multline environment to span a long equation over three lines.
End the lines with\\:
\begin{multline}
\sum = a + b + c + d + e \\
+ f + g + h + i + j \\
+ k + l + m + n
\end{multline}
\end{document}

3.

Typeset and look at the formula:

4.

Now we handle a system of equations. Use the gather environment
to add these equations. Again, end lines with \\:
\begin{gather}
x + y + z = 0 \\
y - z = 1
\end{gather}

5.

Typeset and look at the equations:

[ 199 ]

Typing Math Formulas

6.

Commonly, equation systems are aligned at the equal sign. Let's do this. Use the
& symbol to mark the point that we wish to align:
\begin{align}
x + y + z &= 0 \\
y - z &= 1
\end{align}

7.

Typeset; now the equations are aligned as desired:

What just happened?
Because we loaded the amsmath package, we have access to several multi-line math
environments.
Each line in such an environment is ended by \\, except the last one. The alignment depends
on the environment, as we've seen:
‹‹

multline: The first line is left-aligned, the last line right-aligned, and all
other lines in between are centered

‹‹

gather: All lines are centered

‹‹

align: The lines are aligned at marked relation signs

Let's have a closer look.

Aligning multi-line equations
Here's a list of the amsmath multi-line environments:
Name
multline

Meaning

gather

Each line is centered.

align

Use & to mark a symbol where the formulas shall be aligned. Use another
& to end a column, if you need several aligned columns.

flalign

Similar to align with more than one column, but the columns are flushed
to the left and the right margin, respectively.

alignat

Alignment at several places, each has to be marked by &.

First line is left-aligned, last line is right-aligned, all others are centered.

[ 200 ]

Chapter 8

Name
split

Meaning

aligned,
gathered,
alignedat

Used for an aligned block within a math environment. This can be
displayed math or in-line math.

Similar to align, but within another math environment, thus
unnumbered.

Numbering rows in multi-line formulas
In multi-line math environments, each line would be numbered like a normal equation.
If you wish to suppress the numbering of a line, write \notag before the end of the line.
Use the starred variant like align*, or gather*, if you would like to avoid numbering
completely.

Inserting text into formulas
To insert some text into a formula, standard LaTeX provides the \mbox command. amsmath
offers further commands:
‹‹

\text{words} inserts text within a math formula. The size is adjusted according
to the current math style, that is, \text produces smaller text within subscripts or

superscripts.
‹‹

\intertext{text} suspends the formula, the text follows in a separate

paragraph, then the multi-line formula is resumed, keeping the alignment.
Use it for longer text.

These commands are the best choice, when you would like to use text within math
environments.

Fine-tuning formulas
If we go beyond writing variables and basic math operators, we may need many symbols for
special purposes: certain relation signs, unary and binary operators, function-like operators,
sum and integral symbols and variants of the latter, arrows, and many more. LaTeX and
additional packages offer thousands of symbols for many purposes. We shall have a look at
some of them. But firstly, let's figure out how to write functions.

[ 201 ]

Typing Math Formulas

Using operators
Trigonometric functions, logarithm functions, and other analytic and algebraic functions are
commonly written with upright Roman letters. Simply typing log would otherwise look like a
product of the three variables, namely, l, o, and g. To ease the input, there are commands for
many common functions or so called operators. Here's an alphabetical list of the predefined
ones:
\arccos, \arcsin, \arctan, \arg, \cos, \cosh, \cot, \coth, \scs, \deg, \det, \dim,
\exp, \gcd, \hom, \inf, \ker, \lg, \lim, \liminf, \limsup, \ln, \log, \max, \min,
\Pr, \sec, \sin, \sinh, \sup, \tan, \tanh

The modulo function may be written in two ways, either by using \bmod for a binary relation
or by using \pmod{argument} for a modulo expression in parentheses.
Some operators support subscripts which are set as follows:
\[ \lim_{n=1, 2, \ldots} a_n, \qquad \max_{x

Source Exif Data:
File Type                       : PDF
File Type Extension             : pdf
MIME Type                       : application/pdf
PDF Version                     : 1.6
Linearized                      : No
Tagged PDF                      : Yes
XMP Toolkit                     : Adobe XMP Core 4.0-c316 44.253921, Sun Oct 01 2006 17:14:39
Instance ID                     : uuid:dccaba3d-5f6b-4b71-9f16-0ec9e93f9864
Document ID                     : adobe:docid:indd:7c2210fa-d03b-11df-b78d-ab1f91ee47f1
Original Document ID            : adobe:docid:indd:7c2210fa-d03b-11df-b78d-ab1f91ee47f1
Rendition Class                 : proof:pdf
Derived From Instance ID        : 3e5cc9e6-d03a-11df-b78d-ab1f91ee47f1
Derived From Document ID        : adobe:docid:indd:62516cf1-6ed7-11df-9317-fdc85a3c42b2
History Action                  : saved, saved, saved, saved, saved, saved
History Instance ID             : xmp.iid:6863C3097A50E0118154F41DA417E456, xmp.iid:6963C3097A50E0118154F41DA417E456, xmp.iid:6A63C3097A50E0118154F41DA417E456, xmp.iid:6B63C3097A50E0118154F41DA417E456, xmp.iid:6C63C3097A50E0118154F41DA417E456, xmp.iid:6D63C3097A50E0118154F41DA417E456
History When                    : 2011:03:17 15:20:45+05:30, 2011:03:17 15:20:45+05:30, 2011:03:17 15:20:51+05:30, 2011:03:17 15:28:14+05:30, 2011:03:17 15:31:02+05:30, 2011:03:17 15:31:28+05:30
History Software Agent          : Adobe InDesign 6.0, Adobe InDesign 6.0, Adobe InDesign 6.0, Adobe InDesign 6.0, Adobe InDesign 6.0, Adobe InDesign 6.0
History Changed                 : /, /metadata, /, /, /, /
Create Date                     : 2011:03:17 15:33:26+05:30
Modify Date                     : 2011:03:17 15:38:57+05:30
Metadata Date                   : 2011:03:17 15:38:57+05:30
Creator Tool                    : Adobe InDesign CS4 (6.0)
Thumbnail Format                : JPEG
Thumbnail Width                 : 256
Thumbnail Height                : 256
Thumbnail Image                 : (Binary data 14756 bytes, use -b option to extract)
Doc Change Count                : 1
Format                          : application/pdf
Producer                        : Adobe PDF Library 9.0
Trapped                         : False
Has XFA                         : No
Page Count                      : 336
Creator                         : Adobe InDesign CS4 (6.0)
EXIF Metadata provided by EXIF.tools

Navigation menu