LaTeX Wikibook
LaTeX Wikibook
Contents
1 Getting Started 1
1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1.1 What is TeX? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1.2 What is LaTeX? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1.3 Philosophy of use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.1.4 Terms regarding TeX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.1.5 What next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.1 Distributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.2 Custom installation with TeX Live . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2.3 Editors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2.4 Bibliography management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.2.5 Viewers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.2.6 Tables and graphics tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.2.7 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.3 Installing Extra Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.3.1 Automatic installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.3.2 Manual installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.3.3 Checking package status . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.3.4 Package documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.3.5 External resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.3.6 See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.4 Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.4.1 The LaTeX syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.4.2 Our first document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.4.3 Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.4.4 Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.4.5 And what now? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2 Common Elements 16
2.1 Document Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.1.1 Global structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.1.2 Preamble . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
i
ii CONTENTS
3 Mechanics 77
3.1 Errors and Warnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
3.1.1 Error messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
3.1.2 Warnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
3.1.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
3.1.4 Software that can check your .tex Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
3.2 Lengths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
3.2.1 Units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
3.2.2 Box lengths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
vi CONTENTS
4 Technical Texts 85
4.1 Mathematics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
4.1.1 Mathematics environments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
4.1.2 Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
4.1.3 Greek letters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
4.1.4 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
4.1.5 Powers and indices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
4.1.6 Fractions and Binomials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
4.1.7 Roots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
4.1.8 Sums and integrals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
CONTENTS vii
8 Programming 151
8.1 Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
8.1.1 New commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
8.1.2 New environments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
8.1.3 Declare commands within newenvironment . . . . . . . . . . . . . . . . . . . . . . . . . . 152
8.1.4 Extending the number of arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
8.1.5 Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
8.1.6 Conditionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
CONTENTS xi
9 Miscellaneous 160
9.1 Modular Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
9.1.1 Project structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
9.1.2 Getting LaTeX to process multiple files . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
9.1.3 The file mystyle.sty . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
9.1.4 The main document document.tex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
9.1.5 External Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
9.2 Collaborative Writing of LaTeX Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
9.2.1 Abstract . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
9.2.2 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
9.2.3 Interchanging Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
xii CONTENTS
11 Appendix 181
11.1 Authors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
11.1.1 Included books . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
11.1.2 Wiki users . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
11.2 Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
11.3 Package Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
11.4 Sample LaTeX documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
11.4.1 General examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
11.4.2 Semantics of Programming Languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
11.5 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
11.5.1 A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
11.5.2 B . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
11.5.3 C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
11.5.4 D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
11.5.5 E . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
11.5.6 F . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
11.5.7 G . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
11.5.8 H . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
11.5.9 I . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
11.5.10 L . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
11.5.11 M . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
11.5.12 P . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
11.5.13 Q . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
11.5.14 R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
11.5.15 S . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
11.5.16 T . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
11.5.17 U . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
11.5.18 V . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
11.5.19 W . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
11.5.20 X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
11.6 Command Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
11.6.1 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
11.6.2 A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
xiv CONTENTS
11.6.3 B . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
11.6.4 C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
11.6.5 D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
11.6.6 E . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
11.6.7 F . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
11.6.8 G . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
11.6.9 H . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
11.6.10 I . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
11.6.11 K . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
11.6.12 L . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
11.6.13 M . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
11.6.14 N . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
11.6.15 O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
11.6.16 P . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
11.6.17 Q . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
11.6.18 R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
11.6.19 S . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
11.6.20 T . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
11.6.21 U . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
11.6.22 V . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
Getting Started
1
2 CHAPTER 1. GETTING STARTED
• You don't need to manually adjust fonts, text sizes, Questions and documentation
line heights, or text flow for readability, as LaTeX
takes care of them automatically. Besides internet resources being plentiful, the best doc-
umentation source remains the official manual for every
• In LaTeX the document structure is visible to the specific package, and the reference documentation, i.e.,
user, and can be easily copied to another document. the TeXbook by D. Knuth and LaTeX: A document prepa-
In WYSIWYG applications it is often not obvious ration system by L. Lamport.
how a certain formatting was produced, and it might
be impossible to copy it directly for use in another Therefore before rushing on your favorite web search en-
document. gine, we really urge you to have a look at the package
documentation that causes troubles. This official docu-
• The layout, fonts, tables and so on are consistent mentation is most commonly installed along your TeX
throughout the document. distribution, or may be found on CTAN.
• Mathematical formulae can be easily typeset.
• Indexes, footnotes, citations and references are gen- 1.1.4 Terms regarding TeX
erated easily.
Document preparation systems
• Since the document source is plain text, tables, fig-
ures, equations, etc. can be generated programmat- LaTeX is a document preparation system based on TeX.
ically with any language. So the system is the combination of the language and the
macros.
• You are forced to structure your documents cor-
rectly. Distributions
The LaTeX document is a plain text file containing the TeX distributions are collections of packages and pro-
content of the document, with additional markup. When grams (compilers, fonts, and macro packages) that enable
the source file is processed by the macro package, it can you to typeset without having to manually fetch files and
produce documents in several formats. LaTeX natively configure things.
supports DVI and PDF, but by using other software you
can easily create PostScript, PNG, JPEG, etc. Engines
• the TeX Stack Exchange Q&A, • MacTeX is a Mac OS-specific distribution based on
TeX Live.
• the TeX FAQ,
• and the TeXample.net Community. These, however, do not necessarily include an editor. You
might be interested in other programs that are not part
of the distribution, which will help you in writing and
1.2 Installation preparing TeX and LaTeX files.
If this is the first time you are trying out LaTeX, you don't
even need to install anything. For quick testing purpose *BSD and GNU/Linux
you may just create a user account with an online La-
TeX editor and continue this tutorial in the next chap- In the past, the most common distribution used to be
ter. These websites offer collaboration capabilities while teTeX. As of May 2006 teTeX is no longer actively main-
allowing you to experiment with LaTeX syntax without tained and its former maintainer Thomas Esser recom-
having to bother with installing and configuring a distri- mended TeX Live as the replacement.[1]
bution and an editor. When you later feel that you would The easy way to get TeX Live is to use the package man-
benefit from having a standalone LaTeX installation, you ager or portage tree coming with your operating system.
can return to this chapter and follow the instructions be- Usually it comes as several packages, with some of them
low. being essential, other optional. The core TeX Live pack-
LaTeX is not a program by itself; it is a language. Using ages should be around 200-300 MB.
LaTeX requires a bunch of tools. Acquiring them man- If your *BSD or GNU/Linux distribution does not have
ually would result in downloading and installing multiple the TeX Live packages, you should report a wish to
programs in order to have a suitable computer system that the bug tracking system. In that case you will need to
can be used to create LaTeX output, such as PDFs. TeX download TeX Live yourself and run the installer by hand.
Distributions help the user in this way, in that it is a sin-
gle step installation process that provides (almost) every- You may wish to install the content of TeX Live more
thing. selectively. See below.
At a minimum, you'll need a TeX distribution, a good
text editor and a DVI or PDF viewer. More specifically,
Mac OS X
the basic requirement is to have a TeX compiler (which is
used to generate output files from source), fonts, and the
LaTeX macro set. Optional, and recommended installa- Mac OS X users may use MacTeX, a TeX Live-based dis-
tions include an attractive editor to write LaTeX source tribution supporting TeX, LaTeX, AMSTeX, ConTeXt,
documents (this is probably where you will spend most of XeTeX and many other core packages. Download Mac-
your time), and a bibliographic management program to TeX.mpkg.zip on the MacTeX page, unzip it and follow
manage references if you use them a lot. the instructions. Further information for Mac OS X users
can be found on the TeX on Mac OS X Wiki.
Since Mac OS X is also a Unix-based system, TeX
1.2.1 Distributions Live is naturally available through MacPorts and Fink.
Homebrew users should use the official MacTeX installer
TeX and LaTeX are available for most computer plat- because of the unique directory structure used by TeX
forms, since they were programmed to be very portable. Live. Further information for Mac OS X users can be
They are most commonly installed using a distribution, found on the TeX on Mac OS X Wiki.
such as teTeX, MiKTeX, or MacTeX. TeX distribu-
tions are collections of packages and programs (compil-
ers, fonts, and macro packages) that enable you to type- Microsoft Windows
set without having to manually fetch files and configure
things. LaTeX is just a set of macro packages built for Microsoft Windows users can install MiKTeX onto their
TeX. computer. It has an easy installer that takes care of setting
The recommended distributions for each of the major op- up the environment and downloading core packages. This
erating systems are: distribution has advanced features, such as automatic in-
stallation of packages, and simple interfaces to modify
• TeX Live is a major TeX distribution for *BSD, settings, such as default paper sizes.
GNU/Linux, Mac OS X and Windows. There is also a port of TeX Live available for Windows.
4 CHAPTER 1. GETTING STARTED
Configuration Uninstallation
Formerly, TeX distributions used to be configured with By default TeX Live will install in /usr/local/texlive. The
the texconfig tool from the teTeX distribution. TeX Live distribution is quite proper as it will not write any file out-
still features this tool, but recommends using its own tool side its folder, except for the cache (like font cache, hy-
instead: tlmgr. Note that as of January 2013 not all tex- phenation patters, etc.). By default,
config features are implemented by tlmgr. Only use tex-
config when you cannot do what you want with tlmgr. • the system cache goes in /var/lib/texmf;
List current installation options: • the user cache goes in ~/.texliveYYYY.
tlmgr option
Therefore TeX Live can be installed and uninstalled safely
You can change the install options: by removing the aforementioned folders.
tlmgr option src 1 tlmgr option doc 0 tlmgr option paper Still, TeX Live provides a more convenient way to do this:
letter
# tlmgr uninstall
See the TLMGR(1) man page for more details on its us-
You may still have to wipe out the folders if you put un-
age. If you did not install the documents as told previ-
tracked files in them.
ously, you can still access the tlmgr man page with
tlmgr help
1.2.3 Editors
Installing LaTeX TeX and LaTeX source documents (as well as related
files) are all text files, and can be opened and modified
Now we have a running plain TeX environment, let’s in- in almost any text editor. You should use a text editor
stall the base packages for LaTeX. (e.g. Notepad), not a word processor (Word, OpenOf-
# tlmgr install latex latex-bin latexconfig latex-fonts fice). Dedicated LaTeX editors are more useful than
generic plain text editors, because they usually have au-
In this case you can omit latexconfig latex-fonts as they tocompletion of commands, spell and error checking and
are auto-resolved dependencies to LaTeX. Note that handy macros.
tlmgr resolves some dependencies, but not all. You may
need to install dependencies manually. Thankfully this is
rarely too cumbersome. Cross-platform
Other interesting packages:
BaKoMa TeX BaKoMa TeX is an editor for Windows
# tlmgr install amsmath babel carlisle ec geometry graph- and Mac OS with WYSIWYG-like features. It takes care
ics hyperref lm marvosym oberdiek parskip pdftex-def of compiling the LaTeX source and updating it constantly
url to view changes to document almost in real time. You can
If you installed a package you do not need anymore, use take an evaluation copy for 28 days.
# tlmgr remove <package>
Emacs Emacs is a general purpose, extensible text pro-
cessing system. Advanced users can program it (in elisp)
Hyphenation to make Emacs the best LaTeX environment that will fit
their needs. In turn beginners may prefer using it in com-
If you are using Babel for non-English documents, you bination with AUCTeX and Reftex (extensions that may
need to install the hyphenation patterns for every language be installed into the Emacs program). Depending on your
you are going to use. They are all packaged individually. configuration, Emacs can provide a complete LaTeX edit-
For instance, use ing environment with auto-completion, spell-checking,
# tlmgr install hyphen-{finnish,sanskrit} a complete set of keyboard shortcuts, table of contents
view, document preview and many other features.
for finnish and sanskrit hyphenation patterns.
Note that if you have been using another TeX distribution
gedit-latex-plugin Gedit with gedit-latex-plugin is
beforehand, you may still have hyphenation cache stored
also worth trying out for users of GNOME. GEdit is a
in you home folder. You need to remove it so that the new
cross-platform application for Windows, Mac, and Linux
packages are taken into account. The TeX Live cache
is usually stored in the ~/.texliveYYYY folder (YYYY
stands for the year). You may safely remove this folder Gummi Gummi is a LaTeX editor for Linux, which
as it contains only generated data. TeX compilers will compiles the output of pdflatex in realtime and shows it
re-generate the cache accordingly on next compilation. on the right half of the screen[2] .
6 CHAPTER 1. GETTING STARTED
1.2.4 Bibliography management (Device independent file format), but you will rarely want
it to. DVI files do not contain embedded fonts and many
Bibliography files (*.bib) are most easily edited and mod- document viewers are unable to open them.
ified using a management system. These graphical user
Usually you will use a LaTeX compiler like pdflatex to
interfaces all feature a database form, where information
produce a PDF file directly, or a tool like dvi2pdf to con-
is entered for each reference item, and the resulting text
vert the DVI file to PDF format. Then you can view the
file can be used directly by BibTeX.
result with any PDF viewer.
Practically all LaTeX distributions have a DVI viewer for
Cross-platform viewing the default output of latex, and also tools such
as dvi2pdf for converting the result automatically to PDF
and PS formats.
Here follows a list of various PDF viewers.
• Foxit (Windows)
• Skim (Mac OS X)
Screenshot of JabRef. • Sumatra PDF (Windows)
Mac OS X-only
1.2.6 Tables and graphics tools
1.2.7 References nient feature, upon the compilation of a file requiring non-
installed packages, MikTeX will automatically prompt to
[1] teTeX Home Page (Retrieved January 31, 2007) install the missing ones.
[2] Gummi With TeX Live, it is common to have the distribution
packed into a few big packages. For example, to install
[3] LyX something related to internationalization, you might have
[4] BibDesk
to install a package like texlive-lang. With TeX Live man-
ually installed, use tlmgr to manage packages individu-
ally.
1.3 Installing Extra Packages tlmgr install <package1> <package2> ... tlmgr remove
<package1> <package2> ...
Add-on features for LaTeX are known as packages. The use of tlmgr is covered in the Installation chapter.
Dozens of these are pre-installed with LaTeX and can If you cannot find the wanted package with any of the
be used in your documents immediately. They should previous methods, see the manual installation.
all be stored in subdirectories of texmf/tex/latex named
after each package. The directory name “texmf” stands
for “TEX and METAFONT”. To find out what other 1.3.2 Manual installation
packages are available and what they do, you should use
the CTAN search page which includes a link to Graham Downloading packages
Williams’ comprehensive package catalogue.
What you need to look for is usually two files, one ending
A package is a file or collection of files containing ex-
in .dtx and the other in .ins. The first is a DOCTeX file,
tra LaTeX commands and programming which add new
which combines the package program and its documenta-
styling features or modify those already existing. There
tion in a single file. The second is the installation routine
are two main file types: class files with .cls extension, and
(much smaller). You must always download both files. If
style files with .sty extension. There may be ancillary files
the two files are not there, it means one of two things:
as well. When you try to typeset a document which re-
quires a package which is not installed on your system,
LaTeX will warn you with an error message that it is miss- • Either the package is part of a much larger bun-
ing. You can download updates to packages you already dle which you shouldn't normally update unless you
have (both the ones that were installed along with your change LaTeXversion of LaTeX;
version of LaTeX as well as ones you added). There is no • or it’s an older or relatively simple package written
limit to the number of packages you can have installed by an author who did not use a .dtx file.
on your computer (apart from disk space!), but there is a
configurable limit to the number that can be used inside Download the package files to a temporary directory.
any one LaTeX document at the same time, although it There will often be a readme.txt with a brief description
depends on how big each package is. In practice there is of the package. You should of course read this file first.
no problem in having even a couple of dozen packages
active.
Installing a package
Most LaTeX installations come with a large set of pre-
installed style packages, so you can use the package man-
There are five steps to installing a LaTeX package.
ager of the TeX distribution or the one on your system to
(These steps can also be used on the pieces of a com-
manage them. See the automatic installation. But many
plicated package you wrote yourself; in this case, skip
more are available on the net. The main place to look for
straight to Step 3.)
style packages on the Internet is CTAN. Once you have
identified a package you need that is not in your distri- 1. Extract the files Run LaTeX on the .ins file. That
bution, use the indexes on any CTAN server to find the is, open the file in your editor and process it as if it were
package you need and the directory where it can be down- a LaTeX document (which it is), or if you prefer, type
loaded from. See the manual installation. latex followed by the .ins filename in a command window
in your temporary directory. This will extract all the files
needed from the .dtx file (which is why you must have
1.3.1 Automatic installation both of them present in the temporary directory). Note
down or print the names of the files created if there are
If on an operating system with a package manager or a a lot of them (read the log file if you want to see their
portage tree, you can often find packages in repositories. names again).
With MikTeX there is a package manager that allows you 2. Create the documentation Run LaTeX on the .dtx
to pick the package you want individually. As a conve- file. You might need to run it twice or more, to get the
10 CHAPTER 1. GETTING STARTED
cross-references right (just like any other LaTeX docu- comes with every modern version of TeX and has vari-
ment). This will create a .dvi file of documentation ex- ous names depending on the LaTeX distribution you use.
plaining what the package is for and how to use it. If you (Read the documentation that came with your installa-
prefer to create PDF then run pdfLaTeX instead. If you tion to find out which it is, or consult http://www.tug.org/
created a .idx as well, it means that the document contains fonts/fontinstall.html#fndb):
an index, too. If you want the index to be created prop-
erly, follow the steps in the indexing section. Sometimes • teTeX, TeX Live, fpTeX: texhash
you will see that a .glo (glossary) file has been produced.
• web2c: mktexlsr
Run the following command instead:
• MacTeX: MacTeX appears to do this for
makeindex -s gglo.ist -o name.gls name.glo you.
3. Install the files While the documentation is printing, • MikTeX: initexmf --update-fndb (or use
move or copy the package files from your temporary di- the GUI)
rectory to the right place[s] in your TeX local installa-
• MiKTeX 2.7 or later versions, installed
tion directory tree. Packages installed by hand should al-
on Windows XP through Windows 7:
ways be placed in your “local” directory tree, not in the
Start -> All Programs -> MikTex -> Set-
directory tree containing all the pre-installed packages.
tings. In Windows 8 use the keyword
This is done to a) prevent your new package acciden-
Settings and choose the option of Settings
tally overwriting files in the main TeX directories; and b)
with the MiKTex logo. In Settings menu
avoid your newly-installed files being overwritten when
choose the first tab and click on Refresh
you next update your version of TeX.
FNDB-button (MikTex will then check
For a TDS(TeX Directory Structure)-conformant system, the Program Files directory and update
your “local installation directory tree” is a folder and the list of File Name DataBase). After
its subfolders. The outermost folder should probably be that just verify by clicking 'OK'.
called texmf-local/ or texmf/. Its location depends on
your system: 5. Update font maps If your package installed any True-
Type or Type 1 fonts, you need to update the font map-
• MacTeX: ping files in addition to updating the index. Your pack-
Users/username/Library/texmf/. age author should have included a .map file for the fonts.
• Unix-type systems: Usually ~/texmf/. The map updating program is usually some variant on up-
dmap, depending on your distribution:
• MikTeX: Your local directory tree can be
any folder you like, as long as you then
• TeX Live and MacTeX: updmap --enable
register it as a user-managed texmf direc-
Map=mapfile.map (if you installed the
tory (see http://docs.miktex.org/manual/
files in a personal tree) or updmap-sys
localadditions.html#id573803)
--enable Map=mapfile.map (if you in-
stalled the files in a system directory).
The “right place” sometimes causes confusion, espe-
cially if your TeX installation is old or does not con- • MikTeX: Run initexmf --edit-config-file
form to the TeX Directory Structure(TDS). For a TDS- updmap, add the line “Map mapfile.map
conformant system, the “right place” for a LaTeX .sty to the file that opens, then run initexmf
file is a suitably-named subdirectory of texmf/tex/latex/. --mkmaps.
“Suitably-named” means sensible and meaningful (and
probably short). For a package like paralist, for exam- See http://www.tug.org/fonts/fontinstall.html.
ple, I'd call the directory texmf/tex/latex/paralist. The reason this process has not been automated widely
is that there are still thousands of installations which do
Often there is just a .sty file to move, but in the case of
complex packages there may be more, and they may be- not conform to the TDS, such as old shared Unix systems
long in different locations. For example, new BibTeX and some Microsoft Windows systems, so there is no way
for an installation program to guess where to put the files:
packages or font packages will typically have several files
you have to know this. There are also systems where the
to install. This is why it is a good idea to create a sub-
owner, user, or installer has chosen not to follow the rec-
directory for the package rather than dump the files into
ommended TDS directory structure, or is unable to do
misc along with other unrelated stuff. If there are config-
so for political or security reasons (such as a shared sys-
uration or other files, read the documentation to find out
tem where the user cannot write to a protected directory).
if there is a special or preferred location to move them to.
The reason for having the texmf-local directory (called
For most fonts on CTAN, the foundry is public. texmf.local on some systems) is to provide a place for lo-
4. Update your index Finally, run your TeX indexer cal modifications or personal updates, especially if you
program to update the package database. This program are a user on a shared or managed system (Unix, Linux,
1.4. BASICS 11
Note that the % character can be used to split long input • latex executable calls tex with LaTeX initialization
lines that do not allow whitespace or line breaks, as with files, reads a LaTeX .tex file and creates a .dvi
Supercalifragilisticexpialidocious above.
• pdflatex executable calls pdftex with LaTeX initial-
The core LaTeX language does not have a predefined syn- ization files, reads a LaTeX .tex file and creates a
tax for commenting out regions spanning multiple lines. .pdf
Refer to multiline comments for simple workarounds.
If you compile a Plain TeX document with a LaTeX com-
piler (such as pdflatex) it will work while the opposite is
1.4.2 Our first document
not true: if you try to compile a LaTeX source with a TeX
compiler you will get many errors.
Now we can create our first document. We will produce
the absolute bare minimum that is needed in order to get As a matter of fact, following your operating system latex
some output; the well known Hello World! approach will and pdflatex are simple scripts or symbolic links.
be suitable here. Most of the programs should be already within your
LaTeX distribution; the others come with Ghostscript,
• Open your favorite text-editor. vim, emacs, which is a free and multi-platform software as well. Here
Notepad++, and other text editors will have syntax are common programs you expect to find in any LaTeX
highlighting that will help to write your files. distribution:
When picking a name for your file, make sure it bears a and with Ghostscript:
.tex extension.
• ps2pdf and pdf2ps converts the .ps file to .pdf and
vice-versa.
What does it all mean?
When LaTeX was created, the only format it could cre-
As we have said before, each of the LaTeX commands be-
ate was DVI; later PDF support was added by pdflatex.
gins with a backslash (\). This is LaTeX’s way of knowing
PDF files can be created with both pdflatex and dvipdfm.
that whenever it sees a backslash, to expect some com-
The output of pdflatex takes direct advantage of modern
mands. Comments are not classed as a command, since
features of PDF such as hyperlinks and embedded fonts,
all they tell LaTeX is to ignore the line. Comments never
which are not part of DVI. Passing through DVI imposes
affect the output of the document.
limitations of its older format. On the other hand, some
packages, such as PSTricks, exploit the process of con-
version to DVI, and therefore will not work with pdfla-
1.4.3 Compilation
tex. Some of those packages embed information in the
DVI that doesn't appear when the DVI is viewed, but
Compilation process
reemerges when the DVI is converted to another, newer
format.
The general concept is to transform a plain text document
into a publishable format, mosty a DVI, PS or PDF file. You would write your document slightly differently de-
This process is called compilation, which is done by an pending on the compiler you are using (latex or pdflatex).
executable file called a compiler. But as we will see later it is possible to add a sort of ab-
straction layer to hide the details of which compiler you're
There are two main compilers.
using, while the compiler can handle the translation itself.
• tex compiler reads a TeX .tex file and creates a .dvi. The following diagram shows the relationships between
the LaTeX source code and the formats you can create
• pdftex compiler reads a TeX .tex file and creates a from it:
.pdf. The boxed red text represents the file formats, the blue
text on the arrows represents the commands you have to
These compilers are basically used to compile Plain TeX, use, the small dark green text under the boxes represents
not LaTeX. There is no such LaTeX compiler since La- the image formats that are supported. Any time you pass
TeX is just a bunch of macros for TeX. However, there through an arrow you lose some information, which might
are two executables related to the previous compilers: decrease the features of your document. Therefore, you
14 CHAPTER 1. GETTING STARTED
ps2pdf dvi2ps
PDF pdf2ps
PostScript DVI 1. Type the command: pdflatex hello (as before, the
(pdf, (eps)
png,
jpg) dvipdfm .tex extension is not required)
Picking suitable filenames LaTeX has some nice features for most languages in the
world. You can tell LaTeX to follow typography rules of
Never, ever use directories (folders) or file names that the target language, ease special characters input, and so
contain spaces. Although your operating system probably on. See Special Characters and Internationalization.
supports them, some don't, and they will only cause grief
and tears with TeX. Make filenames as short or as long as
you wish, but strictly avoid spaces. Stick to lower-case let- Modular document
ters without accents (a-z), the digits 0-9, the hyphen (–),
and only one full point or period (.) to separate the file ex- See Modular Documents for good recommendations
tension (somewhat similar to the conventions for a good about the way to organize big projects into multiple files.
Web URL): it will let you refer to TeX files over the Web
more easily and make your files more portable. Some Questions and Issues
operating systems do not distinguish between upper-case
and lower-case letters, others do. Therefore it’s best not We highly urge you to read the FAQ if you have issues
to mix them. about basic features, or if you want to read essential rec-
ommendations. For the more specific questions and is-
Ancillary files sues, refer to the Tips and Tricks page. If you cannot find
what you want here, use the Q&A page.
The TeX compilers are single-pass processes. It means
that there is no way for a compiler to jump around the Macros for the utmost efficiency
document, which would be useful for the table of con-
tents and references. Indeed the compiler cannot guess The full power of LaTeX resides in macros. They make
at which page a specific section is going to be printed, so your documents very dynamic and flexible. See the
when the table of contents is printed before the upcoming dedicated part.
sections, it cannot set the page numbers.
To circumvent this issue, many LaTeX commands which
Working in a team
need to jump use ancillary files which usually have the
same file name as the current document but a different
See chapter Collaborative Writing of LaTeX Documents.
extension. It stores temporary data into these files and
use them for the next compilation. So to have an up-
to-date table of contents, you need to compile the docu-
Chapter 2
Common Elements
The main point of writing a text is to convey ideas, infor- When processing an input file, LaTeX needs to know the
mation, or knowledge to the reader. The reader will un- type of document the author wants to create. This is
derstand the text better if these ideas are well-structured, specified with the \documentclass command. It is rec-
and will see and feel this structure much better if the typo- ommended to put this declaration at the very beginning.
graphical form reflects the logical and semantic structure Here, class specifies the type of document to be created.
of the content. The LaTeX distribution provides additional classes for
LaTeX is different from other typesetting systems in that other documents, including letters and slides. It is also
you just have to tell it the logical and semantical structure possible to create your own, as is often done by journal
of a text. It then derives the typographical form of the text publishers, who simply provide you with their own class
according to the “rules” given in the document class file file, which tells LaTeX how to format your content. But
and in various style files. LaTeX allows users to structure we'll be happy with the standard article class for now. The
their documents with a variety of hierarchical constructs, options parameter customizes the behavior of the docu-
including chapters, sections, subsections and paragraphs. ment class. The options have to be separated by commas.
Example: an input file for a LaTeX document could start
with the line
2.1.1 Global structure
which instructs LaTeX to typeset the document as an ar-
When LaTeX processes an input file, it expects it to fol- ticle with a base font size of 11 points, and to produce a
low a certain structure. Thus every input file must contain layout suitable for double sided printing on A4 paper.
the commands Here are some document classes that can be used with
The area between \documentclass{...} and \be- LaTeX:
gin{document} is called the preamble. It normally The standard document classes that are a part of LaTeX
contains commands that affect the entire document. are built to be fairly generic, which is why they have a
After the preamble, the text of your document is enclosed lot of options in common. Other classes may have differ-
between two commands which identify the beginning and ent options (or none at all). Normally, third party classes
end of the actual document: come with some documentation to let you know. The
most common options for the standard document classes
You would put your text where the dots are. The reason are listed in the following table:
for marking off the beginning of your text is that LaTeX
allows you to insert extra setup specifications before it For example, if you want a report to be in 12pt type on
(where the blank line is in the example above: we'll be us- A4, but printed one-sided in draft mode, you would use:
ing this soon). The reason for marking off the end of your
text is to provide a place for LaTeX to be programmed to
do extra stuff automatically at the end of the document, Packages
like making an index.
While writing your document, you will probably find that
A useful side-effect of marking the end of the document
there are some areas where basic LaTeX cannot solve
text is that you can store comments or temporary text un-
your problem. If you want to include graphics, colored
derneath the \end{document} in the knowledge that La-
text or source code from a file into your document, you
TeX will never try to typeset them:
need to enhance the capabilities of LaTeX. Such en-
hancements are called packages. Some packages come
2.1.2 Preamble with the LaTeX base distribution. Others are provided
separately. Modern TeX distributions come with a large
16
2.1. DOCUMENT STRUCTURE 17
number of packages pre-installed. Packages are activated you use the AMS article class (amsart), then you can use
with the several different commands to enter author information.
command, where package is the name of the package and The email address is at the end, and the \texttt commands
options is a list of keywords that trigger special features formats the email address using a mono-spaced font. The
in the package. For example, to use the color package, built-in command called \today will be replaced with the
which lets you typeset in colors, you would type: current date when processed by LaTeX. But you are free
to put whatever you want as a date, in no set order. If
You can include several package names in one \usepack- braces are left empty, then the date is omitted.
age command by separating the names with commas, like
this: Using this approach, you can create only basic output
whose layout is very hard to change. If you want to create
and you can have more than one \usepackage command. your title freely, see the Title Creation section.
Some packages allow optional settings in square brackets.
If you use these, you must give the package its own sepa-
rate \usepackage command, like geometry shown below: Abstract
Many packages can have additional formatting specifi-
As most research papers have an abstract, there are pre-
cations in optional arguments in square brackets, in the
defined commands for telling LaTeX which part of the
same way as geometry does. Read the documentation for
content makes up the abstract. This should appear in its
the package concerned to find out what can be done. You
logical order, therefore, after the top matter, but before
can pass several options together separated by a comma:
the main sections of the body. This command is available
for the document classes article and report, but not book.
2.1.3 The document environment By default, LaTeX will use the word “Abstract” as a title
for your abstract. If you want to change it into anything
Top matter else, e.g. “Executive Summary”, add the following line
before you begin the abstract environment:
At the beginning of most documents there will be infor-
mation about the document itself, such as the title and
Sectioning commands
date, and also information about the authors, such as
name, address, email etc. All of this type of informa-
The commands for inserting sections are fairly intuitive.
tion within LaTeX is collectively referred to as top matter.
Of course, certain commands are appropriate to different
Although never explicitly specified (there is no \topmat-
document classes. For example, a book has chapters but
ter command) you are likely to encounter the term within
an article doesn't. Here are some of the structure com-
LaTeX documentation.
mands found in simple.tex.
A simple example:
Notice that you do not need to specify section numbers;
The \title, \author, and \date commands are self- LaTeX will sort that out for you. Also, for sections, you
explanatory. You put the title, author name, and date in do not need to use \begin and \end commands to indicate
curly braces after the relevant command. The title and which content belongs to a given block.
author are usually compulsory (at least if you want La-
LaTeX provides 7 levels of depth for defining sections
TeX to write the title automatically); if you omit the \date
(see table below). Each section in this table is a subsection
command, LaTeX uses today’s date by default. You al-
of the one above it.
ways finish the top matter with the \maketitle command,
which tells LaTeX that it’s complete and it can typeset the All the titles of the sections are added automatically to
title according to the information you have provided and the table of contents (if you decide to insert one). But
the class (style) you are using. If you omit \maketitle, the if you make manual styling changes to your heading, for
titling will never be typeset (unless you write your own). example a very long title, or some special line-breaks or
unusual font-play, this would appear in the Table of Con-
Here is a more complicated example:
tents as well, which you almost certainly don't want. La-
as you can see, you can use commands as arguments of TeX allows you to give an optional extra version of the
\title and the others. The double backslash (\\) is the La- heading text which only gets used in the Table of Con-
TeX command for forced linebreak. LaTeX normally de- tents and any running heads, if they are in effect. This
cides by itself where to break lines, and it’s usually right, optional alternative heading goes in [square brackets] be-
but sometimes you need to cut a line short, like here, and fore the curly braces:
start a new one.
If there are two authors separate them with the \and com- Section numbering Numbering of the sections is per-
mand: formed automatically by LaTeX, so don't bother adding
If you are provided with a class file from a publisher, or if them explicitly, just insert the heading you want between
18 CHAPTER 2. COMMON ELEMENTS
the curly braces. Parts get roman numerals (Part I, Part Table of contents
II, etc.); chapters and sections get decimal numbering like
this document, and appendices (which are just a special All auto-numbered headings get entered in the Table of
case of chapters, and share the same structure) are let- Contents (ToC) automatically. You don't have to print a
tered (A, B, C, etc.). ToC, but if you want to, just add the command \tableof-
contents at the point where you want it printed (usually
You can change the depth to which section numbering
after the Abstract or Summary).
occurs, so you can turn it off selectively. By default it
is set to 2. If you only want parts, chapters, and sections Entries for the ToC are recorded each time you process
numbered, not subsections or subsubsections etc., you can your document, and reproduced the next time you pro-
change the value of the secnumdepth counter using the cess it, so you need to re-run LaTeX one extra time to
\setcounter command, giving the depth level you wish. ensure that all ToC pagenumber references are correctly
For example, if you want to change it to “1": calculated. We've already seen how to use the optional
argument to the sectioning commands to add text to the
A related counter is tocdepth, which specifies what depth
ToC which is slightly different from the one printed in
to take the Table of Contents to. It can be reset in exactly
the body of the document. It is also possible to add extra
the same way as secnumdepth. For example:
lines to the ToC, to force extra or unnumbered section
To get an unnumbered section heading which does not headings to be included.
go into the Table of Contents, follow the command name
The commands \listoffigures and \listoftables work in ex-
with an asterisk before the opening curly brace:
actly the same way as \tableofcontents to automatically
All the divisional commands from \part* to \subpara- list all your tables and figures. If you use them, they nor-
graph* have this “starred” version which can be used on mally go after the \tableofcontents command. The \table-
special occasions for an unnumbered heading when the ofcontents command normally shows only numbered sec-
setting of secnumdepth would normally mean it would be tion headings, and only down to the level defined by the
numbered. tocdepth counter, but you can add extra entries with the
If you want the unnumbered section to be in the table of \addcontentsline command. For example if you use an
contents anyway, use the \addcontentsline command like unnumbered section heading command to start a prelim-
this: inary piece of text like a Foreword or Preface, you can
write:
Note that if you use PDF bookmarks you will need to add
a phantom section so that bookmark will lead to the cor- This will format an unnumbered ToC entry for “Preface”
rect place in the document. The \phantomsection com- in the “subsection” style. You can use the same mecha-
mand is defined in the hyperref package, and is imple- nism to add lines to the List of Figures or List of Tables
mented normally as follows: by substituting lof or lot for toc. If the hyperref pack-
age is used and the link does not point to the correct
For chapters you will also need to clear the page (this will chapter, the command \phantomsection in combination
also correct page numbering in the ToC): with \clearpage or \cleardoublepage can be used (see also
The value where the section numbering starts from can Labels and Cross-referencing):
be set with the following command: To change the title of the TOC, you have to paste this
The next section after this command will now be num- command \renewcommand{\contentsname}{<New table
bered 5. of contents title>} in your document preamble. The List
of Figures (LoF) and List of Tables (LoT) names can be
For more details on counters, see the dedicated chapter.
changed by replacing the \contentsname with \listfigure-
name for LoF and \listtablename for LoT.
Section number style See Counters. Depth The default ToC will list headings of level 3 and
above. To change how deep the table of contents displays
automatically the following command can be used in the
preamble:
This will make the table of contents include everything
Ordinary paragraphs
down to paragraphs. The levels are defined above on this
page. Note that this solution does not permit changing
Paragraphs of text come after section headings. Simply the depth dynamically.
type the text and leave a blank line between paragraphs.
The blank line means “start a new paragraph here": it You can change the depth of specific section type, which
does not mean you get a blank line in the typeset output. could be useful for PDF bookmarks (if you are using the
For formatting paragraph indents and spacing between hyperref package) :
paragraphs, refer to the Paragraph Formatting section. In order to further tune the display or the numbering of
2.1. DOCUMENT STRUCTURE 19
the table of contents, for instance if the appendix should 5. Dedication if any, else empty
be less detailed, you can make use of the tocvsec2 pack-
age (CTAN, doc). 6. Table of contents
• The mainmatter chapters works as usual. The com- Introductory chapters with main page numbering
mand resets the page numbering. Page numbers will
be printed in arabic numerals. You may be tempted to put your introductory chapters in
• The \appendix macro can be used to indicate that the main matter so that it follows the same numbering as
following sections or chapters are to be numbered as the main chapters. This is not how the class was meant
appendices. Appendices can be used for the article to be used, so you will run into an issue if you don't want
class too: the chapter to be numbered.
In the above code sample, the second page of the intro-
Only use the \appendix macro once for all appendices. duction will have TABLE OF CONTENTS printed in the
header. This is because the starred \chapter* command
• The backmatter behaves like the frontmatter. It has does not set the leftmark -- see Page Layout. And it will
the same issue with section numbering. not be printed in the table of contents either.
The trick is to set the leftmark and the TOC manually:
As a general rule you should avoid mixing the command TABLE OF CONTENTS is traditionally printed both left
order. Nonetheless all commands are optional, so you and right, but here we print it like other chapters, only
might consider using only a few. right on even pages.
Note that the special content like the table of contents is To make it more convenient, you might use a macro:
considered as an unnumbered chapter.
Page order
2.1.5 Special pages
This is one traditional page order for books. Comprehensive papers often feature special pages at the
end, like indices, glossaries and bibliographies. Since this
is a quite complex topic, we will give you details in the
Frontmatter dedicated part Special Pages.
1. Half-title
Bibliography
2. Empty
3. Title page Any good research paper will have a complete list of ref-
erences. LaTeX has two ways of inserting your refer-
4. Information (copyright notice, ISBN, etc.) ences into a document:
20 CHAPTER 2. COMMON ELEMENTS
• you can embed them within the document itself. It’s The setspace package allows more fine-grained control
simpler, but it can be time-consuming if you are over line spacing. To set “one and a half” line spacing
writing several papers about similar subjects so that document-wide, but not where it is usually unnecessary
you often have to cite the same books. (e.g. footnotes, captions):
• you can store them in an external BibTeX file and To change line spacing within the document, the setspace
then link them via a command to your current doc- package provides the environments singlespace, onehalf-
ument and use a Bibtex style to define how they ap- space, doublespace and spacing:
pear. This way you can create a small database of
the references you might use and simply link them,
Non-breaking spaces
letting LaTeX work for you.
This essential feature is a bit unknown to newcomers,
To learn how to add a bibliography to your document, see
although it is available on most WYSIWYG document
the Bibliography Management section.
processors. A non-breaking space between two tokens
(e.g. words, punctuation marks) prevents the processors
2.1.6 Notes and references from inserting a line break between them. Besides a non-
breaking space cannot be enlarged. It is very important
[1] http://tex.stackexchange.com/questions/20538/ for a consistent reading.
what-is-the-right-order-when-using-frontmatter-tableofcontents-mainmatter
LaTeX uses the '~' symbol as a non-breaking space. You
would usually use non-breaking spaces for punctuation
marks in some languages, for units and currencies, for
2.2 Text Formatting initials, etc. In French typography, you would put a non-
breaking space before all two-parts punctuation marks.
This section will guide you through the formatting tech- Examples:
niques of the text. Formatting tends to refer to most things
to do with appearance, so it makes the list of possible top-
ics quite eclectic: text style, spacing, etc. If formatting Space between words and sentences
may also refer to paragraphs and to the page layout, we
will focus on the customization of words and sentences To get a straight right margin in the output, LaTeX in-
for now. serts varying amounts of space between the words. By
A lot of formatting techniques are required to differenti- default, it also inserts slightly more space at the end of
ate certain elements from the rest of the text. It is often a sentence. However, the extra space added at the end
necessary to add emphasis to key words or phrases. Foot- of sentences is generally considered typographically old-
notes are useful for providing extra information or clarifi- fashioned in English language printing. (The practice is
cation without interrupting the main flow of text. So, for found in nineteenth century design and in twentieth cen-
these reasons, formatting is very important. However, it tury typewriter styles.) Most modern typesetters treat the
is also very easy to abuse, and a document that has been end of sentence space the same as the interword space.
over-done can look and read worse than one with none at (See for example, Bringhurst’s Elements of Typographic
all. Style.) The additional space after periods can be disabled
with the command
LaTeX is so flexible that we will actually only skim the
surface, as you can have much more control over the pre- which tells LaTeX not to insert more space after a pe-
sentation of your document if you wish. Having said that, riod than after ordinary character. Frenchspacing can be
one of the purposes of LaTeX is to take away the stress turned off later in your document via the \nonfrenchspac-
of having to deal with the physical presentation yourself, ing command.
so you need not get too carried away! If an author wishes to use the wider end-of-sentence spac-
ing, care must be exercised so that punctuation marks are
not misinterpreted as ends of sentences. TeX assumes
2.2.1 Spacing that sentences end with periods, question marks or excla-
mation marks. Although if a period follows an uppercase
Line Spacing letter, this is not taken as a sentence ending, since periods
after uppercase letters normally occur in abbreviations.
If you want to use larger inter-line spacing in a document, Any exception from these assumptions has to be specified
you can change its value by putting the by the author. A backslash in front of a space generates a
command into the preamble of your document. Use \line- space that will not be enlarged. A tilde ‘~’ character gen-
spread{1.3} for “one and a half” line spacing, and \line- erates a non-breaking space. The command \@ in front
spread{1.6} for “double” line spacing. Normally the lines of a period specifies that this period terminates a sentence
are not spread, so the default line spread factor is 1. even when it follows an uppercase letter. (If you are us-
2.2. TEXT FORMATTING 21
ing \frenchspacing, then none of these exceptions need be prevents “FORTRAN”, “Fortran” and “fortran” from be-
specified.) ing hyphenated at all. No special characters or symbols
are allowed in the argument. Example:
The command \- inserts a discretionary hyphen into a
Stretched spaces
word. This also becomes the only point where hyphen-
ation is allowed in this word. This command is especially
You can insert a horizontal stretched space with \hfill in a
useful for words containing special characters (e.g., ac-
line so that the rest gets “pushed” toward the right margin.
cented characters), because LaTeX does not automati-
For instance this may be useful in the header.
cally hyphenate words containing special characters.
Similarly you can insert vertical stretched space with
LaTeX does not hyphenate compound words that contain
\vfill. It may be useful for special pages.
a dash[1] . There are two packages that can add back flexi-
See Lengths for more details. bility. The hyphenat package supplies the \hyp command.
This command typesets the dash and then subjects the
constituent words to automatic hyphenation. After load-
Manual spacing ing the package:
one should write, instead of electromagnetic-endioscopy:
The spaces between words and sentences, between para-
graphs, sections, subsections, etc. is determined automat- The extdash package also offers features for controlling
ically by LaTeX. It is against LaTeX philosophy to insert the hyphenation of compound words containing dashes
spaces manually and will usually lead to bad formatting. — as opposed to the words themselves which it leaves to
Manual spacing is a matter of macro writing and package LaTeX. The shortcuts option enables a more compressed
creation. syntax:
See Lengths for more details. Typical usage is as follows, assuming the compressed syn-
tax. In both cases, LaTeX can break and hyphenate the
constituent words, but in the latter case, it will not break
2.2.2 Hyphenation after the L:
One or more words can be kept together on the one line
LaTeX hyphenates words whenever necessary. Hyphen- with the standard LaTeX command:
ation rules will vary for different languages. LaTeX
only supports English by default, so if you want to have This prevents hyphenation and causes its argument to be
correct hyphenation rules for your desired language, see kept together under all circumstances. For example:
Internationalization. \fbox is similar to \mbox, but in addition there will be a
If the hyphenation algorithm does not find the correct hy- visible box drawn around the content.
phenation points, you can remedy the situation by using To avoid hyphenation altogether, the penalty for hyphen-
the following commands to tell TeX about the exception. ation can be set to an extreme value:
The command
You can change the degree to which LaTeX will hyphen-
causes the words listed in the argument to be hyphenated ate by changing the value of \tolerance=1000 and \hy-
only at the points marked by “-”. The argument of the phenpenalty=1000. You'll have to experiment with the
command should only contain words built from normal values to achieve the desired effect. A document which
letters, or rather characters that are considered to be nor- has a low tolerance value will cause LaTeX not to tol-
mal letters by LaTeX. It is known that the hyphenation erate uneven spacing between words, hyphenating words
algorithm does not find all correct American English hy- more frequently than in documents with higher toler-
phenation points for several words. A log of known ex- ances. Also note that using a higher text width will de-
ceptions is published periodically in the TUGboat jour- crease the probability of encountering badly hyphenated
nal. (2012 list: https://www.tug.org/TUGboat/tb33-1/ word. For example adding
tb103hyf.pdf)
will widen the text width and reduce the amount of mar-
The hyphenation hints are stored for the language that gin overruns.
is active when the hyphenation command occurs. This
means that if you place a hyphenation command into the
preamble of your document it will influence the English 2.2.3 Quote-marks
language hyphenation. If you place the command af-
ter the \begin{document} and you are using some pack- LaTeX treats left and right quotes as different entities.
age for national language support like babel, then the hy- For single quotes, ` (on American keyboards, this symbol
phenation hints will be active in the language activated is found on the tilde key (adjacent to the number 1 key
through babel. The example below will allow “hyphen- on most keyboards) gives a left quote mark, and ' is the
ation” to be hyphenated as well as “Hyphenation”, and it right. For double quotes, simply double the symbols, and
22 CHAPTER 2. COMMON ELEMENTS
LaTeX will interpret them accordingly. (Don't use the " \DisableLigatures from the microtype package can dis-
for right double quotes: when the babel package is used able ligatures in the whole document to increase accessi-
for some languages (e.g. German), the " is redefined to bility.
produce an umlaut accent; using " for right double quotes Note that this will also disable ligatures such as "--" to
will either lead to bad spacing or it being used to produce "–", "---" to "—", etc.
an umlaut). On British keyboards, ' ` ' is left of the ' 1 ' key
and shares the key with ' ¬ ', and sometimes ' ¦ ' or ' | '. The If you are using XeLaTeX and OpenType fonts, the
apostrophe (') key is to the right of the colon/semicolon fontspec package allows for standard ligatures to be
key and shares it with the ' @ ' symbol. turned off as well as fancy swash ligatures to be turned
on.
The right quote is also used for apostrophe in LaTeX
without trouble. Another solution is to use the cmap package, which will
help the reader to interpret the ligatures:
For left bottom quote and European quoting style you
need to use T1 font encoding enabled by:
See Fonts for more details on font encoding. 2.2.7 Slash marks
The package csquotes offers a multilingual solution to
quotations, with integration to citation mechanisms of- The normal typesetting of the / character in LaTeX
fered by BibTeX. This package allows one for example does not allow following characters to be “broken” onto
to switch languages and quotation styles according to ba- new lines, which often create “overfull” errors in output
bel language selections. (where letters push off the margin). Words that use slash
marks, such as “input/output” should be typeset as “in-
put\slash output”, which allow the line to “break” after
the slash mark (if needed). The use of the / character in
2.2.4 Diacritics and accents LaTeX should be restricted to units, such as “mm/year”,
which should not be broken over multiple lines.
Most accents and diacritics may be inserted with direct
keyboard input by configuring the preamble properly. For A word after / or \slash is not automatically hyphenated.
symbols unavailable on your keyboard, diacritics may be This is a similar problem to non-hyphenation of words
added to letters by placing special escaped metacharacters with a dash described under Hyphenation. One way to
before the letter that requires the diacritic. have both a line break and automatic hyphenation in both
words is
See Special Characters.
Both / and \slash can be used with a zero \hspace like
this. \slash includes a penalty to make a line break there
2.2.5 Margin misalignment and interword less desirable. This combination can be made into a new
slash macro if desired. The hyphenat package includes an
spacing
\fshyp which will add a hyphen after the slash like “input/-
output” if the line breaks there.
Some very long words, numbers or URLs may not be hy-
phenated properly and move far beyond the side margin.
One solution for this problem is to use sloppypar envi-
ronment, which tells LaTeX to adjust word spacing less
2.2.8 Fonts
strictly. As a result, some spaces between words may be
To change the font family, emphasize text, and other font-
a bit too large, but long words will be placed properly.
related issues, see Fonts.
Another solution is to edit the text to avoid long words,
numbers or URLs approaching the side margin.
2.2.9 Formatting macros
2.2.6 Ligatures Even if you can easily change the output of your fonts
using those commands, you're better off not using explicit
Some letter combinations are typeset not just by setting commands like this, because they work in opposition to
the different letters one after the other, but by actually the basic idea of LaTeX, which is to separate the logical
using special symbols (like "ff"), called ligatures. Liga- and visual markup of your document. This means that
tures can be prohibited by inserting {} or, if this does if you use the same font changing command in several
not work, {\kern0pt} between the two letters in question. places in order to typeset a special kind of information,
This might be necessary with words built from two words. you should use \newcommand to define a “logical wrapper
Here is an example: command” for the font changing command.
Ligatures can interfere with some text-search tools (a This approach has the advantage that you can decide at
search for "finally” wouldn't find the string "finally”). The some later stage that you want to use some visual rep-
2.2. TEXT FORMATTING 23
resentation of danger other than \textit, without having Some fonts do not have text figures built in; the textcomp
to wade through your document, identifying all the oc- package attempts to remedy this by effectively generating
currences of \textit and then figuring out for each one text figures from the currently-selected font. Put \usep-
whether it was used for pointing out danger or for some ackage{textcomp} in your preamble. textcomp also al-
other reason. lows you to use decimal points, properly formatted dollar
See Macros for more details. signs, etc. within \oldstylenums{}.
One common use for text figures is in section, paragraph,
and page numbers. These can be set to use text figures by
2.2.10 Text mode superscript and sub- placing some code in your preamble:
script Should you use additional sectioning or paragraphing
commands, you may adapt the previous code listing to
To superscript text in text-mode, you can use the \textsu-
include them as well.
perscript{} command. This allows you to, for instance,
typeset 6th as 6th :
Note
Subscripting in text-mode is not supported by LaTeX
alone; however, several packages allow the use of A subsequent use of the \pagenumbering command, e.g.,
the \textsubscript{} command. For instance, bpchem, \pagenumbering{arabic}, will reset the \thepage com-
KOMA-Script2, and fixltx2e all support this command. mand back to the original. Thus, if you use the \pagenum-
Of these, fixltx2e is perhaps the most universal option bering command in your document, be sure to reinstate
since it is distributed with LaTeX and requires no ad- your \myThePage definition from the code above:
ditional packages to be implemented. Note that as of
April 2015, fixltx2e has been declared obsolete, and
the \textsubscript{} command can no longer be used. 2.2.12 Dashes and hyphens
changes can be used to restore the \textsubscript{} com-
mand. LaTeX knows four kinds of dashes: a hyphen (-), en dash
(–), em dash (—), or a minus sign (−). You can ac-
If you do not load a package that supports \textsub- cess three of them with different numbers of consecutive
script{}, the math mode must be used. This is easily ac- dashes. The fourth sign is actually not a dash at all—it is
complished in running text by bracketing your text with the mathematical minus sign:
the $ symbol. In math mode subscripting is done using
the underscore: _{}. The names for these dashes are: ‘-’(-) hyphen , ‘--’(–) en-
dash , ‘---’(—) em-dash and ‘ − ’(−) minus sign. They
For example, the formula for water is written as: have different purposes:
Note that in math mode text will appear in a font suit-
able for mathematical variables. In math mode, to gener-
ate Roman text, for example, one would use the \mathrm
command:
Note the use of \<space> to insert a space in math mode.
Similarly, you can superscript using: Use \hyp{} macro from hyphenat package instead of hy-
A very common use of subscripts within the text environ- phen if you want LaTeX to break compound words be-
ment is to typeset chemical formulas. For these purposes, tween lines.
a highly recommended package is mhchem. This pack- The commands \textendash and \textemdash are also used
age is easy to use and works with your text fonts (rather to produce en-dash (–), and em-dash (—), respectively.
than math fonts). To insert a chemical formula, use \ce{}
with the text-equivalent formula, for example:
2.2.13 Ellipsis (…)
See also Chemical Graphics for chemical symbols and
formulas. A sequence of three dots is known as an ellipsis, which is
commonly used to indicate omitted text. On a typewriter,
2.2.11 Text figures (“old style” numerals) a comma or a period takes the same amount of space as
any other letter. In book printing, these characters occupy
Many typographers prefer to use titling figures, some- only a little space and are set very close to the preceding
times called lining figures, when numerals are inter- letter. Therefore, you cannot enter ‘ellipsis’ by just typing
spersed with full caps, when they appear in tables, and three dots, as the spacing would be wrong. Instead, there
when they appear in equations, using text figures else- is a special command for these dots. It is called \ldots:
where. LaTeX allows this usage through the \old- Alternatively, you can use the \textellipsis command
stylenums{} command: which allows the spacing between the dots to vary.
24 CHAPTER 2. COMMON ELEMENTS
2.2.14 Ready-made strings such as extra vertical space inserted before a paragraph
\parskip can have a default dimension plus an amount
There are some very simple LaTeX commands for type- of expansion minus an amount of contraction. This is
setting special text strings: useful on pages in complex documents where not every
page may be an exact number of fixed-height lines long,
so some give-and-take in vertical space is useful. You
specify this in a \setlength command like this:
If you want to indent a paragraph that is not indented, you
can use
at the beginning of the paragraph. Obviously, this will
only have an effect when \parindent is not set to zero. If
you want to indent the beginning of every section, you can
2.2.15 Notes and References use the indentfirst package: once loaded, the beginning
of any chapter/section is indented by the usual paragraph
[1] hyphenat package documentation, p3 indentation.
To create a non-indented paragraph, you can use
This page uses material from Andy Roberts’ Getting to grips
as the first command of the paragraph. This might come
with LaTeX with permission from the author.
in handy when you start a document with body text and
not with a sectioning command.
2.3 Paragraph Formatting Be careful, however, if you decide to set the indent to
zero, then it means you will need a vertical space between
paragraphs in order to make them clear. The space be-
Altering the paragraph formatting is rarely necessary in
tween paragraphs is held in \parskip, which could be al-
academic writing. It is primarily used for formatting text
tered in a similar fashion as above. However, this param-
in floats or for more exotic documents.
eter is used elsewhere too, such as in lists, which means
you run the risk of making various parts of your docu-
2.3.1 Paragraph alignment ment look very untidy by changing this setting. If you
want to use the style of having no indentation with a space
Paragraphs in LaTeX are usually fully justified, i.e. flush between paragraphs, use the parskip package, which does
with both the left and right margins. For whatever rea- this for you, while making adjustments to the spacing of
son, should you wish to alter the justification of a para- lists and other structures which use paragraph spacing, so
graph, there are three environments at hand, and also La- they don't get too far apart. If you want both indent and
TeX command equivalents. break, use
All text between the \begin and \end of the specified en- To indent subsequent lines of a paragraph, use the TeX
vironment will be justified appropriately. The commands command \hangindent. (While the default behaviour is
listed are for use within other environments. For exam- to apply the hanging indent after the first line, this may
ple, p (paragraph) columns in tabular. be changed with the \hangafter command.) An example
follows.
However, if you really need to disable one of the above
commands locally (for example because you have to use The TeX commands \leftskip and \rightskip add addi-
some broken package), you can use the command \justi- tional space to the left and right sides of each line, al-
fying from package ragged2e. lowing the formatting for subsequent paragraphs to differ
from the overall document margins. This space is in ad-
dition to the indentation added by \parindent and \hangin-
2.3.2 Paragraph indent and break dent.
To change the indentation of the last line in a paragraph,
By default, the first paragraph after a heading follows the use the TeX command \parfillskip.
standard Anglo-American publishers’ practice of no in-
dentation. The size of subsequent paragraph indents is
determined by a parameter called \parindent. The de- 2.3.3 \paragraph line break
fault length that this constant holds is set by the document
class that you use. It is possible to override it by using the
Default style for \paragraph may seem odd in the first
\setlength command. This will set paragraph indents to place, as it writes the following text next to the title. If
1cm: you do not like it, use a class other than the traditional ar-
Whitespace in LaTeX can also be made flexible (what ticle/book, or use ConTeXt or PlainTeX. Hacking of the
Lamport calls “rubber” lengths). This means that values class in use is really not the way LaTeX is intended to be
2.3. PARAGRAPH FORMATTING 25
When using this command through the hyperref package, Another drawback is that content is still parsed and pos-
the URL is “clickable” in the PDF document, whereas it sibly expanded, so you cannot put anything you want in it
is not linked to the web when using only the url pack- (such as LaTeX commands).
age. Also when using the hyperref package, to remove
the border placed around a URL, insert pdfborder = {0 0
0 0} inside the \hypersetup{}. (Alternately pdfborder = Skipping parts of the source
{0 0 0} might work if the four zeroes do not.)
A more robust way of making the TeX engine skip some
You can put the following code into your preamble to part of the source is to use the TeX \iffalse-conditional.
change the style, how URLs are displayed to the normal The typical use is
font:
The \iffalse-conditional is always false.
See also Hyperlinks
Quoting text
Listing environment This is also an extension of the
verbatim environment provided by the moreverb pack- LaTeX provides several environments for quoting text;
age. The extra functionality it provides is that it can add they have small differences and they are aimed for dif-
line numbers along side the text. The command: \be- ferent types of quotations. All of them are indented on
gin{listing}[step]{first line}. The mandatory first line ar- either margin, and you will need to add your own quota-
gument is for specifying which line the numbering shall tion marks if you want them. The provided environments
commence. The optional step is the step between num- are:
bered lines (the default is 1, which means every line will
be numbered). quote for a short quotation, or a series of small quotes,
To use this environment, remember to add \usepack- separated by blank lines.
age{moreverb} to the document preamble.
quotation for use with longer quotations, of more than
one paragraph, because it indents the first line of
Multiline comments each paragraph.
2.4.1 Adding the color package If you would like a color not pre-defined, you can use one
of the 68 dvips colors, or define your own. These options
To make use of these color features the color package are discussed in the following sections
must be inserted into the preamble.
Alternatively, one can write: The 68 standard colors known to dvips
The \usepackage is obvious, but the initialization of addi-
tional commands like usenames allows you to use names Invoke the package with the usenames and dvipsnames
of the default colors, the same 16 base colors as used in option. If you are using tikz or pstricks package you must
HTML. The dvipsnames allows you access to more col- declare the xcolor package before that, otherwise it will
ors, another 64, and svgnames allows access to about 150 not work.
colors. The initialization of “table” allows colors to be
added to tables by placing the color command just before
the table. The package loaded here is the xcolor package. 2.4.5 Defining new colors
If you need more colors, then you may also want to look at
If the predefined colors are not adequate, you may wish
adding the x11names to the initialization section as well,
to define your own.
this offers more than 300 colors, but you need to make
sure your xcolor package is the most recent you can down-
load. Place
If the background color and the text color is changed, Among the models you can use to describe the color are
then: the following (several more are described in the xcolor
manual):
There is also \fcolorbox to make framed background
color in yet another color:
Examples
2.4.4 Predefined colors To define a new color, follow the following example,
which defines orange for you, by setting the red to the
The predefined color names are maximum, the green to one half (0.5), and the blue to the
white, black, red, green, blue, cyan, magenta, yellow. minimum:
There may be other pre-defined colors on your system, The following code should give a similar results to the last
but these should be available on all systems. code chunk.
28 CHAPTER 2. COMMON ELEMENTS
If you loaded the xcolor package, you can define colors • The color package documentation
upon previously defined ones.
The first specifies 20 percent blue and 80 percent white;
the second is a mixture of 20 percent blue and 80 percent 2.5 Fonts
black; and the last one is a mixture of (20*0.3) percent
blue, ((100-20)*0.3) percent black and (100-30) percent Fonts are a complex topic. For common documents, only
green. Font families, Emphasizing text, and Font encoding are
xcolor also feature a handy command to define colors really needed. The other sections are more useful to
from color mixes: macro writers or for very specific needs.
Spot colors
2.5.2 Font families
Spot colors are customary in printing. They usually re-
fer to pre-mixed inks based on a swatchbook (like Pan- There are many font families e.g. Computer Modern,
tone, TruMatch or Toyo). The package colorspace ex- Times, Arial and Courier. Those families can be grouped
tends xcolor to provide real spot colors. They are defined into three main categories: roman (rm) or serif, sans serif
with, say: (sf) and monospace (tt) (see Typeface for more details).
Each font family comes with the default design which falls
into one of those categories; however, it is interchange-
2.4.6 Sources able among them. Computer Modern Roman is the de-
fault font family for LaTeX. Fonts in each family also have
• The xcolor manual different properties (size, shape, weight, etc.). Families
2.5. FONTS 29
are meant to be consistent, so it is highly discouraged to Typewriter Fonts Furthermore, the Bera Mono (Bit-
change fonts individually rather than the whole family. Stream Vera Mono) and LuxiMono fonts were designed
The three families are defined by their respective vari- to look good when used in conjunction with the Com-
ables: puter Modern serif font.
\usepackage[scaled=0.85]{beramono}
• \rmdefault
The default family is contained in the \familydefault vari- Mathematical Formula Fonts
able, and it is meant to have one of the three aforemen-
tioned variables as value. The default is defined like the
following assignment: 2.5.4 Emphasizing text
This will turn all the part of the document using the de-
fault font to the default sans serif, which is Computer In order to add some emphasis to a word or a phrase, the
Modern Sans Serif if you did not change the default font. simplest way is to use the \emph{text} command, which
usually italicizes the text. Italics may be specified explic-
Changing font families usually works in two steps:
itly with \textit{text}.
1. First specify which family you want to change (rm, Note that the \emph command is dynamic: if you empha-
sf or tt). size a word which is already in an emphasized sentence,
it will be reverted to the upright font.
2. Second specify the new default family if it is not rm. Text may be emphasized more heavily through the use
of boldface, particularly for keywords the reader may be
Mathematical fonts is a more complex matter. Fonts may trying to find when reading the text. As bold text is gen-
come with a package that will take care of defining all erally read before any other text in a paragraph or even on
three families plus the math fonts. You can do it by your- a page, it should be used sparingly. It may also be used in
self, in which case you do not have to load any package. place of italics when using sans-serif typefaces to provide
a greater contrast with unemphasized text. Bold text can
Below is an example[1] that demonstrates how to change
be generated with the \textbf{text} command.
a specific family.
The three default family font variables and the \familyde-
fault variable should not be confused with their respective 2.5.5 Font encoding
switch:
A character is a sequence of bytes, and should not be con-
• \normalfont fused with its representation, the glyph, which is what the
reader sees. So the character 'a' has different represen-
• \rmfamily tations following the used font, for example the upright
version, the italic version, various weights and heights,
• \sffamily and so on.
• \ttfamily Upon compilation, tex will have to choose the right font
glyph for every character. This is what is called font en-
coding. The default LaTeX font encoding is OT1, the en-
2.5.3 Available LaTeX Fonts [2] coding of the original Computer Modern TeX text fonts.
It contains only 128 characters, many from ASCII, but
To choose a font of your liking, please visit http://www. leaving out some others and including a number that are
tug.dk/FontCatalogue/. Here are some common exam- not in ASCII. When accented characters are required,
ples. TeX creates them by combining a normal character with
an accent. While the resulting output looks perfect, this
Below are some fonts which are installed by default. approach has some caveats.
Sans Serif Fonts • Searches for words with accents in PDFs will fail.
30 CHAPTER 2. COMMON ELEMENTS
• Extracting ('e.g.' copy paste) the umlaut 'Ä' via a files. So it is possible to build a new font family by spec-
PDF viewer actually extracts the two characters '"A'. ifying the font styles of different font families.
To overcome these shortcomings, several 8-bit CM-like The commands in column two are not entirely equiva-
font sets were created. Extended Cork (EC) fonts in T1 lent to the commands in column one: They do not cor-
encoding contains letters and punctuation characters for rect spacing after the selected font style has ended. The
most of the European languages based on Latin script. commands in column one are therefore in general recom-
The LH font set contains letters necessary to typeset doc- mended.
uments in languages using Cyrillic script. Because of You may have noticed the absence of underline. This is
the large number of Cyrillic glyphs, they are arranged because underlining is not recommended for typographic
into four font encodings—T2A, T2B, T2C, and X2. The reasons (it weighs the text down). You should use emph
CB bundle contains fonts in LGR encoding for the com- instead. However underlining text provides a useful extra
position of Greek text. By using these fonts you can form of emphasis during the editing process, for exam-
improve/enable hyphenation in non-English documents. ple to draw attention to changes. Although underlining
Another advantage of using new CM-like fonts is that is available via the \underline{...} command, text under-
they provide fonts of CM families in all weights, shapes, lined in this way will not break properly. This function-
and optically scaled font sizes. ality has to be added with the ulem (underline empha-
All this is not possible with OT1; that’s why you may want sis) package. Stick \usepackage{ulem} in your pream-
to change the font encoding of your document. ble. By default, this overrides the \emph command with
the underline rather than the italic style. It is unlikely
Note that changing the font encoding will have some re- that you wish this to be the desired effect, so it is better
quirements over the fonts being used. The default Com- to stop ulem taking over \emph and simply call the under-
puter Modern font does not support T1. You will need line command as and when it is needed.
Computer Modern Super (cm-super) or Latin Modern
(lmodern), which are Computer Modern-like fonts with
T1 support. If you have none of these, it is quite frequent • To restore the usual \emph formatting, add
(depends on your TeX installation) that tex chooses a \normalem straight after the document envi-
Type3 font such as the Type3 EC, which is a bitmap font. ronment begins. Alternatively, use \usepack-
Bitmap fonts look rather ugly when zoomed or printed. age[normalem]{ulem}.
The fontenc package tells LaTeX what font encoding to • To underline, use \uline{...} along with \usepack-
use. Font encoding is set with: age[normalem]{ulem}..
where encoding is the font encoding. It is possible to load • To add a wavy underline, use \uwave{...} along with
several encodings simultaneously. \usepackage[normalem]{ulem}..
There is nothing to change in your document to use CM
Super fonts (assuming they are installed), they will get • For a strike-out (strikethrough), use \sout{...} along
loaded automatically if you use T1 encoding. For lmod- with \usepackage[normalem]{ulem}..
ern, you will need to load the package after the T1 en-
• For a slash through each individual char-
coding has been set:
acter \xout{...} along with \usepack-
The package ae (almost European) is obsolete. It pro- age[normalem]{ulem}.
vided some workarounds for hyphenation of words with
special characters. These are not necessary any more with
Some font styles are not compatible one with the other.
fonts like lmodern. Using the ae package leads to text en-
But some extra packages will fill this hole. For bold small
coding problems in PDF files generated via pdflatex (e.g.
capitals, you might want to use:
text extraction and searching), besides typographic issues.
Sizing text
2.5.6 Font styles
To apply different font sizes, simply follow the commands
Each family has its own font characteristics (such as italic on this table:
and bold), also known as font styles, or font properties. These commands change the size within a given scope, so
Font styles are usually implemented with different font for instance {\Large some words} will change the size of
2.5. FONTS 31
only some words, and does not affect the font in the rest 2.5.8 Arbitrary font size
of the document. It will work for most parts of the text.
These commands cannot be used in math mode. How- The \tiny...\Huge commands are often enough for most
ever, part of a formula may be set in a different size by contents. These are fixed sizes however. In most docu-
using an \mbox command containing the size command. ment processors, you can usually choose any size for any
The new size takes effect immediately after the size com- font. This is because the characters actually get magni-
mand; if an entire paragraph or unit is set in a certain fied. If it usually looks correct for medium sizes, it will
size, the size command should include the blank line or look odd at extreme sizes because of an unbalanced thick-
the \end{...} which delimits the unit. ness. In TeX it is possible to change the magnification of
anything, but highly discouraged for the aforementioned
The default for \normalsize is 10 point (option 10pt), but reason. Changing the font size is made by changing the
it may differ for some Document Styles or their options. font file. Yes, there is a file for every size: cmr10 for
The actual size produced by these commands also de- Computer Modern Roman 10pt, cmr12 for Computer
pends on the Document Style and, in some styles, more Modern Roman 12pt, etc. This ensure the characters
than one of these size commands may produce the same are correctly balanced and remain readable at all defined
actual size. sizes.
Note that the font size definitions are set by the docu- You may choose a particular font size with the \font-
ment class. Depending on the document style the actual size{<size>}{<line space>} command. Example:
font size may differ from that listed above. And not every
document class has unique sizes for all 10 size commands. If you are using the default Computer Modern font with
OT1 encoding, you may get the following message:
As a technical note, points in TeX follow the standard
American point size in which 1 pt is approximately LaTeX Font Warning: Font shape `OT1/cmr/m/n' in size
0.35136 mm. The standard point size used in most mod- <142.26378> not available (Font) size <24.88> substi-
ern computer programs (known as the desktop publish- tuted on input line 103.
ing point or PostScript point) has 1 pt equal to approx- In that case you will notice that the font size cannot be
imately 0.3527 mm while the standard European point changed beyond \tiny and \Huge. You must switch to a
size (known as the Didot point) had 1 pt equal to approx- more sizable font, e.g.
imately 0.37597151 mm (see: point (typography)).
\fontencoding The font encoding, such as OT1 (TeX 2.5.10 Using arbitrary system fonts
default) or T1 (extended characters support, better
PDF support, widely used). If you use the XeTeX or LuaTeX engine and the fontspec
\fontfamily The font family. package, you'll be able to use any font installed in the
system effortlessly. XeTeX also allows using OpenType
\fontseries The series: l=light, m=medium, b=bold, technology of modern fonts like specifying alternate
bx=very bold. glyphs and optical size variants. XeTeX also uses
Unicode by default, which might be helpful for font is-
\fontshape The shape: it=italic, n=normal, sl=slanted,
sues.
sc=small capitals.
To use the fonts, simply load the fontspec package and set
The \selectfont command is mandatory, otherwise the the font:
font will not be changed. It is highly recommended to Then compile the document with xelatex or lualatex.
enclose the command in a group to cleanly return to the Note that you can only generate .pdf files, and that you
previous font selection when desired. need a sufficiently new TeX distribution (TeX Live 2009
You can use all these commands in a row: should work for XeTeX and Tex Live 2010 for LuaTeX).
Also you should not load the inputenc or fontenc pack-
The default values are stored in \encodingdefault, \fam- age. Instead make sure that your document is encoded as
ilydefault, \seriesdefault and \shapedefault. Setting back UTF-8 and load fontspec, which will take care of the font
the default font properties can be done with encoding. To make your document support both pdfla-
For short, you can use the \use- tex and xelatex/lualatex you can use the \ifxetex/ \ifluatex
font{<encoding>}{<family>}{<series>}{<shape>} macro from the ifxetex/ ifluatex package. For example
command. for xelatex
32 CHAPTER 2. COMMON ELEMENTS
• LaTeX And TrueType Font The description environment is slightly different. You
can specify the item label by passing it as an optional ar-
• True Type Fonts with LaTeX under Linux + MiK- gument (although optional, it would look odd if you didn't
TeX 2.5 include it!). Ideal for a series of definitions, such as a
glossary.
• Unicode Truetype font installer for LaTeX under
Sometimes you want a description where the text begins
Windows + MikTeX
on a new line. This cannot easily be done with \\. The
trick is to use \hfill[1] .
• Using TrueType fonts with TeX (LaTeX) and pdf-
TeX (pdfLaTeX) (for MikTeX)
2.6.2 Nested lists
2.5.13 References LaTeX will happily allow you to insert a list environment
into an existing one (up to a depth of four—if you need
[1] found at the Google discussion group latexlovers more than four, use the easylist package). Simply begin
the appropriate environment at the desired point within
[2] Taken from http://www.macfreek.nl/memory/Fonts_in_ the current list. Latex will sort out the layout and any
LaTeX numbering for you.
2.6. LIST STRUCTURES 33
2.6.3 Customizing lists use any of the style tokens as text they can be en-
closed in braces, e.g. {A} will give a literal A.
Customizing LaTeX is outside the beginners’ domain. <ref ftp://tug.ctan.org/ctan/macros/latex/required/tools/
While not necessarily difficult in itself, because beginners enumerate.pdf> CTAN documentation for enumer-
are already overwhelmed with the array of commands and ate</ref>
environments, moving on to more advanced topics runs Sometimes you may want to place some short text in front
the risk of confusion. of the enumeration for example: “Exercise 1, Exercise 2,
However, since the tutorial aims at being complete, we Execise 3, ...”. This is possible with the enumitem pack-
shall still include a brief guide on customizing lists. Feel age:
free to skip! \bfseries makes it bold, Exercise is the text and \arabic*
Note that in the following when \renewcommand is used inserts the counter followed by a colon (:) which is treated
it must appear after the \begin{document} instruction so as text again.
the changes made are taken into account. This is needed
for both enumerated and itemized lists.
Manually To go any further and do it yourself instead,
Also beware of the spaces in the label definitions. It is a a brief introduction to LaTeX counters is required. You
common error! should check the dedicated chapter as we will not delve
into the details for now.
Line spacing There are four individual counters that are associated with
itemized lists, each one represents the four possible levels
As you may have noticed, in standard LaTeX document of nesting, which are called:
classes, the vertical spacing between items, and above and The counter is incremented by \item before it is printed.
below the lists as a whole, is more than between para- For example to reset enumi use:
graphs: it may look odd if the descriptions are too short.
The command responsible for formatting the various lev-
els of nesting are
Using packages If you want tightly-packed lists, use Example:
the mdwlist package (included in the mdwtools bundle),
This simply redefines the appearance of the label, which is
which provides compact, “starred” versions of the previ-
fine, providing that you do not intend to cross-reference to
ous environments, i.e. itemize*, enumerate* and descrip-
a specific item within the list, in which case the reference
tion*. They work exactly in the same way, but the output
will be printed in the original format. This issue does not
is more compact. Other packages providing compacted
arise if you redefine the counter printer:
lists are paralist and enumitem.
Alternatively, use the memoir class and with \tightlists.
Customizing itemized lists
Customizing manually Inside lists you can redefine Itemized lists are not as complex as they do not need
some length/dimension variables of LaTeX, for example to count. Therefore, to customize, you simply change
using: the labels. It can be done manually for each entry with
Alternatively, to create a unified look in your document \item[new symbol], eg \item[$\star$].
you can redefine the enumerate environment: The itemize labels are accessed via \labelitemi, \la-
Another approach is to redefine the \item command glob- belitemii, \labelitemiii, \labelitemiv, for the four respec-
ally. tive levels.
The above example would set the labels for the first level
to a greater than (>) symbol. Of course, the text symbols
Customizing enumerated lists available in Latex are not very exciting. Why not use one
of the ZapfDingbat symbols, as described in the Symbols
Using packages The thing people want to change most section. Or use a mathematical symbol:
often with Enumerated lists are the counters. A quick so-
Itemized list with tightly set items, that is with no vertical
lution to this problem is provided by the enumerate pack-
space between two consecutive items, can be created as
age of David Carlisle[2] , or the more sophisticated pack-
follows.
age enumitem by Javier Bezos[3] . When using enumerate,
it is possible to specify the style of the numbering: \be-
gin{enumerate}[style].
2.6.4 Inline lists
The options A, a, I, i and 1 define the style and are
self-explanatory, anything else is treated as text. To Inline lists can be achieved as follows.
34 CHAPTER 2. COMMON ELEMENTS
With package paralist The FinalMark parameter sets the punctuation of the fi-
nal counter (Ex: FinalMark3={)}) while FinalSpace sets
The paralist package provides the inparaenum environ- the amount of space between the item and the item’s text.
ment (with an optional formatting specification in square The Margin parameter sets the distance from the left mar-
brackets): gin (Ex: FinalSpace2=1cm). The Progressive parameter
To change the styles of the counter, tokens A, a, I, i, and sets the distance from the left margin of all items in pro-
1 can be used in the optional argument to produce the portion to their level.
counter with one of the styles \Alph, \alph, \Roman, \ro- The {{{1}}} parameter prevents the first n counters from
man and \arabic. For example: \begin{inparaenum}[(i)] appearing in all levels. If there is a number after a param-
produces the labels (i), (ii), (iii) ... eter (Ex: Style3*) then this numbers indicates the level
that it will affect (Ex: Style3=\color{red}).
It features predefined styles which you can set as optional Besides using easylist along with figures may cause some
argument. trouble to the layout and the indentation. LaTeX lists do
not have this problem.
Available styles:
To use easylist with Beamer, each frame that uses easylist
must be marked as fragile:
• tractatus
The rules for producing characters with diacritical marks, cents in it, since both encoding are ASCII superset they
such as accents, differ somewhat depending whether you encode the classic letters the same way. There aren't
are in text mode, math mode, or the tabbing environment. many advantages in using Latin1 over UTF-8, which is
technically superior. UTF-8 is also becoming the most
widely used encoding (on the Web, in modern Unices,
2.7.1 Input encoding etc.).
A technical matter
Dealing with LaTeX
Most of the modern computer systems allow you to input
TeX uses ASCII by default. But 128 characters is not
letters of national alphabets directly from the keyboard. If
enough to support non-english languages. TeX has its
you tried to input these special characters in your LaTeX
own way to do that with commands for every diacritical
source file and compiled it, you may have noticed that
marking (see Escaped codes). But if we want accents and
they do not get printed at all.
other special characters to appear directly in the source
A LaTeX source document is a plain text file. A computer file, we have to tell TeX that we want to use a different
stores data in a binary format, that is a sequence of bits encoding.
(0 and 1). To display a plain text file, we need a code
There are several encodings available to LaTeX:
which tells which sequence of bits corresponds to which
sequence of characters. This association is called input
encoding, character encoding, or more informally charset. • ASCII: the default. Only bare english characters are
supported in the source file.
For historical reasons, there are many different input en-
codings. There is an attempt to unify all the encoding • ISO-8859-1 (a.k.a. Latin 1): 8-bits encoding. It
with a specification that contains all existent symbols that supports most characters for latin languages, but
are known from human history. This specification is Uni- that’s it.
code. It only defines code points, which is a number for a
symbol, but not the way symbols are represented in binary • UTF-8: a Unicode multi-byte encoding. Supports
value. For that, unicode encodings are in charge. There the complete Unicode specification.
are also several unicode encodings available, UTF-8 be-
• Others...
ing one of them.
The ASCII encoding is an encoding which defines 128 In the following we will assume you want to use UTF-8.
characters on 7 bits. Its widespread use has led the vast
majority of encodings to have backward compatibility There are some important steps to specify encoding.
with ASCII, by defining the first 128 characters the same
way. The other characters are added using more bits (8 • Make sure your text editor decodes the file in UTF-
or more). 8.
This is actually a big issue, since if you do not use the • Make sure it saves your file in UTF-8. Most text
right encoding to display a file, it will show weird charac- editors do not make the distinction, but some do,
ters. What most programs try to do is guess statistically such as Notepad++.
the encoding by analyzing the frequent sequences of bits.
Sadly, it is not 100% safe. Some text editors may not • If you are working in a terminal, make sure it is set
bother guessing the encoding and will just use the OS to support UTF-8 input and output. Some old Unix
default encoding. You should consider that other people terminals may not support UTF-8. PuTTY is not set
might not be able to display directly your input files on to use UTF-8 by default, you have to configure it.
their computer, because the default encoding for text file
• Tell LaTeX that the source file is UTF-8 encoded.
is different. It does not mean that the user cannot use an-
other encoding, besides the default one, only that it has
to be configured. For example, the German umlaut ä on inputenc [2] package tells LaTeX what the text encoding
OS/2 is encoded as 132, with Latin1 it is encoded as 228, format of your .tex files is.
while in Cyrillic encoding cp1251 this letter does not ex- The inputenc package allows as well the user to change
ist at all. Therefore you should consider encoding with the encoding within the document by means of the com-
care. mand \inputencoding{'encoding name'}.
The following table shows the default encodings for some
operating systems.
Extending the support
UTF-8 and Latin1 are not compatible. It means that if
you try to open a Latin1-encoded file using a UTF-8 de- The LaTeX support of UTF-8 is fairly specific: it includes
coding, it will display odd symbols only if you used ac- only a limited range of unicode input characters. It only
36 CHAPTER 2. COMMON ELEMENTS
defines those symbols that are known to be available with ier coding of umlauts, the babel package can be config-
the current font encoding. You might encounter a situa- ured as \usepackage[german]{babel}. This provides the
tion where using UTF-8 might result in error: short hand “o for \"o. This is very useful if one needs to
! Package inputenc Error: Unicode char \u8:ũ not set up use some text accents in a label, since no backslash will
for use with LaTeX. be accepted otherwise.
This is due to the utf8 definition not necessarily having a More information regarding language configuration can
be found in the Internationalization section.
mapping of all the character glyphs you are able to enter
on your keyboard. Such characters are for example
ŷŶũŨẽẼĩĨ 2.7.3 Less than < and greater than >
In such case, you may try need to use the utf8x option
to define more character combinations. utf8x is not offi- The two symbols '<' and '>' are actually ASCII charac-
cially supported, but can be viable in some cases. How- ters, but you may have noticed that they will print '¡' and
ever it might break up compatibility with some packages '¿' respectively. This is a font encoding issue. If you want
like csquotes. them to print their real symbol, you will have to use an-
other font encoding such as T1, loaded with the fontenc
Another possiblity is to stick with utf8 and to define the
package. See Fonts for more details on font encoding.
characters yourself. This is easy:
Alternatively, they can be printed with dedicated com-
where codepoint is the unicode codepoint of the desired
mands:
character. TeX sequence is what to print when the char-
acter matching the codepoint is met. You may find code-
points on this site. Codepoints are easy to find on the web.
Example: 2.7.4 Euro € currency symbol
Now inputting 'ŷ' will effectively print 'ŷ'. When writing about money these days, you need the euro
With XeTeX and LuaTeX the inputenc package is no sign. The textcomp package features a \texteuro com-
longer needed. Both engines support UTF-8 directly and mand which gives you the euro symbol as supplied by
allow the use of TTF and OpenType fonts to support Uni- your current text font. Depending on your chosen font
code characters. See the Fonts section for more informa- this may be quite far from the official symbol.
tion. An official version of the euro symbol is provided by eu-
rosym. Load it in the preamble (optionally with the offi-
cial option):
2.7.2 Escaped codes
then you can insert it with the \euro{} command. Finally,
In addition to direct UTF-8 input, LaTeX supports the if you want a euro symbol that matches with the current
composition of special characters. This is convenient if font style (e.g., bold, italics, etc.) you can use a different
your keyboard lacks some desired accents and other dia- option:
critics. again you can insert the euro symbol with \euro{}.
The following accents may be placed on letters. Although Alternatively you can use the marvosym package which
'o' letter is used in most of the examples, the accents may also provides the official euro symbol.
be placed on any letter. Accents may even be placed
above a “missing” letter; for example, \~{} produces a Now that you have succeeded in printing a euro sign, you
tilde over a blank space. may want the '€' on your keyboard to actually print the
euro sign as above. There is a simple method to do that.
The following commands may be used only in paragraph You must make sure you are using UTF-8 encoding along
(default) or LR (left-right) mode. with a working \euro{} or \EUR{}command.
To place a diacritic on top of an i or a j, its dot has to be Complete example:
removed. The dotless version of these letters is accom-
plished by typing \i and \j. For example:
2.7.5 Degree symbol for temperature and
• \^\i should be used for i circumflex 'î';
math
• \"\i should be used for i umlaut 'ï'.
The easiest way to print temperature and angle values is
If a document is to be written completely in a language to use the \SI{value}{unit} command from the siunitx
that requires particular diacritics several times, then using package, which works both in text and math mode:
the right configuration allows those characters to be writ- For more information, see the documentation of the siu-
ten directly in the document. For example, to achieve eas- nitx package.
2.7. SPECIAL CHARACTERS 37
A common mistake is to use the \circ command. It will 2.7.7 In special environments
not print the correct character (though $^\circ$ will). Use
the textcomp package instead, which provides a \textde- Math mode
gree command.
For temperature, you can use the same command or opt Several of the above and some similar accents can also be
for the gensymb package and write produced in math mode. The following commands may
be used only in math mode.
Some keyboard layouts feature the degree symbol, you
can use it directly if you are using UTF-8 and textcomp. When applying accents to letters i and j, you can use
For better results (font quality) we recommend the use of \imath and \jmath to keep the dots from interfering with
an appropriate font, like lmodern: the accents:
Tabbing environment
2.7.6 Other symbols
Some of the accent marks used in running text have other
LaTeX has many symbols at its disposal. The majority of uses in the tabbing environment. In that case they can be
them are within the mathematical domain, and later chap- created with the following command:
ters will cover how to get access to them. For the more
common text symbols, use the following commands: • \a' for an acute accent
Not mentioned in above table, tilde (~) is used in LaTeX
• \a` for a grave accent
code to produce non-breakable space. To get printed tilde
sign, either write \~{} or \textasciitilde{}. And a visible • \a= for a macron accent
space ␣ can be created with \textvisiblespace.
For some more interesting symbols, the Postscript ZipfD-
ingbats font is available thanks to the pifont package. Add 2.7.8 Unicode keyboard input
the declaration to your preamble: \usepackage{pifont}.
Next, the command \ding{number}, will print the speci- Some operating systems provide a keyboard combination
fied symbol. Here is a table of the available symbols: to input any Unicode code point, the so-called unicode
compose key.
Many X applications (*BSD and GNU/Linux) support
the Ctrl+Shift+u combination. A 'u' symbol should ap-
pear. Type the code point and press enter or space to
actually print the character. Example:
<Ctrl+Shift+u> 20AC <space>
will print the euro character.
Desktop environments like GNOME and KDE may fea-
ture a customizable compose key for more memorizable
sequences.
Xorg features advanced keyboard layouts with variants
that let you enter a lot of characters easily with combina-
tion using the aprioriate modifier, like Alt Gr. It highly
depends on the selected layout+variant, so we suggest you
to play a bit with your keyboard, preceeding every key and
dead key with the Alt Gr modifier.
Alternative choice using iflang texts using Cyrillic letters[1] . Support for Cyrillic is based
on standard LaTeX mechanisms plus the fontenc and
The current language can also be tested by using the iflang inputenc packages. AMS-LaTeX packages should be
package by Heiko Oberdiek (the built-in feature from the loaded before fontenc and babel. If you are going to use
babel package is not reliable). Here comes a simple ex- Cyrillics in mathmode, you also need to load mathtext
ample: package before fontenc:
\IfLanguageName{ngerman}{Hallo}{Hello} Generally, babel will automatically choose the default
font encoding, for the above three languages this is T2A.
This allows to easily distinguish between two languages
However, documents are not restricted to a single font
without the need of defining own commands. The babel
encoding. For multilingual documents using Cyrillic and
language is changed by setting
Latin-based languages it makes sense to include Latin
\selectlanguage{english} font encoding explicitly. Babel will take care of switch-
ing to the appropriate font encoding when a different lan-
guage is selected within the document.
2.8.4 Specific languages
On modern operating systems it is beneficial to use Uni-
Arabic script code (utf8 or utf8x) instead of KOI8-RU (koi8-ru) as an
input encoding for Cyrillic text.
For languages which use the Arabic script, including Ara- In addition to enabling hyphenations, translating automat-
bic, Persian, Urdu, Pashto, Kurdish, Uyghur, etc., add the ically generated text strings, and activating some language
following code to your preamble: specific typographic rules (like \frenchspacing), babel
You can input text in either romanized characters or na- provides some commands allowing typesetting according
tive Arabic script encodings. Use any of the following to the standards of Bulgarian, Russian, or Ukrainian lan-
commands and environments to enter in text: guages.
See the ArabTeX Wikipedia article for further details. For all three languages, language specific punctuation is
provided: the Cyrillic dash for the text (it is little nar-
You may also use the Arabi package within Babel to type- rower than Latin dash and surrounded by tiny spaces), a
set Arabic and Persian dash for direct speech, quotes, and commands to facilitate
You may also copy and paste from PDF files produced hyphenation:
with Arabi thanks to the support of the cmap package. The Russian and Ukrainian options of babel define the
You may use Arabi with LyX, or with tex4ht to produce commands
HTML.
which act like \Alph and \alph (commands for turning
See Arabi page on CTAN counters into letters, e.g. a, b, c...), but produce capi-
tal and small letters of Russian or Ukrainian alphabets
(whichever is the active language of the document).
Armenian
The Bulgarian option of babel provides the commands
The Armenian script uses its own characters, which will which make \Alph and \alph produce letters of either
require you to install a text editor that supports Unicode Bulgarian or Latin (English) alphabets. The default be-
and will allow you to enter UTF-8 text, such as Texmaker haviour of \Alph and \alph for the Bulgarian language op-
or WinEdt. These text editors should then be configured tion is to produce letters from the Bulgarian alphabet.
to compile using XeLaTeX.
See the Bulgarian translation of “The Not So Short Intro-
Once the text editor is set up to compile with XeLaTeX, duction to LaTeX” [2] for a method to type Cyrillic letters
the fontspec package can be used to write in Armenian: directly from the keyboard using a different distribution.
or
The Sylfaen font lacks italic and bold, but DejaVu Serif
supports them. Chinese
See Armenian Wikibooks for further details, especially One possible Chinese support is made available thanks to
on how to configure the Unicode supporting text editors the CJK package collection. If you are using a package
to compile with XeLaTeX. manager or a portage tree, the CJK collection is usually
in a separate package because of its size (mainly due to
Cyrillic script fonts).
Make sure your document is saved using the UTF-8 char-
Version 3.7h of babel includes support for the T2* encod- acter encoding. See Special Characters for more details.
ings and for typesetting Bulgarian, Russian and Ukrainian Put the parts where you want to write chinese characters
40 CHAPTER 2. COMMON ELEMENTS
in a CJK environment. ! Package inputenc Error: Unicode char \u8:° not set up
The last argument specifies the font. It must fit the desired for use with LaTeX.
language, since fonts are different for Chinese, Japanese The textcomp package will fix it for you.
and Korean. Possible choices for Chinese include: The great advantage of Babel for French is that it will
handle some elements of French typography for you, es-
• gbsn ( , simplified Chinese) pecially non-breaking spaces before all two-parts punctu-
ation marks. So now you can write:
• gkai ( , simplified Chinese)
The non-breaking space before the euro symbol is still
• bsmi ( , traditional Chinese) necessary because currency symbols and other units or
not supported in general (that’s not specific to French).
• bkai ( , traditional Chinese)
You can use the numprint package along Babel. It will let
you print numbers the French way.
Czech You will also notice that the layout of lists changes when
switching to the French language. This is customizable
Czech is fine using using the \frenchbsetup command. For more information
UTF-8 allows you to have „czech quotation marks“ di- on what the frenchb option of babel does and how you can
rectly in your text. Otherwise, there are macros \clqq customize its behavior, run LaTeX on file frenchb.dtx and
and \crqq to produce left and right quote. You can place read the produced file frenchb.pdf or frenchb.dvi. You
quotated text inside \uv. can get the PDF version on CTAN.
Finnish
There is a variant of TeX intended for Japanese named • hLATEXp by CHA Jaechoon
pTeX, which supports vertical typesetting.
• the CJK package by Werner Lemberg
Another possible way to write in japanese is to use Lu-
alatex and the luatex-ja package. Adapted example from HLATEX and hLATEXp are specific to Korean and pro-
the Luatexja documentation : vide Korean localization on top of the font support. They
You can also use capabilities provided by the Fontspec both can process Korean input text files encoded in EUC-
package and those provided by Luatexja-fontspec to de- KR. HLATEX can even process input files encoded in
clare the font you want to use in your paper. Let us take CP949/Windows-949/UHC and UTF-8 when used along
an example : with Λ, Ω.
Use UTF-8 as your encoding. In case you don't know The CJK package is not specific to Korean. It can process
how to do this, take a look at Texmaker, a LaTeX editor input files in UTF-8 as well as in various CJK encodings
which use UTF-8 by default. including EUC-KR and CP949/Windows-949/UHC, it
42 CHAPTER 2. COMMON ELEMENTS
Persian script
Hyphenation and typography It’s much more
For Persian language, there is a dedicated package called frowned upon to set pages with hyphenation between
XePersian which uses XeLaTeX as the typesetting en- pages than it is customary in American typesetting.
gine. Just add the following code to your preamble: To adjust penalties for hyphenation spanning pages, use
See XePersian page on CTAN this command:
Moreover, Arabic script can be used to type Persian as To adjust penalties for leaving widows and orphans (clubs
illustrated in the corresponding section. in TeX nomenclature) use those commands:
2.8. INTERNATIONALIZATION 43
Commas in math According to Polish typography with Spanish in the way they handle active characters, and
rules, fractional parts of numbers should be delimited by these options disable the internal workings of Spanish to
a comma, not a dot. To make LaTeX not insert addi- allow you to overcome these common pitfalls. Moreover,
tional space in math mode after a comma (unless there is these options may simplify the way LyX customizes some
a space after the comma), use the icomma package. features of the Spanish layout from inside the GUI.
Unfortunately, it is partially incompatible with the dcol-The options mexico,mexico-com provide support for lo-
umn package. One needs to either use dots in columns cal custom in Mexico: the former using decimal dot, as
with numerical data in the source file and make dcolumn customary, and the latter allowing decimal comma, as re-
switch them to commas for display or define the column quired by the Mexican Official Norm (NOM) of the De-
as follows: partment of Economy for labels in foods and goods. More
The alternative is to use the numprint package, but it is localizations are in the making.
much less convenient. The other commands modify the spanish layout after
loading Babel. Two particularly useful commands are
\spanishoperators and \spanishdeactivate.
Further information Refer the Słownik Or-
tograficzny (in Polish) for additional information on The macro \spanishoperators{<list of operators>}{ con-
Polish grammar and typography rules. tains a list of spanish mathematical operators, and may
be redefined at will. For instance, the command
Good extract is available at Zasady Typograficzne
Składania Tekstu (in Polish). only defines sen, overriding all other definitions; the com-
mand \let\spanishoperators\relax disables them all. This
command supports accented or spaced operators: the
Portuguese \acute{<letter>} command puts an accent, and the \,
command adds a small space. For instance, the follow-
Add the following code to your preamble: ing operators are defined by default.
You can substitute the language for brazilian portuguese Finally, the macro \spanishdeactivate{<list of charac-
by choosing brazilian or brazil. ters>} disables some active characters, to keep you out
of trouble if they are redefined by other packages. The
Slovak candidates for deactivation are the set {<>."'}. Please,
beware that some option preempt the availability of some
Basic settings are fine when left the same as Czech, but active characters. In particular, you should not combine
Slovak needs special signs for 'ď', 'ť', 'ľ'. To be able to the es-noquoting option with \spanishdeactivate{<>}, or
type them from keyboard use the following settings: the es-noshorthands with \spanishdeactivate{<>."}.
Please check the documentation for Babel or spanish.dtx
Spanish for further details.
2.9 Rotations just like for normal tables. The H option can not be used
without this package.
2.9.1 The rotating package
The package rotating gives you the possibility to rotate 2.10 Tables
any object of an arbitrary angle. Once you have loaded it
with the standard command in the preamble:
Tables are a common feature in academic writing, often
you can use three new environments: used to summarize research results. Mastering the art of
it will rotate the whole argument by 90 degrees counter- table construction in LaTeX is therefore necessary to pro-
clockwise. Moreover: duce quality papers and with sufficient practice one can
print beautiful tables of any kind.
it will turn the argument of 30 degrees. You can give any
angle as an argument, whether it is positive or negative. Keeping in mind that LaTeX is not a spreadsheet, it makes
It will leave the necessary space to avoid any overlapping sense to use a dedicated tool to build tables and then to
of text. export these tables into the document. Basic tables are not
too taxing, but anything more advanced can take a fair bit
like turn, but it will not add any extra space. of construction; in these cases, more advanced packages
If you want to make a float sideways so that the caption is can be very useful. However, first it is important to know
also rotated, you can use the basics. Once you are comfortable with basic LaTeX
tables, you might have a look at more advanced packages
or or the export options of your favorite spreadsheet. Thanks
Note, though, they will be placed on a separate page. to the modular nature of LaTeX, the whole process can
be automated in a fairly comfortable way.
If you would like to rotate a TikZ picture you could use
sideways together with minipage. For a long time, LaTeX tables were quite a chaotic topic,
with dozens of packages doing similar things, while not
You can also use the \rotatebox command. Let’s rotate a
always being compatible with one another. Sometimes
tabular inside a table for example:
you had to make trade-offs. The situation changed re-
cently (2010) with the release of the tabu package which
Options combines the power of longtable, tabularx and much
more. The tabu environment is far less fragile and re-
Default is sidewaysfigures/sidewaystables are oriented de- stricted than the older alternatives. Nonetheless, before
pending on page number in two sided documents (takes attempting to use this package for the first time it will
two passes). be beneficial to understand how the classic environment
works, since tabu works the same way. Note however that
The rotating package takes the following options.
the author of tabu will not fix bugs to the current version,
and that the next version introduces new syntax that will
counterclockwise/anticlockwise In single sided docu- likely break existing documents.[1]
ments turn sidewaysfigures/sidewaystables counter-
clockwise.
around the text as in a normal paragraph. You can pass Here is a simple example. The following code creates two
the width using any unit supported by LaTeX, such as 'pt' tables with the same code; the only difference is that the
and 'cm', or command lengths, such as \textwidth. You last column of the second one has a defined width of 5
can find a list in chapter Lengths. centimeters, while in the first one we didn't specify any
The optional parameter pos can be used to specify the width. Compiling this code:
vertical position of the table relative to the baseline of the You get the following output:
surrounding text. In most cases, you will not need this
option. It becomes relevant only if your table is not in a
paragraph of its own. You can use the following letters:
To specify a font format (such as bold, italic, etc.) for
an entire column, you can add >{\format} before you
declare the alignment. For example \begin{tabular}{
>{\bfseries}l c >{\itshape}r } will indicate a three col-
umn table with the first one aligned to the left and in bold
font, the second one aligned in the center and with normal
font, and the third aligned to the right and in italic. The
“array” package needs to be activated in the preamble for
this to work.
In the first line you have pointed out how many columns Note that the first table has been cropped, since the output
you want, their alignment and the vertical lines to separate is wider than the page width.
them. Once in the environment, you have to introduce
the text you want, separating between cells and introduc-
Manually broken paragraphs in table cells
ing new lines. The commands you have to use are the
following:
Sometimes it is necessary to not rely on the breaking al-
Note, any white space inserted between these commands gorithm when using the p specifier, but rather specify the
is purely down to ones’ preferences. I personally add line breaks by hand. In this case it is easiest to use a \par-
spaces between to make it easier to read. box:
This example shows how to create a simple table in La- To tweak the space between columns (LaTeX will by de-
TeX. It is a three-by-three table, but without any lines. fault choose very tight columns), one can alter the col-
Expanding upon that by including some vertical lines: umn separation: \setlength{\tabcolsep}{5pt}. The de-
fault value is 6pt.
To add horizontal lines to the very top and bottom edges
of the table:
Space between rows
And finally, to add lines between all rows, as well as
centering (notice the use of the center environment - of Re-define the \arraystretch command to set the space be-
course, the result of this is not obvious from the preview tween rows:
on this web page):
Default value is 1.0.
An alternative way to adjust the rule spacing is to
Text wrapping in tables
add \noalign{\smallskip} before or after the \hline and
LaTeX’s algorithms for formatting tables have a few \cline{i-j} commands:
shortcomings. One is that it will not automatically wrap You may also specify the skip after a line explicitly using
text in cells, even if it overruns the width of the page. glue after the line terminator
For columns that will contain text whose length exceeds
the column’s width, it is recommended that you use the p
attribute and specify the desired width of the column (al- Other environments inside tables
though it may take some trial-and-error to get the result
you want). For a more convenient method, have a look at If you use some LaTeX environments inside table cells,
The tabularx package, or The tabulary package. like verbatim or enumerate:
Instead of p, use the m attribute to have the lines aligned you might encounter errors similar to
toward the middle of the box or the b attribute to align ! LaTeX Error: Something’s wrong--perhaps a missing
along the bottom of the box. \item.
46 CHAPTER 2. COMMON ELEMENTS
To solve this problem, change column specifier to “para- It typically takes some text as its argument, and when ap-
graph” (p, m or b). pended to a column, it will automatically insert that text
into each cell in that column before the actual data for
that cell. This command kills the inter-column space and
Defining multiple columns replaces it with whatever is between the curly braces. To
add space, use @{\hspace{''width''}}.
It is possible to define many identical columns at once Admittedly, this is not that clear, and so will require a few
using the *{''num''}{''str''} syntax. This is particularly examples to clarify. Sometimes, it is desirable in scien-
useful when your table has many columns. tific tables to have the numbers aligned on the decimal
Here is a table with six centered columns flanked by a point. This can be achieved by doing the following:
single column on each side: The space-suppressing qualities of the @-expression ac-
tually make it quite useful for manipulating the horizontal
spacing between columns. Given a basic table, and vary-
Column specification using >{\cmd} and <{\cmd}
ing the column descriptions:
The column specification can be altered using the array
package. This is done in the argument of the tabular en-
vironment using >{\command} for commands executed Aligning columns at decimal points using dcolumn
right before each column element and <{\command} for
commands to be executed right after each column ele-
ment. As an example: to get a column in math mode en- Instead of using @-expressions to build columns of deci-
ter: \begin{tabular}{>{$}c<{$}}. Another example is mals aligned to the decimal point (or equivalent symbol),
changing the font: \begin{tabular}{>{\small}c} to print it is possible to center a column on the decimal separator
the column in a small font. using the dcolumn package, which provides a new column
specifier for floating point data. See the dcolumn package
The argument of the > and < specifications must be cor- documentation for more information, but a simple way to
rectly balanced when it comes to { and } characters. use dcolumn is as follows.
This means that >{\bfseries} is valid, while >{\textbf}
will not work and >{\textbf{} is not valid. If there A negative argument provided for the number of decimal
is the need to use the text of the table as an argu- places in the new column type allows unlimited decimal
ment (for instance, using the \textbf to produce bold places, but may result in rather wide columns. Round-
text), one should use the \bgroup and \egroup commands: ing is not applied, so the data to be tabulated should
>{\textbf\bgroup}c<{\egroup} produces the intended ef- be adjusted to the number of decimal places specified.
fect. This works only for some basic LaTeX commands. Note that a decimal aligned column is typeset in math
For other commands, such as \underline to underline text, mode, hence the use of \mathrm for the column head-
it is necessary to temporarily store the column text in a ing in the example above. Also, text in a decimal aligned
box using lrbox. First, you must define such a box with column (for example the header) will be right-aligned be-
\newsavebox{\boxname} and then you can define: fore the decimal separator (assuming there’s no decimal
separator in the text). While this may be fine for very
This stores the text in a box and afterwards, takes the text short text, or numeric column headings, it looks cum-
out of the box with \unhbox (this destroys the box, if the bersome in the example above. A solution to this is to
box is needed again one should use \unhcopy instead) and use the \multicolumn command described below, spec-
passing it to \underline. (For LaTeX2e, you may want to ifying a single column and its alignment. For exam-
use \usebox{\boxname} instead of \unhbox\boxname.) ple to center the header Decimal over its column in the
This same trick done with \raisebox instead of \underline above example, the first line of the table itself would be
can force all lines in a table to have equal height, instead of Left&Right&Center&\multicolumn{1}{c}{Decimal}\\
the natural varying height that can occur when e.g. math
terms or superscripts occur in the text.
Here is an example showing the use of both p{...} and
Bold text and dcolumn To draw attention to particular
>{\centering} :
entries in a table, it may be nice to use bold text. Ordi-
Note the use of \tabularnewline instead of \\ to avoid a narily this is easy, but as dcolumn needs to see the deci-
Misplaced \noalign error. mal point it is rather harder to do. In addition, the usual
bold characters are wider than their normal counterparts,
meaning that although the decimals may align nicely, the
@-expressions figures (for more than 2-−3 digits on one side of the deci-
mal point) will be visibly misaligned. It is however possi-
The column separator can be specified with the @{...} ble to use normal width bold characters and define a new
construct. bold column type, as shown below.[2]
2.10. TABLES 47
2.10.2 Row specification and opt out the first column that contains the text “Pow-
ers”.
It might be convenient to apply the same command over Here is another example exploiting the same ideas to
every cell of a row, just as for column. Unfortunately the make the familiar and popular “2x2” or double di-
tabular environment cannot do that by default. We will chotomy:
need tabu instead, which provides the \rowfont option.
The command for this looks like this: \multicol- Resizing table including the caption
umn{'num_cols’}{'alignment'}{'contents’}. num_cols is Alternatively you can use \scalebox{ratio}{object} in the
the number of subsequent columns to merge; alignment same way but with ratios rather than fixed sizes:
is either l, c, r, or to have text wrapping specify a width
p{5.0cm} . And contents is simply the actual data you
want to be contained within that cell. A simple example: Changing font size
Columns spanning multiple rows A table can be globally switched to a different font size
by simply adding the desired size command (here: \foot-
The first thing you need to do is add \usepack- notesize) in the table scope, which may be after the \be-
age{multirow} to the preamble[3] . This then pro- gin{table} statement if you use floats, otherwise you need
vides the command needed for spanning rows: \mul- to add a group delimiter.
tirow{''num_rows’'}{''width''}{''contents’'}. The argu- Alternatively, you can change the default font for all the
ments are pretty simple to deduce (* for the width means tables in your document by placing the following code in
the content’s natural width). the preamble:
The main thing to note when using \multirow is that a See Fonts for named font sizes. The table caption font
blank entry must be inserted for each appropriate cell in size is not affected. To control the caption font size, see
each subsequent row to be spanned. Caption Styles.
If there is no data for a cell, just don't type anything, but
you still need the "&" separating it from the next column’s
data. The astute reader will already have deduced that for 2.10.5 Colors
a table of n columns, there must always be n − 1 amper-
sands in each row (unless \multicolumn is also used). Alternate row colors in tables
Spanning in both directions simultaneously The xcolor package provides the necessary commands
to produce tables with alternate row colors, when
Here is a nontrivial example of how to use spanning in loaded with the table option. The command \rowcol-
both directions simultaneously and have the borders of ors{<''starting row''>}{<''odd color''>}{<''even color''>}
the cells drawn correctly: has to be specified right before the tabular environment
starts.
The command \multicolumn{1}{ is just used to draw
vertical borders both on the left and on the right of the The command \hiderowcolors is available to deactivate
cell. Even when combined with \multirow{2}{*}{...}, it highlighting from a specified row until the end of the ta-
still draws vertical borders that only span the first row. ble. Highlighting can be reactivated within the table via
To compensate for that, we add \multicolumn{1}{ in the the \showrowcolors command. If while using these com-
following rows spanned by the multirow. Note that we mands you experience “misplaced \noalign errors” then
cannot just use \hline to draw horizontal lines, since we use the commands at the very beginning or end of a row
do not want the line to be drawn over the text that spans in your tabular.
several rows. Instead we use the command \cline{2-6} or
48 CHAPTER 2. COMMON ELEMENTS
Colors of individual cells by using the X@{} option. Note that the \multicolumn
width (which in this example is 2) should equal the (in
As above this uses the xcolor package. this example 1+1) width of the spanned columns:
In a way analogous to how new commands with argu-
ments can be created with \newcommand, new column
2.10.6 Width and stretching types with arguments can be created with \newcolumn-
type as follows:
We keep providing documentation for tabular* and tab-
ularx although they are completely eclipsed by the much where since there are 4 columns, the sum of the \hsize’s
more powerful and flexible tabu environment. Actually (1 + 0.5 + 0.5 + 2) must be equal to 4. The default value
tabu is greatly inspired by those environments, so it may used by tabularx for \hsize is 1.
be worth it to have an idea how they work, particularly
for tabularx.
The tabulary package
2.10.14 The eqparbox package The captions show now up in the list of tables, if dis-
played.
On rare occasions, it might be necessary to stretch ev-
You can set the optional parameter position specifier to
ery row in a table to the natural width of its longest line,
define the position of the table, where it should be placed.
for instance when one has the same text in two languages
The following characters are all possible placements. Us-
and wishes to present these next to each other with lines
ing sequences of it define your “wishlist” to LaTeX.
synching up. A tabular environment helps control where
lines should break, but cannot justify the text, which leads Default is tbp, which means that it is by default placed on
to ragged right edges. The eqparbox package provides the top of the page. If that’s not possible, it’s placed at
the command \eqmakebox which is like \makebox but in- the bottom if possible, or finally with other floating envi-
stead of a width argument, it takes a tag. During compi- ronments on an extra page.
lation it bookkeeps which \eqmakebox with a certain tagYou can force LaTeX to use one given position. E.g. [!h]
contains the widest text and can stretch all \eqmakeboxes
forces LaTeX to place it exactly where you place it (Ex-
with the same tag to that width. Combined with the array
cept when it’s really impossible, e.g you place a table here
package, one can define a column specifier that justifies and this place would be the last line on a page). Again,
the text in all lines: understand it correctly: it urges LaTeX to put the table at
See the documentation of the eqparbox package for more a specific place, but it will not be placed there if LaTeX
details. thinks it will not look great. If you really want to place
your table manually, do not use the table environment.
Centering the table horizontally works like everything
2.10.15 Floating with table
else, using the \centering command just after opening the
table environment, or by enclosing it with a center envi-
In WYSIWYG document processors, it is common to put
ronment.
tables in the middle of the text. This is what we have
been doing until now. Professional documents, however,
often make it a point to print tables on a dedicated page
2.10.16 Using spreadsheets and data anal-
so that they do not disrupt the flow. From the point of
view of the source code, one has no idea on which page ysis tools
the current text is going to lie, so it is hardly possible to
For complex or dynamic tables, you may want to use a
guess which page may be appropriate for our table. La-
TeX can automate this task by abstracting objects such spreadsheet. You might save lots of time by building ta-
bles using specialized software and exporting them in La-
as tables, pictures, etc., and deciding for us where they
might fit best. This abstraction is called a float. Gener- TeX format. The following plugins and libraries are avail-
able for some popular software:
ally, an object that is floated will appear in the vicinity of
its introduction in the source file, but one can choose to
control its position also. • calc2latex: for OpenOffice.org Calc spreadsheets,
To tell LaTeX we want to use our table as a float, we need • excel2latex: for Microsoft Office Excel,
to place a tabular environment in a table environment,
which is able to float and add a label and caption. • matrix2latex: for MATLAB,
The table environment initiates a type of float just as the • matrix2latex: for Python and MATLAB,
environment figure. In fact, the two bear a lot of sim-
ilarities (positioning, captions, etc.). More information • pandas: pandas DataFrame’s have a method to con-
about floating environments, captions etc. can be found vert data they contain to latex,
in Floats, Figures and Captions.
• latex-tools: a Ruby library,
The environment names may now seem quite confusing.
Let’s sum it up: • xtable: a library for R,
• tabular is for the content itself (columns, lines, etc.). • org-mode: for Emacs users, org-mode tables can be
used inline in LaTeX documents, see for a tutorial.
• table is for the location of the table on the document,
plus caption and label support. • Emacs align commands: the align commands can
clean up a messy LaTeX table.
In the table, we used a label, so now we can refer to it just
like any other reference: • Online Table generator for LATeX: An online tool
for creating simple tables within the browser. La-
The table environment is also useful when you want to TeX format is directly generated as you type.
have a list of tables at the beginning or end of your doc-
ument with the command • Create LaTeX tables online : Online tool.
2.11. TITLE CREATION 51
However, copying the generated source code to your doc- 2.10.18 References
ument is not convenient at all. For maximum flexibility,
generate the source code to a separate file which you can [1] http://tex.stackexchange.com/questions/121841/
input from your main document file with the \input com- is-the-tabu-package-obsolete
mand. If your speadsheet supports command-line, you [2] D Carlisle. “Decimals in table don't align
can generate your complete document (table included) in with dcolumn when bolded”. Stackexchange.
one command, using a Makefile for example. http://tex.stackexchange.com/questions/118458/
decimals-in-table-dont-align-with-dcolumn-when-bolded.
See Modular Documents for more details.
[3] Package multirow on CTAN
• spreadtab: spread sheets allowing the use of formu- 2.11.2 Custom Title Pages
lae
Normally, the benefit of using LaTeX instead of tradi-
• siunitx: alignment of tabular entries tional word processing programs is that LaTeX frees you
to concentrate on content by handling margins, justifica-
• pgfplotstable: Loads, rounds, formats and postpro- tion, and other typesetting concerns. On the other hand,
cesses numerical tables. if you want to write your own title format, it is exactly
52 CHAPTER 2. COMMON ELEMENTS
the opposite: you have to take care of everything — this Remember, if you have a block of text in a different size,
time LaTeX will do nothing to help you. It can be chal- even if it is a bit of text on a single line, end it with \par.
lenging to create your own title format since LaTeX was
not designed to be graphically interactive in the adjust- Filling the page
ment of layout. The process is similar to working with
raw HTML with the added step that each time you want the command \vfill as the last item of your content will
to see how your changes look, you have to re-compile the add empty space until the page is full. If you put it within
source. While this may seem like a major inconvenience, the page, you will ensure that all the following text will be
the benefit is that once the customized title format has placed at the bottom of the page.
been written, it serves as a template for all other docu-
ments that would use the title format you have just made.
A practical example All these tips might have made
In other words, once you have a layout you like, you can
you confused. Here is a practical and compilable exam-
use it for any other documents where you would like the
ple. The picture in use comes with package mwe and
same layout without any additional fiddling with layout.
should be available with every complete LaTeX installa-
The title page of a book or a report is the first a reader will tion. You can start testing right away.
see. Keep that in mind when preparing your title page.
As you can see, the code looks “dirtier” than standard La-
TeX source because you have to take care of the output
Create the title for a report or book as well. If you start changing fonts it gets even more com-
plicated, but you can do it: it’s only for the title and your
A title page for reports to get a university degree is quite complicated code will be isolated from all the rest within
static, it doesn't really change over time. You can prepare its own file.
the titlepage in its own little document and prepare a one
page pdf that you later include into your real document.
Integrating the title page Assuming you have done
This is really useful, if the title page is required to have
the title page of your report in an extra document, let’s
completelyy different margins as the rest of the document.
pretend it is called reportTitlepage2015.pdf, you can in-
It also saves compile time, though it is not much.
clude it quite simply. Here is a short document setup.
You need to know very basic LaTeX layout commands in
order to get your own title page perfect. Usually a custom
titlepage does not contain any semantic markup, every- A title to be re-used multiple times
thing is hand crafted. Here are some of the most often
needed things: Some universities, departments and companies have strict
rules how a title page of a report should look like. To
ensure the very same output for all reports, a redefiniton
Alignment
of the \maketitle command is recommended.
if you want to center some text just use \centering. If you This is best done by an experienced LaTeX user. A sim-
want to align it differently you can use the environment ple example follows, as usual there is no real limit with
\raggedleft for right-alignment and \raggedright for left- respect to complexity.
alignment. As a starting point, a LaTeX package called
columbidaeTitle.sty is generated that defines the
Images complete title matter. It will later be hidden from the
end user. Ideally, the person creating the package should
the command for including images (a logo maintain it for a long time, create an accompanying
for example) is the following : \includegraph- documentation and ensure user support.
ics[width=0.15\textwidth]{./logo}. There is no \be- This package can be loaded within a usual document. The
gin{figure} as you would usually use since you don't want user can set the variables for title and the like. Which
it to be floating, you just want it exactly where want it commands are actually available, and which might be
to be. When handling it, remember that it is considered omissible should be written in a documentation that is
like a big box by the TeX engine. bundled with the package.
Look around what happens if you leave one or the other
Text size
command out.
[2] [http://www.ctan.org/tex-archive/macros/latex/contrib/
frontespizio Frontespizio package webpage in CTAN]
Margin notes Body
7
10
LaTeX and the document class will normally take care of 3
page layout issues for you. For submission to an academic
publication, this entire topic will be out of your hands, as
the publishers want to control the presentation. However, 8
11
for your own documents, there are some obvious settings
that you may wish to change: margins, page orientation Footer
It will not have been immediately obvious - because it • TeX → DVI → PDF
doesn't really cause any serious problems - that the de-
fault page size for all standard document classes is US let- latex myfile # TeX → DVI dvipdf myfile # DVI → PDF
ter. This is shorter by 18 mm (about 3/4 inch), and slightly
wider by 8 mm (about 1/4 inch), compared to A4 (which • TeX → DVI → PS → PDF
is the standard in almost all the rest of the world). While
this is not a serious issue (most printers will print the doc-
latex myfile # TeX → DVI dvips myfile -o myfile.ps #
ument without any problems), it is possible to specify al-
DVI → PS ps2pdf myfile.ps myfile.pdf # PS → PDF
ternative sizes as class option. For A4 format:
Sadly the PDF output page size may not be completely re-
spectful of your settings. Some of these tools do not have
More size options with geometry the same interpretation of the DVI, PS and PDF specifi-
cations, and you may end up with a PDF which has not
One of the most versatile packages for page layout is exactly the right size. Thankfully there is a solution to
the geometry package. The immediate advantage of this that: the \special command lets the user pass PostScript
package is that it lets you customize the page size even or PDF parameters, which can be used here to set the
with classes that do not support the options. For instance, page size appropriately.
to set the page size, add the following to your preamble:
The geometry package has many pre-defined page sizes, • For pdflatex to work fine, using the package geom-
like a4paper, built in. Others include: etry usually works.
• a0paper, a1paper, ..., a6paper, • For the DVI and PS ways, the safest way to always
get the right paper size in the end is to add
• b0paper, b1paper, ..., b6paper,
• letterpaper, to the tex file, and to append the appropriate parameters
to the processors used during output generation:
• legalpaper, dvips -t a4 ... ps2pdf -sPAPERSIZE=a4 ... # On Win-
• executivepaper. dows: ps2pdf -sPAPERSIZE#a4 ... [1]
If you want US Letter instead, replace 210mm,297mm
To explicitly change the paper dimensions using the ge- by 8.5in,11in and a4paper by letter. Also replace a4 by
ometry package, the paperwidth and paperheight options letter in command-line parameters.
can be used. For example:
Page size for tablets
Changing size manually
Those who want to read on tablets or other handheld dig-
Use the \setlength command to adjust the parameters to ital devices need to create documents without the ex-
the appropriate dimensions. See the Lengths chapter. tra whitespace. In order to create PDF documents with
optimal handheld viewing, not only must the text field
• In the preamble, \paperwidth and \paperheight in all and margins be adjusted, so must the page size. If you
cases. are looking for a sensible dimension, consider following
the paper size used by the Supreme Court of the United
• After the preamble, \pdfpagewidth and \pdfpage- States, 441pt by 666pt (or 6.125 inches by 9.25 inches),
height if you are using pdftex. which looks great on tablets. You could also use the
Supreme Court’s text field size of 297 pt by 513 pt, but
Using the PDF dedicated commands has one immediate this is too wide for fonts other than Century Schoolbook,
advantage: it will let you change the page dimension any- the font required by the Supreme Court.
where in the document.
2.12.4 Margins
Page size issues
Readers used to perusing typical physical literature are
If you intend to get a PDF in the end, there are basically probably wondering why there is so much white space
three ways: surrounding the text. For example, on A4 paper a doc-
ument will typically have 44 mm margin widths on the
• TeX → PDF left and right of the page, leaving about 60% of the page
2.12. PAGE LAYOUT 55
width for text. The reason is improved readability. Stud- obsolete and buggy. Use geometry package instead
ies have shown[2][3] that it’s easier to read text when there like this:
are 60–70 characters per line—and it would seem that 66
is the optimal number. Therefore, the page margins are • Edit individual page dimension variables described
set to ensure optimal readability, and excessive margin above, using the \addtolength and \setlength com-
white space is tolerated as a consequence. Sometimes, mands. See the Lengths chapter. For instance,
this white space is left in the inner margin with the as-
sumption that the document will be bound.
If you wish to avoid excessive white space, rather than Odd and even margins
changing the margins, consider instead using a two-
column (or more) layout. This approach is the one usually Using the geometry package, the options left and right are
taken by print magazines because it provides both read- used for the inside and outside margins respectively. They
able line lengths and good use of the page. Another op- also have aliases inner and outer. Thus, the easiest way to
tion for reducing the amount of whitespace on the page handle different margins for odd and even pages is to give
without changing the margins is to increase the font size the twoside option in the document class command and
using the 12pt option to the document class. specify the margins as usually.
If you wish to change the margins of your document, This will result in a value of 4cm on all inner margins (left
there are many ways to do so: margin for odd number pages and right margin for even
pages) and 2cm margin on outer margins.
• One older approach is to use the fullpage package Setting the same value for the inner and outer for geome-
for somewhat standardized smaller margins (around try will remove the difference between the margins. An-
an inch), but it creates lines of more than 100 char- other quick way to eliminate the difference in position
acters per line at with the 10pt default font size (and between even and odd numbered pages would be setting
about 90 if the 12pt documentclass option is used): the values to evensidemargin and oddsidemargin to the
half of odd’s default:
For even narrower margins, the fullpage package has a cm By default, the value of evensidemargin is larger than
option (around 1.5cm), which results in about 120 char- oddsidemargin in the two-sided layout, as one could
acters per line at the 10pt default font size, about double wish to write notes on the side of the page. The side
what is considered readable: for the large margin is chosen opposite to the side where
pages are joined together.
• A more modern and flexible approach is to use the See the Lengths.
geometry package. This package allows you to spec-
ify the 4 margins without needing to remember the
particular page dimensions commands. You can en- Top margin above Chapter
ter the measures in centimeters and inches as well.
Use cm for centimeters and in for inches after each The top margin above a chapter can be changed using the
value (e.g. 1.0in or 2.54cm). Note that by default titlesec package. Example:
(i.e. without any options) this package already re- The command \titleformat must be used when the spacing
duces the margins, so for a 'standard layout' you may of a chapter is changed. In case of a section this command
not need to specify anything. These values are rel- can be omitted.
ative to the edge of paper (0in) and go inward. For
example, this command provides more conventional
margins, better using the vertical space of the page, 2.12.5 Page orientation
without creating the dramatically long lines of the
fullpage package (if the the 11pt documentclass op- When you talk about changing page orientation, it usually
tion is used, the line lengths are about 88 charac- means changing to landscape mode, since portrait is the
ters for leter-sized paper and slightly less when using default. We shall introduce two slightly different styles of
a4paper). changing orientation.
You can combine the margin options with the page size The first is for when you want all of your document to be
options seen in this paragraph. in landscape from the very beginning. There are various
packages available to achieve this, but the one we prefer
• You should not use the a4wide package for a page is the geometry package. All you need to do is call the
with A4 document size with smaller margins. It is package, with landscape as an option:
56 CHAPTER 2. COMMON ELEMENTS
Although, if you intend to use geometry to set your paper Standard page styles
size, don't add the \usepackage commands twice, simply
string all the options together, separating with a comma: The possibilities of changing the headers in plain La-
Using standard LaTeX classes, you can use the same class tex are actually quite limited. There are two commands
options: available: \pagestyle{''style''} will apply the specified
style to the current and all subsequent pages, and \this-
pagestyle{''style''} will only affect the current page. The
possible styles are:
Change orientation of specific part
The commands \markright and \markboth can be used
to set the content of the headings by hand. The follow-
The second method is for when you are writing a docu-
ing commands placed at the beginning of an article docu-
ment in portrait, but you have some contents, like a large
ment will set the header of all pages (one-sided) to contain
diagram or table that would be displayed better on a land-
“John Smith” top left, “On page styles” centered and the
scape page. However, you still want the consistency of
page number top right:
your headers and footers appearing the same place as the
other pages. There are special commands containing details on the
running page of the document.
The lscape package is for this very purpose. It supplies
a landscape environment, and anything inside is basically Note that \leftmark and \rightmark convert the names to
rotated. No actual page dimensions are changed. This uppercase, whichever was the formatting of the text. If
approach is more applicable to books or reports than to you want them to print the actual name of the chapter
typical academic publications. Using pdflscape instead of without converting it to uppercase use the following com-
lscape when generating a PDF document will make the mand:
page appear right side up when viewed: the single page Now \leftmark and \rightmark will just print the name of
that is in landscape format will be rotated, while the rest the chapter and section, without number and without af-
will be left in portrait orientation. fecting the formatting. Note that these redefinitions must
Also, to get a table to appear correctly centered on a land- be inserted after the first call of \pagestyle{fancy}. The
scaped page, one must place the tabular environment in- standard book formatting of the \chaptermark is:
side a table environment, which is itself inside the land- Watch out: if you provide long text in two different
scape environment. For instance it should look like this: “parts” only in the footer or only in the header, you might
see overlapping text.
Moreover, with the following commands you can define
Change orientation of floating environment the thickness of the decorative lines on both the header
and the footer:
If you use the above code, you will see that the table is
The first line for the header, the second for the footer.
inserted where it is in the code. It will not be floated! To
Setting it to zero means that there will be no line.
fix this you need the package rotating. See the Rotations
chapter.
Plain pages issue An issue to look out for is that the
major sectioning commands (\part, \chapter or \maketi-
2.12.6 Margins, page size and rotation of a tle) specify a \thispagestyle{plain}. So, if you wish to
specific page suppress all styles by inserting a \pagestyle{empty} at the
beginning of your document, then the style command at
If you need to rotate the page so that the figure fits, the each section will override your initial rule, for those pages
chances are good that you need to scale the margins and only. To achieve the intended result one can follow the
the font size too. Again, the geometry package comes in new section commands with \thispagestyle{empty}. The
handy for specifying new margins for a single page only. \part command, however, cannot be fixed this way, be-
cause it sets the page style, but also advances to the next
Note that order matters! page, so that \thispagestyle{} cannot be applied to that
page. Two solutions:
The tricky problem when customizing headers and foot- Hopefully, the behaviour of the above commands is fairly
ers is to get things like running section and chapter names intuitive: if it has head in it, it affects the head etc, and
in there. Standard LaTeX accomplishes this with a two- obviously, l, c and r means left, centre and right respec-
stage approach. In the header and footer definition, you tively.
use the commands \rightmark and \leftmark to represent
the current section and chapter heading, respectively. The • You can also use the command \fancyhead for
values of these two commands are overwritten whenever header and \fancyfoot for footer. They work in the
a chapter or section command is processed. For ultimate same way, so we'll explain only the first one. The
flexibility, the \chapter command and its friends do not re- syntax is:
define \rightmark and \leftmark themselves. They call yet
another command (\chaptermark, \sectionmark, or \sub-
You can use multiple selectors optionally separated by a
sectionmark) that is responsible for redefining \rightmark
comma. The selectors are the following:
and \leftmark, except if they are starred -- in such a case,
\markboth{Chapter/Section name}{} must be used in- so CE,RO will refer to the center of the even pages and
side the sectioning command if header and footer lines to the right side of the odd pages.
are to be updated.
Again, several packages provide a solution: • \fancyhf is a merge of \fancyhead and \fancyfoot,
hence the name. There are two additional selectors
H and F to specify the header or the footer, respec-
• an alternative one-stage mechanism is provided by
tively. If you omit the H and the F, it will set the
the package titleps);
fields for both.
• fancyhdr will handle the process its own way.
These commands will only work for fancy and fancyplain.
To customize LaTeX default style you need the \fancy-
Customizing with fancyhdr plainstyle command. See below for examples.
To get better control over the headers, one can use the For a clean customization, we recommend you start from
package fancyhdr written by Piet van Oostrum. It pro- scratch. To do so you should erase the current pagestyle.
vides several commands that allow you to customize the Providing empty values will make the field blank. So
header and footer lines of your document. For a more will just delete the current heading/footer configuration,
complete guide, the author of the package produced this so you can make your own.
documentation.
To begin, add the following lines to your preamble:
Plain pages There are two ways to change the style of
You can now observe a new style in your document. plain pages like chapters and titlepage.
The \headheight needs to be 13.6pt or more, otherwise First you can use the fancyplain style. If you do so, you
you will get a warning and possibly formatting issues. can use the command \fancyplain{...}{...} inside fancy-
Both the header and footer comprise three elements each hdr commands like \lhead{...}, etc.
according to its horizontal position (left, centre or right).
When LaTeX wants to create a page with an empty style,
The styles supported by fancyhdr: it will insert the first argument of \fancyplain, in all the
other cases it will use the second argument. For instance:
• the four LaTeX styles; It has the same behavior of the previous code, but you
will get empty header and footer in the title and at the
• fancy defines a new header for all pages but plain-
beginning of chapters.
style pages such as chapters and titlepage;
Alternatively you could redefine the plain style, for ex-
• fancyplain is the same, but for absolutely all pages. ample to have a really plain page when you want. The
command to use is \fancypagestyle{plain}{...} and the ar-
Style customization The styles can be customized gument can contain all the commands explained before.
with fancyhdr specific commands. Those two styles may An example is the following:
be configured directly, whereas for LaTeX styles you In that case you can use any style but fancyplain because
need to make a call to the \fancypagestyle command. it would override your redefinition.
To set header and footer style, fancyhdr provides three
interfaces. They all provide the same features, you just Examples For two-sided, it’s common to mirror the
use them differently. Choose the one you like most. style of opposite pages, you tend to think in terms of inner
and outer. So, the same example as above for two-sided
• You can use the following six commands. is:
58 CHAPTER 2. COMMON ELEMENTS
This is effectively saying author name is top outer, to- • Additionally, the environment can be nested inside
day’s date is top inner, and current page number is bottom other environments, such as figure.
outer. Using \fancyhf can make it shorter:
• multicol outputs balanced columns, whereby the
Here is the complete code of a possible style you could columns on the final page will be of roughly equal
use for a two-sided document: length.
Using \fancypagestyle one can additionally define multi-
ple styles for one’s document that are easy to switch be- • Vertical rules between columns can be customised.
tween. Here’s a somewhat complicated example for a
two-sided book style: • Column environments can be easily customised lo-
cally or globally.
Page n of m
Using multicol package
Some people like to put the current page number in con-
The multicol package overcomes some of the shortcom-
text with the whole document. LaTeX only provides ac-
ings of twocolumn and provides the multicol environ-
cess to the current page number. However, you can use
ment. To create a typical two-column layout:
the lastpage package to find the total number of pages,
like this: Floats are not fully supported by this environment. It can
only cope if you use the starred forms of the float com-
Note the capital letters. Also, add a backslash after \thep-
mands (e.g., \begin{figure*} ) which makes the float span
age to ensure adequate space between the page number
all columns. This is not hugely problematic, since floats
and 'of'. And recall, when using references, that you
of the same width as a column may be too small, and you
have to run LaTeX an extra time to resolve the cross-
would probably want to span them anyway. See this sec-
references.
tion for a more detailed discussion.
The multicol package has two important parameters
Alternative packages which can be set using \setlength:
Other packages for page styles are scrpage2, very simi- • \columnseprule, sets the width of the vertical rule
lar to fancyhdr, and titleps, which takes a one-stage ap- between columns and defaults to 0pt
proach, without having to use \leftmark or \rightmark.
• \columnsep, sets the horizontal space between
columns and the defaults to 10pt, which is quite nar-
2.12.8 Page background row
The eso-pic package will let you print content in the back- To force a break in a column, the command \columnbreak
ground of every page or individual pages. is used.
The starred-version of the \AddToShipoutPicture com-
mand applies to the current page only.
2.12.10 Manual page formatting
2.12.9 Multi-column pages There may be instances, especially in very long docu-
ments, such as books, that LaTeX will not get all page
Using the twocolumn optional class argument breaks looking as good as it could. It may, therefore,
be necessary to manually tweak the page formatting. Of
Using a standard Latex document class, like article, you course, you should only do this at the very final stage of
can simply pass the optional argument twocolumn to the producing your document, once all the content is com-
document class: \documentclass[twocolumn]{article} plete. LaTeX offers the following:
which will give the desired effect.
While this approach is useful, it has limitations. The mul- 2.12.11 Widows and orphans
ticol package provides the following advantages:
In professional books, it’s not desirable to have single lines
• Can support up to ten columns. at the beginning or end of a page. In typesetting such sit-
uations are called 'widows’ and 'orphans’. Normally it is
• Implements a multicols environment, therefore, it is possible that widows and orphans appear in LaTeX docu-
possible to mix the number of columns within a doc- ments. You can try to deal with them using manual page
ument. formatting, but there’s also an automatic solution.
2.13. IMPORTING GRAPHICS 59
LaTeX has a parameter for 'penalty' for widows and or- 2.13.1 Raster graphics vs. vector graphics
phans ('club lines’ in LaTeX terminology). With the
greater penalty LaTeX will try more to avoid widows Raster graphics will highly contrast with the quality of the
and orphans. You can try to increase these penalties by document if they are not in a high resolution, which is the
putting following commands in your document preamble: case with most graphics. The result may be even worse
If this does not help, you can try increasing these values once printed.
even more, to a maximum of 10000. However, it is not Most drawing tools (e.g. for diagrams) can export in vec-
recommended to set this value too high, as setting it to tor format. So you should always prefer PDF or EPS to
10000 forbids LaTeX from doing this altogether, which PNG or JPG.
might result in strange behavior.
It also helps to have rubber band values for the space be-
tween paragraphs:
2.13.2 The graphicx package
Alternatively, you can use the needspace package to re- As stated before, LaTeX can't manage pictures directly,
serve some lines and thus to prevent page breaking for so we will need some extra help: we have to load the
those lines. graphicx package in the preamble of our document:
This package accepts as an argument the external driver to
2.12.12 Troubleshooting be used to manage pictures; however, the latest version of
this package takes care of everything by itself, changing
A very useful troubleshooting and designing technique is the driver according to the compiler you are using, so you
to turn on the showframe option in the geometry package don't have to worry about this. Still, just in case you want
(which has the same effect as the showframe package de- to understand better how it works, here are the possible
scribed above. It draws bounding boxes around the major options you can pass to the package:
page elements, which makes where the various regions
of the page are, which is often unclear because of white • dvips (default if compiling with latex), if you are
whitespace. compiling with latex to get a DVI and you want to
see your document with a DVI or PS viewer.
2.12.13 Notes and References • dvipdfm, if you are compiling with latex to get a
DVI that you want to convert to PDF using dvipdfm,
This page uses material from Andy Roberts’ Getting to grips to see your document with any PDF viewer.
with LaTeX with permission from the author.
• pdftex (default if compiling with pdflatex), if you
are compiling with pdftex to get a PDF that you will
[1] How to use Ghostscript
see with any PDF viewer.
[2] http://webtypography.net/2.1.2
[3] http://baymard.com/blog/line-length-readability But, again, you don't need to pass any option to the pack-
age because the default settings are fine in most of the
cases.
2.13 Importing Graphics In many respects, importing your images into your docu-
ment using LaTeX is fairly simple... once you have your
images in the right format that is! Therefore, I fear for
There are two possibilities to include graphics in your
many people the biggest effort will be the process of con-
document. Either create them with some special code,
verting their graphics files. Now we will see which for-
a topic which will be discussed in the Creating Graph-
mats we can include and then we will see how to do it.
ics part, (see Introducing Procedural Graphics) or import
productions from third party tools, which is what we will
be discussing here. 2.13.3 Document Options
Strictly speaking, LaTeX cannot manage pictures di-
rectly: in order to introduce graphics within documents, The graphics and graphicx packages recognize the draft
LaTeX just creates a box with the same size as the im- and final options given in the \documentclass[...]{...}
age you want to include and embeds the picture, without command at the start of the file. (See Document Classes.)
any other processing. This means you will have to take Using draft as the option will suppress the inclusion of the
care that the images you want to include are in the right image in the output file and will replace the contents with
format to be included. This is not such a hard task be- the name of the image file that would have been seen. Us-
cause LaTeX supports the most common picture formats ing final will result in the image being placed in the output
around. file. The default is final.
60 CHAPTER 2. COMMON ELEMENTS
2.13.4 Supported image formats • EPS can be used with the help of the epstopdf pack-
age. Depending on your installation,
As explained before, the image formats you can use de-
pend on the driver that graphicx is using but, since the • you may just need to have it installed, there is
driver is automatically chosen according to the compiler, no need to load it in your document;
then the allowed image formats will depend on the com- • if it does not work, you need to load it just after
piler you are using. the graphicx package. Additionally, since ep-
Consider the following situation: you have added some stopdf will need to convert the EPS file into a
pictures to your document in JPG and you have success- PDF file and store it, you need to give “writing
fully compiled it in PDF. Now you want to compile it in permissions” to your compiler. This is done by
DVI, you run latex and you get a lot of errors... because adding an option to the compiling command,
you forgot to provide the EPS versions of the pictures you e.g. pdflatex -shell-escape file.tex (if you use a
want to insert. LaTeX editor, they usually allow to modify the
command in the configuration options). Check
At the beginning of this book, we had stated that the same
the epstopdf documentation for other compil-
LaTeX source can be compiled in both DVI and PDF
ers.
without any change. This is true, as long as you don't
use particular packages, and graphicx is one of those. In
any case, you can still use both compilers with documents
with pictures as well, as long as you always remember to 2.13.5 Including graphics
provide the pictures in two formats (EPS and one of JPG,
PNG or PDF). Now that we have seen which formats we can include and
how we could manage those formats, it’s time to learn
how to include them in our document. After you have
Compiling with latex loaded the graphicx package in your preamble, you can
include images with \includegraphics, whose syntax is the
The only format you can include while compiling with following:
latex is Encapsulated PostScript (EPS). As usual, arguments in square brackets are optional,
The EPS format was defined by Adobe Systems for mak- whereas arguments in curly braces are compulsory.
ing it easy for applications to import postscript-based The argument in the curly braces is the name of the im-
graphics into documents. Because an EPS file declares age. Write it without the extension. This way the La-
the size of the image, it makes it easy for systems like La- TeX compiler will look for any supported image format
TeX to arrange the text and the graphics in the best way. in that directory and will take the best one (EPS if the
EPS is a vector format—this means that it can have very output is DVI; JPEG, PNG or PDF if the output is PDF).
high quality if it is created properly, with programs that Images can be saved in multiple formats for different pur-
are able to manage vector graphics. It is also possible to poses. For example, a directory can have “diagram.pdf”
store bit-map pictures within EPS, but they will need a for high-resolution printing, while “diagram.png” can be
lot of disk space. used for previewing on the monitor. You can specify
which image file is to be used by pdflatex through the
preamble command:
Compiling with pdflatex
which specifies the files to include in the document (in or-
If you are compiling with pdflatex to produce a PDF, you der of preference), if files with the same basename exist,
have a wider choice. You can insert: but with different extensions.
The variety of possible attributes that can be set is fairly
• JPG, widely used on Internet, digital cameras, etc. large, so only the most common are covered below:
They are the best choice if you want to insert photos. In order to use more than one option at a time, simply sep-
arate each with a comma. The order you give the options
• PNG, a very common format (even if not as much as matters. E.g you should first rotate your graphic (with
JPG); it’s a lossless format and it’s the best choice for angle) and then specify its width.
diagrams (if you were not able to generate a vector
Included graphics will be inserted just there, where you
version) and screenshots.
placed the code, and the compiler will handle them as
• PDF, it is widely used for documents but can be “big boxes”. As we will see in the floats section, this can
used to store images as well. It supports both vec- disrupt the layout; you'll probably want to place graphics
tor and bit-map images, but it’s not recommended inside floating objects.
for the latter, as JPG or PNG will provide the same Also note that the trim option does not work with XeLa-
result using less disk space. Tex.
2.13. IMPORTING GRAPHICS 61
Be careful using any options, if you are working with of the border by adjusting the \setlength\fboxrule{0.5pt}
the chemnum-package. The labels defined by \cmp- command.
dref{<label name>} might not behave as expected. Scal- See Boxes for more details on \framebox and \fbox.
ing the image for instance may be done by \scalebox in-
stead.
The star version of the command will work for .eps files
2.13.6 Graphics storage
only. For a more portable solution, the standard way
should take precedence. The star command will take the
crop dimension as extra parameter: The command \graphicspath tells LaTeX where to look
for images, which can be useful if you store images cen-
trally for use in many different documents. The \graphic-
Examples spath command takes one argument, which specifies the
additional paths you want to be searched when the \in-
OK, it’s time to see graphicx in action. Here are some cludegraphics command is used. Here are some examples
examples. Say you had a file 'chick.jpg' you would include (trailing / is required):
it like: Please see http://www.ctan.org/tex-archive/macros/
This simply imports the image, without any other pro- latex/required/graphics/grfguide.pdf. In the third exam-
cessing. However, it is very large (so we won't give an ple shown there should be a directory named “images”
example of how it would look here!) So, let’s scale it in the same directory as your main tex file, i.e. this is
down: RELATIVE addressing.
This has now scaled it by half. If you wish to be more Using absolute paths, \graphicspath makes your file less
specific and give actual lengths of the image dimensions, portable, while using relative paths (like the third exam-
this is how to go about it: ple), there should not be any problem with portability.
The fourth example uses the “safe” (MS-DOS) form of
One can also specify the scale with respect to the width the Windows MyPictures folder because it’s a bad idea to
of a line in the local environment (\linewidth), the width use directory names containing spaces. Again, ensure file
of the text on a page (\textwidth) or the height of the text names do not contain spaces or alternatively if you are
on a page (\textheight) (pictures not shown): using PDFLaTeX, you can use the package grffile which
To rotate (I also scaled the image down): will allow you to use spaces in file names.
And finally, an example of how to crop an image should Note that you cannot make the graphicx package search
you wish to focus on one particular area of interest: directories recursively. Under Linux/Unix, you can
achieve a recursive search using the environment variable
Note: the presence of clip, as the trim operation will not
TEXINPUTS, e.g., by setting it to
work without it.
export TEXINPUTS=./images//:./Snapshots//
Trick: You can also use negative trim values to add blank
space to your graphics, in cases where you need some
manual alignment. before running latex/pdflatex or your TeX-IDE. (But this,
of course, is not a portable method.)
Spaces in names
If the image file were called “chick picture.png”, then you 2.13.7 Images as figures
need to include the full filename when importing the im-
age: The figure environment is not exclusively used for images.
We will only give a short preview of figures here. More
One option is to not use spaces in file names (if possible), information on the figure environment and how to use it
or to simply replace spaces with underscores (“chick pic- can be found in Floats, Figures and Captions.
ture.png” to “chick_picture.png”)
There are many scenarios where you might want to ac-
company an image with a caption and possibly a cross-
Borders reference. This is done using the figure environment. The
following code sample shows the bare minimum required
It is possible to have LaTeX create a border around your to use an image as a figure.
image by using \fbox: The above code extract is relatively trivial, and doesn't of-
You can control the border padding with the fer much functionality. The following code sample shows
\setlength\fboxsep{0pt} command, in this case I set it to an extended use of the figure environment which is almost
0pt to avoid any padding, so the border will be placed universally useful, offering a caption and label, centering
tightly around the image. You can control the thickness the image and scaling it to 80% of the width of the text.
62 CHAPTER 2. COMMON ELEMENTS
2.13.8 Text wrapping around pictures You should also take a look at Export To Other Formats
for other possibilities.
See Floats, Figures and Captions.
epstopdf
2.13.9 Seamless text integration You can convert EPS to PDF with the epstopdf utility,
included in package of the same name. This tool is actu-
The drawback of importing graphics that were gener- ally called by pdflatex to convert EPS files to PDF in the
ated with a third-party tool is that font and size will not background when the graphicx package is loaded. This
match with the rest of the document. There are still some process is completely invisible to the user.
workarounds though.
You can batch convert files using the command-line. In
The easiest solution is to use the picture environment and Bourne Shell (Unix) this can be done by:
then simply use the “put” command to put a graphics file
$ for i in *.eps; do epstopdf "$i"; done
inside the picture, along with any other desired LaTeX
element. For example:
In Windows, multiple files can be converted by placing
Note that the border around the picture in the above ex-
the following line in a batch file (a text file with a .bat
ample was added by using \fbox, so the contents of the
extension) in the same directory as the images:
border is the picture as generated by the above code.
for %%f in (*.eps) do epstopdf %%f
Tools like Inkscape or Xfig have a dedicated LaTeX ex-
port feature that will let you use correct font and size for
text in vector graphics. See #Third-party graphics tools. which can then be run from the command line.
For a perfect integration of graphics, you might consider If epstopdf produces whole page with your small graphics
procedural graphics capabilities of some LaTeX packages somewhere on it, use
like TikZ or PSTricks. It lets you draw from within a $ epstopdf --gsopt=-dEPSCrop foo.eps
document source. While the learning curve is steeper, it
is worth it most of the time.
or try using ps2pdf utility which should be installed with
Ghostscript (required for any TeX distribution).
2.13.10 Including full PDF pages $ ps2pdf -dEPSCrop foo.eps
There is a great package for including full pages of PDF
files: pdfpages. It is capable of inserting entire pages as to crop final PDF.
is and more pages per one page in any layout (e.g. 2x3).
eps2eps
The package has several options:
Options: When all of the above fails, one can simplify the EPS file
before attempting other conversions, by using the eps2eps
• final: Inserts pages. This is the default. tool (also see next section):
$ eps2eps input.eps input-e2.eps
• draft: Does not insert pages, but prints a box and
the filename instead.
This will convert all the fonts to pre-drawn images, which
• enable-survey: Activates survey functionalities. is sometimes desirable when submitting manuscripts for
(Experimental, subject to change.) publication. However, on the downside, the fonts are
NOT converted to lines, but instead to bitmaps, which
The first command is reduces the quality of the fonts.
Options for key=val (A comma separated list of options
using the key = value syntax) imgtops
You can also inserts pages of several external PDF docu- imgtops is a lightweight graphics utility for conversions
ments. between raster graphics (JPG, PNG, ...) and EPS/PS
Several PDFs can be placed table-like on one page. See files.
more information in its documentation.
Inkscape
2.13.11 Converting graphics Inkscape can also convert files from and to several for-
mats, either from the GUI or from the command-line. For
Note instance, to obtain a PDF from a SVG image you can do:
2.13. IMPORTING GRAPHICS 63
pstoedit
2.13.12 Third-party graphics tools
To properly edit an EPS file, you can convert it to an ed- We will not tackle the topic of procedural graphics cre-
itable format using pstoedit. For instance, to get an Xfig- ated from within LaTeX code here (TikZ, PSTricks,
editable file, do: MetaPost and friends). See Introducing Procedural
$ pstoedit -f fig input.eps output.fig Graphics for that.
You should prefer vector graphics over raster graphics for
And to get an SVG file (editable with any vector graphics their quality. Raster graphics should only be used in case
tool like Inkscape) you can do: of photos. Diagrams of any sort should be vectors.
$ pstoedit -f plot-svg input.eps output.svg As we have seen before, LaTeX handles
Vector editor TpX separates geometric objects from text And you're done!
objects. Geometric objects are saved into .PDF file, the
For more details on using xfig with LaTeX, this chapter
rest is saved in .TpX file to be processed by LaTeX. User
of the xfig User Manual may prove helpful.
just create the graphics in TpX editor and calls the .TpX
file from latex file by command \input{...TpX}.
Other tools
Xfig
Commercial vector graphics software, such as Adobe
Illustrator, CorelDRAW, and FreeHand are commonly
Xfig is a basic program that can produce vector graphics,
used and can read and write EPS figures. However, these
which can be exported to LaTeX. It can be installed on
products are limited to Windows and Mac OS X plat-
Unix platforms.
forms.
On Microsoft Windows systems, Xfig can only be in-
stalled using Cygwin-X; however, this will require a fast
internet connection and about 2 gigabytes of space on Raster graphics
your computer. With Cygwin, to run Xfig, you need to
first start the “Start X - Server”, then launch “xterm” to Adobe Photoshop
bring up a terminal. In this terminal type “xfig” (without
the quotation marks) and press return. It can save to EPS.
Alternatively, WinFIG is an attempt to achieve the func-
tionality of xfig on Windows computers. GIMP
There are many ways to use xfig to create graphics for La-
GIMP, has a graphical user interface, and it is multi-
TeX documents. One method is to export the drawing as
platform. It can save to EPS and PDF.
a LaTeX document. This method, however, suffers from
various drawbacks: lines can be drawn only at angles that
are multiples of 30 and 45 degrees, lines with arrows can Plots and Charts
only be drawn at angles that are multiples of 45 degrees,
several curves are not supported, etc. Generic Mapping Tools (GMT)
Exporting a file as PDF/LaTeX or PS/LaTeX, on the
other hand, offers a good deal more flexibility in draw- Generic Mapping Tools (GMT), maps and a wide range
ing. Here’s how it’s done: of highly customisable plots.
2.14. FLOATS, FIGURES AND CAPTIONS 65
when the next page is started (but not earlier). an option to change the definition of \section to auto-
matically include a \FloatBarrier. This can be set by
• Once a page has finished, LaTeX examines this loading the package with the option [section] (\usepack-
holding queue and tries to empty it as best as possi- age[section]{placeins}). \FloatBarrier may also be useful
ble. For this it will first try to generate as many float to prevent floats intruding on lists created using itemize
pages as possible (in the hope of getting floats off or enumerate. The flafter package can be used to force
the queue). Once this possibility is exhausted, it will floats to appear after they are defined, and the endfloat
next try to place the remaining floats into top and package can be used to place all floats at the end of a
bottom areas. It looks at all the remaining floats and document. The float package provides the H option to
either places them or defers them to a later page (i.e., floating environments, which stops them from floating.
re-adding them to the holding queue once more).
In some special cases LaTeX won't follow these position-The location of the caption is traditionally underneath the
ing parameters and additional commands will be neces- float. However, it is up to you to therefore insert the cap-
sary, for example, if one needs to specify an alignment tion command after the actual contents of the float (but
still within the environment). If you place it before, then
other than centered for a float that sits alone in one page[3] .
the caption will appear above the float. Try out the fol-
Use \listoffigures to add a list of the figures in the be- lowing example to demonstrate this effect:
ginning of the document. To change the name used in
the caption from Figure to Example, use \renewcom- Note that the command \reflectbox{...} flips its content
mand{\figurename}{Example} in the figure contents. horizontally.
You will notice that the figure environment is set up as If tables and figures are not adequate for your needs, then
usual. You may also use a table environment for subta- you always have the option to create your own! Exam-
bles. For each subfloat, you need to use: ples of such instances could be source code examples, or
maps. For a program float example, one might therefore
If you intend to cross-reference any of the subfloats, see
wish to create a float named program. The package float
where the label is inserted; \caption outside the subfigure-
is your friend for this task. All commands to set up the
environment will provide the global caption.
new float must be placed in the preamble, and not within
subcaption will arrange the figures or tables side-by-side the document.
providing they can fit, otherwise, it will automatically
shift subfloats below. This effect can be added manually,
1. Add \usepackage{float} to the preamble of your
by putting the newline command (\\) before the figure you
document
wish to move to a newline.
Horizontal spaces between figures are controlled by one 2. Declare your new float using:
of several commands, which are placed in between \be- \newfloat{type}{placement}{ext}[outer counter],
gin{subfigure} and \end{subfigure}: where:
• A non-breaking space (specified by ~ as in the exam- • type - the new name you wish to call your float,
ple above) can be used to insert a space in between in this instance, 'program'.
the subfigs. • placement - t, b, p, or h (as previously de-
scribed in Placement), where letters enumer-
• Math spaces: \qquad, \quad, \;, and \,
ate permitted placements.
• Generic space: \hspace{''length''} • ext - the file name extension of an auxiliary
file for the list of figures (or whatever). Latex
• Automatically expanding/contracting space: \hfill
writes the captions to this file.
• outer counter - the presence of this parameter
2.14.8 Wide figures in two column docu- indicates that the counter associated with this
ments new float should depend on outer counter, for
example 'chapter'.
If you are writing a document using two columns (i.e.
you started your document with something like \docu- 3. The default name that appears at the start of the cap-
mentclass[twocolumn]{article}), you might have noticed tion is the type. If you wish to alter this, use \float-
that you can't use floating elements that are wider than the name{type}{floatname}
2.15. HYPERLINKS 69
4. Changing float style can be issued with \float- 2.14.10 Labels in the figures
style{style} (Works on all subsequent \newfloat
commands, therefore, must be inserted before There is a LaTeX package lpic to put LaTeX on top of
\newfloat to be effective). included graphics, thus allowing to add TeX annotations
to imported graphics. It defines a convenient interface to
• plain - the normal style for Latex floats, but the put TeX over included graphics, and allows for drawing
caption is always below the content. a white background under the typeset material to over-
• plaintop - the normal style for Latex floats, but shadow the graphics. It is a better alternative for labels
the caption is always above the content. inside of graphics; you do not have to change text size
when rescaling pictures, and all LaTeX power is available
• boxed - a box is drawn that surrounds the float, for labels.
and the caption is printed below.
A very similar package, with somewhat different syntax,
• ruled - the caption appears above the float, is pinlabel . The link given also points to the packages
with rules immediately above and below. Then psfrag and overpic.
the float contents, followed by a final horizon-
A much more complicated package which can be used
tal rule.
in the same way is TikZ. TikZ is a front-end to a draw-
ing library called pgf (which is used to make beamer for
Float styles can also be customized as the second example instance). It can be used to label figures by adding text
below illustrates. nodes on top of an image node.
An example document using a new program float type:
The verbatim environment is an environment that is al-
2.14.11 Summary
ready part of LaTeX. Although not introduced so far, its
name is fairly intuitive! LaTeX will reproduce everything
That concludes all the fundamentals of floats. You will
you give it, including new lines, spaces, etc. It is good for
hopefully see how much easier it is to let LaTeX do all
source code, but if you want to introduce a lot of code
the hard work and tweak the page layouts in order to get
you might consider using the listings package, that was
your figures in the best place. As always, the fact that
made just for it.
LaTeX takes care of all caption and reference numbering
While this is useful, one should be careful when embed- is a great time saver.
ding the float within another float. In particular, the error
not in outer par mode
may occur. One solution might be to use the [H] option
2.14.12 Notes and references
(not any other) on the inner float, as this option “pins” the
[1] http://www.ctan.org/tex-archive/macros/latex/contrib/
inner float to the outer one.
float/
Newly created floats with \newfloat can also be used in
combination with the wrapfig package from above. E.g. [2] Float environment positioning, by Frank Mittelbach
the following code creates a floating text box, which floats
in the text on the right side of the page and is complete [3] http://tex.stackexchange.com/questions/28556/
with caption, numbering, an index file with the extension how-to-place-a-float-at-the-top-of-a-floats-only-page
.lob and a customization of the float’s visual layout:
[4] http://ftp.univie.ac.at/packages/tex/macros/latex/
contrib/wrapfig/wrapfig-doc.pdf
Caption styles
[5] http://www.tex.ac.uk/cgi-bin/texfaq2html?label=
To change the appearance of captions, use the caption 2colfltorder
package. For example, to make all caption labels small
and bold: This page uses material from Andy Roberts’ Getting to grips
The KOMA script packages have their own caption cus- with LaTeX with permission from the author.
tomizing features with e.g. \captionabove, \captionformat
and \setcapwidth. However these definitions have limited
effect on newly created float environments with the wrap-
fig package.
2.15 Hyperlinks
Alternatively, you can redefine the \thefigure command: LaTeX enables typesetting of hyperlinks, useful when the
See this page for more information on counters. Finally, resulting format is PDF, and the hyperlinks can be fol-
note that the caption2 package has long been deprecated. lowed. It does so using the package hyperref.
70 CHAPTER 2. COMMON ELEMENTS
\url Usage:
2.15.3 Customization
It will show the URL using a mono-spaced font and, if
you click on it, your browser will be opened pointing at The standard settings should be fine for most users, but
it. if you want to change something, that is also possible.
There are several variables and two methods to pass those
to the package. Options can be passed as an argument of
\href Usage: the package when it is loaded (the standard way packages
It will show the string description using standard docu- work), or the \hypersetup command can be used as fol-
ment font but, if you click on it, your browser will be lows:
2.15. HYPERLINKS 71
you can pass as many options as you want; separate them Possible solution: Add the following to your preamble:
with a comma. Options have to be in the form:
exactly the same format has to be used if you pass those
options to the package while loading it, like this: Problems with Links and Pages
Here is a list of the possible variables you can change (for
the complete list, see the official documentation). The Messages like the following:
default values are written in an upright font:
! pdfTeX warning (ext4): destination with the same iden-
Checkout 3.8 Big list at hyperref-manual at tug.org tifier (name{page.1}) has been already used, duplicate ig-
Please note, that explicit RGB specification is only al- nored
lowed for the border colors (like linkbordercolor etc.), appear when a counter gets reinitialized, for example by
while the others may only assigned to named colors using the command \mainmatter provided by the book
(which you can define your own, see Colors). In order document class. It resets the page number counter to 1
to speed up your customization process, here is a list with prior to the first chapter of the book. But as the preface
the variables with their default value. Copy it in your doc- of the book also has a page number 1 all links to “page
ument and make the changes you want. Next to the vari- 1” would not be unique anymore, hence the notice that
ables, there is a short explanations of their meaning: “duplicate has been ignored.” The counter measure con-
If you don't need such a high customization, here are sists of putting plainpages=false into the hyperref options.
some smaller but useful examples. When creating PDFs This unfortunately only helps with the page counter. An
destined for printing, colored links are not a good thing as even more radical solution is to use the option hypertex-
they end up in gray in the final output, making it difficult names=false, but this will cause the page links in the index
to read. You can use color frames, which are not printed: to stop working.
or make links black: The best solution is to give each page a unique name by
using the \pagenumbering command:
When you just want to provide information for the Doc-
ument Info section of the PDF file, as well as enabling Another solution is to use \pagenumbering{alph} before
back references inside bibliography: the command \maketitle, which will give the title page
the label page.a. Since the page number is suppressed, it
By default, URLs are printed using mono-spaced fonts. won't make a difference to the output.
If you don't like it and you want them to be printed with
the same style of the rest of the text, you can use this: By changing the page numbering every time before the
counter is reset, each page gets a unique name. In this
case, the pages would be numbered a, b, c, i, ii, iii, iv, v,
2.15.4 Troubleshooting 1, 2, 3, 4, 5, ...
If you don't want the page numbers to be visi-
Problems with Links and Equations 1 ble (for example, during the front matter part), use
\pagestyle{empty} ... \pagestyle{plain}. The important
Messages like the following point is that although the numbers are not visible, each
! pdfTeX warning (ext4): destination with the same iden- page will have a unique name.
tifier (name{ equation.1.7.7.30}) has been already used, Another more flexible approach is to set the counter to
duplicate ignored something negative:
appear, when you have made something like which will give the first pages a unique negative number.
The error disappears, if you use instead this form: The problem can also occur with the algorithms package:
Beware that the shown line number is often completely because each algorithm uses the same line-numbering
different from the erroneous line. scheme, the line identifiers for the second and follow-on
algorithms will be duplicates of the first.
Possible solution: Place the amsmath package before the
hyperref package. The problem occurs with equation identifiers if you
use \nonumber on every line of an eqnarray environ-
ment. In this case, use the *'ed form instead, e.g. \be-
Problems with Links and Equations 2 gin{eqnarray*} ... \end{eqnarray*} (which is an unnum-
bered equation array), and remove the now unnecessary
Messages like the following \nonumber commands.
! Runaway argument? {\@firstoffive }\fi ), Some text If your url’s are too long and running off of the page, try
from your document here (\ref {re\ETC. Latex Error: using the breakurl package to split the url over multiple
Paragraph ended before \Hy@setref@link was complete. lines. This is especially important in a multicolumn envi-
appear when you use \label inside an align environment. ronment where the line width is greatly shortened.
72 CHAPTER 2. COMMON ELEMENTS
Problems with bookmarks Problems with already existing .toc, .lof and similar
files
The text displayed by bookmarks does not always look
like you expect it to look. Because bookmarks are “just The format of some of the auxilliary files generated by la-
text”, much fewer characters are available for bookmarks tex changes when you include the hyperref package. One
than for normal LaTeX text. Hyperref will normally no- can therefore encounter errors like
tice such problems and put up a warning: ! Argument of \Hy@setref@link has an extra }.
Package hyperref Warning: Token not allowed in a PDF- when the document is typeset with hyperref for the first
DocEncoded string: time and these files already exist. The solution to the
You can now work around this problem by providing a problem is to delete all the files that latex uses to get ref-
text string for the bookmarks, which replaces the offend- erences right and typeset again.
ing text:
Math expressions are a prime candidate for this kind of Problems with footnotes and special characters
problem:
which turns \section{$E=mc^2$} to E=mc2 in the book- See the relevant section.
mark area. Color changes also do not travel well into
bookmarks: Problems with Beamer
produces the string “redRed!". The command \textcolor
gets ignored but its argument (red) gets printed. If you Using the command
use: is broken when pointed at a label. Instead of sending the
the result will be much more legible. user to the desired label, upon clicking the user will be
sent to the first frame. A simple work around exists; in-
If you write your document in unicode and use the uni-
stead of using
code option for the hyperref package you can use unicode
characters in bookmarks. This will give you a much larger to label your frames, use
selection of characters to pick from when using \texor- and reference it with
pdfstring.
[4] http://www.ctan.org/tex-archive/macros/latex/contrib/
Problems with long caption and \listoffigures or long hyperref/README
title
[5] Wrapfig package webpage in CTAN
There is an issue when using \listoffigures with hyper-
ref for long captions or long titles. This happens when
the captions (or the titles) are longer than the page width 2.16 Labels and Cross-referencing
(about 7-9 words depending on your settings). To fix this,
you need to use the option breaklinks when first declar-
2.16.1 Introduction
ing:
This will then cause the links in the \listoffigures to word In LaTeX you can easily reference almost anything that
wrap properly. is numbered (sections, figures, formulas), and LaTeX will
2.16. LABELS AND CROSS-REFERENCING 73
take care of numbering, updating it whenever necessary. \label{...}, but these prefixes become increasingly useful
The commands to be used do not depend on what you are as your document grows in size.
referencing, and they are: Another suggestion: try to avoid using numbers within
labels. You are better off describing what the object is
\label{marker} you give the object you want to reference about. This way, if you change the order of the objects,
a marker, you can see it like a name. you will not have to rename all your labels and their ref-
erences.
\ref{marker} you can reference the object you have
marked before. This prints the number that was as- If you want to be able to see the markers you are using
signed to the object. in the output document as well, you can use the showkeys
package; this can be very useful while developing your
\pageref{marker} It will print the number of the page document. For more information see the Packages sec-
where the object is. tion.
As you can see, the label is placed soon after the begin-
ning of the math mode. In order to reference a formula,
you have to use an environment that adds numbers. Most
of the times you will be using the equation environment;
that is the best choice for one-line formulae, whether you
\caption{Close-up of a gull\label{fig:gull}}
are using amsmath or not. Note also the eq: prefix in the
label.
See the Floats, Figures and Captions section for more
about the figure and related environments.
eqref The amsmath package adds a new command for
referencing formulae; it is \eqref{}. It works exactly like
\ref{}, but it adds parentheses so that, instead of printing
Fixing wrong labels The command \label must ap- a plain number as 5, it will print (5). This can be useful
pear after (or inside) \caption. Otherwise, it will pick up to help the reader distinguish between formulae and other
the current section or list number instead of what you in- things, without the need to repeat the word “formula” be-
tended. fore any reference. Its output can be changed as desired;
\begin{figure} \centering \includegraph- for more information see the amsmath documentation.
ics[width=0.5\textwidth]{gull} \caption{Close-up
of a gull} \label{fig:gull} \end{figure}
tag The \tag{eqnno} command is used to manually set
equation numbers where eqnno is the arbitrary text string
you want to appear in the document. It is normally better
to use labels, but sometimes hard-coded equation num-
Issues with links to tables and figures handled by bers might offer a useful work-around. This may for in-
hyperref In case you use the package hyperref to cre- stance be useful if you want to repeat an equation that is
ate a PDF, the links to tables or figures will point to the used before, e.g. \tag{\ref{eqn:before}}.
caption of the table or figure, which is always below the
table or figure itself[1] . Therefore the table or figure will
not be visible, if it is above the pointer and one has to numberwithin The amsmath package adds the
scroll up in order to see it. If you want the link point to \numberwithin{countera}{counterb} command which
the top of the image you can give the option hypcap to replaces the simple countera by a more sophisti-
the caption package: cated counterb.countera. For example \number-
within{equation}{section} in the preamble will prepend
\usepackage[hypcap]{caption} the section number to all equation numbers.
just like \ref; if the object is far away it will print some- you can disable the creation of hyperlinks in hy-
thing like “5 on page 25”, i.e. it adds the page number au- perref, and just use these commands for automatic
tomatically. If the object is close, it can use more refined text.
sentences like “on the next page” or “on the facing page”
automatically, according to the context and the document • Keep in mind that the \label must be placed inside
class. an environment with a counter, such as a table or
This command has to be used very carefully. It outputs a figure. Otherwise, not only the number will refer
more than one word, so it may happen its output falls on to the current section, as mentioned above, but the
two different pages. In this case, the algorithm can get name will refer to the previous environment with a
confused and cause a loop. Let’s make an example. You counter. For example, if you put a label after closing
label an object on page 23 and the \vref output happens a figure, the label will still say “figure n”, on which
to stay between page 23 and 24. If it were on page 23, n is the current section number.
it would print like the basic ref, if it were on page 24, it
would print “on the previous page”, but it is on both, and
this may cause some strange errors at compiling time that nameref
are very hard to be fixed. You could think that this hap-
pens very rarely; unfortunately, if you write a long docu- The hyperref package also automatically includes the
ment it is not uncommon to have hundreds of references, nameref package, and a similarly named command. It
so situations like these are likely to happen. One way to is similar to \autoref{}, but inserts text corresponding to
avoid problems during development is to use the standard the section name, for example.
ref all the time, and convert it to vref when the document Input:
is close to its final version, and then making adjustments
\section{MyFirstSection} \label{sec:marker} \sec-
to fix possible problems.
tion{MySecondSection} In section~\nameref{sec:
marker} we defined...
2.16.4 The hyperref package
Output:
autoref In section MyFirstSection we defined...
Mechanics
3.1 Errors and Warnings cessfully) by interfering with the letter spacing, LaTeX
takes the view that the author or editor should be able to
LaTeX describes what it is typesetting while it does it. If contribute. While it is certainly possible to set LaTeX’s
it encounters something it doesn't understand or can't do, parameters so that the spacing is sufficiently sloppy that
it will display a message saying what is wrong. It may also you will almost never get a warning about badly-fitting
display warnings for less serious conditions. lines or pages, you will almost certainly just be delaying
matters until you start to get complaints from your readers
Don't panic if you see error messages: it is very common or publishers.
to mistype or misspell commands, forget curly braces,
type a forward slash instead of a backslash, or use a spe-
cial character by mistake. Errors are easily spotted and
easily corrected in your editor, and you can then run La-
3.1.3 Examples
TeX again to check you have fixed everything. Some of
Only a few common error messages are given here: those
the most common errors are described in next sections.
most likely to be encountered by beginners. If you find
another error message not shown here, and it’s not clear
3.1.1 Error messages what you should do, ask for help.
Most error messages are self-explanatory, but be aware
The format of an error message is always the same. Er- that the place where LaTeX spots and reports an error
ror messages begin with an exclamation mark at the start may be later in the file than the place where it actually
of the line, and give a description of the error, followed occurred. For example if you forget to close a curly brace
by another line starting with the number, which refers to which encloses, say, italics, LaTeX won't report this until
the line-number in your document file which LaTeX was something else occurs which can't happen until the curly
processing when the error was spotted. Here’s an exam- brace is encountered (e.g. the end of the document!)
ple, showing that the user mistyped the \tableofcontents Some errors can only be righted by humans who can read
command: and understand what the document is supposed to mean
! Undefined control sequence. l.6 \tableofcotnetns or look like.
When LaTeX finds an error like this, it displays the error Newcomers should remember to check the list of special
message and pauses. You must type one of the following characters: a very large number of errors when you are
letters to continue: learning LaTeX are due to accidentally typing a special
character when you didn't mean to. This disappears after
Some systems (Emacs is one example) run LaTeX with a few days as you get used to them.
a “nonstop” switch turned on, so it will always process
through to the end of the file, regardless of errors, or until
a limit is reached. Too many }'s
77
78 CHAPTER 3. MECHANICS
Undefined control sequence typesetting when it found this, and the number in square
brackets is the number of the page onto which the of-
! Undefined control sequence. l.6 \dtae {December fending line was printed. The codes separated by slashes
2004} are the typeface and font style and size used in the line.
Ignore them for the moment.
In this example, LaTeX is complaining that it has no such
command (“control sequence”) as \dtae. Obviously it’s This comes up if you force a linebreak, e.g., \\, and have
been mistyped, but only a human can detect that fact: all a return before it. Normally TeX ignores linebreaks, pro-
LaTeX knows is that \dtae is not a command it knows viding full paragraphs to ragged text. In this case it is
about: it’s undefined. Mistypings are the most common necessary to pull the linebreak up one line to the end of
source of errors. Some editors allow common commands the previous sentence.
and environments to be inserted using drop-down menus This warning may also appear when inserting im-
or icons, which may be used to avoid these errors. ages. It can be avoided by using the \textwidth
or possibly \linewidth options, e.g. \includegraph-
Not in Mathematics Mode ics[width=\textwidth]{image_name}
! Missing $ inserted
A character that can only be used in the mathematics was Overfull hbox
inserted in normal text. If you intended to use mathemat-
ics mode, then use $...$ or \begin{math}...\end{math} or [101] Overfull \hbox (9.11617pt too wide) in para-
use the 'quick math mode': \ensuremath{...}. If you did graph at lines 860-−861 []\LY1/brm/m/n/10 Windows,
not intend to use mathematics mode, then perhaps you are \LY1/brm/m/it/10 see \LY1/brm/m/n/10 X Win-
trying to use a special character that needs to be entered
in a different way; for example _ will be interpreted as a An overfull \hbox means that there is a hyphenation or
subscript operator in mathematics mode, and you need \_ justification problem: moving the last word on the line
to get an underscore character. to the next line would make the spaces in the line wider
than the current limit; keeping the word on the line would
This can also happen if you use the wrong character make the spaces smaller than the current limit, so the
encoding, for example using utf8 without "\usepack- word is left on the line, but with the minimum allowed
age[utf8]{inputenc}" or using iso8859-1 without "\usep- space between words, and which makes the line go over
ackage[latin1]{inputenc}", there are several character the edge.
encoding formats, make sure to pick the right one.
The warning is given so that you can find the line in the
code that originates the problem (in this case: 860-861)
Runaway argument and fix it. The line on this example is too long by a shade
over 9pt. The chosen hyphenation point which minimizes
Runaway argument? {December 2004 \maketitle ! Para- the error is shown at the end of the line (Win-). Line num-
graph ended before \date was complete. <to be read bers and page numbers are given as before. In this case,
again> \par l.8 9pt is too much to ignore (over 3mm), and a manual cor-
rection needs making (such as a change to the hyphen-
In this error, the closing curly brace has been omitted
ation), or the flexibility settings need changing.
from the date. It’s the opposite of the error of too many
}'s, and it results in \maketitle trying to format the title If the “overfull” word includes a forward slash, such as
page while LaTeX is still expecting more text for the date! “input/output”, this should be properly typeset as “in-
As \maketitle creates new paragraphs on the title page, put\slash output”. The use of \slash has the same effect
this is detected and LaTeX complains that the previous as using the "/" character, except that it can form the end
paragraph has ended but \date is not yet finished. of a line (with the following words appearing at the start
of the next line). The "/" character is typically used in
units, such as “mm/year” character, which should not be
Underfull hbox broken over multiple lines.
The warning can also be issued when the \end{document}
Underfull \hbox (badness 1394) in paragraph at lines 28-
tag was not included or was deleted.
−30 [][]\LY1/brm/b/n/10 Bull, RJ: \LY1/brm/m/n/10
Ac-count-ing in Busi- [94]
This is a warning that LaTeX cannot stretch the line wide
enough to fit, without making the spacing bigger than its Easily spotting overfull hboxes in the document To
currently permitted maximum. The badness (0-10,000) easily find the location of overfull hbox in your document,
indicates how severe this is (here you can probably ignore you can make latex add a black bar where a line is too
a badness of 1394). It says what lines of your file it was wide:
3.2. LENGTHS 79
• height
No error message, but won't compile
• width
One common cause of (pdf)LaTeX getting stuck is for-
getting to include \end{document} See Boxes.
80 CHAPTER 3. MECHANICS
You can change the values of the variables defining the \paperheight The height of the page.
page layout with two commands. With this one you can
set a new value for an existing length variable: \parindent The normal paragraph indentation.
with this other one, you can add a value to the existing \parskip The extra vertical space between paragraphs.
one:
You can create your own length with the command, and \tabcolsep The default separation between columns in a
you must create a new length before you attempt to set it: tabular environment.
You may also set a length from the size of a text with one \textheight The height of text on the page.
of these commands:
When using these commands, you may duplicate the text \textwidth The width of the text on the page.
that you want to use as reference if you plan to also dis-
play it. But LaTeX also provides \savebox to avoid this \topmargin The size of the top margin.
duplication. You may wish to look at the example below
to see how you can use these. See Boxes for more details. \unitlength Units of length in picture environment.
To view, it is the same as with LaTeX, using the command TeX features some macros for fixed-length spacing.
\the.
\smallskip Inserts a small space in vertical mode (be-
tween two paragraphs).
3.2.4 LaTeX default lengths
\medskip Inserts a medium space in vertical mode (be-
Common length macros are: tween two paragraphs).
\baselineskip The normal vertical distance between \bigskip Inserts a big space in vertical mode (between
lines in a paragraph. two paragraphs).
\baselinestretch Multiplies \baselineskip.
The vertical mode is during the process of assembling
\columnsep The distance between columns. boxes “vertically”, like paragraphs to build a page. The
horizontal mode is during the process of assembling
\columnwidth The width of the column.
boxes “horizontally”, like letters to build a word or words
\evensidemargin The margin for 'even' pages (think of to build a paragraph.
a printed booklet). The fact they are vertical mode commands mean they will
\linewidth The width of a line in the local environment. be ignored (or fail) in horizontal mode such as in the mid-
dle of a paragraph. The first token next the a double line-
\oddsidemargin The margin for 'odd' pages (think of a break is still in vertical mode if it does not expand to char-
printed booklet). acters.
3.3. COUNTERS 81
You can also use \fill instead of \stretch{1}. To increase the counter, either use
• subsubsection The past chapters have already dealt with some boxes, al-
though they weren't described as such. The tabular en-
• paragraph vironment and the \includegraphics, for example, both
• subparagraph produce a box. This means that one can easily arrange
two tables or images side by side. You just have to make
• page sure that their combined width is not larger than the \tex-
twidth.
• equation
• figure
3.4.1 TeX character boxes
• table
TeX characters are stored in boxes like every printed el-
• footnote ement. Boxes have three dimensional properties:
• mpfootnote
• The height is the length between the baseline and the
top of the box.
For the enumerate environment:
• The depth is the length between the baseline and the
• enumi bottom of the box.
• enumiii
• enumiv
• \fboxsep: the distance between the frame and the Paragraphs in all boxes
content.
You can make use of the long capabilities of minipage
• \fboxrule: the thickness of the rule. and parbox to embed paragraphs in non-long boxes. For
instance:
This prints a thick and more distant frame: This prevents the overfull badness.
This shows the box frame of a letter. You can also use
from the pbox package which will create a box of minimal
size around the text. Note that the \pbox command takes
3.4.4 framed an optional argument that specifies the vertical position
of the text:
An alternative to these approaches is the usage of the The valid values are b (bottom), t (top), and c (center). If
framed environment (you will need to include the framed you specify a length in the first (required) argument, the
package to use it). This provides an easy way to box a text will be wrapped:
paragraph within a document:
You can do it manually with a parbox.
3.4.7 savebox
See Rotations.
3.4.6 minipage and parbox
Most standard LaTeX boxes are not long com- 3.4.9 colorbox and fcolorbox
mands, i.e. they do not support breaks nor para-
graphs. However you can pack a paragraph See Colors. \fcolorbox can also be tweaked with \fboxsep
of your choice into a box with either the \par- and \fboxrule.
box[pos][height][contentpos]{width}{text} command or
the \begin{minipage}[pos][height][contentpos]{width}
text \end{minipage} environment. 3.4.10 resizebox and scalebox
The pos parameter can take one of the letters center, top
or bottom to control the vertical alignment of the box, The graphicx package features additional boxes.
relative to the baseline of the surrounding text. The height
parameter is the height of the parbox or minipage. The
contentpos parameter is the position of the content and 3.4.11 fancybox
can be one of center, top, bottom or spread. width takes
a length argument specifying the width of the box. The
the fancybox package provides additional boxes.
main difference between a minipage and a \parbox is that
you cannot use all commands and environments inside a
parbox, while almost anything is possible in a minipage. • \doublebox
This should print 3 boxes on the same line. Do not put
another linebreak between the \fbox, otherwise you will • \ovalbox
put the following \fbox in another paragraph on another
line. • \shadowbox
84 CHAPTER 3. MECHANICS
3.5.1 Rules
The \rule command in normal use produces a simple
black box:
The depth, width and height parameters are explained in
the Boxes chapter.
Here is an example:
This is useful for drawing vertical and horizontal lines.
3.5.2 Struts
A special case is a rule with no width but a certain height.
In professional typesetting, this is called a strut. It is used
to guarantee that an element on a page has a certain min-
imal height. You could use it in a tabular environment
or in boxes to make sure a row has a certain minimum
height.
In LaTeX a strut is defined as
Technical Texts
LaTeX needs to know beforehand that the subsequent Inserting “Displayed” maths inside blocks of text
text does indeed contain mathematical elements. This is
because LaTeX typesets maths notation differently from In order for some operators, such as \lim or \sum to be
normal text. Therefore, special environments have been displayed correctly inside some math environments (read
declared for this purpose. They can be distinguished into $......$), it might be convenient to write the \displaystyle
two categories depending on how they are presented: class inside the environment. Doing so might cause the
line to be taller, but will cause exponents and indices to be
• text — text formulas are displayed inline, that is, displayed correctly for some math operators. For exam-
within the body of text where it is declared, for ex- ple, the $\sum$ will print a smaller
∑ Σ and $\displaystyle
ample, I can say that a + a = 2a within this sentence. \sum$ will print a bigger one , like in equations (This
85
86 CHAPTER 4. TECHNICAL TEXTS
only works with AMSMATH package). It is also possi- To use operators that are not pre-defined, such as argmax,
ble to force this behaviour for all math environments by see custom operators
declaring \everymath{\displaystyle} at the very beginning
(i.e. before \begin{document}), which is useful in longer
documents. 4.1.5 Powers and indices
Powers and indices are equivalent to superscripts and sub-
4.1.2 Symbols scripts in normal text mode. The caret (^; also known as
the circumflex accent) character is used to raise some-
thing, and the underscore (_) is for lowering. If more
Mathematics has many symbols! One of the most dif-
than one expression is raised or lowered, they should be
ficult aspects of learning LaTeX is remembering how to
grouped using curly braces ({ and }).
produce symbols. There is of course a set of symbols that
can be accessed directly from the keyboard: For powers with more than one digit, surround the power
with {}.
+-=! /()[]<>|':
An underscore (_) can be used with a vertical bar ( | ) to
Beyond those listed above, distinct commands must be
denote evaluation using subscript notation in mathemat-
issued in order to display the desired symbols. There are
ics:
many examples such as Greek letters, set and relations
symbols, arrows, binary operators, etc.
For example: 4.1.6 Fractions and Binomials
Fortunately, there’s a tool that can greatly simplify the
A fraction is created using the
search for the command for a specific symbol. Look for
\frac{numerator}{denominator} command. (for
“Detexify” in the external links section below. Another
those who need their memories refreshed, that’s the
option would be to look in the “The Comprehensive La-
top and bottom respectively!). Likewise, the binomial
TeX Symbol List” in the external links section below.
coefficient (aka the Choose function) may be written
using the \binom command[3] :
4.1.3 Greek letters It is also possible to use the \choose command without
the amsmath package:
Greek letters are commonly used in mathematics, and You can embed fractions within fractions:
they are very easy to type in math mode. You just have to
Note that when appearing inside another fraction, or in
type the name of the letter after a backslash: if the first
inline text ab , a fraction is noticeably smaller than in dis-
letter is lowercase, you will get a lowercase Greek letter,
played mathematics. The \tfrac and \dfrac commands[3]
if the first letter is uppercase (and only the first letter),
force the use of the respective styles, \textstyle and \dis-
then you will get an uppercase letter. Note that some up-
playstyle. Similarly, the \tbinom and \dbinom commands
percase Greek letters look like Latin ones, so they are not
typeset the binomial coefficient.
provided by LaTeX (e.g. uppercase Alpha and Beta are
just “A” and “B” respectively). Lowercase epsilon, theta, Another way to write fractions is to use the \over com-
kappa, phi, pi, rho, and sigma are provided in two differ- mand without the amsmath package:
ent versions. The alternate, or variant, version is created
For relatively simple fractions, especially within the text,
by adding “var” before the name of the letter: it may be more aesthetically pleasing to use powers and
Scroll down to #List of Mathematical Symbols for a com- indices:
plete list of Greek symbols. If this looks a little “loose” (overspaced), a tightened ver-
sion can be defined by inserting some negative space
4.1.4 Operators If you use them throughout the document, usage of xfrac
package is recommended. This package provides \sfrac
command to create slanted fractions. Usage:
An operator is a function that is written as a word: e.g.
trigonometric functions (sin, cos, tan), logarithms and ex- If fractions are used as an exponent curly braces have to
ponentials (log, exp), limits (lim), as well as trace and de- be used around the \sfrac command:
terminant (tr, det). LaTeX has many of these defined as $x^\frac{1}{2}$ % no error $x^\sfrac{1}{2}$ % error
commands: $x^{\sfrac{1}{2}}$ % no error
For certain operators such as limits, the subscript is In some cases, using the package alone will result in er-
placed underneath the operator: rors about certain font shapes not being available. In that
For the modular operator there are two commands: case, the lmodern and fix-cm packages need to be added
\bmod and \pmod: as well.
4.1. MATHEMATICS 87
Alternatively, the nicefrac package provides the \nicefrac There are many other “big” commands which operate in
command, whose usage is similar to \sfrac. a similar manner:
For more integral symbols, including those not included
Continued fractions by default in the Computer Modern font, try the esint
package.
Continued fractions should be written using \cfrac The \substack command[3] allows the use of \\ to write
command[3] : the limits over multiple lines:
If you want the limits of an integral to be specified above
Multiplication of two numbers and below the symbol (like the sum), use the \limits com-
mand:
To make multiplication visually similar to a fraction, a However if you want this to apply to ALL integrals, it is
nested array can be used, for example multiplication of preferable to specify the intlimits option when loading the
numbers written one below the other. amsmath package:
Subscripts and superscripts in other contexts as well as
4.1.7 Roots other parameters to amsmath package related to them are
described in Advanced Mathematics chapter.
The \sqrt command creates a square root surrounding an For bigger integrals, you may use personal declarations,
expression. It accepts an optional argument specified in or the bigints package [4] .
square brackets ([ and ]) to change magnitude:
Some people prefer writing the square root “closing” it
over its content. This method arguably makes it more 4.1.9 Brackets, braces and delimiters
clear what is in the scope of the root sign. This habit is
not normally used while writing with the computer, but How to use braces in multi line equations is described in the
if you still want to change the output of the square root, Advanced Mathematics chapter.
LaTeX gives you this possibility. Just add the following The use of delimiters such as brackets soon becomes im-
code in the preamble of your document: portant when dealing with anything but the most trivial
This TeX code first renames the \sqrt command as \old- equations. Without them, formulas can become ambigu-
sqrt, then redefines \sqrt in terms of the old one, adding ous. Also, special types of mathematical structures, such
something more. The new square root can be seen in the as matrices, typically rely on delimiters to enclose them.
picture on the left, compared to the old one on the right. There are a variety of delimiters available for use in La-
Unfortunately this code won't work √ if you want to use TeX:
multiple roots: if you try to write b a as \sqrt[b]{a} after
you used the code above, you'll just get a wrong output. where \lbrack and \rbrack may be used in place of [ and
In other words, you can redefine the square root this way ].
only if you are not going to use multiple roots in the whole
document.
Automatic sizing
An alternative piece of TeX code that does allow multiple
roots is Very often mathematical features will differ in size, in
However this requires the \usepackage{letltxmacro} which case the delimiters surrounding the expression
package should vary accordingly. This can be done automatically
using the \left, \right, and \middle commands. Any of
the previous delimiters may be used in combination with
4.1.8 Sums and integrals these:
Curly braces are defined differently by using \left\{ and
The \sum and \int commands insert the sum and integral
\right\},
symbols respectively, with limits specified using the caret
(^) and underscore (_). The typical notation for sums is: If a delimiter on only one side of an expression is re-
quired, then an invisible delimiter on the other side may
or
be denoted using a period (.).
The limits for the integrals follow the same notation. It’s
also important to represent the integration variables with
an upright d, which in math mode is obtained through the Manual sizing
\mathrm{} command, and with a small space separating
it from the integrand, which is attained with the \, com- In certain cases, the sizing produced by the \left and \right
mand. commands may not be desirable, or you may simply want
88 CHAPTER 4. TECHNICAL TEXTS
finer control over the delimiter sizes. In this case, the \big, columns be pre-specified:
\Big, \bigg and \Bigg modifier commands may be used: You may see that the AMS matrix class of environments
These commands are primarily useful when dealing with doesn't leave enough space when used together with frac-
nested delimiters. For example, when typesetting tions resulting in output similar to this:
5 1
we notice that the \left and \right commands produce the 6 6 0
same size delimiters as those nested within it. This can M = 65 0 16
be difficult to read. To fix this, we write 0 65 16
Manual sizing can also be useful when an equation is too To counteract this problem, add additional leading space
large, trails off the end of the page, and must be sepa- with the optional parameter to the \\ command:
rated into two lines using an align command. Although If you need “border” or “indexes” on your matrix, plain
the commands \left. and \right. can be used to balance TeX provides the macro \bordermatrix
the delimiters on each line, this may lead to wrong de-
limiter sizes. Furthermore, manual sizing can be used to
avoid overly large delimiters if an \underbrace or a similar
Matrices in running text
command appears between the delimiters.
To insert a small matrix, and not increase leading in the
line containing it, use smallmatrix environment:
Typesetting intervals
here is that you can have better control over the font for- instance, you want the sign to appear close to the appro-
matting, rather than the standard text achieved with \text. priate element to show their association. If you put a + or
a − with nothing before it but you want it to be handled
like a binary operator you can add an invisible character
4.1.12 Formatting mathematics symbols before the operator using {}. This can be useful if you
are writing multiple-line formulas, and a new line could
See also: w:Mathematical Alphanumeric Sym- start with a = or a +, for example, then you can fix some
bols, w:Help:Displaying a formula#Alphabets strange alignments adding the invisible character where
and typefaces and w:Wikipedia:LaTeX sym- necessary.
bols#Fonts
A plus-minus sign is written as:
We can now format text; what about formatting mathe- Similarly, there exists also a minus-plus sign:
matical expressions? There are a set of formatting com-
mands very similar to the font formatting ones just used,
except that they are specifically aimed at text in math
4.1.15 Controlling horizontal spacing
mode (requires amsfonts)
LaTeX is obviously pretty good at typesetting maths—it
These formatting commands can be wrapped around the was one of the chief aims of the core TeX system that
entire equation, and not just on the textual elements: they LaTeX extends. However, it can't always be relied upon
only format letters, numbers, and uppercase Greek, and to accurately interpret formulas in the way you did. It
other math commands are unaffected. has to make certain assumptions when there are ambigu-
To bold lowercase Greek or other symbols use the ous expressions. The result tends to be slightly incorrect
\boldsymbol command[3] ; this will only work if there horizontal spacing. In these events, the output is still sat-
exists a bold version of the symbol in the current font. isfactory, yet any perfectionists will no doubt wish to fine-
As a last resort there is the \pmb command[3] (poor tune their formulas to ensure spacing is correct. These are
mans bold): this prints multiple versions of the charac- generally very subtle adjustments.
ter slightly offset against each other. There are other occasions where LaTeX has done its job
To change the size of the fonts in math mode, see correctly, but you just want to add some space, maybe
Changing font size. to add a comment of some kind. For example, in the
following equation, it is preferable to ensure there is a
decent amount of space between the maths and the text.
Accents This code produces errors with Miktex 2.9 and does not
yield the results seen on the right. Use \mathrm instead
So what to do when you run out of symbols and fonts? of just \text.
Well the next step is to use accents:
(Note that this particular example can be expressed in
more elegant code by the cases construct provided by the
4.1.13 Color amsmath package described in Advanced Mathematics
chapter.)
The package xcolor, described in Colors, allows us to add LaTeX has defined two commands that can be used any-
color to our equations. For example, where in documents (not just maths) to insert some hor-
The only problem is that this disrupts the default LaTeX izontal space. They are \quad and \qquad
formatting around the - operator. To fix this, we enclose A \quad is a space equal to the current font size. So, if you
it in a \mathbin environment, since - is a binary operator. are using an 11pt font, then the space provided by \quad
This process is described here. will also be 11pt (horizontally, of course.) The \qquad
gives twice that amount. As you can see from the code
from the above example, \quads were used to add some
4.1.14 Plus and minus signs separation between the maths and the text.
Latex deals with the + and − signs in two possible ways. OK, so back to the fine tuning as mentioned at the be-
The most common is as a binary operator. When two ginning of the document. A good example would be dis-
maths elements appear on either side of the sign, it is playing the simple equation for the indefinite integral of
assumed to be a binary operator, and as such, allocates y with respect to x:
∫
some space either side of the sign. The alternative way y dx
is a sign designation. This is when you state whether a
mathematical quantity is either positive or negative. This If you were to try this, you may write:
is common for the latter, as in maths, such elements are However, this doesn't give the correct result. LaTeX
assumed to be positive unless a − is prefixed to it. In this doesn't respect the white-space left in the code to signify
90 CHAPTER 4. TECHNICAL TEXTS
that the y and the dx are independent entities. Instead, it same thing, but use \displaystyle instead.
lumps them altogether. A \quad would clearly be overkill
in this situation—what is needed are some small spaces to
be utilized in this type of instance, and that’s what LaTeX 4.1.17 Advanced Mathematics: AMS
provides: Math package
NB you can use more than one command in a sequence
The AMS (American Mathematical Society) mathemat-
to achieve a greater space if necessary.
ics package is a powerful package that creates a higher
So, to rectify the current problem: layer of abstraction over mathematical LaTeX language;
The negative space may seem like an odd thing to use, if you use it it will make your life easier. Some com-
however, it wouldn't be there if it didn't have some use! mands amsmath introduces will make other plain LaTeX
Take the following example: commands obsolete: in order to keep consistency in the
final output you'd better use amsmath commands when-
The matrix-like expression for representing binomial co- ever possible. If you do so, you will get an elegant out-
efficients is too padded. There is too much space between put without worrying about alignment and other details,
the brackets and the actual contents within. This can eas- keeping your source code readable. If you want to use it,
ily be corrected by adding a few negative spaces after the you have to add this in the preamble:
left bracket and before the right bracket.
In any case, adding some spaces manually should be
Introducing dots in formulas
avoided whenever possible: it makes the source code
more complex and it’s against the basic principles of
amsmath defines also the \dots command, that is a gen-
a What You See is What You Mean approach. The
eralization of the existing \ldots. You can use \dots in
best thing to do is to define some commands using all
both text and math mode and LaTeX will replace it with
the spaces you want and then, when you use your com-
three dots "…" but it will decide according to the context
mand, you don't have to add any other space. Later, if
whether to put it on the bottom (like \ldots) or centered
you change your mind about the length of the horizontal
(like \cdots).
space, you can easily change it modifying only the com-
mand you defined before. Let us use an example: you
want the d of a dx in an integral to be in roman font and Dots
a small space away from the rest. If you want to type
an integral like \int x \, \mathrm{d} x, you can define a LaTeX gives you several commands to insert dots (el-
command like this: lipses) in your formulae. This can be particularly useful
in the preamble of your document. We have chosen \dd if you have to type big matrices omitting elements. First
just because it reminds the “d” it replaces and it is fast to of all, here are the main dots-related commands LaTeX
type. Doing so, the code for your integral becomes \int x provides:
\dd x. Now, whenever you write an integral, you just have Instead of using \ldots and \cdots, you should use the se-
to use the \dd instead of the “d”, and all your integrals will mantically oriented commands. It makes it possible to
have the same style. If you change your mind, you just adapt your document to different conventions on the fly,
have to change the definition in the preamble, and all your in case (for example) you have to submit it to a publisher
integrals will be changed accordingly. who insists on following house tradition in this respect.
The default treatment for the various kinds follows Amer-
ican Mathematical Society conventions.
4.1.16 Manually Specifying Formula Style
To manually display a fragment of a formula using text Write an equation with the align environment
style, surround the fragment with curly braces and pre-
fix the fragment with \textstyle. The braces are required How to write an equation with the align environment with
because the \textstyle macro changes the state of the ren- the amsmath package is described in Advanced Mathe-
derer, rendering all subsequent mathematics in text style. matics.
The braces limit this change of state to just the fragment
enclosed within. For example, to use text style for just
the summation symbol in a sum, one would enter 4.1.18 List of Mathematical Symbols
The same thing as a command would look like this: All the pre-defined mathematical symbols from the \TeX\
Note the extra braces. Just one set around the expression package are listed below. More symbols are available
won't be enough. That would cause all math after \tsum from extra packages.
k to be displayed using text style. Note: To use the Greek Letters in LaTeX that have the
To display part of a formula using display style, do the same appearance as their Roman equivalent, just use the
4.2. ADVANCED MATHEMATICS 91
Roman form: e.g., A instead of Alpha, B instead of Beta, 4.2.1 Equation numbering
etc.
The equation environment automatically numbers your
equation:
4.1.19 Summary You can also use the \label and \ref (or \eqref from
the amsmath package) commands to label and reference
As you begin to see, typesetting math can be tricky at equations, respectively. For equation number 1, \ref re-
times. However, because LaTeX provides so much con- sults in 1 and \eqref results in (1) :
trol, you can get professional quality mathematics type-
setting with relatively little effort (once you've had a bit of Further information is provided in the labels and cross-
practice, of course!). It would be possible to keep going referencing chapter.
and going with math topics because it seems potentially To have the enumeration follow from your section or sub-
limitless. However, with this tutorial, you should be able section heading, you must use the amsmath package or
to get along sufficiently. use AMS class documents. Then enter
to the preamble to get enumeration at the section level or
4.1.20 Notes to have the enumeration go to the subsection level.
If the style you follow requires putting dots after ordi-
[1] http://www.ams.org/publications/authors/tex/amslatex
nals (as it is required at least in Polish typography) the
[2] http://www.tex.ac.uk/ctan/macros/latex/contrib/ \numberwithin{equation}{subsection} command in the
mathtools/mathtools.pdf preamble will result in the equation number in the above
example to be rendered in this way: (1.1..1).
[3] requires the amsmath package To remove the duplicate dot, add the following command
immediately after \numberwithin{equation}{section}:
[4] http://hdl.handle.net/2268/6219
For a numbering scheme using \number-
[5] requires the mathtools package within{equation}{subsection}, use:
in the preamble of the document.
4.1.21 Further reading Note: Though it may look like the \renewcommand works
by itself, it won't reset the equation number with each new
• meta:Help:Displaying a formula: Wikimedia uses a section. It must be used together with manual equation
subset of LaTeX commands. number resetting after each new section beginning or with
the much cleaner \numberwithin.
This page outlines some more advanced uses of math- A problem often encountered with displayed environ-
ematics markup using LaTeX. In particular it makes ments (displaymath and equation) is the lack of any abil-
heavy use of the AMS-LaTeX packages supplied by the ity to span multiple lines. While it is possible to define
American Mathematical Society. lines individually, these will not be aligned.
92 CHAPTER 4. TECHNICAL TEXTS
Above and below Notice that we've added some indenting on the second
line. Also, we need to insert the double braces ({}) before
The \overset and \underset commands[1] typeset symbols the + sign, otherwise latex won't create the correct spac-
above and below expressions. Without AmsTex the same ing after the + sign. The reason for this is that without
result of \overset can be obtained with \stackrel. This can the braces, latex interprets the + sign as a unary operator,
be particularly useful for creating new binary relations: instead of the binary operator that it really is.
or to show usage of L'Hôpital’s rule: More complicated alignments are possible, with addi-
It is convenient to define a new operator that will set the tional &'s on a single line specifying multiple “equation
equal sign with H and the provided fraction: columns”, each of which is aligned. The following exam-
ple illustrates the alignment rule of align*:
which reduces the above example to:
If the purpose is to make comments on particular parts of Braces spanning multiple lines
an equation, the \overbrace and \underbrace commands
may be more useful. However, they have a different syn- If you want a brace to continue across a new line, do the
tax (and can be aligned with the \vphantom command): following:
Sometimes the comments are longer than the formula be- In this construction, the sizes of the left and right braces
ing commented on, which can cause spacing problems. are not automatically equal, in spite of the use of \left\{
These can be removed using the \mathclap command[2] : and \right\}. This is because each line is typeset as a com-
Alternatively, to use brackets instead of braces use \un- pletely separate equation —notice the use of \right. and
derbracket and \overbracket commands[2] : \left. so there are no unpaired \left and \right commands
within a line (these aren't needed if the formula is on one
The optional arguments set the rule thickness and bracket
line). You can control the size of the braces manually
height respectively:
with the \big, \Big, \bigg, and \Bigg commands.
The \xleftarrow and \xrightarrow commands[1] produce
Alternatively, the height of the taller equation can be
arrows which extend to the length of the text. Yet again,
replicated in the other using the \vphantom command:
the syntax is different: the optional argument (using [ and
]) specifies the subscript, and the mandatory argument
(using { and }) specifies the superscript (which can be Using aligned braces for piecewise functions You
left empty by inserting a blank space). can also use \left\{ and \right. to typeset piecewise func-
For more extensible arrows, you must use mathtools tions:
package:
and for harpoons: The cases environment
4.2.5 Boxed Equations While you can place symbols in subscript or superscript
(in summation style symbols) with \nolimits:
For a single equation or alignment building block, with
the tag outside the box, use \boxed{}: It’s impossible to mix them with typical usage of such
symbols:
If you want the entire line or several equations to be
boxed, use a minipage inside an \fbox{}: To add both prime and a limit to a symbol, one might use
\sideset command:
There is also the mathtools \Aboxed{} which is able to
box across alignment marks: It is very flexible: for example, to put letters in each cor-
ner of the symbol use this command:
If you wish to place them on the corners of an arbitrary
4.2.6 Custom operators symbol, you should use \fourIdx from the fouridx pack-
age.
Although many common operators are available in La- However, a simple grouping can solve the problem:
TeX, sometimes you will need to write your own, e.g. to
typeset the argmax operator. The \operatorname and \op- since a math operator can be used with limits or no limits.
eratorname* commands[1] display custom operators; the If you want to change its state, simply group it. You can
* version sets the underscored option underneath like the make it another math operator if you want, and then you
\lim operator: can have limits and then limits again.
Put
Definition 3 Here is a new definition
before
to force all math to with line breaks separating it from the rest of the text.
4.3. THEOREMS 95
defines the mydef environment, which will generate def- To define your own style, use the \newtheoremstyle
initions without numbering. This requires amsthm pack- command[1] :
age.
\newtheoremstyle{stylename}% name of the style to be
used {spaceabove}% measure of space to leave above the
4.3.3 Proofs theorem. E.g.: 3pt {spacebelow}% measure of space to
leave below the theorem. E.g.: 3pt {bodyfont}% name
The proof environment[1] can be used for adding the of font to use in the body of the theorem {indent}%
proof of a theorem. The basic usage is: measure of space to indent {headfont}% name of head
\begin{proof} Here is my proof \end{proof} font {headpunctuation}% punctuation between head and
body {headspace}% space after theorem head; " " =
normal interword space {headspec}% Manually specify
It just adds Proof in italics at the beginning of the text head
given as argument and a white square (Q.E.D. symbol,
also known as a tombstone) at the end of it. If you are
writing in another language than English, just use babel (Any arguments that are left blank will assume their de-
with the right argument and the word Proof printed in fault value). Here is an example headspec:
the output will be translated accordingly; anyway, in the \thmname{#1}\thmnumber{ #2}:\thmnote{ #3}
source the name of the environment remains proof.
If you would like to manually name the proof, include the which would look something like:
name in square brackets: Definition 2: Topology
\begin{proof}[Proof of important theorem] Here is my for the following:
important proof \end{proof} \begin{definition}[Topology]...
If the last line of the proof is displayed math then the (The note argument, which in this case is Topology, is
Q.E.D. symbol will appear on a subsequent empty line. always optional, but will not appear by default unless you
To put the Q.E.D. symbol at the end of the last line, use specify it as above in the head spec).
the \qedhere command:
96 CHAPTER 4. TECHNICAL TEXTS
4.3.5 Conflicts an angle relative to the angle of the preceding bond. Fi-
nally, predefined angles are whole numbers from 0 to 7
The theorem environment conflicts with other environ- indicating intervals of 45 degrees. These are produced
ments, for example wrapfigure. A work around is to re- with the syntax [< predefined angle>]. The predefined
define theorem, for example the following way: angles and their corresponding absolute angles are repre-
sented in the diagram below.
% Fix latex \def\smallskip{\vskip\smallskipamount}
\def\medskip{\vskip\medskipamount} <bond type> describes the bond attaching <atom1> and
\def\bigskip{\vskip\bigskipamount} % Hand <atom2>. There are 9 different bond types:
made theorem \newcounter{thm}[section] \re- <coeff> represents the factor by which the bond’s length
newcommand{\thethm}{\thesection.\arabic{thm}} will be multiplied.
\def\claim#1{\par\medskip\noindent\refstepcounter{thm}\hbox{\bf
\arabic{chapter}.\arabic{section}.\arabic{thm}. #1.} <tikz code> includes additional options regarding the
\it\ %\ignorespaces } \def\endclaim{ \par\medskip} color or style of the bond.
\newenvironment{thm}{\claim}{\endclaim} A methane molecule, for instance, can be produced with
the following code:
In this case theorem looks like: Linear molecules (such as methane) are a weak example
\begin{thm}{Claim}\label{lyt-prob} Let it be. Then of this, but molecules are formed in chemfig by nesting.
you know. \end{thm}
4.4.3 Rings
4.3.7 External links
Rings follow the syntax <atom>*<n>(code), where “n”
indicates the number of sides in the ring and “code” repre-
• amsthm documentation
sents the specific content of each ring (bonds and atoms).
The LaTeX source can be written to a format familiar Note to users who switched from the old algorithmic
to programmers so that it is easy to read. This will not, package: comments may be placed everywhere in the
however, affect the final layout in the document. source; there are no limitations as in the old algorithmic
package.
\floatname{algorithm}{Procedure} \renewcom-
mand{\algorithmicrequire}{\textbf{Input:}} \re-
newcommand{\algorithmicensure}{\textbf{Output:}}
100 CHAPTER 4. TECHNICAL TEXTS
This defines two commands \<start> and \<end> which List of algorithms
have no parameters. The text displayed by them is
\textbf{<start>} and \textbf{<end>}. When you use figures or tables, you can add a list of them
close to the table of contents; the algorithm package pro-
With \algblockdefx you can give the text to be output by
vides a similar command. Just put
the starting and ending command and the number of pa-
rameters for these commands. In the text the n-th param- \listofalgorithms
eter is referenced by #n.
\algblockdefx[<block>]{<start>}{<end>} [<startparam- anywhere in the document, and LaTeX will print a list of
count>][<default value>]{<start text>} [<endparam- the “algorithm” environments in the document with the
count>][<default value>]{<end text>} corresponding page and the caption.
(eg \S1 typesets {\bf S$_1$} etc). Primes work normally, Here’s the original program:
eg \S‘‘. \begin{program} \VAR \seq{m := 0, p := 0, |last| := ``
Below is an example of typesetting a basic algorithm us- ''}; \ACTIONS |prog|: |prog| \ACTIONEQ % \seq{|line|
ing the program package (remember to add the \usepa- := `` '', m := 0, i := 1}; \CALL |inhere| \ENDACTION l
ckage{program} statement to your document preamble): \ACTIONEQ % i := i+1; \IF (i=(n+1)) \THEN \CALL
\begin{program} \mbox{A fast exponentiation proce- |alldone| \FI ; m := 1; \IF |item|[i] \neq |last| \THEN
|write|(|line|); |line| := `` ''; m := 0; \CALL |inhere| \FI ;
dure:} \BEGIN \\ % \FOR i:=1 \TO 10 \STEP 1 \DO
|expt|(2,i); \\ |newline|() \OD % \rcomment{This text \CALL |more| \ENDACTION |inhere| \ACTIONEQ %
will be set flush to the right margin} \WHERE \PROC p := |number|[i]; |line| := |item|[i]; |line| := |line| \concat ``
|expt|(x,n) \BODY z:=1; \DO \IF n=0 \THEN \EXIT \FI; '' \concat p; \CALL |more| \ENDACTION |more| \AC-
\DO \IF |odd|(n) \THEN \EXIT \FI; \COMMENT{This TIONEQ % \IF (m=1) \THEN p := |number|[i]; |line| :=
is a comment statement}; n:=n/2; x:=x*x \OD; \{ n>0 |line| \concat ``, '' \concat p \FI ; |last| := |item|[i]; \CALL
\}; n:=n-1; z:=z*x \OD; |print|(z) \ENDPROC \END l \ENDACTION |alldone| \ACTIONEQ |write|(|line|);
\end{program} \CALL Z \ENDACTION \ENDACTIONS \END
\end{program}
The listings package supports highlighting of all the most Pascal4 , Perl, PHP, PL/I, Plasm, POV, Prolog, Promela,
common languages and it is highly customizable. If you Python, R, Reduce, Rexx, RSL, Ruby, S4 , SAS, Scilab,
just want to write code within your document the package sh, SHELXL, Simula4 , SQL, tcl4 , TeX4 , VBScript, Ver-
provides the lstlisting environment: ilog, VHDL4 , VRML4 , XML, XSLT.
Another possibility, that is very useful if you created a For some of them, several dialects are supported. For
program on several files and you are still editing it, is to more information, refer to the documentation that comes
import the code from the source itself. This way, if you with the package, it should be within your distribution
modify the source, you just have to recompile the LaTeX under the name listings-*.dvi.
code and your document will be updated. The command
is: Notes
in the example there is a Python source, but it doesn't
matter: you can include any file but you have to write 1. It supports Mathematica code only if you are typing
the full file name. It will be considered plain text and it in plain text format. You can't include *.NB files
will be highlighted according to your settings, that means \lstinputlisting{...} as you could with any other pro-
it doesn't recognize the programming language by itself. gramming language, but Mathematica can export in
You can specify the language while including the file with a pretty-formatted LaTeX source.
the following command:
2. Specification of the dialect is manda-
You can also specify a scope for the file. tory for these languages (e.g. lan-
This comes in handy if you are sure that the file will not guage={[x86masm]Assembler}).
change (at least before the specified lines). You may also
3. Modelica is supported via the dtsyntax package
omit the firstline or lastline parameter: it means every-
available here.
thing up to or starting from this point.
This is a basic example for some Pascal code: 4. For these languages, multiple dialects are supported.
C, for example, has ANSI, Handel, Objective and
\documentclass{article} \usepackage{listings} % Sharp. See p. 12 of the listings manual for an
Include the listings-package \begin{document} \lst- overview.
set{language=Pascal} % Set your language (you can
change the language for each code-block optionally) 5. Defined as a dialect of another language
\begin{lstlisting}[frame=single] % Start your code-
block for i:=maxint to 0 do begin { do nothing } end;
Write('Case insensitive '); Write('Pascal keywords.'); Settings
\end{lstlisting} \end{document}
You can modify several parameters that will affect how
the code is shown. You can put the following code any-
where in the document (it doesn't matter whether before
or after \begin{document}), change it according to your
needs. The meaning is explained next to any line.
\usepackage{listings} \usepackage{color} \de-
finecolor{mygreen}{rgb}{0,0.6,0} \define-
color{mygray}{rgb}{0.5,0.5,0.5} \define-
color{mymauve}{rgb}{0.58,0,0.82} \lstset{ % back-
groundcolor=\color{white}, % choose the background
color; you must add \usepackage{color} or \usepack-
age{xcolor} basicstyle=\footnotesize, % the size of the
fonts that are used for the code breakatwhitespace=false,
% sets if automatic breaks should only happen at
Supported languages
whitespace breaklines=true, % sets automatic line
breaking captionpos=b, % sets the caption-position
It supports the following programming languages: to bottom commentstyle=\color{mygreen}, % com-
ABAP2,4 , ACSL, Ada4 , Algol4 , Ant, Assembler2,4 , ment style deletekeywords={...}, % if you want to
Awk4 , bash, Basic2,4 , C#5 , C++4 , C4 , Caml4 , Clean, delete keywords from the given language escapein-
Cobol4 , Comal, csh, Delphi, Eiffel, Elan, erlang, Eu- side={\%*}{*)}, % if you want to add LaTeX within
phoria, Fortran4 , GCL, Gnuplot, Haskell, HTML, IDL4 , your code extendedchars=true, % lets you use non-
inform, Java4 , JVMIS, ksh, Lisp4 , Logo, Lua2 , make4 , ASCII characters; for 8-bits encodings only, does
Mathematica1,4 , Matlab, Mercury, MetaPost, Miranda, not work with UTF-8 frame=single, % adds a frame
Mizar, ML, Modelica3 , Modula-2, MuPAD, NAS- around the code keepspaces=true, % keeps spaces in
TRAN, Oberon-2, Objective C5 , OCL4 , Octave, Oz, text, useful for keeping indentation of code (possibly
4.6. SOURCE CODE LISTINGS 103
needs columns=flexible) keywordstyle=\color{blue}, % In our example, we only set two options globally: the de-
keyword style language=Octave, % the language of the fault style and the escape character. Usage:
code otherkeywords={*,...}, % if you want to add more \begin{lstlisting} #include <stdio.h> #define N 10 /*
keywords to the set numbers=left, % where to put the Block * comment */ int main() { int i; // Line com-
line-numbers; possible values are (none, left, right) num- ment. puts(“Hello world!"); for (i = 0; i < N; i++) {
bersep=5pt, % how far the line-numbers are from the puts(“LaTeX is also great for programmers!"); } return
code numberstyle=\tiny\color{mygray}, % the style that 0; } \end{lstlisting} \lstinputlisting[caption=Scheduler,
is used for the line-numbers rulecolor=\color{black}, % style=customc]{hello.c}
if not set, the frame-color may be changed on line-breaks
within not-black text (e.g. comments (green here))
showspaces=false, % show spaces everywhere adding The C part will print as
particular underscores; it overrides 'showstringspaces’
showstringspaces=false, % underline spaces within
strings only showtabs=false, % show tabs within strings
adding particular underscores stepnumber=2, % the
step between two line-numbers. If it’s 1, each line will
be numbered stringstyle=\color{mymauve}, % string
literal style tabsize=2, % sets default tabsize to 2 spaces
title=\lstname % show the filename of files included with
\lstinputlisting; also try caption instead of title }
escapeinside
The package lets you define styles, i.e. profiles specifying In this example, we create one command to ease source
a set of settings. code inclusion. We set the default style to be customc. All
listings will have their name as caption: we do not have
Example to write the file name twice thanks to the macro. Finally
\lstdefinestyle{customc}{ belowcaption- we list all listings with this command from the listings
skip=1\baselineskip, breaklines=true, frame=L, package.
xleftmargin=\parindent, language=C, show- See Macros for more details.
stringspaces=false, basicstyle=\footnotesize\ttfamily,
keywordstyle=\bfseries\color{green!40!black}, com-
mentstyle=\itshape\color{purple!40!black}, identi- Encoding issue
fierstyle=\color{blue}, stringstyle=\color{orange},
} \lstdefinestyle{customasm}{ belowcap- By default, listings does not support multi-byte encoding
tionskip=1\baselineskip, frame=L, xleftmar- for source code. The extendedchar option only works for
gin=\parindent, language=[x86masm]Assembler, 8-bits encodings such as latin1.
basicstyle=\footnotesize\ttfamily, com-
mentstyle=\itshape\color{purple!40!black}, } \lst- To handle UTF-8, you should tell listings how to interpret
set{escapechar=@,style=customc} the special characters by defining them like so
\lstset{literate= {á}{<!---->{\'a}<!---->}1 {é}{<!----
104 CHAPTER 4. TECHNICAL TEXTS
>{\'e}<!---->}1 {í}{<!---->{\'i}<!---->}1 {ó}{<!---- code highlighting, which as of Nov 2014 boasts over 300
>{\'o}<!---->}1 {ú}{<!---->{\'u}<!---->}1 {Á}{<!- supported languages and text formats.
--->{\'A}<!---->}1 {É}{<!---->{\'E}<!---->}1 As the package relies on external Python code, the setup
{Í}{<!---->{\'I}<!---->}1 {Ó}{<!---->{\'O}<!---->}1 require a few more steps than a usual LaTeX package, so
{Ú}{<!---->{\'U}<!---->}1 {à}{<!---->{\`a}<!---->}1 please have a look at their GitHub repo and their manual.
{è}{<!---->{\`e}<!---->}1 {ì}{<!---->{\`i}<!---->}1
{ò}{<!---->{\`o}<!---->}1 {ù}{<!---->{\`u}<!---->}1
{À}{<!---->{\`A}<!---->}1 {È}{<!---->{\'E}<!---->}1 4.6.3 References
{Ì}{<!---->{\`I}<!---->}1 {Ò}{<!---->{\`O}<!---->}1
{Ù}{<!---->{\`U}<!---->}1 {ä}{<!---->{\"a}<!---->}1 A lot more detailed information can be found in a PDF
{ë}{<!---->{\"e}<!---->}1 {ï}{<!---->{\"i}<!---->}1 by Carsten Heinz and Brooks Moses.
{ö}{<!---->{\"o}<!---->}1 {ü}{<!---->{\"u}<!---->}1
{Ä}{<!---->{\"A}<!---->}1 {Ë}{<!---->{\"E}<!---- Details and documentation about the Listings package
>}1 {Ï}{<!---->{\"I}<!---->}1 {Ö}{<!---->{\"O}<!--- can be found at its CTAN website.
->}1 {Ü}{<!---->{\"U}<!---->}1 {â}{<!---->{\^a}<!--
-->}1 {ê}{<!---->{\^e}<!---->}1 {î}{<!---->{\^i}<!--
-->}1 {ô}{<!---->{\^o}<!---->}1 {û}{<!---->{\^u}<!- 4.7 Linguistics
--->}1 {Â}{<!---->{\^A}<!---->}1 {Ê}{<!----
>{\^E}<!---->}1 {Î}{<!---->{\^I}<!---->}1 {Ô}{<!- There are a number of LaTeX packages available for
--->{\^O}<!---->}1 {Û}{<!---->{\^U}<!---->}1 writing linguistics papers. Various packages have been
{œ}{<!---->{\oe}<!---->}1 {Œ}{<!---->{\OE}<!---- created for enumerated examples, syntactic trees, OT
>}1 {æ}{<!---->{\ae}<!---->}1 {Æ}{<!---->{\AE}<!- tableaux, feature matrices, IPA fonts, and many other ap-
--->}1 {ß}{<!---->{\ss}<!---->}1 {ű}{{\H{u}}}1 plications. Some packages such as the tipa package are
{Ű}{{\H{U}}}1 {ő}{{\H{o}}}1 {Ő}{{\H{O}}}1 effectively standard within the field, while others will vary
{ç}{<!---->{\c c}<!---->}1 {Ç}{<!---->{\c C}<!- by author preference.
--->}1 {ø}{<!---->{\o}<!---->}1 {å}{<!---->{\r
Some recommended packages:[1]
a}<!---->}1 {Å}{<!---->{\r A}<!---->}1 {€}{<!---
->{\EUR}<!---->}1 {£}{<!---->{\pounds}<!---->}1
}<!----> • Glosses: gb4e or Covington;
• IPA symbols: tipa;
The above table will cover most characters in latin lan-
• OT Tableaux: OTtablx;
guages. For a more detailed explanation of the usage of
the literate option check section 5.4 in the Listings Doc- • Syntactic trees: qtree + tree-dvips (for drawing ar-
umentation. rows);
Another possibility is to replace \usepackage{listings} (in
the preamble) with \usepackage{listingsutf8}. • Alternatively, xyling is very powerful but
not as user friendly as qtree;
• The xy package itself has a steep learning
Customizing captions curve, but allows a lot of control; for sim-
plest trees use the xymatrix feature and
You can have fancy captions (or titles) for your listings arrows;
using the caption package. Here is an example for listings.
• tikz-qtree has the same syntax as qtree,
\usepackage{caption} \usepackage{listings} \Declare- but uses PGF/TikZ, which allows more
CaptionFont{white}{ \color{white} } \DeclareCaption- options for drawing arrows, etc.
Format{listing}{ \colorbox[cmyk]{0.43, 0.35, 0.35,0.01
}{ \parbox{\textwidth}{\hspace{15pt}#1#2#3} } • Dependency trees and bubble parses:
} \captionsetup[lstlisting]{ format=listing, label-
font=white, textfont=white, singlelinecheck=false,
• The TikZ-dependency package provides
margin=0pt, font={bf,footnotesize} } % ... \lstinputlist-
a high-level, convenient interface to draw
ing[caption=My caption]{sourcefile.lang}
dependency graphs. It is based on
PGF/TikZ but does not require prior
knowledge of TikZ in order to be used
productively.
4.6.2 The minted package
• Attribute-Value Matrices (AVMs): avm
minted is an alternative to listings which has become pop-
ular. It uses the external Python library Pygments for • John Frampton’s expex: expex
4.7. LINGUISTICS 105
gb4e
produces:
\enumsentence{This is the first example.} \enumsen-
tence{This is the second example.} \enumsentence{This
is the third.}
produces:
Constituent trees IMPORTANT: If you use gb4e package, let it be the last
\usepackage call in the document’s preamble. Otherwise
While there are several packages for drawing syntactic you may get exceeded parameter stack size error.
trees available for LaTeX, this article focuses on the qtree
and xyling packages.
tikz-qtree Using the same syntax as qtree, tikz-qtree
is another easy-to-use alternative for drawing syntactic
qtree Drawing trees with qtree is relatively straightfor- trees.
ward. First, the qtree package has to be included in the For simple trees, tikz-qtree is completely interchangable
document’s preamble: with qtree. However, some of qtree’s advanced features
\usepackage{qtree} are implemented in a different way, or not at all. On the
other hand, tikz-qtree provides other features such as con-
trolling the direction of the tree’s growth (top to bottom,
A new tree is started using the \Tree command, each
left to right etc.) or different styles for edges.
(sub-)tree is indicated by brackets [ ]. The root of a (sub-
)tree is always preceded by a ., leaf nodes are simply ex- To use the tikz-qtree package for drawing trees, put the
pressed by their labels. following into the document’s preamble:
For example, the following code \usepackage{tikz} \usepackage{tikz-qtree}
\Tree [.S [.NP LaTeX ] [.VP [.V is ] [.NP fun ] ] ]
The syntax of tikz-qtree and result when drawing a simple
tree is the same as for qtree.
produces this syntactic tree as output:
\Tree [.S [.NP LaTeX ] [.VP [.V is ] [.NP fun ] ] ]
Note that, other than for qtree, trees are not centered by
Dependency Trees
A dependency tree above running text created using xytree Vertically aligned glosses are separated by spaces, so if
it’s necessary to include a space in part the gloss, simply
enclose the connected parts inside braces.
Dependency Trees using TikZ-dependency The \begin{exe} \ex \gll Pekka pel\"astyi karhusta.\\ Pekka
package provides high level commands to design and style {became afraid} bear.ELA\\ \trans `Pekka became afraid
dependency graphs. To draw a graph, you only need to because of the/a bear.' \end{exe}
create a dependency environment, write the text of the
sentence within the deptext environment and use depedge
commands to draw the edges. Global and local optional
parameters can be used to style and fine tune the looks of
the graph, as shown in the following example: With lingmacros
% In the preamble: \usepackage{tikz-dependency}
% In the document: \begin{dependency}[theme The lingmacros package uses the \shortex command to in-
= simple] \begin{deptext}[column sep=1em] troduce glossed examples inside the \enumsentence and
A \& hearing \& is \& scheduled \& on \& \eenumsentence commands. This command takes four
the \& issue \& today \& . \\ \end{deptext} arguments and builds off the normal tabular environment.
\deproot{3}{ROOT} \depedge{2}{1}{ATT} Its first argument specifies the number of columns in the
\depedge[edge start x offset=−6pt]{2}{5}{ATT} gloss. The second and third arguments give the text and
\depedge{3}{2}{SBJ} \depedge{3}{9}{PU} its gloss respectively, and items within each column are
\depedge{3}{4}{VC} \depedge{4}{8}{TMP} divided by the usual & tabular separator. The fourth ar-
\depedge{5}{7}{PC} \depedge[arc an- gument is the translation.
gle=50]{7}{6}{ATT} \end{dependency} \enumsentence{\shortex{3} {Pekka & pel\"astyi &
karhu-sta.} {Pekka & became afraid & bear.ELA}
This code snippet would produce the following result: {`Pekka became afraid because of the/a bear.'} }
XeLaTeX
4.7.6 References
[1] LaTeX for Linguists presentation
Special Pages
where key is the index entry and does not appear in the makeindex -s [style file] filename
final layout. You enter the index commands at the points If you use a GUI for compiling latex and index files, you
in the text that you want to be referenced in the index, may have to set this in the options. Here are some con-
likely near the reason for the key. For example, the text figuration tips for typical tools:
can be re-written as
to create an entry called 'Fourier Series’ with a reference
to the target page. Multiple uses of \index with the same MakeIndex settings in WinEdt Say you want to add
key on different pages will add those target pages to the an index style file named simpleidx.ist
same index entry.
To show the index within the document, merely use the
command • Texify/PDFTexify: Options→Execution
Modes→Accessories→PDFTeXify, add to the
It is common to place it at the end of the document. The
Switches: --mkidx-option="-s simpleidx.ist”
default index format is two columns.
The showidx package that comes with LaTeX prints out
all index entries in the right margin of the text. This is • MakeIndex alone: Options→Execution
quite useful for proofreading a document and verifying Modes→Accessories→MakeIndex, add to com-
the index. mand line: -s simpleidx.ist
110
5.1. INDEXING 111
Controlling sorting In order to determine how an in- Run LaTeX 2 times then
dex key is sorted, place a value to sort by before the key makeindex filename.nlo -s nomencl.ist -o filename.nls
with the @ as a separator. This is useful if there is any
followed by running LaTeX once again.
formatting or math mode, so one example may be
To add the abbreviation list to the table of content, intoc
so that the entry in the index will show as ' F⃗ ' but be
option can be used when declare the nomencl package,
sorted as 'F'.
i.e.
To combine with the above feature for subentries, you
instead of using the code in Adding Index to Table Of
should style the appropriate component(s):
Contents section.
The title of the list can be changed using the following
Changing page number style To change the format- command:
ting of a page number, append a | and the name of some
command which does the formatting. This command
should only accept one argument. 5.1.3 Multiple indices
For example, if on page 3 of a book you introduce bull-
dogs and include the command If you need multiple indices you can use the package
multind .
and on page 10 of the same book you wish to show the
main section on bulldogs with a bold page number, use This package provides the same commands as makeidx,
but now you also have to pass a name as the first argument
This will appear in the index as bulldog, 3, 10 to every command.
If you use texindy in place of makeindex, the classified
entries will be sorted too, such that all the bolded entries
will be placed before all others by default. 5.1.4 Adding index to table of contents
By default, Index won't show in Table Of Contents, so
Multiple pages To perform multi-page indexing, add you have to add it manually.
a |( and |) to the end of the \index command, as in To add index as a chapter, use these commands:
The entry in the index for the subentry 'History' will be If you use the book class, you may want to start it on an
the range of pages between the two \index commands. odd page by using \cleardoublepage.
You can make a list of abbreviations with the package Unfortunately, current version of xindy and hyperref
nomencl . You may also be interested in using the glos- are incompatible. When you use textbf or textit mod-
112 CHAPTER 5. SPECIAL PAGES
ifiers, texindy will print error message:unknown cross- iconv -f latin2 -t utf8 latin2.xdy >utf8.xdy
reference-class `hyperindexformat'! (ignored) and won't in folder
add those pages to index. Work-around for this bug is
described on the talk page. /usr/share/xindy/tex/inputenc
To generate international index file you have to use (You must have root privileges)
texindy instead of makeindex.
xindy is a much more extensible and robust indexing sys- xindy in kile To use texindy instead of makeindex in
tem than the makeindex system. kile, you have to either redefine the MakeIndex tool in
For example, one does not need to write: Settings → Configure Kile... → Tools → Build, or define
new tool and redefine other tools to use it (for example by
to get the Lin entry after LAN and before LZA, instead,
adding it to QuickBuild).
it’s enough to write
The xindy definition should look similar to this:
But what is much more important, it can properly sort
index files in many languages, not only English. General: Command: texindy Options: -L polish -M
lang/polish/utf8 -I latex '%S.idx' Advanced: Type: Run
Unfortunately, generating indices ready to use by LaTeX
Outside of Kile Class: Compile Source extension: idx
using xindy is a bit more complicated than with makein-
Target extension: ind Target file: <empty> Relative dir:
dex.
<empty> State: Editor Menu: Add tool to Build menu:
First, we need to know in what encoding the .tex project Compile Icon: the one you like
file is saved. In most cases it will be UTF-8 or ISO-8859-
1, though if you live, for example in Poland it may be ISO-
8859-2 or CP-1250. Check the parameter to the inputenc
package. 5.2 Glossary
Second, we need to know which language is prominently
Many technical documents use terms or acronyms un-
used in our document. xindy can natively sort indices
known to the general population. It is common practice
in Albanian, Belarusian, Bulgarian, Croatian, Czech,
to add a glossary to make such documents more accessi-
Danish, Dutch, English, Esperanto, Estonian, Finnish,
ble.
French, Georgian, German, Greek, Gypsy, Hausa, He-
brew, Hungarian, Icelandic, Italian, Klingon, Kurdish, The glossaries package can be used to create glossaries.
Latin, Latvian, Lithuanian, Macedonian, Mongolian, It supports multiple glossaries, acronyms, and symbols.
Norwegian, Polish, Portuguese, Romanian, Russian, Ser- This package replaces the glossary package and can be
bian Slovak, Slovenian, Sorbian, Spanish, Swedish, Turk- used instead of the nomencl package.[1] Users requir-
ish, Ukrainian and Vietnamese, ing a simpler solution should consider hand-coding their
entries by using the description environment, or the
I don't know if other languages have similar problems,
longtabu environment provided by the tabu package.
but with Polish, if your .tex is saved using UTF-8, the
.ind produced by texindy will be encoded in ISO-8859-2
if you use only -L polish. While it’s not a problem for
entries containing polish letters, as LaTeX internally en- 5.2.1 Jump start
codes all letters to plain ASCII, it is for accented letters at
beginning of words, they create new index entry groups, Place \usepackage{glossaries} and \makeglossaries in
if you have, for example an "średnia” entry, you'll get a your preamble (after \usepackage{hyperref} if present).
"Ś" encoded in ISO-8859-2 .ind file. LaTeX doesn't like Then define any number of \newglossaryentry and
if part of the file is in UTF-8 and part is in IS-8859-2. The \newacronym glossary and acronym entries in your
obvious solution (adding -C utf8) doesn't work, texindy preamble (recommended) or before first use in your doc-
stops with ument proper. Finally add a \printglossaries call to locate
the glossaries list within your document structure. Then
ERROR: Could not find file “tex/inputenc/utf8.xdy” pepper your writing with \gls{mylabel} macros (and sim-
error. The fix this, you have to load the definiton style for ilar) to simultaneously insert your predefined text and
the headings using -M switch: build the associated glossary. File processing must now
include a call to makeglossaries followed by at least one
-M lang/polish/utf8 further invocation of latex or pdflatex.
In the end we have to run such command:
texindy -L polish -M lang/polish/utf8 filename.idx
5.2.2 Using glossaries
Additional way to fix this problem is use “iconv” to create
utf8.xdy from latin2.xdy To use the glossaries package, you have to load it explic-
itly:
5.2. GLOSSARY 113
if you wish to use xindy (recommended) for the indexing This will avoid the wrong long plural: Frame per Seconds.
phase, as opposed to makeindex (the default), you need So far, the glossary entries have been defined as key-value
to specify the xindy option: lists. Sometimes, a description is more complex than just
For the glossary to show up in your Table of Contents, a paragraph. For example, you may want to have multiple
you need to specify the toc option: paragraphs, itemized lists, figures, tables, etc. For such
See also Custom Name at the bottom of this page. glossary entries use the command longnewglossaryentry
in which the description follows the key-value list. The
Finally, place the following command in your document computer entry then looks like this:
preamble in order to generate the glossary:
Any links in resulting glossary will not be “clickable” un-
Defining symbols
less you load the glossaries package after the hyperref
package.
Defined entries can also be symbols:
In addition, users who wish to make use of makeglos-
You can also define both a name and a symbol:
saries will need to have Perl installed — this is not nor-
mally present by default on Microsoft Windows plat- Note that not all glossary styles show defined symbols.
forms. That said, makeglossaries simply provides a con-
venient interface to makeindex and xindy and is not es-
Defining acronyms
sential.
To define a new acronym you use the \newacronym
5.2.3 Defining glossary entries macro:
where <label> is the unique label identifying the
To use an entry from a glossary you first need to define it. acronym, <abbrv> is the abbreviated form of the
There are few ways to define an entry depending on what acronym and <full> is the expanded text. For example:
you define and how it is going to be used.
Defined acronyms can be put in separate list if you use
Note that a defined entry won't be included in the printed acronym package option:
glossary unless it is used in the document. This enables
you to create a glossary of general terms and just \include
it in all your documents. 5.2.5 Using defined terms
When you have defined a term, you can use it in a docu-
5.2.4 Defining terms ment. There are many different commands used to refer
to glossary terms.
To define a term in glossary you use the \newglossaryentry
macro:
<label> is a unique label used to identify an entry in glos- General references
sary, <settings> are comma separated key=value pairs
A general reference is used with \gls command. If, for
used to define an entry.
example, you have glossary entries defined as those above,
For example, to define a computer entry: you might use it in this way:
The above example defines an entry that has the same la- Description of commands used in above example:
bel and entry name. This is not always the case as the
next entry will show: This command prints the term associated with <label>
passed as its argument. If the hyperref package was
When you define terms, you need to remember that they loaded before glossaries it will also be hyperlinked to the
will be sorted by makeindex or xindy. While xindy is entry in glossary.
a bit more LaTeX aware, it does it by omitting latex
macros (\"{\i}) thus incorrectly sorting the above exam- This command prints the plural of the defined term, other
than that it behaves in the same way as gls.
ple as nave. makeindex won't fare much better, because it
doesn't understand TeX macros, it will interpret the word This command prints the singular form of the term with
exactly as it was defined, putting it inside symbol class, the first character converted to upper case.
before words beginning with naa. Therefore it’s needed This command prints the plural form with first letter of
to extend our example and specify how to sort the word: the term converted to upper case.
You can also specify plural forms, if they are not formed This command creates the link as usual, but typesets the
by adding “s” (we will learn how to use them in next sec- alternate text instead. It can also take several options
tion): which changes its default behavior (see the documenta-
Or, for acronyms: tion).
114 CHAPTER 5. SPECIAL PAGES
This command prints what ever is defined in \newglos- Syntax: \newdualentry[glossary options][acronym op-
saryentry{<label>}{symbol={Output of glssymbol}, ...} tions]{label}{abbrv}{long}{description}
This command prints what ever is defined in \newglos- then, define new (dual) entries for glossary and acronym
saryentry{<label>}{description={Output of glsdesc}, list like this:
...}
Custom Name
Referring acronyms
The name of the glossary section can be replaced with a
Acronyms behave a bit differently than normal glossary custom name or translated to a different language. Add
terms. On first use the \gls command will display "<full> the option title to \printglossary to specify the glossary’s
(<abbrv>)". On subsequent uses only the abbreviation title. Add the option toctitle to specify a the title used in
will be displayed. the table of content (if not used, title is used as default).
[4]
To reset the first use of an acronym use:
or, if you want to reset the use status of all acronyms:
Remove the point
If you just want to print the long version of an acronym
without the abbreviation "<full>", use :
To omit the dot at the end of each description, use this
If you just want to print the long version of an acronym code:
with the abbreviation "<full> (<abbrv>)", use :
If you just want to print the abbreviation "<abbrv>", use
Changing Glossary Entry Presentation Using Glos-
:
sary Styles
Dual entries with reference to a glosssary entry from Building your document and its glossary requires three
an acronym It may be useful to have both an acronym steps:
and a glossary entry for the same term. To link these two,
define the acronym with a reference to the glossary entry 1. build your LaTeX document — this will also gener-
like this: ate the files needed by makeglossaries
Refer to acronym with \gls{OWD} and the glossary with 2. invoke makeglossaries — a script which selects the
\gls{gls-OWD} correct character encodings and language settings
To make this easier, we can use this command (modified and which will also run xindy or makeindex if these
from example in the official docs): are specified in your document file
5.4. EXAMPLE FOR USE IN WINDOWS WITH TEXMAKER 115
[2] http://mirror.ox.ac.uk/sites/ctan.org/macros/latex/
1. Menuitem = makeglossaries contrib/glossaries/glossaries-user.html#dx1-35001
2. Command = makeglossaries %
[3] http://mirror.ox.ac.uk/sites/ctan.org/macros/latex/
contrib/glossaries/glossaries-user.html#dx1-43001
Now push Alt+Shift+F1and then ->F1
Note, for use with the “use build directory” option of Tex- [4] User Manual for glossaries.sty v4.02 as of 2014.01.13
maker: makeglossaries needs to find the aux file. Thank- http://mirror.ox.ac.uk/sites/ctan.org/macros/latex/
fully, while Texmaker does not help there, the option -d contrib/glossaries/glossaries-user.html#sec:printglossary
<dir> of makeglossaries provides for the subdirectory
case. Hence the Command in this case should be:
• The glossaries documentation, http://tug.ctan.org/
Command = makeglossaries -d build % instead.
tex-archive/macros/latex/contrib/glossaries/
5.4.2 Document preamble • Using LaTeX to Write a PhD Thesis, Nicola L.C. Tal-
bot,
In preample should be included (note, hyperref should
be loaded before the glossaries):
• glossaries FAQ, Nicola L. C. Talbot, glossaries FAQ
\usepackage[nomain,acronym,xindy,toc]{glossaries} %
nomain, if you define glossaries in a file, and you
use \include{INP-00-glossary} \makeglossaries \usepa- • Glossaries, Nomenclature, Lists of Symbols and
ckage[xindy]{imakeidx} \makeindex Acronyms, Nicola L. C. Talbot, link
116 CHAPTER 5. SPECIAL PAGES
5.5 Bibliography Management you want more than nine, then input any two-digit num-
ber, such as '56' which allows up to 99 references.
For any academic/research writing, incorporating ref- Next is the actual reference entry itself. This is pre-
erences into a document is an important task. Fortu- fixed with the \bibitem{cite_key} command. The cite_key
nately, LaTeX has a variety of features that make dealing should be a unique identifier for that particular reference,
with references much simpler, including built-in support and is often some sort of mnemonic consisting of any se-
for citing references. However, a much more powerful quence of letters, numbers and punctuation symbols (al-
and flexible solution is achieved thanks to an auxiliary though not a comma). I often use the surname of the first
tool called BibTeX (which comes bundled as standard author, followed by the last two digits of the year (hence
with LaTeX). Recently, BibTeX has been succeeded by lamport94). If that author has produced more than one
BibLaTeX, a tool configurable within LaTeX syntax. reference for a given year, then I add letters after, 'a', 'b',
BibTeX provides for the storage of all references in an etc. But, you should do whatever works for you. Every-
external, flat-file database. (BibLaTeX uses this same thing after the key is the reference itself. You need to
syntax.) This database can be referenced in any La- type it as you want it to be presented. I have put the dif-
TeX document, and citations made to any record that is ferent parts of the reference, such as author, title, etc.,
contained within the file. This is often more convenient on different lines for readability. These linebreaks are ig-
than embedding them at the end of every document writ- nored by LaTeX. I wanted the title to be in italics, so I
ten; a centralized bibliography source can be linked to as used the \emph{} command to achieve this.
many documents as desired (write once, read many!). Of
course, bibliographies can be split over as many files as
one wishes, so there can be a file containing sources con- 5.5.2 Citations
cerning topic A (a.bib) and another concerning topic B
(b.bib). When writing about topic AB, both of these files To actually cite a given document is very easy. Go to
can be linked into the document (perhaps in addition to the point where you want the citation to appear, and use
sources ab.bib specific to topic AB). the following: \cite{cite_key}, where the cite_key is that
of the bibitem you wish to cite. When LaTeX processes
the document, the citation will be cross-referenced with
the bibitems and replaced with the appropriate number
5.5.1 Embedded system citation. The advantage here, once again, is that LaTeX
looks after the numbering for you. If it were totally man-
If you are writing only one or two documents and aren't ual, then adding or removing a reference would be a real
planning on writing more on the same subject for a chore, as you would have to re-number all the citations by
long time, you might not want to waste time creating a hand.
database of references you are never going to use. In this
case you should consider using the basic and simple bib- Instead of WYSIWYG editors, typesetting systems like
liography support that is embedded within LaTeX. \TeX{} or \LaTeX{} \cite{lamport94} can be used.
Bibliography styles
• Overview of Bibtex-Styles: Filterable list of styles
There are several different ways to format lists of bibli- with preview.
ographic references and the citations to them in the text.
These are called citation styles, and consist of two parts: • Preview of several often used styles
the format of the abbreviated citation (i.e. the marker
that is inserted into the text to identify the entry in the list
of references) and the format of the corresponding entry No cite
in the list of references, which includes full bibliographic
details. If you only want a reference to appear in the bibliography,
but not where it is referenced in the main text, then the
Abbreviated citations can be of two main types: num-
\nocite{} command can be used, for example:
bered or textual. Numbered citations (also known as the
Vancouver referencing system) are numbered consecu- Lamport showed in 1995 something...
tively in order of appearance in the text, and consist in \nocite{lamport95}.
Arabic numerals in parentheses (1), square brackets [1],
superscript1 , or a combination thereof[1] . Textual cita- A special version of the command, \nocite{*}, includes
tions (also known as the Harvard referencing system) use all entries from the database, whether they are referenced
the author surname and (usually) the year as the abbrevi- in the document or not.
ated form of the citation, which is normally fully (Smith
2005) or partially enclosed in parenthesis, as in Smith
(2005). The latter form allows the citation to be inte- Natbib
grated in the sentence it supports.
Below you can see three of the styles available with La- Using the standard LaTeX bibliography support, you will
TeX: see that each reference is numbered and each citation cor-
responds to the numbers. The numeric style of citation is
quite common in scientific writing. In other disciplines,
the author-year style, e.g., (Roberts, 2003), such as Har-
vard is preferred. A discussion about which is best will
not occur here, but a possible way to get such an output
is by the natbib package. In fact, it can supersede La-
TeX’s own citation commands, as Natbib allows the user
to easily switch between Harvard or numeric.
plain The first job is to add the following to your preamble in
order to get LaTeX to use the Natbib package:
\usepackage[options]{natbib}
Here are some more often used styles: Customization The main commands simply add a t for
'textual' or p for 'parenthesized', to the basic \cite com-
However, keep in mind that you will need to use the nat- mand. You will also notice how Natbib by default will
bib package to use most of these. compress references with three or more authors to the
More examples can be found here: more concise 1st surname et al version. By adding an
118 CHAPTER 5. SPECIAL PAGES
asterisk (*), you can override this default and list all au- of the file is also quite simple. An example of a BibTeX
thors associated with that citation. There are some other entry:
specialized commands that Natbib supports, listed in the @article{greenwade93, author = “George D. Green-
table here. Keep in mind that for instance abbrvnat does wade”, title = “The {C}omprehensive {T}ex {A}rchive
not support \citet* and will automatically choose between {N}etwork ({CTAN})", year = “1993”, journal =
all authors and et al.. “TUGBoat”, volume = “14”, number = “3”, pages =
The final area that I wish to cover about Natbib is cus- “342-−351” }
tomizing its citation style. There is a command called
\bibpunct that can be used to override the defaults and Each entry begins with the declaration of the reference
change certain settings. For example, I have put the fol- type, in the form of @type. BibTeX knows of practically
lowing in the preamble: all types you can think of, common ones are: book, arti-
\bibpunct{(}{)}{;}{a}{,}{,} cle, and for papers presented at conferences, there is in-
proceedings. In this example, I have referred to an article
The command requires six mandatory parameters. within a journal.
After the type, you must have a left curly brace '{' to sig-
1. The symbol for the opening bracket. nify the beginning of the reference attributes. The first
one follows immediately after the brace, which is the ci-
2. The symbol for the closing bracket. tation key, or the BibTeX key. This key must be unique
for all entries in your bibliography. It is this identifier that
3. The symbol that appears between multiple citations. you will use within your document to cross-reference it to
this entry. It is up to you as to how you wish to label each
4. This argument takes a letter:
reference, but there is a loose standard in which you use
• n - numerical style. the author’s surname, followed by the year of publication.
This is the scheme that I use in this tutorial.
• s - numerical superscript style.
Next, it should be clear that what follows are the rele-
• any other letter - author-year style.
vant fields and data for that particular reference. The
5. The punctuation to appear between the author and field names on the left are BibTeX keywords. They are
the year (in parenthetical case only). followed by an equals sign (=) where the value for that
field is then placed. BibTeX expects you to explicitly la-
6. The punctuation used between years, in multiple ci- bel the beginning and end of each value. I personally use
tations when there is a common author. e.g., (Chom- quotation marks ("), however, you also have the option
sky 1956, 1957). If you want an extra space, then of using curly braces ('{', '}'). But as you will soon see,
you need {,~}. curly braces have other roles, within attributes, so I prefer
not to use them for this job as they can get more confus-
Some of the options controlled by \bibpunct are also ac- ing. A notable exception is when you want to use char-
cessible by passing options to the natbib package when it acters with umlauts (ü, ö, etc), since their notation is in
is loaded. These options also allow some other aspect of the format \"{o}, and the quotation mark will close the
the bibliography to be controlled, and can be seen in the one opening the field, causing an error in the parsing of
table (right). the reference. Using \usepackage[utf8]{inputenc} in the
preamble to the .tex source file can get round this, as the
So as you can see, this package is quite flexible, especially accented characters can just be stored in the .bib file with-
as you can easily switch between different citation styles out any need for special markup. This allows a consistent
by changing a single parameter. Do have a look at the format to be kept throughout the .bib file, avoiding the
Natbib manual, it’s a short document and you can learn need to use braces when there are umlauts to consider.
even more about how to use it.
Remember that each attribute must be followed by a
comma to delimit one from another. You do not need to
5.5.3 BibTeX add a comma to the last attribute, since the closing brace
will tell BibTeX that there are no more attributes for this
I have previously introduced the idea of embedding ref- entry, although you won't get an error if you do.
erences at the end of the document, and then using the It can take a while to learn what the reference types are,
\cite command to cite them within the text. In this tuto- and what fields each type has available (and which ones
rial, I want to do a little better than this method, as it’s are required or optional, etc). So, look at this entry type
not as flexible as it could be. I will concentrate on using reference and also this field reference for descriptions of
BibTeX. all the fields. It may be worth bookmarking or printing
A BibTeX database is stored as a .bib file. It is a plain text these pages so that they are easily at hand when you need
file, and so can be viewed and edited easily. The structure them. Much of the information contained therein is re-
5.5. BIBLIOGRAPHY MANAGEMENT 119
peated in the following table for your convenience. @book A published book
+ Required fields, O Optional fields • Required fields: author/editor, title, publisher,
year.
Authors • Optional fields: volume/number, series, ad-
dress, edition, month, note.
BibTeX can be quite clever with names of authors. It
can accept names in forename surname or surname, fore- @book{Xbook, author = "", title = "", publisher = "",
name. I personally use the former, but remember that %volume = "", %number = "", %series = "", %address =
the order you input them (or any data within an entry for "", %edition = "", year = “XXXX”, %month = "", %note
that matter) is customizable and so you can get BibTeX = "", }
to manipulate the input and then output it however you
like. If you use the forename surname method, then you
must be careful with a few special names, where there @booklet A bound work without a named publisher or
are compound surnames, for example “John von Neu- sponsor.
mann”. In this form, BibTeX assumes that the last word
is the surname, and everything before is the forename, • Required fields: title.
plus any middle names. You must therefore manually tell • Optional fields: author, howpublished, ad-
BibTeX to keep the 'von' and 'Neumann' together. This dress, month, year, note.
is achieved easily using curly braces. So the final result
would be “John {von Neumann}". This is easily avoided @booklet{Xbooklet, %author = "", title = "", %howpub-
with the surname, forename, since you have a comma to lished = "", %address = "", %year = “XXXX”, %month
separate the surname from the forename. = "", %note = "", }
Secondly, there is the issue of how to tell BibTeX when a
reference has more than one author. This is very simply
done by putting the keyword and in between every author. @conference Equal to inproceedings
As we can see from another example:
• Required fields: author, title, booktitle, year.
@book{goossens93, author = “Michel Goossens and • Optional fields: editor, volume/number, se-
Frank Mittelbach and Alexander Samarin”, title = ries, pages, address, month, organization, pub-
“The LaTeX Companion”, year = “1993”, publisher = lisher, note.
“Addison-Wesley”, address = “Reading, Massachusetts”
}
@conference{Xconference, author = "", title = "",
booktitle = "", %editor = "", %volume = "", %number
This book has three authors, and each is separated as de- = "", %series = "", %pages = "", %address = "", year
scribed. Of course, when BibTeX processes and outputs = “XXXX”, %month = "", %publisher= "", %note = "", }
this, there will only be an 'and' between the penultimate
and last authors, but within the .bib file, it needs the ands
so that it can keep track of the individual authors. @inbook A section of a book without its own title.
• Required fields: author/editor, title, chapter
Standard templates and/or pages, publisher, year.
• Optional fields: volume/number, series, type,
Be careful if you copy the following templates, the % sign
address, edition, month, note.
is not valid to comment out lines in bibtex files. If you
want to comment out a line, you have to put it outside the
@inbook{Xinbook, author = "", editor = "", title = "",
entry.
chapter = "", pages = "", publisher= "", %volume = "",
%number = "", %series = "", %type = "", %address= "",
@article An article from a magazine or a journal. %edition= "", year = "", %month = "", %note = "", }
• Required fields: author, title, journal, year.
• Optional fields: volume, number, pages, @incollection A section of a book having its own title.
month, note.
• Required fields: author, title, booktitle, pub-
@article{Xarticle, author = "", title = "", journal = "", lisher, year.
%volume = "", %number = "", %pages = "", year = • Optional fields: editor, volume/number, se-
“XXXX”, %month = "", %note = "", } ries, type, chapter, pages, address, edition,
month, note.
120 CHAPTER 5. SPECIAL PAGES
@incollection{Xincollection, author = "", title = "", • Optional fields: address, month, keywords,
booktitle= "", publisher= "", %editor = "", %volume = note.
"", %number = "", %series = "", %type = "", %chapter=
"", %pages = "", %address= "", %edition= "", year = "", @phdthesis{Xphdthesis, author = "", title = "", school =
%month = "", %note = "", } "", %address = "", year = "", %month = "", %keywords
= "", %note = "", }
• Required fields: author, title, school, year. @unpublished An unpublished article, book, thesis,
• Optional fields: type (eg. “diploma thesis”), etc.
address, month, note.
• Required fields: author, title, note.
@mastersthesis{Xthesis, author = "", title = "", school
• Optional fields: month, year.
= "", %type = “diploma thesis”, %address = "", year =
“XXXX”, %month = "", %note = "", }
@unpublished{Xunpublished, author = "", title = "",
%year = "", %month = "", note = "", }
@misc Template useful for other kinds of publication
@collection
@phdthesis Ph.D. thesis
Preserving case of letters W. and Kutter, Elizabeth and Carlson, Karin and Miller,
Eric S. and Spicer, Eleanor”, publisher = “ASM Press,
In the event that BibTeX has been set by the chosen style Washington DC”, year = “1994” },
to not preserve all capitalization within titles, problems
can occur, especially if you are referring to proper nouns,
If you have to cite a website you can use @misc, for ex-
or acronyms. To tell BibTeX to keep them, use the good
ample:
old curly braces around the letter in question, (or letters,
if it’s an acronym) and all will be well! It is even possible @misc{website:fermentas-lambda, author = “Fermentas
that lower-case letters may need to be preserved - for ex- Inc.”, title = “Phage Lambda: description \& restriction
ample if a chemical formula is used in a style that sets a map”, month = “November”, year = “2008”, url =
title in all caps or small caps, or if “pH” is to be used in a "http://www.fermentas.com/techinfo/nucleicacids/
style that capitalises all first letters. maplambda.htm" },
title = “The {LaTeX} Companion”, The note field comes in handy if you need to add unstruc-
tured information, for example that the corresponding is-
However, avoid putting the whole title in curly braces, as sue of the journal has yet to appear:
it will look odd if a different capitalization format is used: @article{blackholes, author="Rabbert Klein”, ti-
tle="Black Holes and Their Relation to Hiding Eggs”,
title = "{The LaTeX Companion}", journal="Theoretical Easter Physics”, publisher="Eggs
Ltd.”, year="2010”, note="(to appear)" }
For convenience though, many people simply put double
curly braces, which may help when writing scientific ar-
ticles for different magazines, conferences with different
BibTex styles that do sometimes keep and sometimes not Getting current LaTeX document to use your .bib file
keep the capital letters:
At the end of your LaTeX file (that is, after the content,
title = {{The LaTeX Companion}}, but before \end{document}), you need to place the fol-
lowing commands:
As an alternative, try other BibTex styles or modify the \bibliographystyle{plain} \bibliogra-
existing. The approach of putting only relevant text in phy{sample1,sample2,...,samplen} % Note the lack
curly brackets is the most feasible if using a template un- of whitespace between the commas and the next bib file.
der the control of a publisher, such as for journal submis-
sions. Using curly braces around single letters is also to
Bibliography styles are files recognized by BibTeX that
be avoided if possible, as it may mess up the kerning, es-
tell it how to format the information stored in the .bib file
pecially with biblatex,[1] so the first step should generally
when processed for output. And so the first command
be to enclose single words in braces. listed above is declaring which style file to use. The style
file in this instance is plain.bst (which comes as standard
with BibTeX). You do not need to add the .bst extension
A few additional examples
when using this command, as it is assumed. Despite its
name, the plain style does a pretty good job (look at the
Below you will find a few additional examples of bibliog-
raphy entries. The first one covers the case of multiple output of this tutorial to see what I mean).
authors in the Surname, Firstname format, and the sec- The second command is the one that actually specifies
ond one deals with the incollection case. the .bib file you wish to use. The ones I created for this
@article{AbedonHymanThomas2003, author = tutorial were called sample1.bib, sample2.bib, . . ., sam-
“Abedon, S. T. and Hyman, P. and Thomas, C.”, plen.bib, but once again, you don't include the file ex-
year = “2003”, title = “Experimental examination of tension. At the moment, the .bib file is in the same di-
bacteriophage latent-period evolution as a response rectory as the LaTeX document too. However, if your
to bacterial availability”, journal = “Applied and En- .bib file was elsewhere (which makes sense if you in-
vironmental Microbiology”, volume = “69”, pages = tend to maintain a centralized database of references
“7499-−7506” }, @incollection{Abedon1994, author for all your research), you need to specify the path as
= “Abedon, S. T.”, title = “Lysis and the interaction well, e.g \bibliography{/some/where/sample} or \bibli-
between free phages and infected cells”, pages = “397- ography{../sample1} (if the .bib file is in the parent di-
−405”, booktitle = “Molecular biology of bacteriophage rectory of the .tex document that calls it).
T4”, editor = “Karam, Jim D. Karam and Drake, John Now that LaTeX and BibTeX know where to look for the
W. and Kreuzer, Kenneth N. and Mosig, Gisela and Hall, appropriate files, actually citing the references is fairly
Dwight and Eiserling, Frederick A. and Black, Lindsay trivial. The \cite{ref_key} is the command you need,
122 CHAPTER 5. SPECIAL PAGES
making sure that the ref_key corresponds exactly to one (Extensions are optional, if you put them note that the
of the entries in the .bib file. If you wish to cite more bibtex command takes the AUX file as input.)
than one reference at the same time, do the following: Note that if you are editing your source in vim and at-
\cite{ref_key1, ref_key2, ..., ref_keyN}. tempt to use command mode and the current file shortcut
(%) to process the document like this:
Why won't LaTeX generate any output?
1. :! pdflatex %
The addition of BibTeX adds extra complexity for the
processing of the source to the desired output. This is 2. :! bibtex %
largely hidden from the user, but because of all the com-
plexity of the referencing of citations from your source You will get an error similar to this:
LaTeX file to the database entries in another file, you ac-
tually need multiple passes to accomplish the task. This 1. I couldn't open file name 'current_file.tex.aux'
means you have to run LaTeX a number of times. Each
pass will perform a particular task until it has managed to It appears that the file extension is included by default
resolve all the citation references. Here’s what you need when the current file command (%) is executed. To pro-
to type (into command line): cess your document from within vim, you must explicitly
name the file without the file extension for bibtex to work,
1. latex latex_source_code.tex as is shown below:
2. bibtex latex_source_code.aux
1. :! pdflatex %
3. latex latex_source_code.tex
2. :! bibtex %:r (without file extension, it looks for the
4. latex latex_source_code.tex AUX file as mentioned above)
3. :! pdflatex %
(Extensions are optional, if you put them note that the
bibtex command takes the AUX file as input.) 4. :! pdflatex %
After the first LaTeX run, you will see errors such as:
However, it is much easier to install the Vim-LaTeX plu-
LaTeX Warning: Citation `lamport94' on page 1 unde-
gin from here. This allows you to simply type \ll when
fined on input line 21. ... LaTeX Warning: There were
not in insert mode, and all the appropriate commands are
undefined references.
automatically executed to compile the document. Vim-
The next step is to run bibtex on that same LaTeX source LaTeX even detects how many times it has to run pdfla-
(or more precisely the corresponding AUX file, however tex, and whether or not it has to run bibtex. This is just
not on the actual .bib file) to then define all the references one of the many nice features of Vim-LaTeX, you can
within that document. You should see output like the fol- read the excellent Beginner’s Tutorial for more about the
lowing: many clever shortcuts Vim-LaTeX provides.
This is BibTeX, Version 0.99c (Web2C 7.3.1) The top- Another option exists if you are running Unix/Linux or
level auxiliary file: latex_source_code.aux The style file: any other platform where you have make. Then you can
plain.bst Database file #1: sample.bib simply create a Makefile and use vim’s make command
The third step, which is invoking LaTeX for the second or use make in shell. The Makefile would then look like
time will see more errors like “LaTeX Warning: Label(s) this:
may have changed. Rerun to get cross-references right.”. latex_source_code.pdf: latex_source_code.tex la-
Don't be alarmed, it’s almost complete. As you can guess, tex_source_code.bib pdflatex latex_source_code.tex
all you have to do is follow its instructions, and run LaTeX bibtex latex_source_code.aux pdflatex la-
for the third time, and the document will be output as tex_source_code.tex pdflatex latex_source_code.tex
expected, without further problems.
If you want a pdf output instead of a dvi output you can Including URLs in bibliography
use pdflatex instead of latex as follows:
As you can see, there is no field for URLs. One possibility
1. pdflatex latex_source_code.tex is to include Internet addresses in howpublished field of
@misc or note field of @techreport, @article, @book:
2. bibtex latex_source_code.aux
howpublished = "\url{http://www.example.com}"
3. pdflatex latex_source_code.tex
Note the usage of \url command to ensure proper appear-
4. pdflatex latex_source_code.tex ance of URLs.
5.5. BIBLIOGRAPHY MANAGEMENT 123
Another way is to use special field url and make bibliog- applied to a LaTeX document.
raphy style recognise it. If you are using a custom built .bst file, it is important
url = "http://www.example.com" that LaTeX can find it! So, make sure it’s in the same
You need to use \usepackage{url} in the first case or directory as the LaTeX source file, unless you are using
one of the standard style files (such as plain or plainnat,
\usepackage{hyperref} in the second case.
that come bundled with LaTeX - these will be automati-
Styles provided by Natbib (see below) handle this field, cally found in the directories that they are installed. Also,
other styles can be modified using urlbst program. Modi- make sure the name of the .bst file you want to use is
fications of three standard styles (plain, abbrv and alpha) reflected in the \bibliographystyle{style} command (but
are provided with urlbst. don't include the .bst extension!).
If you need more help about URLs in bibliography, visit
FAQ of UK List of TeX. Localizing bibliography appearance
One should be alert to the fact that bibliographic • BibSonomy — A free social bookmark and publica-
databases are frequently the product of several genera- tion management system based on BibTeX.
tions of automatic processing, and so the resulting Bib-
Tex code is prone to a variety of minor errors, especially • BibTeXSearch BibTeXSearch is a free searchable
in older entries. BibTeX database spanning millions of academic
records.
• Synapsen — Hypertextual Card Index / Reference This will include the Bibliography in the Table of Con-
Manager with special support for BiBTeX / biblatex, tents without numbering. If you want to have proper
written in Java. numbering, include the following code in the preamble:
• Zotero Zotero is a free and open reference manager \usepackage[nottoc,numbib]{tocbibind}
working as a Firefox plugin or standalone applica-
tion, capable of importing and exporting bib files. The tocbibind package can also handle including the List
of Figures, List of Tables and the Table of Contents itself
Summary in the Table of Contents. It has many options for num-
bering, document structure etc. to fit almost any scenario.
Although it can take a little time to get to grips with Bib- See the tocbibind CTAN page for detailed documenta-
TeX, in the long term, it’s an efficient way to handle your tion.
references. It’s not uncommon to find .bib files on web-
sites that people compile as a list of their own publica-
Other methods
tions, or a survey of relevant works within a given topic,
etc. Or in those huge, online bibliography databases, you As unnumbered item If you want your bibliography
often find BibTeX versions of publications, so it’s a quick to be in the table of contents, just add the following two
cut-and-paste into your own .bib file, and then no more lines just before the thebibliography environment:
hassle!
\clearpage% or cleardoublepage \addcon-
Having all your references in one place can be a big ad- tentsline{toc}{chapter}{Bibliography}
vantage. And having them in a structured form, that al-
lows customizable output is another one. There are a vari-
ety of free utilities that can load your .bib files, and allow (OR \addcontentsline{toc}{section}{Bibliography} if
you to view them in a more efficient manner, as well as you're writing an article)
sort them and check for errors. The first line just terminates the current paragraph and
page. If you are writing a book, use \cleardoublepage to
match the style used. The second line will add a line in
5.5.4 Bibliography in the table of contents the Table of Contents (first option, toc), it will be like the
ones created by chapters (second option, chapter), and
If you are writing a book or report, you'll likely insert your the third argument will be printed on the corresponding
bibliography using something like: line in the Table of Contents; here Bibliography was cho-
\begin{thebibliography}{99} \bibitem{bib:one_book} sen because it’s the same text the thebibliography environ-
some information \bibitem{bib:one_article} other ment will automatically write when you use it, but you are
126 CHAPTER 5. SPECIAL PAGES
free to write whatever you like. If you are using separate database) that can be used in a document. For now, refer
bib file, add these lines between \bibliographystyle and to its comprehensive documentation on CTAN.
\bibliography.
If you use hyperref package, you should also use \phan- Entry and field types in .bib files
tomsection command to enable hyperlinking from the ta-
ble of contents to bibliography. The following table shows most field types. Some field
\clearpage% or cleardoublepage \phantomsection \add- types are lists, either lists of person names, others are
contentsline{toc}{chapter}{Bibliography} literal lists. A date can either be given in parts or full,
some keys are necessary, page references are provided as
ranges and certain special fields contain verbatim code.
This trick is particularly useful when you have to insert There are many kinds of titles.
the bibliography in the Table of Contents, but it can work
for anything. When LaTeX finds the code above, it will Some entry types are hard to distinguish and are treated
record the info as described and the current page number, the same by standard styles:
inserting a new line in the Contents page.
• @article is the same as hypothetic *@inperiodical
and therefore encompasses existing @suppperiodi-
As numbered item If you instead want bibliography cal
to be numbered section or chapter, you'll likely use this
• @inbook = @bookinbook = @suppbook
way:
\cleardoublepage % This is needed if the book class • @collection = @reference
is used, to place the anchor in the correct page, % • @mvcollection = @mvreference
because the bibliography will start on its own page. %
Use \clearpage instead if the document class uses the • @incollection = @suppcollection = @inreference
“oneside” argument \renewcommand*{\refname}{} %
• @online = @electronic = @www
This will define heading of bibliography to be empty, so
you can... \section{Bibliography} % ...place a normal • @report = @techreport
section heading before the bibliography entries. \be-
gin{thebibliography}{99} ... \end{thebibliography} • @thesis = @mastersthesis = @phdthesis
[2] http://ctan.org/pkg/multibib
which correspond to the three styles available by default
[3] http://ctan.org/pkg/bibtopic in BibTeX where you have a plain numbered style, an
abbreviated numbered style and an unsorted numbered
style.
This page uses material from Andy Roberts’ Getting to grips
with LaTeX with permission from the author. Alongside these new styles is an extended set of citation
commands to provide flexible citation formats. These are
\citet[]{}
5.6 More Bibliographies
and
This is a gentle introduction to using some of the bib-
liography functionality available to LaTeX users beyond \citep[]{}
the BibTeX basics. This introduction won't be discussing
how to create new styles or packages but rather how to each of which has a number of variants.
use some existing ones. It is worth noting that Harvard,
for example, is a citation style. It is associated with an al-
phabetical reference list secondarily ordered on date, but The Preamble
the only strictly defined element of Harvard style is the
citation in author-date format. All Natbib styles require that you load the package in your
document preamble. So, a skeleton LaTeX file with Nat-
bib might look like this:
5.6.1 The example data \documentclass[]{article} \usepackage[round]{natbib}
\begin{document} Document body text with citations.
The database used for my examples contains just the fol- \bibliographystyle{plainnat} \bibliography{myrefs}
lowing \end{document}
@article{Erdos65, title = {Some very hard sums}, jour-
nal={Difficult Maths Today}, author={Paul Erd\H{o}s
and Arend Heyting and Luitzen Egbertus Brouwer},
year={1930}, pages={30} } Options Options available with Natbib can be specified
in the brackets on the \usepackage command. Among
them are:
Clearly some of these options require explanation but that
5.6.2 The limits of BibTeX styles will be achieved via examples below. For now, we just
note that they can be passed through \usepackage[]{} in
Using cite.sty and BibTeX makes it very easy to produce the preamble of your LaTeX file.
some bibliography styles. But author-date styles - for ex-
ample the often mentioned, never defined “Harvard” - are
not so easy. It’s true that you can download some .bst 5.6.4 Citation
files from CTAN that will handle some variants but using
them is not always straightforward. This guide deals with Basic Citation Commands
Natbib a supplementary package that can access .bib files
and has sophisticated functionality for producing custom To cite with Natbib, use the commands \citet or \citep in
or default author-year format citations and bibliographies your document. The “plain” versions of these commands
as well as the numerical styles handled by BibTeX. produced abbreviated lists in the case of multiple authors
but both have * variants which result in full author listings.
We assume the use of the round option in these examples.
5.6.3 Natbib
Natbib is a package created by Patrick Daly as a replace- \citet and \citet* The \citet command is used for tex-
ment for the cite.sty package when author-date citation tual citations, that is to say that author names appear in
styles are required. Natbib provides three associated bib- the text outside of the parenthetical reference to the date
liography styles: of publication. This command can take options for chap-
ter, page numbers etc. Here are examples
• plainnat Here are the \citet* versions
5.6. MORE BIBLIOGRAPHIES 129
Special Documents
6.1 Letters
Sometimes the mundane things are the most painful.
However, it doesn't have to be that way because of
evolved, user-friendly templates. Thankfully, LaTeX al-
lows for very quick letter writing, with little hassle.
130
6.1. LETTERS 131
\longindentation=0pt It is reported that pdflatex creates the right page size but
not dvips despite what it says in the geometry manual.
The amount of space to the left can be adjusted by in- It will never work though unless your printer settings are
creasing the 0pt. adjusted to the correct page style. These settings depend
on the printer filter you are using and in CUPS might be
available on the lpr command line.
6.1.2 Envelopes
Using the envlab package
The envlab package provides customization to the \make- 6.1.3 Windowed envelopes
labels command, allowing the user to print on any of an
assortment of labels or envelope sizes. For example, be- An alternative to separately printing addresses on en-
ginning your LaTeX file the following way produces a velopes is to use the letter class from the KOMA package.
document which includes the letter and a business-size It supports additional features like folding marks and the
(#10) envelope on the following page. correct address placement for windowed envelopes. Us-
ing the scrlttr2 document class from the KOMA package
Refer to the envlab user guide for more information about
the example letter code is:
this capable package. Note that the envlab package has
issues displaying characters outside the base ASCII char- % koma_env.tex \documentclass[a4paper]{scrlttr2}
acter set, see this bug report for more information. \usepackage{lmodern} \usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc} \usepackage[english]{babel}
\usepackage{url} \setkomavar{fromname}{Joe Bloggs}
Using the geometry package \setkomavar{fromaddress}{21 Bridge Street \\ Smallville
\\ Dunwich DU3 4WE} \setkomavar{fromphone}{0123
Here is a relatively simple envelope which uses the ge- 45679} \begin{document} \begin{letter}{Director \\
ometry package which is used because it vastly simplifies Doe \& Co \\ 35 Anthony Road \\ Newport \\ Ipswich IP3
the task of rearranging things on the page (and the page 5RT} \KOMAoptions{fromphone=true,fromfax=false}
itself). \setkomavar{subject}{Wikipedia} \setko-
mavar{customer}{2342} \opening{Dear Sir or Madam,}
I am writing to you on behalf of the Wikipedia project
(\url{http://www.wikipedia.org/}), an endeavour to
build a fully-fledged multilingual encyclopaedia in an
entirely open manner, to ask for permission to use your
copyrighted material. \ldots That said, allow me to
reiterate that your material will be used to the noble
end of providing a free collection of knowledge for
everyone; naturally enough, only if you agree. If that
A sample envelope to be printed in landscape mode. is the case, could you kindly fill in the attached form
and post it back to me? We shall greatly appreciate
it. Thank you for your time and consideration. I
Printing look forward to your reply. \closing{Yours Faith-
fully,} \ps{P.S. You can find the full text of GFDL
The above will certainly take care of the spacing but the license at \url{http://www.gnu.org/copyleft/fdl.html}.}
actual printing is between you and your printer. One user \encl{Copyright permission form} \end{letter}
reports that printing envelopes created with envlab is rel- \end{document}
atively painless. If you use the geometry package, you
may find the following commands useful for printing the The output is generated via
envelope.
$ pdflatex koma_env Folding the print of the resulting
$ pdflatex envelope.tex $ pdf2ps envelope.pdf $ lpr -o file koma_env.pdf according the folding marks it can be
landscape envelope.ps placed into standardized windowed envelopes DIN C6/5,
Alternatively, you can use the latex dvi output driver. DL, C4, C5 or C6.
In the first line, dvips command converts the .dvi file pro- In addition to the default, the KOMA-package includes
duced by latex into a .ps (PostScript) file. In the second predefined format definitions for different standardized
line, the PostScript file is sent to the printer. Swiss and Japanese letter formats.
132 CHAPTER 6. SPECIAL DOCUMENTS
Introductory example
6.1.5 Sources
6.2 Presentations
Style • circles
• inmargin
Themes The first solution is to use a built-in theme
such as Warsaw, Berlin, etc. The second solution is to • rounded
specify colors, inner themes and outer themes.
You can define the color of every element:
The Built-in solution To the preamble you can add \setbeamercolor{alerted text}{fg=orange} \setbeam-
the following line: ercolor{background canvas}{bg=white} \setbeamer-
color{block body alerted}{bg=normal text.bg!90!black}
\usetheme{Warsaw} \setbeamercolor{block body}{bg=normal
text.bg!90!black} \setbeamercolor{block body ex-
to use the “Warsaw” theme. Beamer has several themes, ample}{bg=normal text.bg!90!black} \setbeamer-
many of which are named after cities (e.g. Frankfurt, color{block title alerted}{use={normal text,alerted
Madrid, Berlin, etc.). text},fg=alerted text.fg!75!normal text.fg,bg=normal
text.bg!75!black} \setbeamercolor{block ti-
This Theme Matrix contains the various theme and color
tle}{bg=blue} \setbeamercolor{block title exam-
combinations included with beamer. For more customiz-
ple}{use={normal text,example text},fg=example
ing options, have a look to the official documentation in-
text.fg!75!normal text.fg,bg=normal text.bg!75!black}
cluded in your distribution of beamer, particularly the
\setbeamercolor{fine separation line}{} \set-
part Change the way it looks.
beamercolor{frametitle}{fg=brown} \setbeam-
The full list of themes is: ercolor{item projected}{fg=black} \setbeamer-
Color themes, typically with animal names, can be spec- color{normal text}{bg=black,fg=yellow} \set-
ified with beamercolor{palette sidebar primary}{use=normal
text,fg=normal text.fg} \setbeamercolor{palette
\usecolortheme{beaver} sidebar quaternary}{use=structure,fg=structure.fg}
\setbeamercolor{palette sidebar sec-
The full list of color themes is: ondary}{use=structure,fg=structure.fg} \setbeam-
ercolor{palette sidebar tertiary}{use=normal
text,fg=normal text.fg} \setbeamercolor{section in
The do it yourself solution First you can specify the sidebar}{fg=brown} \setbeamercolor{section in side-
outertheme. The outertheme defines the head and the bar shaded}{fg=grey} \setbeamercolor{separation
footline of each slide. line}{} \setbeamercolor{sidebar}{bg=red} \setbeam-
\useoutertheme{infolines} ercolor{sidebar}{parent=palette primary} \setbeam-
ercolor{structure}{bg=black, fg=green} \setbeamer-
color{subsection in sidebar}{fg=brown} \setbeam-
Here is a list of all available outer themes: ercolor{subsection in sidebar shaded}{fg=grey}
\setbeamercolor{title}{fg=brown} \setbeamer-
• infolines color{titlelike}{fg=brown}
• miniframes
Colors can be defined as usual:
• shadow
\definecolor{chocolate}{RGB}{33,33,33}
• sidebar
Then you can add the innertheme: You can also suppress the navigation bar:
\useinnertheme{rectangles} \beamertemplatenavigationsymbolsempty
Math Fonts The default settings for beamer use a dif- in the preamble.
ferent set of math fonts than one would expect from cre-
ating a simple math article. One quick fix for this is to Animations
use at the beginning of the file the option mathserif
\documentclass[mathserif]{beamer} The following is merely an introduction to the possibili-
ties in beamer. Chapter 8 of the beamer manual provides
much more detail, on many more features.
Others have proposed to use the command
Making items appear on a slide is possible by simply using
\usefonttheme[onlymath]{serif}
the \pause statement:
\begin{frame} \frametitle{Some background} We
but it is not clear if this works for absolutely every math
start our discussion with some concepts. \pause The
character.
first concept we introduce originates with Erd\H os.
\end{frame}
Frames Options
Text or figures after \pause will display after one of the
The plain option. Sometimes you need to include a large following events (which may vary between PDF viewers):
figure or a large table and you don't want to have the bot- pressing space, return or page down on the keyboard, or
tom and the top off the slides. In that case, use the plain using the mouse to scroll down or click the next slide but-
option: ton. Pause can be used within \itemize etc.
\frame[plain]{ % ... }
Text animations For text animations, for example in
If you want to include lots of text on a slide, use the shrink the itemize environment, it is possible to specify appear-
option. ance and disappearance of text by using <a-b> where a
and b are the numbers of the events the item is to be dis-
\frame[shrink]{ % ... } played for (inclusive). For example:
\begin{itemize} \item This one is always shown \item<1-
The allowframebreaks option will auto-create new frames > The first time (i.e. as soon as the slide loads) \item<2->
if there is too much content to be displayed on one. The second time \item<1-> Also the first time \only<1-
\frame[allowframebreaks]{ % ... } 1> {This one is shown at the first time, but it will
hide soon (on the next event after the slide loads).}
Before using any verbatim environment (like listings), \end{itemize}
you should pass the option fragile to the frame environ-
ment, as verbatim environments need to be typeset dif- A simpler approach for revealing one item per click is to
ferently. Usually, the form fragile=singleslide is usable use \begin{itemize}[<+->].
(for details see the manual). Note that the fragile option
\begin{frame} \frametitle{`Hidden higher-order con-
may not be used with \frame commands since it expects cepts?'} \begin{itemize}[<+->] \item The truths of
to encounter a \end{frame}, which should be alone on a arithmetic which are independent of PA in some sense
single line. themselves `{contain} essentially {\color{blue}{hidden
\begin{frame}[fragile] \frametitle{Source code} \be- higher-order}}, or infinitary, concepts’??? \item `Truths
gin{lstlisting}[caption=First C example] int main() in the language of arithmetic which \ldots \item That sug-
{ printf(“Hello World!"); return 0; } \end{lstlisting} gests stronger version of Isaacson’s thesis. \end{itemize}
136 CHAPTER 6. SPECIAL DOCUMENTS
\end{frame} and this will hide your slide in both modes. (The order
matters. Don't put handout:0|beamer:0 or it won't work.)
In all these cases, pressing page up, scrolling up, or click- A last word about the handout mode is about the notes.
ing the previous slide button in the navigation bar will Actually, the full syntax for a frame is
backtrack through the sequence.
\begin{frame} ... \end{frame} \note{...} \note{...} ...
and you can write your notes about a frame in the field
Handout mode note (many of them if needed). Using this, you can add
an option to the class calling, either
In beamer class, the default mode is presentation which
\documentclass[12pt,handout,notes=only]{beamer}
makes the slides. However, you can work in a different
mode that is called handout by setting this option when
calling the class: or
\documentclass[12pt,handout]{beamer} \documentclass[12pt,handout,notes=show]{beamer}
This mode is useful to see each slide only one time with all The first one is useful when you make a presentation to
its stuff on it, making any \itemize[<+->] environments have only the notes you need, while the second one could
visible all at once (for instance, printable version). Nev- be given to those who have followed your presentation or
ertheless, this makes an issue when working with the only those who missed it, for them to have both the slides with
command, because its purpose is to have only some text what you said.
or figures at a time and not all of them together. Note that the 'handout' option in the \documentclass line
If you want to solve this, you can add a statement to spec- suppress all the animations.
ify precisely the behavior when dealing with only com- Important: the notes=only mode is literally doing only
mands in handout mode. Suppose you have a code like the notes. This means there will be no output file but the
this DVI. Thus it requires you to have run the compilation
\only<1>{\includegraphics{pic1.eps}} in another mode before. If you use separate files for a
\only<2>{\includegraphics{pic2.eps}} better distinction between the modes, you may need to
copy the .aux file from the handout compilation with the
slides (w/o the notes).
These pictures being completely different, you want them
both in the handout, but they cannot be both on the same
slide since they are large. The solution is to add the hand- Columns and Blocks
out statement to have the following:
\only<1| handout:1>{\includegraphics{pic1.eps}} There are two handy environments for structuring a
\only<2| handout:2>{\includegraphics{pic2.eps}} slide: “blocks”, which divide the slide (horizontally) into
headed sections, and “columns” which divides a slide
(vertically) into columns. Blocks and columns can be
This will ensure the handout will make a slide for each used inside each other.
picture.
Now imagine you still have your two pictures with the
only statements, but the second one show the first one Columns Example
plus some other graphs and you don't need the first one to\begin{frame}{Example of columns 1} \be-
appear in the handout. You can thus precise the handout gin{columns}[c] % the “c” option specifies center
mode not to include some only commands by: vertical alignment \column{.5\textwidth} % column
\only<1| handout:0>{\includegraphics{pic1.eps}} designated by a command Contents of the first column
\only<2>{\includegraphics{pic2.eps}} \column{.5\textwidth} Contents split \\ into two lines
\end{columns} \end{frame} \begin{frame}{Example
of columns 2} \begin{columns}[T] % contents are
The command can also be used to hide frames, e.g. top vertically aligned \begin{column}[T]{5cm}
\begin{frame}<handout:0> % each column can also be its own environment
Contents of first column \\ split into two lines
\end{column} \begin{column}[T]{5cm} % alter-
or even, if you have written a frame that you don't want native top-align that’s better for graphics \include-
anymore but maybe you will need it later, you can write graphics[height=3cm]{graphic.png} \end{column}
\begin{frame}<0| handout:0> \end{columns} \end{frame}
6.2. PRESENTATIONS 137
Numbering slides
\begin{document} \begin{slide}{This is the first slide} • The solution is given in the solution environment.
%Content goes here \end{slide} \begin{slide}{This is It appears only if \printanswers or answers as an
the second slide} %More content goes here \end{slide} option of the \documentclass are specified in the
% etc \end{document} preamble.
Here is an example :
6.2.3 References \begin{questions} % Begins the questions environment
\question[2] What is the solution? % Introduces a
[1] Andrew Mertz and William Slough Beamer by Example new question which is worth 2 points \begin{solution}
Here is the solution \end{solution} \question[5] What
[2] Other possible values are defined in the hyperref manual is your opinion? \begin{solution} This is my opinion
\end{solution} \end{questions}
[3] Appendix Slides in Beamer: Controlling frame numbers
6.3.3 References
6.3.2 The exam class
[1] examdoc Using the exam document class
We present the exam class. The exam class is well suited [2] Probsoln Creating problem sheets optionally with solu-
to design exams with solutions. You just have to specify tions
in the preamble if you want the solutions to be printed or
not. You can also count the number of points. [3] mathexm documentation
In the preamble you can specify the following lines : 6.4 Curriculum Vitae
You can replace the 3 first lines with the following :
A curriculum vitæ or résumé has a universal requirement:
its formatting must be flawless. This is a great example
Document of cases where the power of LaTeX comes to the front.
Thanks to its strong typographical stance, LaTeX is def-
• The exam is included in the questions environment. initely a document processor of choice to write a CV.
• The command \question introduces a new question. Of course you can design your own CV by hand. Other-
wise, you may want to use a dedicated class for that task.
• The number of points is specified in squared brack- This way, writing a CV in LaTeX is as simple as filling
ets. the forms, and you are done. Seeveeze makes 3 of them
6.4. CURRICULUM VITAE 139
6.4.1 curve
6.4.2 europecv
6.4.3 moderncv
From CTAN:
Moderncv provides a documentclass for typesetting
modern curriculums vitae, both in a classic and in a casual
style. It is fairly customizable, allowing you to define your
own style by changing the colours, the fonts, etc.
The official package provides some well commented tem-
plates which may be a good start. You can find those tem-
plates in your distribution (if documentation is installed
along packages) or ultimately on CTAN.
We will not repeat the templates here, so we will only
provide a crash course. You should really have a look at
the templates for more details.
First document
Theme previews
• Themes
6.4.5 References
Chapter 7
Creating Graphics
See the Importing Graphics for more details on graphics Perhaps the most powerful graphical tool related with
importation and some attempts to circumvent to integra- LaTeX is MetaPost, the twin of Donald E. Knuth’s
tion issue. METAFONT. MetaPost has the very powerful and
mathematically sophisticated programming language of
METAFONT. Contrary to METAFONT, which gener-
7.1.1 Overview ates bitmaps, MetaPost generates encapsulated PostScript
files, which can be imported in LaTeX. For an introduc-
The picture environment allows programming pictures tion, see A User’s Manual for MetaPost. A very thorough
directly in LaTeX. On the one hand, there are rather se- discussion of LaTeX and TEX strategies for graphics (and
vere constraints, as the slopes of line segments as well fonts) can be found in TEX Unbound.
as the radii of circles are restricted to a narrow choice The last but certainly not least are the PGF/TikZ and
of values. On the other hand, the picture environment Asymptote systems. While the previous systems (pic-
of LaTeX2e brings with it the \qbezier command, “q” ture, epic, pstricks or metapost) focus on the how to draw,
meaning quadratic. Many frequently-used curves such TikZ and Asymptote focus more on the what to draw.
as circles, ellipses, and catenaries can be satisfactorily One could say that TikZ and Asymptote are to drawing
approximated by quadratic Bézier curves, although this in LaTeX as LaTeX is to digital typesetting. It’s recom-
may require some mathematical toil. If a programming mended to use one of these if your LaTeX distribution
language like Java is used to generate \qbezier blocks of includes it. TikZ is a pure (La)TeX system, not reliant
LaTeX input files, the picture environment becomes quite on external software, while Asymptote is an external sys-
powerful. tem which integrates seamlessly with (La)TeX. If using
Although programming pictures directly in LaTeX is Asymptote, it is very helpful to use latexmk to manage
severely restricted, and often rather tiresome, there are the compilation steps.
still reasons for doing so. The documents thus produced In many cases, especially for more advanced diagrams, it
are “small” with respect to bytes, and there are no addi-
140
7.3. PICTURE 141
may be easier to draw the graphics using external vector Bézier curves are an exception. They are drawn with the
graphics software, and then import the file into the doc- command
ument (see LaTeX/Importing_Graphics). However most With the package picture absolute dimension (like 15pt)
software does not support LaTeX fonts or mathematical and expression are allowed, in addition to numbers rela-
notation, which can result in not suitable and inconsistent tive to \unitlength.
graphics. There are several solutions to this problem.
The first pair, (x, y) , affects the reservation, within the draws a circle with center (x, y) and diameter (not radius)
document, of rectangular space for the picture. specified by diameter. The picture environment only ad-
mits diameters up to approximately 14mm, and even be-
The optional second pair, (x0 , y0 ) , assigns arbitrary co- low this limit, not all diameters are possible. The \circle*
ordinates to the bottom left corner of the reserved rect- command produces disks (filled circles). As in the case of
angle. line segments, one may have to resort to additional pack-
The numbers x, y, x0, y0 are numbers (lengths) in the ages, such as eepic, pstricks, or tikz.
units of \unitlength, which can be reset any time (but not There is another possibility within the picture environ-
within a picture environment) with a command such as ment. If one is not afraid of doing the necessary calcula-
The default value of \unitlength is 1pt. tions (or leaving them to a program), arbitrary circles and
ellipses can be patched together from quadratic Bézier
Most drawing commands have one of the two forms curves. See Graphics in LaTeX2e for examples and Java
or source files.
142 CHAPTER 7. CREATING GRAPHICS
As this example shows, text and formulae can be written The command
in the environment with the \put command in the usual
draws a quadratic bezier curve where P1 = (x1 , y1 ) ,
way:
P2 = (x2 , y2 ) denote the end points, and S = (x, y)
denotes the intermediate control point. The respective
tangent slopes, m1 and m2 , can be obtained from the
7.3.6 \multiput and \linethickness equations
The command
{
has 4 arguments: the starting point, the translation vector x = m2 x2 −m 1 x1 −(y2 −y1 )
m2 −m1
from one object to the next, the number of objects, and y = yi + mi (x − xi ); (i = 1, 2 gives same solution)
the object to be drawn. The \linethickness command ap-
plies to horizontal and vertical line segments, but neither
to oblique line segments, nor to circles. It does, however, See Graphics in LaTeX2e for a Java program which gen-
apply to quadratic Bézier curves! erates the necessary \qbezier command line.
As this example illustrates, splitting up a circle into 4
quadratic Bézier curves is not satisfactory. At least 8
are needed. The figure again shows the effect of the
7.3.7 Ovals \linethickness command on horizontal or vertical lines,
and of the \thinlines and the \thicklines commands on
The command oblique line segments. It also shows that both kinds of
or commands affect quadratic Bézier curves, each command
overriding all previous ones.
produces an oval centered at (x, y) and having width w and
height h. The optional position arguments b, t, l, r refer to
“top”, “bottom”, “left”, “right”, and can be combined, as
the example illustrates. Line thickness can be controlled
by two kinds of commands: \linethickness{''length''} on
7.3.10 Catenary
the one hand, \thinlines and \thicklines on the other.
While \linethickness{''length''} applies only to horizontal In this figure, each symmetric half of the catenary y =
and vertical lines (and quadratic Bézier curves), \thinlines cosh x − 1 is approximated by a quadratic Bézier curve.
and \thicklines apply to oblique line segments as well as The right half of the curve ends in the point (2, 2.7622),
to circles and ovals. the slope there having the value m = 3.6269. Using again
equation (*), we can calculate the intermediate control
points. They turn out to be (1.2384, 0) and (−1.2384, 0).
The crosses indicate points of the real catenary. The error
7.3.8 Multiple use of predefined picture is barely noticeable, being less than one percent. This
boxes example points out the use of the optional argument of
the \begin{picture} command. The picture is defined in
A picture box can be declared by the command convenient “mathematical” coordinates, whereas by the
command
then defined by
its lower left corner (marked by the black disk) is assigned
and finally arbitrarily often be drawn by the coordinates (−2.5,−0.25).
The optional position parameter has the effect of defining
the “anchor point” of the savebox. In the example it is set
to “bl” which puts the anchor point into the bottom left
corner of the savebox. The other position specifiers are 7.3.11 Plotting graphs
top and right.
The name argument refers to a LaTeX storage bin and The control points of the two Bézier curves were calcu-
therefore is of a command nature (which accounts for the lated with formulas (*). The positive branch is deter-
backslashes in the current example). Boxed pictures can mined by P1 = (0, 0) , m1 = 1 and P2 = (2, tanh 2)
be nested: In this example, \foldera is used within the , m2 = 1/ cosh2 2 . Again, the picture is defined in
definition of \folderb. The \oval command had to be used mathematically convenient coordinates, and the lower left
as the \line command does not work if the segment length corner is assigned the mathematical coordinates (−3,−2)
is less than about 3 mm. (black disk).
7.4. PGF/TIKZ 143
or alternatively
\tikz[⟨options⟩]{⟨tikz commands⟩}
Writing text along a given path using the node command Multiline text can be included inside a node. A new
is shown as simple example: line is indicated by double backslash "\\", but additionally
you have to specify the alignment using the node option
\draw[dotted] (0,0) node {1st node} -- (1,1) node {2nd “align=". Here an example:
node} -- (0,2) node {3rd node} -- cycle;
\filldraw (0,0) circle (2pt) node[align=left, below] {test
1\\is aligned left} -- (4,0) circle (2pt) node[align=center,
Possible options for the node command are e.g. “in- below] {test 2\\is centered} -- (8,0) circle (2pt)
ner sep=<dimension>", “outer sep=<dimension>", node[align=right, below] {test 3\\is right aligned};
“minimum size=<dimension>", “shape as-
pect=<aspect ratio>", “text=<color>", “font=",
“align=<left_right_center>". Path construction operations try to be clever, such that the
path starts at the border of the node’s shape and not from
A node is centered at the current coordinate by default. the node’s center.
Often it would be better to have the node to the besides
the actual coordinate: Right (“right” or “anchor=west”), \path (0,0) node(x) {Hello World!} (3,1)
left (“left” or “anchor=east”), above (“above” or “an- node[circle,draw](y) {$\int_1^2 x \mathrm d x$};
146 CHAPTER 7. CREATING GRAPHICS
\draw[->,blue] (x) -- (y); \draw[->,red] (x) -| node[near node[right] {$f(x) = \frac{1}{20} \mathrm e^x$};
start,below] {label} (y); \draw[->,orange] (x) .. controls \end{tikzpicture} \end{document}
+(up:1cm) and +(left:1cm) .. node[above,sloped]
{label} (y);
Once the node x has been defined, you can use anchors 7.5 PSTricks
as defined above relative to (x) as "(x.<anchor>)", like
"(x.north)". PSTricks is a set of extensions. The base package is
pstricks, other packages may be loaded when required.
The xcolor extension gets loaded along PSTricks, so there
7.4.5 Examples is no need to load it manually.
Example 3: A Torus Thus the size of the picture is (x1-x0)x(y1-y0). The de-
\documentclass{article} \usepackage{tikz} \be- fault unit for coordinates is centimeters (cm); this can be
gin{document} \begin{tikzpicture} \draw (−1,0) changed with \psset, as in \psset{unit=1bp}. Any TeX
to[bend left] (1,0); \draw (−1.2,.1) to[bend right] dimension is allowed.
(1.2,.1); \draw[rotate=0] (0,0) ellipse (100pt and 50pt);
\end{tikzpicture} \end{document}
7.5.2 Fundamental objects
Example 4: Some functions Lines and polylines
\documentclass{article} \usepackage{tikz} \be-
gin{document} \begin{tikzpicture}[domain=0:4] A simple line gets printed with
\draw[very thin,color=gray] (−0.1,−1.1) grid (3.9,3.9); \psline(x0,y0)(x1,y1)
\draw[->] (−0.2,0) -- (4.2,0) node[right] {$x$};
\draw[->] (0,−1.2) -- (0,4.2) node[above] {$f(x)$};
\draw[color=red] plot (\x,\x) node[right] {$f(x) =x$}; To get a vector, add an arrow as parameter:
\draw[color=blue] plot (\x,{sin(\x r)}) node[right] {$f(x) \psline{->}(x0,y0)(x1,y1)
= \sin x$}; \draw[color=orange] plot (\x,{0.05*exp(\x)})
7.5. PSTRICKS 147
You can add as many points as you want to get a polyline: will print a symetric parabola with vertical asymptote,
\psline(x0,y0)(x1,y1)(x2,y3)…(xn,yn) vertex (x1,y1) and ending at (x0,y0).
Use \psbezier to print a Bézier curve with an arbitrary
To get rounded corners, add the following option: number of control points. Arcs have at most 4 control
points. Use the showpoints=true option to print the con-
\psline[linearc=0.2]{->}(0,0)(2,1)(1,1) trol points and the tangents.
Use \pscurve to print the interpolation of the given points.
or The \psecurve command omits the first and the last arcs.
\psline[linearc=0.2,arrows=->](0,0)(2,1)(1,1)
7.5.3 Text
Use
Rectangles
\rput(x,y){text}
\psframe(x0,y0)(x1,y1) \psframe*(x0,y0)(x1,y1)
to print text. Provide an angle to rotate the text.
The starred version prints a filled rectangle. Use the fol- \rput{angle}(x,y){text}
lowing parameter to get rounded corners:
\psframe[framearc=0.2](x0,y0)(x1,y1) You can provide the anchor of the text which will be at
the specified coordinate.
\rput[t]{45}(5,5){text}
Polygons
Available anchors:
Polygons are always closed. The syntax is the same as for
\psline: • B, Bl, Br: baseline center, left and right.
\pspolygon(x0,y0)(x1,y1)(x2,y2)...(xn,yn) • t, tl, tr: top center, left and right.
• b, bl, br: bottom center, left and right.
As for rectangles, the starred version prints a filled poly-
gon. And the linearc=0.2 option will print rounded cor-
ners. There is also the \uput command with further options:
\uput{distance}[angle](x,y){text}
To restrict the drawing to an arc, append the starting and • \psshadowbox{text}: shaded rectangle.
ending angles in trigonometric notation:
• \pstcirclebox{text}: circle.
\psarc(x,y){r}{angle1}{angle2}
• \psovalbox{text}: oval.
Example:
Curves \rput(5,5){\psdiabox*[fillcolor=green]{text}}
\pstextpath{shape}{text} Axis
To print a text following a path without printing the path, If you want to add axes, use the pstricks-add extension
you need to use \psset{linestyle=none}. with the following commands:
Example: \psaxes(xmin,ymin)(xmax,ymax)
\psaxes(x0,y0)(xmin,ymin)(xmax,ymax)
\usepackage{pst-text} % ... \be-
gin{pspicture}(5,5) \psset{linestyle=none} \ps-
textpath{\psline(0,0)(1,1)(2,0)}{triangle text} (xmin,ymin) and (xmax,ymax) being the extreme, (x0,y0)
\end{pspicture} being the intersection.
Options
7.5.4 Grids
• Dx=value and Dy=value defines the spacing be-
tween graduations.
Without any parameter, the \psgrid command will print
a grid all over the pspicture, with a spacing of 0.2 (i.e. • comma lets you use the comma as decimal separa-
2mm). You can specify parameters: tor.
• \psgrid(xmax,ymax): prints a grid from (0,0) to • As for lines, {->} adds arrows on axes.
(xmax,ymax).
Example
• \psgrid(xmin,ymin)(xmax,ymax): prints a grid from
(xmin,ymin) to (xmax,ymax).
\usepackage{pstricks-add} %
• \psgrid(x0,y0)(xmin,ymin)(xmax,ymax): prints a ... \begin{pspicture}(−1,−1)(5,5)
grid from (xmin,ymin) to (xmax,ymax), one of the \psaxes[comma,Dx=0.5,Dy=0.5]{->}(0,0)(3,3)
node is at (x0,y0). \end{pspicture}
• griddots=value: the full line of the main graduations
is replaced by a dotted line. The value is the number
of dots per graduation.
7.5.5 Generic parameters
• subgriddots=value: same as griddots but for sub-
graduations. All shapes
• unit=value
7.5.6 Object location
• xunit=value and yunit=value
The \rput and \uput commands can be used to move any
object.
value is a number with or without unit. This changes the
scale of the drawings, but will not change the width of
lines. Example
\begin{pspicture}(5,5) \psline{->}(0,0)(1,1)
Open shapes \rput(1,1){\psline{->}(0,0)(1,1)} \end{pspicture}
Usage
Closed shapes
For closed shape you may define the fillstyle. • Declare the PDFTricks packages in the preamble.
• Place all PSTricks extensions in a psinputs environ-
• fillstyle=value: pattern. Possible values: crosshatch, ment; place all PSTricks commands in a pdfpic en-
crosshatch*, vlines, vlines*, hlines, hlines*, solid. vironment.
• fillcolor=color. • Compile with pdflatex -shell-escape <file>.
150 CHAPTER 7. CREATING GRAPHICS
The -shell-escape parameter enables shell command calls. The modifiers between the slashes define how the curves
It is required for PDFTricks to run. are drawn. Xy-pic offers many ways to influence the
drawing of curves; for more information, check the Xy-
pic documentation.
Example
If you are interested in a more thorough introduction then
consult the Xy-pic Home Page, which contains links to
\documentclass{article} \usepackage{pdftricks} several other tutorials as well as the reference documen-
\begin{psinputs} \usepackage{pstricks} \usepack- tation.
age{multido} \end{psinputs} % ... \begin{document}
% ... \begin{pdfpic} \psset{unit=\linewidth} \be-
gin{pspicture}(0,0)(10,10) [...] \end{pspicture}
\end{pdfpic} % ... \end{document} 7.7 Creating 3D graphics
For creating three-dimensional graphics, there is basic
Another way to use PSTricks with pdflatex is the pst-pdf
functionality in the PGF/TikZ package, although drawing
package.
3D graphics with PGF/TikZ is very non-flexible, mainly
because it lacks functionality for identifying the surfaces
that are covered by other surfaces and should be excluded
7.6 Xy-pic from the rendered image.
A package that can handle this correctly is the pst-
xy is a special package for drawing diagrams. To use it, solides3d package.
simply add the following line to the preamble of your doc- Another way to create 3D graphics is to use Asymptote.
ument:
Yet another way to create 3D graphics is to use Sketch.
\usepackage[all]{xy}
Programming
8.1.1 New commands Note When the command is used with an explicit first
parameter it is given enclosed with brackets (here
To add your own commands, use the "[lots of users]").
command. Basically, the command requires two argu-
ments: the name of the command you want to create,
and the definition of the command. Note that the com-
mand name can but need not be enclosed in braces, as Here is a common example: if you are writing a book
you like. The num argument in square brackets is optionalabout Mathematics and you have to use vectors, you have
and specifies the number of arguments the new command to decide how they will look. There are several different
standards, used in many books. If a is a vector, some
takes (up to 9 are possible). If missing it defaults to 0, i.e.
no argument allowed. people like to add an arrow over it ( ⃗a ), other people write
it underlined (a); another common version is to write it
The following two examples should help you to get the bold (a). Let us assume you want to write your vectors
idea. The first example defines a new command called with an arrow over them; then add the following line in
\wbal that will print “The Wikibook about LaTeX”. Such your mystyle.sty.
a command could come in handy if you had to write the
title of this book over and over again. and write your vectors inside the new \myvec{...} com-
mand. You can call it as you wish, but you'd better choose
The next example illustrates how to define a new com- a short name because you will probably write it very of-
mand that takes one argument. The #1 tag gets replaced ten. Then, if you change your mind and you want your
by the argument you specify. If you wanted to use more vectors to look differently you just have to change the
than one argument, use #2 and so on, these arguments are definition of your \myvec{...}. Use this approach when-
added in an extra set of brackets. ever you can: this will save you a lot of time and increase
Name your new command \wbalTwo and not \wbal2 as the consistency of your document.
151
152 CHAPTER 8. PROGRAMMING
DeclareRobustCommand Also, if you're still having problems with extra space be-
ing appended at the end of your environment when using
Some commands are fragile, that is they fail in some en- the \input for external source, make sure there is no space
vironments. If a macro works in body text but not in (for between the beginning, sourcing, and end of the environ-
example) a figure caption, it’s worth trying to replace the ment, such as:
\newcommand{\MyCommand}... declaration with \De- or
clareRobustCommand{\MyCommand}... in the pream-
ble. This is especially true for macros which, when ex-
panded, produce text that is written to a .aux file.
8.1.3 Declare commands within newenvi-
ronment
8.1.2 New environments
New commands can be declared within newenvironment.
Just as with the \newcommand command, there is a com- Commands declared within the newenvironment refer to
mand to create your own environments. The \newenvi- their arguments by doubling the # character. In the fol-
ronment command uses the following syntax: lowing example, a new environment is declared along
with a nested command:
Again \newenvironment can have an optional argument.
When the \begin{name} command (which starts the en- If, by mistake, the arguments passed to the \topics macro
vironment) is encountered, the material specified in the are defined with a single # character, the following error
before argument is processed before the text in the en- message will be thrown:
vironment gets processed. The material in the after ar- ! Illegal parameter number in definition of \topics.
gument gets processed when the \end{name} command
(which ends the environment) is encountered.
The num argument is used the same way as in the \new- 8.1.4 Extending the number of arguments
command command. LaTeX makes sure that you do not
define an environment that already exists. If you ever The xkeyval packages will let you define key/value op-
want to change an existing command, you can use the tions for commands.
\renewenvironment command. It uses the same syntax as
the \newenvironment command. The package is quite complete and documentation is ex-
haustive. We recommend that package developers read
The example below illustrates the usage of the \newenvi- it.
ronment command:
Let’s provide a simple example[1] :
Unmatched braces
8.1.5 Arithmetic
Often, part of the motive behind creating an environment
is to surround its body in a grouping of braces. How- LaTeX can manipulate numbers.
ever, this requires unmatched braces to appear in both the
beginning and end portions of the environment declara- The calc package provides the common infix notation.
tion, which will prevent the document from compiling. For high-precision computations, you can use the fp[2]
To solve this issue, use the TeX synonyms \bgroup and package.
\egroup instead of typing { and } in this case.
When creating a new environment you may easily get LaTeX can use conditionals thanks to the ifthen package.
bitten by extra spaces creeping in, which can potentially
have fatal effects. For example when you want to create a
title environment which suppresses its own indentation as 8.1.7 Loops
well as the one on the following paragraph. The \ignores-
paces command in the begin block of the environment The PGF/TikZ extension provides the \foreach com-
will make it ignore any space after executing the begin mand.
block. The end block is a bit more tricky as special pro-
cessing occurs at the end of an environment. With the If you are only using \foreach and not drawing graphics,
\ignorespacesafterend LaTeX will issue an \ignorespaces you may instead use the pgffor package directly.
after the special ‘end’ processing has occurred. Alternatively you can check out the multido package.
8.2. PLAIN TEX 153
• position of a substring Up to a few exceptions, you can use the full Plain TeX
language within a valid LaTeX document whereas the op-
• number of recurrences of a substring posite is false.
Examples:
8.2.1 Vocabulary
8.1.9 LaTeX Hooks To avoid confusion it seems necessary to explain some
terms.
LaTeX provide two hooks:
• \AtBeginDocument will let you specify a set • A group is everything after an opening brace and
of commands that will be executed when \be- before the matching closing brace.
gin{document} is met.
• A token is a character, a control sequence, or a
• \AtEndDocument does the same for group.
\end{document}.
• A control sequence is anything that begins with a \. It
This gives you some more flexiblity for macros. It can is not printed as is, it is expanded by the TeX engine
be useful to override settings that get executed after the according to its type.
preamble. These hooks can be called several times. The
commands will be executed in the order they were set. • A command (or function or macro) is a control se-
For instance, let’s replace the page numbers with old- quence that may expand to text, to (re)definition of
stylenums: control sequences, etc.
There are also hooks for classes and packages. See • A primitive is a command that is hard coded in the
Creating Packages. TeX engine, i.e. it is not written in Plain TeX.
[1] tex.stackexchange.com
There may be more terms, but we hope that it will do it
[2] ctan.mackichan.com for now.
154 CHAPTER 8. PROGRAMMING
In TeX some characters have a special meaning that is not If you have done a bit of LaTeX hacking, you must
to print the associated glyph. For example, \ is used to in- have encountered those two commands, \makeatletter
troduce a control sequence, and will not print a backslash and \makeatother.
by default. In TeX the '@' characters belongs to catcode 11 letters by
To distinguish between different meanings of the charac- default. It means you can use it for macro names. LaTeX
ters, TeX split them into category codes, or catcodes for makes use of the catcode to specify a rule: all non-public,
short. There are 16 category codes in TeX. internal macros that are not supposed to be accessed by
the end-user contains at least one '@' character in their
A powerful feature of TeX is its ability to redefine the
name. In the document, LaTeX changes the catcode of
language itself, since there is a \catcode function that will
'@' to 12, others.
let you change the category code of any characters.
That’s why when you need to access LaTeX internals, you
However, this is not recommended, as it can make code
must enclose all the commands accessing private func-
difficult to read. Should you redefine any catcode in a
tions with \makeatletter and \makeatother. All they do is
class or in a style file, make sure to revert it back at the
just changing the catcode:
end of your file.
If you redefine catcodes in your document, make sure to
do it after the preamble to prevent clashes with package 8.2.3 Plain TeX macros
loading.
\newcommand and \renewcommand are LaTeX-specific
control sequences. They check that no existing command
Active characters gets shadowed by the new definition.
In Plain TeX, the primitives for macro definition make no
Active characters resemble macros: they are single char- check on possible shadowing. It’s up to you to make sure
acters that will expand before any other command. you are not breaking anything.
Note that an active character needs to be directly followed The syntax is
by a definition, otherwise the compilation will fail.
You can use (almost) any sequence of character between
arguments. For instance let’s write a simple macro that
will convert the decimal separator from point to comma.
Examples
First try:
Texinfo This will print (123,4)56. We added the parentheses just
to highlight the issue here. Each parameter is the shortest
possible input sequence that matches the macro defini-
Texinfo uses a syntax similar to TeX with one major dif- tion, separators included. Thus #1 matches all characters
ference: all functions are introduced with a @ instead of up to the first point, and #2 matches the first token only,
a \. This is not by chance: it actually uses TeX to print i.e. the first character, since there is no separator after it.
the PDF version of the files. What it basically does is in-
putting texinfo.tex which redefines the control sequence Solution: add a second separator. A space may seem con-
character. Possible implementation: venient:
With this redefinition, the '@' should now introduce ev- As a general rule, everytime you expect several parame-
ery command, while the '\' will actually print a backslash ters with specific separators, think out the last separator.
character. If you do not want to play with separators, then Plain TeX
macros are used just as LaTeX macros (without default
parameter):
Itemize
Expanded definitions
Some may find the LaTeX syntax of list environments a
bit cumbersome. Here is a quick way to define a wiki-like TeX has another definition command: \edef, which stands
itemize: for expanded def. The syntax remains the same:
The content gets expanded (but not executed, i.e. printed)
Dollar and math at the point where \edef is used, instead of where the de-
fined macro is used. Macro expansion is not always ob-
If you have many 'dollar' symbols to print, you may be vious...
better off to change the math shift character. Example:
8.2. PLAIN TEX 155
Here the redefinition of \intro will have no effect on \ex- \futurelet<csname><token1><token2>... works a bit dif-
ample. ferently. token2 is assigned to csname; after that TeX
processes the <token1><token2>... sequence. So \fu-
turelet allows you to assign a token while using it right
Global definitions after.
• catcodes
Outer definitions
• chardef
This prefix macro prevent definitions from being used in
• font parameters
some context. It is useful to consolidate macros and make
them less error-prone because of bad contexts. Outer • internal parameters
macros are meant to be used outside of any context, hence
the name. • lengths
For instance the following code will fail: • registers
Outer macros are not allowed to appear in: • ...
• ...
8.2.4 Registers
Registers are kind of typed variables. They are limited
let and futurelet in numbers, ranging from 0 to 255. There are 6 different
types:
\let<csname><token> is the same as \ex- TeX uses some registers internally, so you would be better
pandafter\def\expandafter<csname>\expandafter{<content>}. off not using them.
It defines a new control sequence name which is equiva-
lent to the specified token. The token is usually another List of reserved registers:
control sequence.
• \box255 is used for the contents of a page
Note that \let will expand the token one time only, con-
trary to \edef which will expand recursively until no fur- • \count0-\count9 are used for page numbering
ther expansion is possible.
Example[1] : Scratch registers (freely available):
156 CHAPTER 8. PROGRAMMING
• \skip0-\skip9
Case statement
Assign register using the '=' control character. For box
registers, use the \setbox command instead. The syntax is \ifcase <num-
You may use one of the following reservation macro to ber><case0>\or<case1>\or...\else<defaultcase>\fi.
prevent any clash: If number is equal to the case number, its content will be
printed. Note that it starts at 0.
These macros use the following syntax: \new*<csname>.
Example: \else is used to specify the default case (whenever none of
the previous cases have matched).
These commands can not be used inside macros, other-
wise every call to the macro would reserve another regis-
ter.
You can print a register using the \the command. For 8.2.7 Loops
counters use the \number command instead. For boxes
use the \box command. The base syntax is
As always, content and true action are arbitrary TeX con-
tents. \if* refers to any of the conditionals. Note that
8.2.5 Arithmetic there is no false action, you cannot put an \else between
\if* and \repeat. In some case this will be the opposite
The arithmetic capabilities of TeX are very limited, al-
of what you want; you have to change the condition or to
though this base suffice to extend it to some interesting
define a new conditional using \newif. Example:
features. The three main functions:
The above code will print TeX ten times.
register may be of type count, dimen, muskip or skip. It
does not make sense for box nor toks.
chardef and mathchardef Another problem arises: how to define a command whose
name is a variable? In most programming languages that’s
You can define control sequence to expand to a not possible at all. What we could be tempted to write is
specific char. The syntax is \chardef<control se-
It will fail for two reasons.
quence>=<charcode>. The following sequences do the
same thing.
1. The two last '#1' are supposed to refer to the argu-
Example: ments of the new macro, but they get expanded to
the \localedef macro first argument because they are
in the body of that macro.
Font encoding map
2. \#1 gets expanded to two tokens: '#' and '1', and the
We can use the above primitive to print the font encoding \def command will fail as it requires a valid control
map. sequence name.
Another version, with different fonts, one entry per line:
The solution to problem 1 is simple: use '##1', which will
expand to '#1' when the macro is executed.
8.2.10 Verbatim lines and spaces For problem 2, it is a little bit tricky. It is possible to
tell tex that a specific token is a control sequence. This is
It is rather confusing to discover (La)TeX treats all what the \csname...\endcsname is used for. However
whitespace as the same type of spacing glue. Plain TeX
provides some commands to preserve the spacing and will fail because it will redefine \csname to '#1', which is
newlines as you wrote it: not what we want, then tex will encounter \endcsname,
which will result in an error.
which means that you will probably need to combine your
own verbatim environment, and your command: We need to delay the expansion of \def, i.e. to
tell tex to expand the \csname stuff first, then to ap-
and then in your tex file: ply \def on it. There is a command for that: \ex-
pandafter{token1}{token2}. It will expand {token2} be-
fore {token1}.
8.2.11 Macros defining macros
Finally if we want to set language from command line, we
This is useful in some case, for example to define lan- must be able to set the \locale variable so that the one in
guage commands as explained in Multilingual versions, the source code is the default value that can be overridden
where the end user can write by the one in the command line. This can be done with
\provdecommand:
and make sure it switches to the appropriate Babel lan-
guage. The final code is
Let’s define a macros that will define language commands And you can compile with
for instance. These commands are simple: if the argu- latex '\providecommand\locale{en}\input{mydocument.tex}'
ment is the value of the \locale variable, then the corre-
sponding macro prints its content directly. Otherwise, it
does nothing. 8.2.12 Notes and References
Basicly, what we want to do is extremely simple: define a
[1] From tex.stackexchange.com: What is the difference be-
bunch of macros like this: tween \let and \edef?
In the previous snippet of code, only the \de command in
going to output its content, \en and \fr will print nothing Further reading
at all. That’s what we want. The problem arises when
you want to automate the task, or if you have a lot of • The TeXbook, Donald Knuth
languages, and you want to change the language selection.
You just have to move the #1, but that’s not convenient • TeX by Topic, Victor Eijkhout
and it makes it impossible to choose the Babel language • TeX for the Impatient, Paul W. Abrahams, Karl
from command line. Think this out... Berry and Kathryn A. Hargreaves
What we are going to do is to define the language com-
mands dynamically following the value of the \locale vari-
able (or any variable of your choice). Hence the use of 8.3 Creating Packages
the \equal command from the ifthen package.
Since it is hardly possible to write it in LaTeX, we will If you define a lot of new environments and commands,
use some Plain TeX. the preamble of your document will get quite long. In
158 CHAPTER 8. PROGRAMMING
this situation, it is a good idea to create a LaTeX package • Write whatever you want in it using all the LaTeX
or class containing all your command and environment commands you know. Normally you should define
definitions. It can be made dynamic enough to fit to all new commands or import other packages.
your future documents.
• \endinput: this must be the last command.
Classes are .cls files, packages are stored in .sty files. They
are very similar, the main difference being that you can
Once your package is ready, we can use it in any doc-
load only one class per document.
ument. Import your new package with the known com-
mand \usepackage{mypack}. The file custom.sty and the
LaTeX source you are compiling must be in the same di-
8.3.1 makeatletter and makeatother rectory.
By default, LaTeX will allow the use of the '@' characters For a more convenient use, it is possible to place the
for control sequences from within package and class files, package within $TEXMFHOME (which is ~/texmf by
but not from within an end-user document. This way it is default) according to the TeX Directory Structure (TDS).
possible to protect commands, i.e. to make them accessi- That would be
ble from packages only. $TEXMFHOME/tex/latex/custom/custom.sty
However it is possible to override this security with the On Windows '~' is often C:\Users\username.
duo \makeatletter and \makeatother. These commands
only make sense in a regular document, they are not You may have to run texhash (or equivalent) to make your
needed in package or class files. TeX distribution index the new file, thus making it avail-
able for use for any document. It will allow you to use
your package as detailed above, but without it needing to
8.3.2 Creating your own package be in the same directory as your document.
Your package can be made available in your document 8.3.3 Creating your own class
just like any other package: using the \usepackage com-
mand. Writing a package basically consists of copying It is also possible to create your own class file. The pro-
the contents of your document preamble into a separate cess is similar to the creation of your own package, you
file with a name ending in .sty. can call your own style file in the preamble of any docu-
Let’s write a first custom.sty file as an example package: ment by the command:
The name of the class file is then myclass.cls. Let’s write
• \NeedsTeXFormat{...} specifies which version of a simple example:
TeX or LaTeX is required at least to run your pack-
age. The optional date may be used to specify the • \ProvidesClass is the counterpart of \ProvidesPack-
version more precisely. age.
• \PassOptionsToClass and \PassOptionsToPackage
• \ProvidesPackage has to have the same name of the
are used to automatically invoke the corresponding
file without the extension. It tells LaTeX the name
options when the class or the package is loaded.
of the package and will allow it to issue a sensible
error message when you try to include a package • \DeclareOption*: the starred version lets you handle
twice. The date is important since it can be used non-implemented options.
by other package to specify the minimum version
requirement they need to use your package. • \ClassWarning will show the corresponding message
in the TeX compiler output.
• Next you may write some TeX or LaTeX code like
• \LoadClass specifies the unique parent class, if any.
loading package, but write only the bare minimum
needed for the package options set below.
• \DeclareOptions are end-user parameters. Each op- There are also hooks for classes and packages.
tion is declared by one such command.
• \AtEndOfPackage
• \ExecuteOptions{...} tells which are the default.
• \AtEndOfClass
• \ProcessOptions\relax terminates the option pro-
cessing. They behave as the document hooks. See LaTeX Hooks.
8.4. THEMES 159
Newcomers to LaTeX often feel disappointed by the lack This is definitely the most complex part. It is not that hard
of visual customization offered by the system. Actually since the code is almost the same for \section, \subsection
this is done on purpose: the LaTeX philosophy takes a and \subsubsection.
point at doing the formatting while the writer focuses on
We use \needspace to make sure there is no line break
the content. right after a sectioning command. We enclose the com-
In this chapter, we will show what we can achieve with mand in a group where we set a font size since the space
some efforts. we need is \baselineskip which depends on the font size.
Starred commands will not set the counters (LaTeX de-
tault behaviour). You can choose to handle starred com-
8.4.1 Introduction mand differently by resetting the counters for instance.
We preceed the section printing by a \noindent. We make
In the following we will write the theme, a package that
sure to end the section printing by a \par command to
will only change the appearance of the document, so that
make sure following text gets printed properly.
our document will work with or without the theme.
For \subsection we make use of the mirrors option to
Note that if it may look eye-candy, this is absolutely not a
change the appearance accordingly.
model of typography. You should not use such theme for
serious publications. This is more a technogical example To handle the PDF bookmarks properly we need the fol-
to exhibit LaTeX capabilities. lowing lines at the end of the definitions.
Finally, for \section only, we want it to print in the header,
• Custom theme (TOC) so we call the \sectionmark command. Here we changed
the behaviour of the starred command over the original
• Custom theme LaTeX version, since we define and use the \sectionmark-
star command.
• Custom theme (red)
Miscellaneous
9.1 Modular Documents book. In such cases it is good practice to split your work
into several files. For example, if you are writing a book,
During this guide we have seen what is possible to do and it makes a lot of sense to write each chapter in a sepa-
how this can be achieved, but the question is: I want to rate .tex file. LaTeX makes this very easy thanks to two
write a proper text with LaTeX, what to do then? Where commands:
should I start from? This is a short step-by-step guide \input{filename}
about how to start a document properly, keeping a good
high-level structure. This is all about organizing your files
and
using the modular capabilities of LaTeX. This way it will
be very easy to make modifications even when the doc- \include{filename}
ument is almost finished. These are all just suggestions,
but you might take inspiration from that to create your
own document.
Comparing the methods: input vs include
9.1.1 Project structure The differences between these two ways to include files
is explained below. What they have in common is that
Create a clear structure of the whole project this way: they process the contents of filename.tex before continu-
ing with the rest of the base file (the file that contains these
statements). When the compiler processes your base file
1. create a directory only for the project. We'll refer to
and reaches one of the commands \input or \include, it
that in the following parts as the root directory
reads filename.tex and processes its content in accordance
2. create two other directories inside the root, one for with the formatting commands specified in the base file.
LaTeX documents, the other one for images. Since This way you can put all the formatting options in your
you'll have to write their name quite often, choose base file and write the contents using \input or \include in
short names. A suggestion would be simply tex and the files which contain the actual content of your work.
img. This means that the important part of your working pro-
cess, i.e. writing, is kept largely separate from format-
3. create your document (we'll call it document.tex, ting choices. This is one of the main reasons why LaTeX
but you can use the name you prefer) and your own is so good for serious writing! You will thus be dealing
package (for example mystyle.sty); this second file solely with text and very basic commands such as \sec-
will help you to keep the code cleaner. tion, \emph etc. Your document will be uncluttered and
much easier to work with.
If you followed all those steps, these files should be in The second method of including a file, \in-
your root directory, using "/" for each directory: clude{filename}, differs from the first in some important
./document.tex ./mystyle.sty ./tex/ ./img/ ways. You cannot nest \include statements within a file
added via \include, whereas \input, on the other hand,
nothing else.
allows you to call files which themselves call other files,
ad infinitum (well, nearly!). You can, however, \include
9.1.2 Getting LaTeX to process multiple a file which contains one or more \input commands.
Please resist the temptation to nest files in this way
files
simply because the system can do it: you will end up
As your work grows, your LaTeX file can become un- with just another kind of complexity!
wieldy and confusing, especially if you are writing a long Another important difference is that using \include will
article with substantial, discrete sections, or a full-length force a page break (which makes it ideal for a book’s
160
9.1. MODULAR DOCUMENTS 161
chapters), whereas the \input command does not (which tree. Writing
in turn makes it ideal for use within, say, a long article \input{./filename.tex}
with discrete sections, which of course are not normally
set on a new page).
will have exactly the same effect as writing
In either case the .tex filename extension is optional.
\input{filename.tex}
Working on discrete parts of your documents has conse-
quences for how the base file is compiled; these will be
dealt with below. but if you found it more convenient to put all your files in
a sub-directory of your current directory, called myfiles,
you would refer to that file by specifying
Using different paths \input{./myfiles/filename.tex}
When the LaTeX compiler finds a reference to an external Indeed, in our example of the absolute path above, you
file in the base file, it will look for it in the same directory. could refer to that file relatively, too:
However, you can in principle refer to any file on your
system, using both absolute and relative paths. \input{../../documents/useful/foo.tex}
put{Section_1} %\input{Section_2} %\in- In the main document, the package must be loaded as:
put{Section_3} \input{Section_4} %\input{Section_5} \usepackage{subfiles}
\end{document}
If you need to insert an existing, possibly multi-page, 9.1.4 The main document document.tex
PDF file into your LaTeX document, whether or not the
included PDF was compiled with LaTeX or another tool, Then create a file called document.tex; this will be the
consider using the pdfpages package. In the preamble, main file, the one you will compile, even if you shouldn't
include the package: need to edit it very often because you will be working on
\usepackage[final]{pdfpages} other files. It should look like this (it’s the sample code
for a report, but you might easily change it to article or
whatever else):
This package also allows you to specify which pages you
wish to include: for example, to insert pages 3 to 6 from \documentclass[12pt,a4paper]{report} \usepack-
some file insertme.pdf, use: age{graphicx} \usepackage{ifpdf} \ifpdf % put here
packages only for the PDF: \DeclareGraphicsExten-
\includepdf[pages=3-6]{insertme.pdf}
sions{.pdf,.png,.jpg,.mps} \usepackage{hyperref}
\else % put here packages only for the DVI: \fi % put
To insert the whole of insertme.pdf: all the other packages here: \usepackage{mystyle}
\includepdf[pages=-]{insertme.pdf} \begin{document} \input{./tex/title.tex} %\maketi-
tle \tableofcontents \listoffigures \listoftables \in-
put{./tex/intro.tex} \input{./tex/main_part.tex}
For full functionality, compile the output with pdflatex. \input{./tex/conclusions.tex} \appendix \in-
Additional information can be found in the chapter put{./tex/myappendix.tex} % Bibliography: \clearpage
Export To Other Formats. \addcontentsline{toc}{chapter}{Bibliography} \in-
put{./tex/mybibliography.tex} \end{document}
9.1.3 The file mystyle.sty Here a lot of code expressed in previous sections has been
used. At the beginning there is the header discussed in the
Instead of putting all the packages you need at the be- Tips & Tricks section, so you will be able to compile in
ginning of your document as you could, the best way is both DVI and PDF. Then you import the only package
to load all the packages you need inside another dummy you need, that is your mystyle.sty (note that in the code
package called mystyle you will create just for your doc- it has to be imported without the extension), then your
ument. The good point of doing this is that you will just document starts. Then it inserts the title: we don't like
have to add one single \usepackage in your document, the output of \maketitle so we created our own, the code
keeping your code much cleaner. Moreover, all the info for it will be in a file called title.tex in the folder called
about your style will be within one file, so when you will tex we created before. How to write it is explained in the
start another document you'll just have to copy that file Title Creation section. Then tables of contents, figure and
and include it properly, so you'll have exactly the same tables are inserted. If you don't want them, just comment
style you have used. out those lines. Then the main part of the document in
inserted. As you can see, there is no text in document.tex:
Creating your own style is very simple: create a file called everything is in other files in the tex directory so that you
mystyle.sty (you could name it as you wish, but it has to can easily edit them. We are separating our text from the
end with ".sty”). Write at the beginning: structural code, so we are improving the “What You See is
\ProvidesPackage{mystyle} What You Mean” nature of LaTeX. Then we can see the
appendix and finally the Bibliography. It is in a separate
164 CHAPTER 9. MISCELLANEOUS
file and it is manually added to the table of contents using • Another option for collaboration is dropbox. It has 2
a tip suggested in the Tips & Tricks. GB free storage and versioning system. Works like
Once you have created your document.tex you won't need SVN, but more automated and therefore especially
to edit it anymore, unless you want to add other files in the useful for beginning LaTeX users. However, Drop-
tex directory, but this is not going to happen very often. box is not a true versioning control system, and as
Now you can write your document, separating it into as such it does not allow you to roll the article back to
many files as you want and adding many pictures without previous versions.
getting confused: thanks to the rigid structure you gave
to the project, you will be able to keep track of all your • You can use an online collaborative tool built on top
edits clearly. of a versioning control system, such as Authorea or
ShareLatex. Authorea performs most of the actions
A suggestion: do not give your files names like “chap-
described in this document, but in the background
ter_01.tex” or “figure_03.png”, i.e. try to avoid using
(it is built on Git). It allows authors to enter LaTeX
numbers in file-names: if the numbering LaTeX gives
or Markdown via a GUI with mathematical notation,
them automatically, is different from the one you gave
figures, d3.js plots, IPython notebooks, data, and ta-
(and this will likely happen) you will get really confused.
bles. All content is rendered to HTML5. Authorea
When naming a file, stop for a second, think about a short
also features a commenting system and article-based
name that can fully explain what is inside the file without
chat to ease collaboration and review.
being ambiguous, it will let you save a lot of time as soon
as the document gets larger.
• As the LaTeX system uses plain text, you can use
synchronous collaborative editors like Gobby. In
9.1.5 External Links Gobby you can write your documents in collabo-
ration with anyone in real time. It is strongly rec-
• Subfiles package documentation ommended that you use utf8 encoding (especially if
there are users on multiple operating systems collab-
• Standalone package documentation orating) and a stable network (typically wired net-
works).
• pdfpages package documentation
• TitanPad (or other clones of EtherPad). To compile
use the command:
9.2 Collaborative Writing of La- wget -O filename.tex "http://titanpad.com/ep/
pad/export/xxxx/latest?format=txt" && (latex
TeX Documents filename.tex)
where 'xxxx' should be replaced by the pad number
Note: This Wikibook is based on the article Tools for (something like 'z7rSrfrYcH').
Collaborative Writing of Scientific LaTeX Documents by
Arne Henningsen that is published in The PracTeX Jour- • With a dedicated Linux box with LaTeX & Dropbox
nal 2007, number 3 (http://www.tug.org/pracjourn/). it’s possible to use Google docs and some scripting to
get automatically generated PDFs on Dropbox from
updates on Google Docs.
9.2.1 Abstract
Collaborative writing of documents requires a strong syn- • You can use a distributed version control system
chronisation among authors. This Wikibook describes such as Mercurial or Git. This is the definitive solu-
a possible way to organise the collaborative preparation tion for users looking for control and advanced fea-
of LaTeX documents. The presented solution is primar- tures like branch and merge. The learning curve will
ily based on the version control system Subversion (http: be steeper than that for a web-based solution.
//subversion.apache.org/). The Wikibook describes how
Subversion can be used together with several other soft-
9.2.2 Introduction
ware tools and LaTeX packages to organise the collabo-
rative preparation of LaTeX documents. The collaborative preparation of documents requires a
considerable amount of coordination among the authors.
Other Methods This coordination can be organised in many different
ways, where the best way depends on the specific circum-
• You can use one of the online solutions listed in the stances.
Installation chapter. Most of them have collabora- In this Wikibook, I describe how the collaborative writ-
tion features. ing of LaTeX documents is organised at our department
9.2. COLLABORATIVE WRITING OF LATEX DOCUMENTS 165
(Division of Agricultural Policy, Department of Agricul- on other computers (e.g. on the version control server).
tural Economics, University of Kiel, Germany). I present Third, this allows the user to easily switch between dif-
our software tools, and describe how we use them. Thus, ferent computers (e.g. office, laptop, home).
this Wikibook provides some ideas and hints that will be
useful for other LaTeX users who prepare documents to-
gether with their co-authors. 9.2.4 The Version Control System Subver-
sion
9.2.3 Interchanging Documents Subversion (SVN) comes as a successor to the popular
version control system CVS. SVN operates on a client-
There are many ways to interchange documents among server model in which a central server hosts a project
authors. One possibility is to compose documents by in- repository that users copy and modify locally. A repos-
terchanging e-mail messages. This method has the advan- itory functions similarly to a library in that it permits
tage that common users generally do not have to install users to check out the current project, make changes, and
and learn the usage of any extra software, because virtu- then check it back in. The server records all changes a
ally all authors have an e-mail account. Furthermore, the user checks in (usually with a message summarizing what
author who has modified the document can easily attach changes the user made) so that other users can easily ap-
the document and explain the changes by e-mail as well. ply those changes to their own local files.
Unfortunately, there is a problem when two or more au-
Each user has a local working copy of a remote repos-
thors are working at the same time on the same document.
itory. For instance, users can update changes from the
So, how can authors synchronise these files?
repository to their working copy, commit changes from
A second possibility is to provide the document on a com- their own working copy to the repository, or (re)view the
mon file server, which is available in most departments. differences between working copy and repository.
The risk of overwriting each others’ modifications can be
To set up a SVN version control system, the SVN server
eliminated by locking files that are currently edited. How-
software has to be installed on a (single) computer with
ever, generally the file server can be only accessed from
permanent internet access. (If this computer has no static
within a department. Hence, authors who are out of the
IP address, one can use a service like DynDNS to be able
building cannot use this method to update/commit their
to access the server with a static hostname.) It can run
changes. In this case, they will have to use another way to
on many Unix, modern MS Windows, and Mac OS X
overcome this problem. So, how can authors access these
platforms.
files?
Users do not have to install the SVN server software, but
A third possibility is to use a version control system.
a SVN “client” software. This is the unique way to ac-
A comprehensive list of version control systems can be
cess the repositories on the server. Besides the basic SVN
found at Wikipedia. Version control systems keep track
command-line client, there are several Graphical User In-
of all changes in files in a project. If many authors modify
terface Tools (GUIs) and plug-ins for accessing the SVN
a document at the same time, the version control system
server (see http://subversion.tigris.org/links.html). Ad-
tries to merge all modifications automatically. However,
ditionally, there are very good manuals about SVN freely
if multiple authors have modified the same line, the mod-
available on the internet (e.g. http://svnbook.red-bean.
ifications cannot be merged automatically, and the user
com).
has to resolve the conflict by deciding manually which
of the changes should be kept. Authors can also com- At our department, we run the SVN server on a GNU-
ment their modifications so that the co-authors can eas- Linux system, because most Linux distributions include
ily understand the workflow of this file. As version con- it. In this sense, installing, configuring, and maintaining
trol systems generally communicate over the internet (e.g. SVN is a very simple task.
through TCP/IP connections), they can be used from dif- Most MS Windows users access the SVN server by the
ferent computers with internet connections. A restrictive TortoiseSVN client, because it provides the most usual
firewall policy might prevent the version control system interface for common users. Linux users usually use
from connecting to the internet. In this case, the net- SVN utilities from the command-line, or eSvn--a GUI
work administrator has to be asked to open the appro- frontend--with KDiff3 for showing complex differences.
priate port. The internet is only used for synchronising
the files. Hence, a permanent internet connection is not
required. The only drawback of a version control system 9.2.5 Hosting LaTeX files in Subversion
could be that it has to be installed and configured.
Moreover, a version control system is useful even if a sin- On our Subversion server, we have one repository for
gle user is working on a project. First, the user can track a common texmf tree. Its structure complies with the
(and possibly revoke) all previous modifications. Sec- TeX Directory Structure guidelines (TDS, http://www.
ond, this is a convenient way to have a backup of the files tug.org/tds/tds.html, see figure 1). This repository pro-
166 CHAPTER 9. MISCELLANEOUS
7. Verify that your code can be compiled flawlessly be- 9.2.7 Managing collaborative bibliogra-
fore committing your modifications to the reposi- phies
tory.
Writing of scientific articles, reports, and books requires
8. Use Subversion's diff feature to critically review the citation of all relevant sources. BibTeX is an excel-
your modifications before committing them to the lent tool for citing references and creating bibliographies
repository. (Markey 2005, Fenn 2006). Many different BibTeX
styles can be found on CTAN (http://www.ctan.org) and
on the LaTeX Bibliography Styles Database (http://jo.
9. Add a meaningful and descriptive comment when irisson.free.fr/bstdatabase/). If no suitable BibTeX style
committing your modifications to the repository. can be found, most desired styles can be conveniently as-
sembled with custombib/makebst (http://www.ctan.org/
tex-archive/macros/latex/contrib/custom-bib/). Fur-
10. Use the Subversion client for copying, moving, or re- thermore, BibTeX style files can be created or modified
naming files and folders that are under revision con- manually; however this action requires knowledge of the
trol. (unnamed) postfix stack language that is used in BibTeX
style files (Patashnik 1988).
If the users are willing to let go of the built-in diff utility At our department, we have a common bibliographic data
of SVN and use diff tools that are local on their worksta- base in the BibTeX format (.bib file). It resides in our
tions, they can put to use such tools that are more tailored common texmf tree (see section 'Hosting LaTeX files in
to text documents. The diff tool that comes with SVN was Subversion') in the subdirectory /bibtex/bib/ (see figure
designed with source code in mind. As such, it is built to 1). Hence, all users can specify this bibliography by only
be more useful for files of short lines. Other tools, such using the file name (without the full path) --- no matter
as Compare It! allows to conveniently compare text files where the user’s working copy of the common texmf tree
where each line can span hundreds of characters (such as is located.
when each line represents a paragraph). When using a All users edit our bibliographic data base with the graph-
diff tool that allows convenient views of files with long ical BibTeX editor JabRef (http://jabref.sourceforge.
lines, the users can author the TeX files without a strict net/). As JabRef is written in Java, it runs on all major
line-breaking policy. operating systems. As different versions of JabRef gener-
ally save files in a slightly different way (e.g. by introduc-
ing line breaks at different positions), all users should use
the same (e.g. last stable) version of JabRef. Otherwise,
Visualizing diffs in LaTeX: latexdiff and changebar there would be many differences between different ver-
sions of .bib files that solely originate from using different
The tools latexdiff and changebar can visualize differ- version of JabRef. Hence, it would be hard to find the real
ences of two LaTeX files inside a generated document. differences between the compared documents. Further-
This makes it easier to see impact of certain changes more, the probability of conflicts would be much higher
or discuss changes with people not custom to LaTeX. (see section 'Subversion really makes the difference'). As
Changebar comes with a script chbar.sh which inserts a JabRef saves the BibTeX data base with the native new-
bar in the margin indicating parts that have changed. La- line character of the author’s operating system, it is rec-
texdiff allows different styles of visualization. The de- ommended to add the Subversion property 'svn:eol-style'
fault is that discarded text is marked as red and added and set it to 'native' (see section 'Subversion really makes
text is marked as blue. It also supports a mode similar the difference').
to Changebar which adds a bar in the margin. Latexd-
iff comes with a script latexrevise which can be used to
accept or decline changes. It also has a wrapper script
to support version control systems such as the discussed
Subversion.
An example on how to use Latexdiff in the Terminal.
latexdiff old.tex new.tex > diff.tex # Files old.tex and
new.tex are compared and the file visualizing the changes
is written to diff.tex pdflatex diff.tex # Create a PDF
showing the changes
The program DiffPDF can be used to compare two ex-
isting PDFs visually. There is also a command line tool
comparepdf based on DiffPDF. Figure 3: Specify default key pattern in JabRef
9.2. COLLABORATIVE WRITING OF LATEX DOCUMENTS 169
JabRef is highly flexible and can be configured in many the Perl script aux2bib (http://www.ctan.org/tex-archive/
details. We make the following changes to the default biblio/bibtex/utils/bibtools/aux2bib).
configuration of JabRef to simplify our work. First,
we specify the default pattern for BibTeX keys so that
JabRef can automatically generate keys in our desired 9.2.8 Conclusion
format. This can be done by selecting Options → Pref-
erences → Key pattern and modifying the desired pat- This wikibook describes a possible way to efficiently
tern in the field Default pattern. For instance, we use organise the collaborative preparation of LaTeX docu-
[auth:lower{]}{[}shortyear] to get the last name of the ments. The presented solution is based on the Subversion
first author in lower case and the last two digits of the version control system and several other software tools
year of the publication (see figure 3). and LaTeX packages. However, there are still a few is-
sues that can be improved.
First, we plan that all users install the same LaTeX distri-
bution. As the TeX Live distribution (http://www.tug.org/
texlive/) is available both for Unix and MS Windows op-
erating systems, we might recommend our users to switch
to this LaTeX distribution in the future. (Currently, our
users have different LaTeX distributions that provide a
different selection of LaTeX packages and different ver-
Figure 4: Set up general fields in JabRef sions of some packages. We solve this problem by pro-
viding some packages on our common texmf tree.)
Second, we add the BibTeX field location for informa-
tion about the location, where the publication is available Second, we consider to simplify the solution for a com-
as hard copy (e.g. a book or a copy of an article). This mon bibliographic data base. Currently it is based on
field can contain the name of the user who has the hard the version control system Subversion, the graphical Bib-
copy and where he has it or the name of a library and the TeX editor JabRef, and a file server for the PDF files of
publications in the data base. The usage of three dif-
shelf-mark. This field can be added in JabRef by select-
ing Options → Set up general fields and adding the word ferent tools for one task is rather challenging for infre-
quent users and users that are not familiar with these tools.
location (using the semicolon (;) as delimiter) somewhere
in the line that starts with General: (see figure 4). Furthermore, the file server can be only accessed by lo-
cal users. Therefore, we consider to implement an in-
tegrated server solution like WIKINDX (http://wikindx.
sourceforge.net/), Aigaion (http://www.aigaion.nl/), or
refBASE (http://refbase.sourceforge.net/). Using this so-
lution only requires a computer with internet access and
a web browser, which makes the usage of our data base
considerably easier for infrequent users. Moreover, the
stored PDF files are available not only from within the
department, but throughout the world. (Depending on
the copy rights of the stored PDF files, the access to
the server --- or least the access to the PDF files --- has
Figure 5: Specify 'Main PDF directory' in JabRef to be restricted to members of the department.) Even
Non-LaTeX users of our department might benefit from
Third, we put all PDF files of publications in a specific a server-based solution, because it should be easier to use
subdirectory in our file server, where we use the BibTeX this bibliographic data base in (other) word processing
key as file name. We inform JabRef about this subdi- software packages, because these servers provide the data
rectory by selecting Options → Preferences → External not only in BibTeX format, but also in other formats.
programs and adding the path of the this subdirectory in All readers are encouraged to contribute to this wikibook
the field Main PDF directory (see figure 5). If a PDF file by adding further hints or ideas or by providing further so-
of a publication is available, the user can push the Auto lutions to the problem of collaborative writing of LaTeX
button left of JabRef's Pdf field to automatically add the documents.
file name of the PDF file. Now, all users who have access
to the file server can open the PDF file of a publication
by simply clicking on JabRef's PDF icon. 9.2.9 Acknowledgements
If we send the LaTeX source code of a project to a jour-
nal, publisher, or somebody else who has no access to our Arne Henningsen thanks Francisco Reinaldo and Géral-
common texmf tree, we do not include our entire bibli- dine Henningsen for comments and suggestions that
ographic data base, but extract the relevant entries with helped him to improve and clarify this paper, Karsten
170 CHAPTER 9. MISCELLANEOUS
Heymann for many hints and advices regarding LaTeX, 9.3.1 Tools installation
BibTeX, and Subversion, and Christian Henning as well
as his colleagues for supporting his intention to establish This chapter features a lot of third-party tools; most of
LaTeX and Subversion at their department. them are installed independently of your TeX distribu-
tion.
Some tools are Unix-specific (*BSD, GNU/Linux and
9.2.10 References Mac OS X), but it may be possible to make them work on
Windows. If you have the choice, it is often easier with
• Fenn, Jürgen (2006): Managing citations and your Unix systems for command line tools.
bibliography with BibTeX. The PracTEX Journal,
4. http://www.tug.org/pracjourn/2006-4/fenn/. Some tools may already be installed. For instance, you
can check if dvipng is installed and ready to use (Unix
only):
• Markey, Nicolas (2005): Tame the BeaST. The B
to X of BibTeX. http://www.ctan.org/tex-archive/ which dvipng
info/bibtex/tamethebeast/ttb_en.pdf. Version 1.3. You get a directory if it is OK. [[w Most of these tools
are installable using your package manager or portage tree
• Oren Patashnik. Designing BibTeX styles. (Unix only).
http://www.ctan.org/tex-archive/info/biblio/
bibtex/contrib/doc/btxhak.pdf.
9.3.2 Preview mode
• Tools for collaborative paper-writing
This section describes how to generate a screenshot of a
LaTeX page or of a specific part of the page using the
LaTeX package preview. Screenshots are useful, for ex-
9.3 Export To Other Formats ample, if you want to include a LaTeX generated formula
on a presentation using you favorite slideware like Pow-
Strictly speaking, LaTeX source can be used to directly erpoint, Keynote or LibreOffice Impress. First, start by
generate two formats: making sure you have preview. See Installing Extra Pack-
ages.
• DVI using latex, the first one to be supported; Say you want to take a screenshot of
from DVI
Merging PDF
dvi2ps my_file.dvi
If you have created different PDF documents and you
want to merge them into one single PDF file you can use
the following command-line command. You need to have 9.3.5 Convert to RTF
Ghostscript installed:
LaTeX can be converted into an RTF file, which in turn
can be opened by a word processor such as LibreOffice
Using Windows gswin32 -dNOPAUSE -
Writer or Microsoft Word. This conversion is done
sDEVICE=pdfwrite -sOUTPUTFILE=Merged.pdf
through latex2rtf, which may run on any computer plat-
-dBATCH 1.pdf 2.pdf 3.pdf
form, however is only actively supported on Windows,
Linux and BSD, with the last mac update being from
Using Linux gs -dNOPAUSE -sDEVICE=pdfwrite 2001. The program operates by reading the LaTeX
-sOUTPUTFILE=Merged.pdf -dBATCH 1.pdf 2.pdf source, and mimicking the behaviour of the LaTeX pro-
3.pdf gram. latex2rtf supports most of the standard implemen-
tations of LaTeX, such as standard formatting, some math
Alternatively, PDF-Shuffler is a small python-gtk applica- typesetting, inclusion of EPS, PNG or JPG graphics, and
tion, which helps the user to merge or split pdf documents tables. As well, it has some limited support for packages,
and rotate, crop and rearrange their pages using an in- such as varioref, and natbib. However, many other pack-
teractive and intuitive graphical interface. This program ages are not supported.
may be avaliable in your Linux distribution’s repository.
latex2rtf is simple to use. The Windows version has a
Another option to check out is pdftk (or PDF toolkit), GUI (l2rshell.exe), which is straightforward to use. The
which is a command-line tool that can manipulate PDFs command-line version is offered for all platforms, and can
in many ways. To merge one or more files, use: be used on an example mypaper.tex file:
pdftk 1.pdf 2.pdf 3.pdf cat output 123.pdf latex mypaper bibtex mypaper # if you use bibtex la-
tex2rtf mypaper
Using pdfLaTeX Note: If you are merging external Both latex and (if needed) bibtex commands need to be
PDF documents into a LaTeX document which is com- run before latex2rtf, because the .aux and .bbl files are
piled with pdflatex, a much simpler option is to use the needed to produce the proper output. The result of this
pdfpages package, e.g.: conversion will create myfile.rtf, which you may open in
Three simple shell scripts using the pdfpages package are many word processors such as Microsoft Word or Libre-
provided in the pdfjam bundle by D. Firth. They include Office.
options to merge several pdf files (pdfjoin), put several
pages in one physical sheet (pdfnup) and rotate pages
9.3.6 Convert to HTML
(pdf90).
See also Modular Documents There are many converters to HTML.
HEVEA
XeTeX
hevea mylatexfile
You can also use XeTeX (or, more precisely, XeLaTeX),
which works in the same way as pdflatex: it creates a latex2html
PDF file directly from LaTeX source. One advantage of
XeTeX over standard LaTeX is support for Unicode and latex2html -html_version 4.0,latin1,unicode -split 1 -
modern typography. See its Wikipedia entry for more nonavigation -noinfo -title “MyDocument” MyDocu-
details. ment.tex
172 CHAPTER 9. MISCELLANEOUS
bibtex2html mybibtexfile
ps2svg
9.3.7 Convert to image formats Alternatively DVI or PDF can be converted to PS as de-
scribed before, then the bash script ps2svg.sh can be used
It is sometimes useful to convert LaTeX output to image (as all the software used by this script is multiplatform,
formats for use in systems that do not support DVI nor this is also possible in Windows, a step-by-step guide
PDF files, such as Wikipedia. could be written).
There are two family of graphics:
dvisvgm
• Vector graphics can be scaled to any size, thus do
not suffer from quality loss. SVG is a vector format. One can also use dvisvgm, an open source utility that con-
• Raster graphics define every pixel explicitly. PNG verts from DVI to SVG.
is a raster format. dvisvgm -n file.dvi
Open your file with GIMP. It will ask you which page If you want to keep the formating, you can use a DVI-to-
you want to convert, whether you want to use anti-aliasing plain text converter, like catdvi. Example:
(choose strong if you want to get something similar to catdvi yourfile.dvi | fmt -u
what you see on the screen). Try different resolutions to
fit your needs, but 100 dpi should be enough. Once you The use of fmt -u (available on most Unices) will remove
have the image within GIMP, you can post-process it as the justification.
you like and save it to any format supported by GIMP, as
PNG for example.
dvipng
ImageMagick
optipng
174
10.1. FAQ 175
if it looks right the first time, the content is likely to ren- not have more weight than normal characters, so they are
der really badly if you change anything before the point usually a better choice for emphasizing small amounts of
you manually formatted. text.
The only place where page breaks are recommended is at The original and more appropriate use of bold and under-
the upper level of sectioning in your documents, e.g. parts line is for special parts, such as headers, the index, glos-
or chapters (although when you start a new part or chap- saries, and so on. (Actually, underlining is rarely used in
ter, LaTeX will ordinarily do this for you). When you do professional environments.)
manually insert a page break, you should use \clearpage LaTeX has a macro \emph{...} for emphasizing text us-
or \cleardoublepage which print currently floating figures ing italics. It should be preferred to \textit{...} because
before starting a new page. \emph{...} will correctly print emphasized text inside
If you absolutely have to insert line or page breaks man- other italic text in the regular font.
ually, you should do it after you are sure you have com-
pleted your document otherwise, so that you don't later
have to come back and update it. 10.1.10 The proper way to use figures
10.1.14 Learning LaTeX quickly or cor- 10.1.17 Use vector graphics rather than
rectly raster images
Nowadays it is very common to “learn” on the web by us- Raster (bitmap) graphics scale poorly and often create
ing a search engine and copying and pasting things here jagged or low-quality results which clash with the doc-
and there. As with every programming language, this is ument quality, particularly when printed.
generally a poor method which will lead to lack of control,
Using vector (line-oriented) graphics instead, either
unexpected results, and a lot of frustration. Really learn-
through LaTeX’s native diagramming tools or by export-
ing LaTeX is not that difficult and does not take that long.
ing vector formats from your drawing or diagramming
Most chapters in this book are dedicated to a specific us-
tools, will produce much higher quality results. When
age, so the basics are actually covered very quickly.
possible, you should prefer PDF, EPS, or SVG graphics
If you are getting frustrated with a specific package, make over PNG or JPG.
sure you read its official documentation, which is usually
the best source of information. Content found on the web,
even in this book, is rarely as accurate as the official docu-
mentation. Inaccurate information might result in causing 10.1.18 Stretching tables
mistakes without you understanding why.
The time you spend learning is worth it, and it quickly Trying to stretch tables with the default tabular environ-
makes up for the time you would lose if you don't learn ment will often lead to unexpected results. The nice tabu
things properly and end up stuck all the time. package will do what you want and even much more. Al-
ternatively if you cannot use the tabu package you may
try tabularx or tabulary packages See Tables.
10.1.15 Non-breaking spaces
exceptions.
In early days, LaTeX users used Xfig for their drawings.
The editor is still used by quite a few people nowadays
because it has special 'export to LaTeX' features. It also
gives you some very basic ways of encapsulating LaTeX
text and math in the image (setting the text’s 'special flag'
to 'special' instead of 'normal'). When exporting, all La-
TeX text will be put in a .tex-file, separately from the rest
of the image (which is put in a .ps file).
A newer and easier-to-use vector image editor specially
tailored to LaTeX use is IPE. It allows any LaTeX com-
mand, including but not limited to mathematical formu-
lae in the image. The program saves its files as editable 3
2.5
.eps or .pdf files, which eliminates the need of exporting 2
-1.5 1.5
your image each time you have edited it. -1 1
-0.5 0.5
A very versatile vector image editor is Inkscape. It does 0 0
0.5
not support LaTeX text by itself, but you can use the plu- 1
1.5
gin Textext for that. This allows you to put any block of
LaTeX code in your image. Additionally since version
gnuplot can plot various numerical data, functions, error distri-
0.48 you can export to vectorgraphics with texts sepa- bution as well as 3D graphs and surfaces
rated in a .tex file. Using this way text is rendered by the
latex compiler itself.
LaTeXDraw is a free and open source graphical PSTricks set format "$%g$" set title “Graph 3: Dependence
generator and editor. It allows you to draw basic geomet- of $V_p$ on $R_0$" set xlabel “Resistance $R_0$
ric objects and save the result in a variety of formats in- [$\Omega$]" set ylabel “Voltage $V_p$ [V]" set border 3
cluding .jpg, .png, .eps, .bmp as well as .tex. In the last set xtics nomirror set ytics nomirror set terminal epslatex
case the saved file contains PSTricks/LaTeX code only. set output “graph1.eps” plot “graph1.csv” using 1:3 #Plot
Owing to that you can include any possible LaTeX code the data
in the picture, since the file is rendered by your LaTeX
Now gnuplot produces two files: the graph drawing in
environment directly.
graph.eps and the text in graph.tex. The second includes
Another way to generate vectorgraphics is using the the EPS image, so that we only need to include the file
Asymptote language. It is a programming language graph.tex in our document:
which produces vector images in encapsulated postscript
\input{graph1.tex}
format and supports LaTeX syntax in any textlabels.
The above steps can be automated by the package gnu-
plottex. By placing gnuplot commands inside \be-
Graphs with gnuplot gin{gnuplot}\end{gnuplot}, and compiling with latex -
shell-escape, the graphs are created and added into your
A simple method to include graphs and charts in LaTeX document.
documents is to create it within a common spreadsheet
software (OpenOffice Calc or MS Office Excel etc.) and Failure to access gnuplot from latex for Windows can be
include it in the document as a cropped screenshot. How- solved by making file title only in one word. Don't type
ever, this produces poor quality rasterized images. Calc my report.tex for your title file, but do myreport.tex .
also allows you to copy-paste the charts into OpenOffice When you are using gnuplottex it is also possible to di-
Draw and save them as PDF files. rectly pass the terminal settings as an argument to the en-
Using Microsoft Excel 2010, charts can be copied di- vironment
rectly to Microsoft Expression Design 4, where they can \begin{gnuplot}[terminal=epslatex, terminalop-
be saved as PDF files. These PDF files can be included tions=color, scale=0.9, linewidth=2 ] ... \end{gnuplot}
in LaTeX. This method produces high quality vectorized
images. Using gnuplottex can cause fraudulent text-highlighting in
some editors when using algebraic functions on imported
An excellent method to render graphs is through gnuplot, data, such as:
a free and versatile plotting software, that has a special
output filter directly for exporting files to LaTeX. We as- (2*($1)):2
sume, that the data is in a CSV file (comma separated Some editors will think of all following text as part of a
text) in the first and third column. A simple gnuplot script formula and highlight it as such (because of the '$' that is
to plot the data can look like this: interpreted as part of the latex code). This can be avoided
10.2. TIPS AND TRICKS 179
See Export To Other Formats. If you want to put a sidebar with information like copy-
right and author, you might want to use the eso-pic pack-
age. Example:
10.2.6 Spell-checking and Word Counting \usepackage{eso-pic} ... \AddToShipoutPic-
ture{% \AtPageLowerLeft{% \rotatebox{90}{%
If you want to spell-check your document, you can use \begin{minipage}{\paperheight} \center-
the command-line aspell, hunspell (preferably), or ispell ing\textcopyright~\today{} Humble me \end{minipage}
programs. % } } % }%
ispell yourfile.tex aspell --mode=tex -c yourfile.tex hun-
spell -l -t -i utf-8 yourfile.tex If you want it on one page only, use the starred version of
All three understand LaTeX and will skip LaTeX com- the AddToShipoutPicture command at the page you want
mands. You can also use a LaTeX editor with built-in it. (\AddToShipoutPicture*{...})
spell checking, such as LyX, Kile, or Emacs. Last another
option is to convert LaTeX source to plain text and open
10.2.9 Hide auxiliary files
resulting file in a word processor like OpenOffice.org or
KOffice. If you're using pdflatex you can create a folder in which
If you want to count words you can, again, use LyX or all the output files will be stored, so your top directory
convert your LaTeX source to plain text and use, for ex- looks cleaner.
ample, UNIX wc command: pdflatex -output-directory tmp
detex yourfile | wc
An alternative to the detex command is the pdftotext Please note that the folder tmp should exist. However if
command which extracts an ASCII text file from PDF: you're using a Unix-based system you can do something
1. pdflatex yourfile.tex 2. pdftotext yourfile.pdf 3. wc like this:
yourfile.txt alias pdflatex='mkdir -p tmp; pdflatex -output-directory
180 CHAPTER 10. HELP AND RECOMMENDATIONS
tmp'
Appendix
181
182 CHAPTER 11. APPENDIX
• Vel’s introduction to LaTeX: What is it, why should • The Comprehensive LaTeX Symbol List (in PDF)
you use it, who should use it and how to get started: http://www.ctan.org/tex-archive/info/symbols/
http://www.vel.co.nz/vel.co.nz/Blog/Entries/2009/ comprehensive/symbols-a4.pdf
11/4_LaTeX_Document_Preparation_System.
html • Getting to Grips with LaTeX (HTML) Collection
of Latex tutorials taking you from the very basics
• Peter Flynn’s beginner’s guide (formatting): towards more advanced topics
http://www.ctan.org/tex-archive/info/beginlatex/ http://www.andy-roberts.net/misc/latex/index.html
beginlatex-3.6.pdf
• Chapter 8 (about typesetting mathematics) of the
• The AMS Short Math Guide for LaTeX, a concise LaTeX companion
summary of math formula typesetting features http://www.macrotex.net/texbooks/
http://www.ams.org/tex/amslatex.html latexcomp-ch8.pdf
• amsmath users guide (PDF) and related files:
http://www.ctan.org/tex-archive/macros/latex/ Reference
required/amslatex/math/
• LaTeX Project Site
• LaTeX Primer from the Indian TeX Users Group:
http://sarovar.org/projects/ltxprimer/ • The Comprehensive TeX Archive Network Latest
(La)TeX-related packages and software
• LaTeX Primer
http://www.maths.tcd.ie/~{}dwilkins/ • TeX Directory Structure, used by many (La)TeX
LaTeXPrimer/ distributions
• PSTricks--fancy graphics exploiting PDF capabili- • Natural Math converts natural language math for-
ties mulas to LaTeX representation
http://sarovar.org/projects/pstricks/
• Obsolete packages and commands
• PDFScreen--create LaTeX PDF files that have nav-
igation buttons used for presentations: • Lamport’s book LaTeX: A Document Preparation
http://sarovar.org/projects/pdfscreen/ System
11.5.6 F 11.5.10 L
• Figures • Labels
• Floats • Letters
• Fonts • Links
• Footnotes
11.5.11 M
• Formatting
• makeidx package
11.5.7 G • \maketitle
• Creating • Mathematics
• Embedding • Matrices
• Importing
• Minipage environment example
• graphicx package
• Multi-column Pages
11.5.8 H
11.5.12 P
• Header, Page
• Packages
• HTML output
• Creating 1
• Hyperlinks
• Page Layout
• hyperref package
• PDF output
• hyphen
• picture
• Hyphenation
• Pictures
• PNG output
11.5.9 I
• Presentations
• i.e. (id est)
• Pseudocode
• Images
• Introduction 11.5.14 R
• Italics • References
11.5.15 S 11.6.1 #
• Sentences / see slash marks
• Small Capitals \@ following period ends sentence
• Source Code Listings \\[*][extra-space] new line
• Superscript and subscript: powers and indices \: medium space, math mode
• Superscript and subscript: text mode \! negative thin space, math mode
• URLs
11.6.2 A
11.6.3 B 11.6.6 E
\backslash prints a backslash \em Toggles italics on/off for the text inside curly braces
with the command. Such as {\em This is in italics
\baselineskip a length command (see Lengths), which
\em but this isn't \em and this is again}. This com-
specifies the minimum space between the bottom of
mand allows nesting.
two successive lines in a paragraph
\baselinestretch scales the value of \baselineskip \emph Toggles italics on/off for the text in curly braces
following the command e.g. \emph{This is in italics
\bf Boldface typeface \emph{but this isn't} and this is again}.
\bibitem generates a labeled entry for the bibliography \ensuremath (LaTeX2e) Treats everything inside the
\bigskipamount curly braces as if it were in a math environment.
Useful when creating commands in the preamble as
\bigskip equivalent to \vspace{\bigskipamount} they will work inside or out of math environments.
\boldmath bold font in math mode \epigraph Adds an epigraph. Requires epigraph pack-
\boldsymbol bold font for symbols age.
\euro Prints euro € symbol. Requires eurosym pack-
11.6.4 C age.
11.6.5 D 11.6.8 G
\dashbox 11.6.9 H
\date
\hfill Abbreviation for \hspace{\fill}.
\ddots Inserts a diagonal ellipsis (3 diagonal dots) in
math mode \hline adds a horizontal line in a tabular environment.
See also \cline, Tables chapter.
\documentclass[options]{style} Used to begin a latex
document \href Add a link, or an anchor. See Hyperlinks
\dotfill \hrulefill
11.6. COMMAND GLOSSARY 187
\Huge Sets font size. See Text Formatting. \listoffigures Inserts a list of the figures in the docu-
ment. Similar to TOC
\hyphenation{word list} Overrides default hyphenation
algorithm for specified words. See Hyphenation \listoftables Inserts a list of the tables in the document.
Similar to TOC
11.6.10 I \location
\LaTeXe Prints current LaTeX version logo. See \newline Ends current line and starts a new one. See
Formatting. Page Layout.
\ldots Prints sequence of three dots. See Formatting. \newpage Ends current page and starts a new one. See
Page Layout.
\left
\newsavebox
\lefteqn
\newtheorem
\line
\nocite Adds a reference to the bibliography without an
\linebreak Suggests LaTeX to break line in this place. inline citation. \nocite{*} causes all entries in a bib-
See Page Layout. tex database to be added to the bibliography.
188 CHAPTER 11. APPENDIX
\noindent 11.6.17 Q
\nolinebreak \quad Similar to space, but with the size of a capital M
\nonfrenchspacing Setting the command untoggles the
\qquad double \quad
command \frenchspacing and activates LaTeX stan-
dards to insert more space after a period (´.´) than
after an ordinary character. 11.6.18 R
\normalsize Sets default font size. See Text Formatting.
\raggedbottom Command used for top justified within
\nopagebreak Suggests LaTeX not to break page in this other environments.
place. See Page Layout.
\raggedleft Command used for right justified within
\not other environments.
\roman
11.6.16 P \rule Creates a line of specified width and height. See
LaTeX/Rules and Struts.
\pagebreak Suggests LaTeX breaking page in this
place. See Page Layout.
\pagenumbering Defines the type of characters used 11.6.19 S
for the page numbers. Options : arabic, roman, Ro-
man, alph, Alph, gobble (invisible). \savebox Makes a box and saves it in a named storage
bin.
\pageref Used to reference to number of page where
a previously declared \label is located. See Floats, \sbox The short form of \savebox with no optional ar-
Figures and Captions. guments.
\subsubsection Starts a new sub-subsection. See \uline Underlines text. Requires ulem package. See
Document Structure. Formatting.
\underbrace
11.6.20 T \underline
\tableofcontents Inserts a table of contents (based on \unitlength
section headings) at the point where the command
appears. \usebox
\textwidth
Chapter 12
12.1 Text
• LaTeX/Introduction Source: https://en.wikibooks.org/wiki/LaTeX/Introduction?oldid=2986065 Contributors: Ævar Arnfjörð Bjarma-
son, Tualha, Iamunknown, 3mta3, Jraregris, Goodgerster, Derbeth, Graemeg~enwikibooks, Elwikipedista~enwikibooks, Withinfocus, Pde-
long, Orderud, Whiteknight, Kernigh, Latexing, Sgenier~enwikibooks, Igjimh, Alejo2083, Chazz, Gronau~enwikibooks, Xania, Rehoot,
Sjlegg, Conrad.Irwin, Urhixidur, Nbrouard, Vadik wiki, Pi zero, Dan Polansky, Waldir, QuiteUnusual, Piksi, Kri, Mckay, Tom Morris,
Avila.gas, Nobelium, Ambrevar, Martinkunev, PAC2, Anarchyboy, Tomato86, Staticshakedown, E.lewis1, InverseHypercube, Polytropos
Technikos, Torbjorn T., TinyTimZamboni, AllenZh, Ppadmapriya, Benson Muite, Steelangel, Reddraggone9 and Anonymous: 75
• LaTeX/Installation Source: https://en.wikibooks.org/wiki/LaTeX/Installation?oldid=2986066 Contributors: 3mta3, Koavf, Michael-
Billington, Mwtoews, Bryant1410, Pi zero, Marcus Cyron, Gyro Copter, Kazkaskazkasako, QuiteUnusual, Nobelium, Ambrevar, PAC2,
Jason barrington~enwikibooks, Mfwitten, Tomato86, Benregn, Torbjorn T., LlamaAl, Hahc21, RainCity471, Leaderboard, Dplaza000,
Simplelatex, Alansandiego and Anonymous: 41
• LaTeX/Installing Extra Packages Source: https://en.wikibooks.org/wiki/LaTeX/Installing_Extra_Packages?oldid=2771441 Contribu-
tors: Alejo2083, Az1568, Xania, Pi zero, Zylorian, Ollydbg, Mabdul, Ambrevar, Lotus noir, Netheril96, DarkSheep, Dplaza000 and
Anonymous: 21
• LaTeX/Basics Source: https://en.wikibooks.org/wiki/LaTeX/Basics?oldid=2979079 Contributors: Krischik, Chuckhoffmann, 3mta3,
ABCD, Derbeth, Jonathan Webley, Withinfocus, Snaxe920~enwikibooks, Jtwdog~enwikibooks, Tpr~enwikibooks, Jguk, Bilbo1507,
Igjimh, Dilaudid, Alejo2083, Mwtoews, Thenub314, Rehoot, Vadik wiki, Qeny, Atallcostsky, Pi zero, Waldir, MER-C, TomyDuby,
CrazyTerabyte, Kri, Adrignola, Constantine, Ambrevar, PAC2, Chisophugis, Immae, Janskalicky, Tomato86, Robbiemorrison, E.lewis1,
BrettMontgomery, Guyrobbie, Patuck, ATC2~enwikibooks, DragonLord, Guzo, Wickedjargon, Pater Christophorus, Johannes Bo, Red-
draggone9, Negative24, Dplaza000 and Anonymous: 82
• LaTeX/Document Structure Source: https://en.wikibooks.org/wiki/LaTeX/Document_Structure?oldid=2988234 Contributors: Derbeth,
Withinfocus, Orderud, Stephan Schneider, Snaxe920~enwikibooks, Jtwdog~enwikibooks, Jomegat, Nkour, Igjimh, Dilaudid, Alejo2083,
JECompton~enwikibooks, Mwtoews, BiT, Thenub314, ConditionalZenith~enwikibooks, Xania, FlashSheridan, Spelemann~enwikibooks,
Kovianyo, Recent Runes, Astrophizz~enwikibooks, Spag85~enwikibooks, Pi zero, Tully~enwikibooks, Waldir, Nux, Jan Winnicki, Quite-
Unusual, Neet, Kri, Lovibond, Adrignola, Hosszuka, Wdcf, Ambrevar, DagErlingSmørgrav, Lucasreddinger, Keplerspeed, Dirk Hünniger,
Frap, Tomato86, Derwaldrandfoerster, Echeban, Torbjorn T., LlamaAl, Ntypanski, Wickedjargon, Genethecist, Johannes Bo, Reddrag-
gone9, Kurlovitsch, Kw CUACS.TOPS and Anonymous: 77
• LaTeX/Text Formatting Source: https://en.wikibooks.org/wiki/LaTeX/Text_Formatting?oldid=2972771 Contributors: Derbeth, Within-
focus, Igjimh, Thenub314, Pi zero, ChrisHodgesUK, Adrignola, Ambrevar, Dirk Hünniger, Robbiemorrison, Fishix, Bgeron, RubensMatos,
Leaderboard, Kurlovitsch, Lindhea, Kevin Ryde and Anonymous: 20
• LaTeX/Paragraph Formatting Source: https://en.wikibooks.org/wiki/LaTeX/Paragraph_Formatting?oldid=2953044 Contributors:
Ish ishwar~enwikibooks, ABCD, Derbeth, QuantumEleven, Jonathan Webley, Withinfocus, Orderud, Jtwdog~enwikibooks,
Andyr~enwikibooks, Igjimh, Alejo2083, Mwtoews, Thenub314, ConditionalZenith~enwikibooks, Mcld, Kovianyo, MartinSpacek,
Crasshopper, Recent Runes, Pi zero, Tully~enwikibooks, Ffangs, Hjsb, Yez, Waldir, CarsracBot, Hannes Röst, Rror, Adri-
anwn, ChrisHodgesUK, Pstar, QuiteUnusual, Neet, LR~enwikibooks, Adrignola, Nixphoeni, PatrickDevlin21, Ambrevar, Zzo38,
Cdecoro, Keplerspeed, Zrisher, GPHemsley, Henrybissonnette, TorfusPolymorphus, Smobbl Bobbl, ToematoeAdmn, Dirk Hünniger,
Mouselb, EvanKroske, Tomato86, Fishpi, Robbiemorrison, Tazquebec, Brammers, Listdata, Neoriddle, Xonqnopp, C3l, Harrikoo,
Gmh04~enwikibooks, InverseHypercube, Halilsen, RealSebix, Akim Demaille, Dlituiev, SamuelLB, CD-Stevens, Incognito668, Gmacar,
Dplaza000 and Anonymous: 144
• LaTeX/Colors Source: https://en.wikibooks.org/wiki/LaTeX/Colors?oldid=2964184 Contributors: Alejo2083, Xania, Pi zero, Dan Polan-
sky, Daniel Mietchen, Waldir, Gms, JackPotte, White gecko, ChrisHodgesUK, Kazkaskazkasako, Trace, QuiteUnusual, Kri, Adrig-
nola, Benjaminevans82~enwikibooks, ChristianGruen, Sanderd17, Scorwin, Ambrevar, PAC2, Velociostrich, Dirk Hünniger, Tomato86,
Conighion, Qzxpqbp, SamuelLB, Henry Tallboys, Nicolas Perrault III, Tisep, Tpapastylianou, Honza889, Dplaza000, David Gaudet and
Anonymous: 51
• LaTeX/Fonts Source: https://en.wikibooks.org/wiki/LaTeX/Fonts?oldid=2989509 Contributors: Ish ishwar~enwikibooks, Derbeth, Xa-
nia, Jacho, Mihai Capotă, Joaospam, Pi zero, Waldir, ChrisHodgesUK, Dreaven3, Ambrevar, Wikieditoroftoday, Crissov, InverseHyper-
cube, Flamenco108, SamuelLB, BYIST, TortoiseWrath, Abramsky, Ben9243 and Anonymous: 32
190
12.1. TEXT 191
12.2 Images
• File:50_percents.svg Source: https://upload.wikimedia.org/wikipedia/commons/6/62/50_percents.svg License: CC0 Contributors: File:
50%.svg Original artist: Ftiercel
194 CHAPTER 12. TEXT AND IMAGE SOURCES, CONTRIBUTORS, AND LICENSES