You are on page 1of 26

Introductory LATEX — Dr Ha Quoc Trung

Teaching materials are produced using the materials given by Dr Nicola L. C. Talbot
at http://theoval.cmp.uea.ac.uk/~nlct

Everyone learns at a different rate, some people find they need a bit more time to absorb new ideas, whereas
others like to steam ahead. If you find yourself struggling, just do the parts of the exercises marked e . If you’re
speeding ahead, try doing the additional bits, marked ! .

1 Creating a Document
At the start of any LATEX 2ε file, you must have the command

\documentclass[options]{class}

which declares what class file to use. For example:


\documentclass[a4paper,12pt]{article}

All the text that is actually contained in the document must be enclosed in a document environment:
\begin{document}
specifies the start of the document, and
\end{document}

specifies the end of the document.


All LATEX documents must have the following three lines:

\documentclass[a4paper,12pt] {article}

\begin{document}

\end{document}
The italic text may change, but the rest must occur exactly as above.

Exercise 1
Let’s start with a very simple example. Figure 1 on page 2 shows the contents of the file exercise1.tex. Try
creating this file as described in the slides. Note that not only are we specifying A4 paper, but we are also specifying
12 point text, rather than the default 10 point text.
Once you have finished typing up the source code, LATEX your document as described in the slides. You should
now find three additional files in your directory: exercise1.aux, exercise1.log and exercise1.dvi. The .aux
file is the auxiliary file, LATEX uses it to store information it uses for cross-referencing and citations. The .log file
is the log file, LATEX writes to that file everything that you saw on the screen when you LATEXed the file, plus some
additional information. The .dvi file is the typeset document, which you can now load into the DVI viewer.

Self Assessment

• Did you remember to force a space after the command \LaTeX?

• Did you notice that the text has automatically been fully justified, and the page number has automatically
appeared at the foot of the page?

Introductory LATEX N.L.C.T. 1


% exercise1.tex - a simple example file illustrating basic input

e \documentclass[a4paper,12pt]{article}

e \begin{document}

e This is a simple example that shows how easy it is to create a


e \LaTeX\ file.
Note that the page is automatically numbered at the bottom.
Anything following a percent sign (\%) is ignored up to the end of
the line. %This is a comment, and will not appear in the document.
e Today’s date is \today.
e
This is the start of the second paragraph.
e Footnotes are easy\footnote{Here is a footnote}.
It is possible to have notes in the margin\marginpar{like this}.

e \end{document}

Figure 1: Contents of the file exercise1.tex. If you are struggling, just do the lines beginning with e

2 Simple Font Changing Commands


You can either change the font of a specific group of text using a command (Table 1), or switch to a different font
for the remainder of the current group using a declaration (Table 2 on page 2). You can switch to a different font
size using one of the declarations shown in Table 3 on page 3. Environments can also be used by using the name of
the corresponding declaration without the backslash (Table 4 on page 3).

Table 1: Font Changing Commands

Command Sample Input Sample Output

z
\textrm{text} \textrm{Roman} Roman
Sans serif Family Weight
}| {z }| {z
\textsf{text} \textsf{Sans serif}
\texttt{text} \texttt{typewriter} typewriter
\textmd{text} \textmd{medium} medium
\textbf{text} \textbf{bold} bold
\textup{text} \textup{upright} upright
\textit{text} \textit{italic} italic
Shape

slanted
}|

\textsl{text} \textsl{slanted}
\textsc{text} \textsc{Small Caps} Small Caps
\emph{text} \emph{emphasized} emphasized
{

\textnormal{text} \textnormal{default} default

Exercise 2
Go back to the file you created in Exercise 1 and typeset the first paragraph in a large sans serif font, but keep
the second paragraph in normal sized Roman font. Once you have done this, emphasize the word “Footnotes” in the
second paragraph, and then change the entire second paragraph to italic.

Introductory LATEX N.L.C.T. 2


Table 2: Font Changing Declarations

Declaration Sample Input Sample Output

z
\rmfamily \rmfamily Roman Roman

Family Weight
Sans serif

}| {z }| z{
\sffamily \sffamily Sans serif
\ttfamily \ttfamily typewriter typewriter
\mdseries \mdseries medium medium
\bfseries \bfseries bold bold
\upshape \upshape upright upright
\itshape \itshape italic italic

Shape
}|
\slshape \slshape slanted slanted
\scshape \scshape Small Caps Small Caps
\em \em emphasized emphasized

{
\normalfont \normalfont default default

Table 3: Font Size Declarations


\tiny tiny text

\scriptsize script sized text


\footnotesize footnote sized text
\small small text
\normalsize normal sized text
\large large text
\Large even larger
\LARGE larger still
\huge huge
\Huge really huge

Table 4: Font Environments


rmfamily sffamily ttfamily mdseries bfseries
upshape itshape slshape scshape em
tiny scriptsize footnotesize small normalsize
large Large LARGE huge Huge

Introductory LATEX N.L.C.T. 3


Self Assessment

• How did you set the first paragraph in sans serif? Did you use a command, a declaration or an environment?
Which do you think is best for a large body of text?
• When you typeset the second paragraph in italic, did the emphasized text come out in an upright font?

3 Punctuation, Accents and Symbols


Standard symbols are shown in Table 5. Note that spaces are ignored after commands made up of a backslash
followed by alphabetic characters (e.g. \pounds 10 produces £10) but not after commands made up of a backslash
followed by a symbol (e.g. \# 10 produces # 10).

Table 5: Symbols

\pounds £ \ \P ¶ - -
\copyright c \$ $ \S § -- –
\ddag ‡ \{ { \ldots ... --- —
\dag † \} } \i ı ?‘ ¿
\textregistered
R \# # \j  !‘ ¡
TM
\texttrademark \% % ’ ’ ’’ ”
\yen U \& & ‘ ‘ ‘‘ “

Accents are placed over the specified letter using accent commands (Table 6). Ligatures and foreign symbols are
shown in Table 7.

Table 6: Accent commands


Example Example
Definition Input Output Definition Input Output
\’{object} \’{c} ć \={object} \={c} c̄
\‘{object} \‘{c} c̀ \.{object} \.{c} ċ
\^{object} \^{c} ĉ \~{object} \~{c} c̃
\"{object} \"{c} c̈ \v{object} \v{c} č
\u{object} \u{c} c̆ \H{object} \H{c} c̋
\t{object} \t{cc} cc \c{object} \c{c} ç
\d{object} \d{c} c. \b{object} \b{c} c
¯

Table 7: Ligatures and Foreign Symbols

\AE Æ \ae æ \OE Œ \oe œ


\AA Å \aa å \L L \l l
\O Ø \o ø \SS SS \ss ß

Exercise 3
Using the appropriate commands, create a LATEX document that will produce the output shown in Figure 2.

Introductory LATEX N.L.C.T. 4


Naı̈ve people who eat fluffy pâté end up manœuvring themselves towards the bathroom,
resulting in an æger.
“The façade is my piéce de resistance, do you like it? It cost £1000.00 — 10% under
budget.”
“It’s a bit passé.”
! He had a feeling of déjà vu on seeing Chlöe Müller, née Hřebı́ček, wearing a fine négligé
to the matinée.
! “¿Dónde esta el cuarto de baño?”

Figure 2: Exercise 3 — Accents and Symbols. Sentences marked ! are for the more adventurous.

Self Assessment

• Did you notice the fl, ff and fi ligatures?

• Did you notice the œ and æ ligatures?


• Did you remember to use an em dash instead of a hyphen?

4 Document Classes and Sectioning Commands


There are hundreds of class files, but the basic ones are: article, report, book, slides and letter. The standard sectioning
commands available are:
\part[short title]{Title} \subsubsection[short title]{Title}
\chapter[short title]{Title} \paragraph[short title]{Title}
\section[short title]{Title} \subparagraph[short title]{Title}
\subsection[short title]{Title}

Some of these commands may not be available to certain class files (e.g. the article class file has no \chapter
command.) Numbering is done automatically, but the number can be omitted by appending an asterisk after the
command name (e.g. \chapter*{Acknowledgements}). Abstracts should be placed in the abstract environment.
The document’s title information is first stored using the commands:

\author{Author Names}
\title{Document Title}
\date{Date}

The information is then displayed using the command:

\maketitle

To switch to appendices, use the command:

\appendix

and continue using \chapter, \section etc. The table of contents can be produced using the command:

\tableofcontents

This command typically goes after \maketitle.


Page numbers are produced automatically. The page style can be changed using the command

\pagestyle{style}

“from this point onwards”, or using the command

\thispagestyle{style}

Introductory LATEX N.L.C.T. 5


to change the style of the current page only. Common styles are: plain, empty and headings.
The style of the page numbers can be changed using the command:

\pagenumbering{style}

where style can be one of: arabic, roman, Roman, alph or Alph. This command will also reset the page number to
one.

Exercise 4
For this exercise, you will need to copy the file sectioning.tex, as per the instructions on the slides. Load this
file into the editor: you should see that it contains the text from a short document, however it does not yet contain
the sectioning commands. Comments have been inserted into appropriate parts of the file denoting the title and
authors of the document, the abstract, and the start of new chapters and sections. Use the appropriate commands
to create the title, table of contents, chapters and sections. You will also need to use the abstract environment to
correctly format the abstract. For example, where you see the comment
% CHAPTER : Introduction
insert

\chapter{Introduction}
on the following line.
! Try adding an appendix, and experiment with changing the page style. When you changed the page style did
all the pages change? The command \thispagestyle overrides \pagestyle so certain pages will not be affected by
\pagestyle. (For example, the title page should be empty, regardless of the style of the rest of the document.) The
front matter (table of contents etc) usually has lowercase Roman numbering, whereas the main document usually
has Arabic numbering. See if you can change the page numbering style.

5 Paragraph Formatting
Paragraphs are fully justified by default, but this can be changed, either using a declaration or an environment.
Declaration \raggedright \raggedleft \centering
Environment flushleft flushright center
You can centre a single line of text using the command:

\centerline{text}

Lines can be broken, without justification, using either \\[text] or \newline. Justified line breaks can made using
the command \linebreak[n] where n is a value from 0 to 4. You can prevent a linebreak using \nolinebreak[n].
Again, n can be an integer from 0 to 4. If you want to have a space, but you don’t want a line break to occur at
that space, you can use an “unbreakable space” which is produced using the tilde special character: ~.
You can force a ragged page break using the command:

\newpage

or you can force a page break with vertical justification using the command:

\pagebreak[n]

or prevent a page break occurring:

\nopagebreak[n]

The command

\clearpage

is similar to \newpage, but forces all unprocessed floats (see Section 19) to be immediately processed.

Introductory LATEX N.L.C.T. 6


Exercise 5
Try to reproduce the output shown in Figure 3. You need to decide whether to use environments, commands or
declarations.

This paragraph here is fully justified, but note how we have


forced the end of the line to occur before the word “forced”.

These lines
are centred.

Here we have some


left justified
text.

Here we have some


right justified
text.

This text is centered.

Figure 3: Exercise 5 — Formatting

Self Assessment

• Did you force a line break on the first line? Can you see that this line has been fully justified, but there is a
lot of blank space between the words? If you look when you LATEX the file, you should see something like

Underfull \hbox (badness 6316) in paragraph at lines 7--9


[]\OT1/cmr/m/n/10 This para-graph here is fully jus-ti-fied,
but note how we have

This is LATEX complaining about the excessive white space. Where would the line have ended if you hadn’t
forced the line break?
• What do you think is the best way to centre the last line? Did you use \centering, the center environment,
or \centerline{}?

6 Defining New Commands


To define a new command use:

\newcommand{cmd-name}[nargs][default]{text}

where cmd-name is the name of the new command (remember the backslash), nargs is the numbers of arguments the
new command takes (default 0), default is the default value for the first argument should an optional argument be
required and text is what LATEX should do every time it encounters this command. If nargs is greater than 0, each
argument is represented by #1, #2 etc.
Existing commands can be redefined using \renewcommand instead of \newcommand, but never redefine a com-
mand whose existing meaning is unknown to you. You should only redefine a command if you want to modify the
behaviour of that command. For example, if you want to change the way \today formats the current date (see later)
you would need to redefine \today, however if you want a command to display a specific date, you would need to
define a new command.

Introductory LATEX N.L.C.T. 7


Exercise 6
Create a new document called, say exercise6.tex, and define the command \timeofday. (Note: ensure
that you call the command \timeofday, not \time as this command already exists.) The command should take
two parameters, the first is the hour and the second is the number of minutes past the hour. The command
\timeofday{10}{25} should produce the output: 10:25. (It is best to define this command in the preamble.) Once
you have defined the command, you now need to use it, so create the output shown in Figure 4 where the times are
produced using the \timeofday command. Once you have done this, change the definition of the command so that
the time is displayed in bold, and the hours and minutes are separated using a dash instead of a colon (e.g. 10-00
instead of 10:00).

The Introductory LATEX course runs for four days from 10:00 to 13:00, with a coffee break
at 11:30.

Figure 4: Output for Exercise 6

Self Assessment

• Did you remember to define the command \timeofday?

• Did you use this command to display the times? (You should have used this command three times.)
• Did you modify your definition of \timeofday so that the times are formatted differently?

7 Alternative Output Formats


LATEX saves the formatted document in a DVI (device independent) file. However, it is possible to change to a
different format. DVI files can be converted to PostScript by clicking on the “dvips” button The PostScript file can
either be sent directly to a PostScript printer, or can be loaded into kghostview where you can preview it and send
it to a non-PostScript printer.
The proliferation of the world wide web has encouraged many authors to create PDF documents which can be
viewed in Adobe’s Acrobat Reader. PostScript files can be converted to PDF using ps2pdf. Alternatively, PDF output
can be obtained from LATEX documents using PDFLaTeX instead of LATEX. If you use either dvips or PDFLATEX,
you can:

• Include images in your document


• have color
te
ta

• tcefler or resize text.


ro

With PDFLATEX, you can also have active links (or hyperlinks) in your document.

Exercise 7
Try converting the document (sectioning.tex) that you modified in Exercise 4 into a PostScript file, and view
it using kghostview. Also, try creating a PDF version using PDFLATEX.

8 Lists
There are three standard list making environments: itemize (unordered list), enumerate (ordered list) and description
(named list). Within each of these environments, you must have the \item command at the start of each entry
within the list. It is also possible to nest the list making environments. The itemize command uses symbols to label

Introductory LATEX N.L.C.T. 8


each item, the enumerate environment uses numbers or letters to label each item, and the description environment
does not label each item by default. You can override the default label using the optional argument to \item.

Exercise 8
Create a document that produces the output shown in Figure 5, and save it as exercise8.tex.
! Once you have done this, change all your enumerate environments to itemize environments. The default labels
for each level of nested itemize environments are: • – ∗ and ·. These are produced by the commands: \labelitemi,
\labelitemii, \labelitemiii and \labelitemiv. Try redefining \labelitemi so that the outer itemize items are
labelled with the † symbol instead of •, and redefine \labelitemii so that the next level items are labelled with the
§ symbol.

1. Animal
(a) Mammals
(b) Birds
(c) Reptiles. For example:
i. dinosaurs
ii. crocodiles

2. Vegetable
(a) Cultivated
(b) Wild
3. Mineral

Figure 5: Exercise 8 — Lists

9 Tabulated Material
Material can be aligned in rows and columns using the tabular environment. This environment takes one mandatory
argument which specifies the column justifications. Basic column justifications are: l (left justified), r (right justified)
and c (centred). The column specifier | indicates a vertical line should be placed there. Horizontal lines can be
added using

\hline

for a horizontal line spanning all columns, or

\cline{n-m}

for a horizontal line spanning columns n to m. Entries between columns are separated using the special character &.
For example:
\begin{tabular}{|l|c|}
\hline Item Cost
Item & Cost \\ \hline\hline
CD £11.75
CD & \pounds 11.75\\
Video £14.10
Video & \pounds 14.10\\ \hline
Total £25.85
Total & \pounds 25.85\\ \hline
\end{tabular}
Text can be placed spanning several columns using the command:

\multicolumn{n}{alignment}{text}

Introductory LATEX N.L.C.T. 9


where n is the number of columns to be spanned, alignment specifies the alignment (a single letter l, r or c with
optionally the vertical line specifier |) and text is the text to go in that entry.

Exercise 9
When creating tables, it’s best to start with a simple table, and then add to it.
e Try creating the output shown in Figure 6
! Modify this code so that it looks like the output shown in Figure 7. Notice that the last 4 columns are now
right justified, except for the first two rows. The entries in the header rows can be changed using \multicolumn
spanning a single column for each entry.
Note that the final table uses just one tabular environment where rows 3 and 7 span the entire table. Once you
have finished, try centering the entire table.

Year 1 Year 2 Year 3 Total


(£) (£) (£) (£)
Books 100.00 150.00 200.00 450.00
Stationary 50.00 45.00 55.00 150.00
Software 500.00 600.00 300.00 1400.00
US Conference 2000.00 2500.00 3000.00 7500.00
EU Conference 500.00 500.00 500.00 1500.00
Total 3150.00 3795.00 4055.00 11000.00

Figure 6: Exercise 9 — e Tabulated Material

Year 1 Year 2 Year 3 Total


(£) (£) (£) (£)
Equipment Expenditure
Books 100.00 150.00 200.00 450.00
Stationary 50.00 45.00 55.00 150.00
Software 500.00 600.00 300.00 1400.00
Travel Expenditure
US Conference 2000.00 2500.00 3000.00 7500.00
EU Conference 500.00 500.00 500.00 1500.00
Total 3150.00 3795.00 4055.00 11000.00

Figure 7: Exercise 9 — ! Tabulated Material

10 Basic Mathematics
There are two types or maths: “in-line” and “displayed”. In-line maths occurs within a line of text and is created
using the math environment. Displayed maths occurs on a line of its own. There are a number of environments used
to display maths, but the two basic ones are: displaymath and equation. The math environment has two shorthand
notations: \( . . . \) and $ . . . $. The displaymath and equation environments are for a single line of maths.
Subscripts are created using the command _{subscript}, and superscripts are created using the command ^{superscript}.
Fractions are produced using the command:

\frac{numerator}{denominator}

Roots are produced using the command:

\sqrt[n]{maths}

Functional names, such as log or sin, can be produced using \log, \sin etc. Lower case Greek letters, such as α or β,
can be produced using \alpha, \beta etc. Upper case Greek letters, such as Γ or ∆, can be produced using \Gamma,

Introductory LATEX N.L.C.T. 10


\Delta etc. Commands are only available for those letter that are different from the equivalent Roman letter (e.g.
there is no \omicron or \Alpha). Symbols whose size depends on whether they are in in-line or displayed maths are
shown in Table 8.

Table 8: Maths Symbols with Two Sizes


T \ S [ J K
\bigcap \bigcup \bigodot
N O L M F G
\bigotimes \bigoplus \bigsqcup
U ] W _ V ^
\biguplus \bigvee \bigwedge
Z I
` a R H
\coprod \int \oint
Q Y P X
\prod \sum

Exercise 10
e Produce the output shown in Figure 8, or ! produce the output shown in Figure 9.
You will need the following commands:
e and ! \Delta ∆
! \rightarrow or \to →
Once you have done this make the equation a numbered equation by using the equation environment instead of the
displaymath environment.

∆y y1 − y0
=
∆x x1 − x0

Figure 8: Exercise 10 — e Basic Mathematics

Given a function f (x), the derivative of f with respect to x can be found from first
principles using:
df f (x + ∆x) − f (x)
= lim
dx ∆x→0 ∆x

Figure 9: Exercise 10 — ! Basic Mathematics

11 Delimiters and Arrays


Delimiters are created using the commands:

\leftsymbol
\rightsymbol

where symbol is one of the symbols shown in Table 9 on page 11. Note that for every \left, you must have a
corresponding \right, however you can have an invisible delimiter by substituting symbol with a full stop.
Arrays are created using the array environment. This has exactly the same format as the tabular environment,
but can only be used in one of the maths environments.

Introductory LATEX N.L.C.T. 11


Table 9: Delimiters
( ( ) ) [ [ ] ]
\{ { \} } | | \| k
/ / \backslash \ \langle h \rangle i
\lfloor b \rfloor c \lceil d \rceil e
\uparrow ↑ \downarrow ↓ \Uparrow ⇑ \Downarrow ⇓
\updownarrow l \Updownarrow m

Exercise 11
e Produce the output shown in Figure 10, or ! produce the output shown in Figure 11. You will need the
following commands:
..
\cdots ··· \vdots .
..
\ddots . \neq 6=

Here we have a matrix equation:


   
5 3 10 6
2 =
2 6 4 12

Figure 10: Exercise 11 — e Arrays

This is an augmented matrix:


 
a11 ··· a1n b1
 .. .. .. .. 
 . . . . 
an1 ··· ann bn

The Kronecker delta is defined as follows:



1 i=j
δij =
0 i 6= j

Figure 11: Exercise 11 — ! Arrays

12 Multiline Formulæ
As mentioned earlier, the displaymath and equation environments only allow one line of mathematics. If you want
several lines, you will need to use a different environment. There are a number available, but the basic one is
eqnarray. This environment is predefined to have three columns, the first column is right aligned, the second is
centred and the third is left aligned. It is designed to allow you to have a number of equations, each aligned on the
= or similar symbol. Each line is numbered by default, however individual numbers can be removed by specifying
the command \nonumber on the appropriate line, or all numbering can be suppressed by using the starred form of
the environment: eqnarray*. As with tabular and array, column entries are separated using the & special character,
and rows are separated using the \\ command. Example:
\begin{eqnarray}
f & = & x^2 + x\\
f = x2 + x (1)
f’ & = & 2x + 1 0
\end{eqnarray} f = 2x + 1 (2)

Introductory LATEX N.L.C.T. 12


Exercise 12
e Produce the output shown in Figure 12, or ! produce the output shown in Figure 13. You will need the
following commands:

\approx ≈ \pm ±
\partial ∂ \leq ≤
\varepsilon ε

f (x) = x2 − x − 2
= (x − 2)(x + 1)

Figure 12: Exercise 12 — e Multiline Formulae

For |x| ≤ ±ε where ε is small:

f (x) = sin(x)
x3
≈ x−
6
Some partial differentiation:

f (x, y) = x2 + 2xy + y 2
∂f
= 2x + 2y
∂x

Figure 13: Exercise 12 — ! Multiline Formulae

13 Cross-Referencing
You should have noticed by now that LATEX automatically numbers various parts of the document, such as chapters
and equations. You can cross-reference these parts of the documents by first assigning a label to the place you want
to reference using the command:

\label{text}

The argument text can be anything you like, but it’s best to keep it relatively short and memorable, e.g. sec:intro
or ch:results. The \label command should come immediately after the command that generates the number, or
within the environment that generates the number. For example:

\section{Introduction}
\label{sec:intro}
or
\begin{equation}
E = mc^2
\label{eqn:einstein}
\end{equation}
Note that the \label command does not generate any text.
Once the label has been defined, it can be referenced using the command:

\ref{label}

Introductory LATEX N.L.C.T. 13


where the argument label is the label you defined with the \label command. For example, \ref{sec:intro} will
produce the number associated with the label sec:intro. Alternatively, you can reference the page on which the
label was defined using:

\pageref{label}

You can refer to a label that is defined later on in the document, however you will need to LATEX your source code
twice in order to get all the cross-references up-to-date. References to unknown labels are displayed with two question
marks: ??

Exercise 13
Try to reproduce the document shown in Figure 14. Don’t cheat by simply inserting the numbers, as that would
defeat the point of the exercise, make sure you use the \label and \ref commands.
! In addition try inserting an extra section between the introductory section and the section on Bayes’s Theorem,
and inserting an additional equation to see how LATEX automatically updates the cross-references. You could also
try inserting a title and table of contents as extra practice.

1 Introduction
The Rev Thomas Bayes was an 18th century cleric who was also a mathematician. His
theorem, known as Bayes’ Theorem and described in Section 2, was published posthumuously,
and it is only thanks to LaPlace that it is so well known, as many other academics at the
time failed to take the theorem seriously.

2 Bayes’ Theorem
Bayes’ Theorem is given in Equation 1, and simply states that the posterior of an event B
given that event A has occurred is proportional to the prior for event B.

P (A|B)P (B)
P (B|A) = (1)
P (A)
Equation 1 is fundamental to the whole study and implementation of Bayesian belief
networks.

Figure 14: Exercise 13 — Cross referencing

14 Packages
Packages are files with the extension .sty that either define new commands or redefine existing commands. If you
want to use a package, it must be specified with the command:

\usepackage[options]{package-name}

where package-name is the name of the package file, without the .sty extension, and options is a comma separated
list of options to be passed to the package. This command may only be used in the preamble. Any commands defined
in this package may now be used in the document.
New packages are being created all the time, so it is possible that the package you require is not installed on your
system. If this is the case, the package can be downloaded. Many packages are distributed with the documentation
and code all bundled up in one file with the extension .dtx. The file should come with an installation script, which
will have the extension .ins (or sometimes .drv). The documentation can be extracted by passing the .dtx file to
LATEX or PDFLATEX. The package (or class file) can be obtained by passing the installation script to LATEX.

Introductory LATEX N.L.C.T. 14


Exercise 14
If you are multilingual, you could try using the babel package. There are a great many different languages you
can choose from. You specify the name of the language as the package option. For example, if you are writing your
document in French, you can do:
\usepackage[francais]{babel}

Try using the babel package in the sectioning.tex file you edited in Exercise 4, and notice how the chapter and
table of contents headings have changed.
Alternatively, go back to the file you created in Exercise 13, and use the hyperref package to make your cross
references active links. Use PDFLATEX instead of LATEX to produce a PDF file. The option colorlinks will typeset
the links in colour instead of in a box. Note that you will need to delete the auxiliary file (.aux) before you LATEX
your document, as the hyperref package redefines the way the references are stored.
! If you haven’t already done so, add a title using the \maketitle command. Recall that if you don’t use
the \date command, today’s date will be used (generated by the command \today). Try changing the way this is
formatted using the datetime package. (You will need to download this package, and extract the code.)

15 Citations
Bibliographies can be created using the thebibliography environment. This is similar to the list making environments
described in Section 8, but instead of using \item you use the command:

\bibitem[label]{key}

where key is a unique identifier for this reference, and label can be used to override the default item label (this is
usually [1], [2], etc). The reference can then be cited in the document using the command:

\cite[text]{key-list}

where key-list is a comma separated list of unique identifiers defined in \bibitem, e.g. \cite{lamport,kopka},
and text is additional information about this reference, e.g. \cite[Chapter 4]{lamport}. The thebibliography
environment takes one compulsory argument that should be the widest label in the thebibliography environment.
Many people prefer to generate the thebibliography environment using the application BibTEX. You need to create
a separate file, with a .bib extension, that contains all your references (the bibliography database), and BibTEX will
only include the references that are cited within your document. BibTEX will also sort all the entries, and format
them in a consist manner.
In order to use BibTEX, you must first specify the bibliography database within your LATEX document using the
command:

\bibliography{filename}

where filename is the name of your database without the .bib extension. This command should go where you want
your bibliography to appear, usually at the end of your document (i.e. just before \end{document}).
There are many different bibliography styles. For example, you may want your references in alphabetic order,
or in order of citation. You may want your references numbered, or you may want them labelled according to the
author and year of publication. You specify the bibliography style you want using the command:

\bibliographystyle{style}

where style is the name of your bibliography style. Common styles are: plain, unsrt, alpha and abbrv.
Each entry in the bibliography database should be entered in the form:
@entry type{keyword ,
field = "text",
..
.
field = "text"
}

Introductory LATEX N.L.C.T. 15


For example:
@book{lamport,
author = "Leslie Lamport",
title = "\LaTeX\ : a document preparation system",
publisher = "Addison-Wesley",
edition = 2,
year = 1994
}

Multiple authors should be separated using the keyword and. For example:
@book{goossens,
author = "Michel Goossens and Frank Mittlebach and Alexander Samarin",
title = "The \LaTeX\ Companion",
publisher = "Addison-Wesley",
year = 1994
}
Once you have created your bibliography database, and edited your LATEX source code so that it includes the
commands \bibliographystyle and \bibliography, you need to LATEX the source code, then pass the auxilary file
(without the .aux extension) to BibTEX, and then LATEX the source code twice to ensure that all cross-references
are up-to-date.

Exercise 15
Produce a BibTEX database that contains the references shown in Figure 15 on page 17, and create the document
shown in that figure. You will need to create two files: exercise15.tex (to create the actual document) and
exercise15.bib (to create the bibliography database.) You will need the following entry types and fields:
Entry Type Fields
article author, title, journal, volume, number, pages, month, year
inproceedings author, title, booktitle, volume, address, pages, month, year
book author, title, edition, publisher, year
incollection author, title, booktitle, chapter, pages, editor, publisher, year

Try changing the bibliography style so that the entries are printed in order of citation. (You need the unsrt style for
this). Try other styles, such as alpha, abbrv and acm, to see the differences between styles. If you have a number of
citations, such as [3,2,4], you might prefer to have it printed as a range, such as [2–4], instead. There is a package
called citesort that redefines the \cite command to do this. Try using this package with the unsrt bibliography style.
! Try making your own customised bibliography style using makebst. Try typing
Ilatex makebst
at the command prompt, and follow the instructions. Then modify the argument to \bibliographystyle so that
your document uses this new style.

16 Lengths
LATEX has commands that represent lengths (e.g. \textwidth). There are two types of length:
rigid A fixed length, e.g. 4in

rubber A length with a certain amount of flexibility (e.g. 2in plus 0.1in minus 0.1in). This tells LATEX your
prefered length (in this case 2in) and the amount of deviation you are prepared to put up with. This allows
LATEX to stretch or compress white space in order to maintain a fully justified format.
Lengths can be changed using the command:

\setlength{cmd}{value}

Introductory LATEX N.L.C.T. 16


There is a very useful mathematics text book for engineering students written by Erwin
Kreyszig [2]. For those of you interested in the hazard from Clostridium botulinum associated
with Alaskan native foods should refer to [5]. For information on a fast index assignment
algorithm that uses quadratic assignment, see [3, 1, 4].

References
[1] Gavin Cawley and Nicola Talbot. A fast index assignment algorithm for vector quan-
tization over noisy transmission channels. I.E.E. Electronic Letters, 32(15):1343–1344,
July 1996.

[2] Erwin Kreyszig. Advanced Engineering Mathematics. Wiley, 6th edition, 1988.
[3] Nicola Talbot and Gavin Cawley. A quadratic index assignment algorithm for vector quan-
tisation over noisy transmission channels. In Proceedings of the Institute of Acoustics Au-
tumn Conference on Speech and Hearing, volume 18, pages 195–199, November 1996.

[4] Nicola Talbot and Gavin Cawley. A fast index assignment algorithm for robust vector
quantisation of image data. In Proceedings of the I.E.E.E. International Conference on
Image Processing, Santa Barbara, California, USA, October 1997.
[5] Robert B. Wainwright. Hazards from Northern native foods. In Andreas H. W. Hauschild
and Karen L. Dodds, editors, Clostridium botulinum: Ecology and control in Foods, chap-
ter 12, pages 305–322. Marcel Dekker, Inc, 1993.

Figure 15: Exercise 15 — Citations

which sets the length represented by the command cmd to value. Alternatively, you can extend a length using the
command:

\addtolength{cmd}{value}

This will add value to the length represented by cmd. If value is negative cmd will be make smaller. It is also possible
to set the length to the width, height or depth of a segment of text using the commands:

\settowidth{cmd}{text}
\settoheight{cmd}{text}
\settodepth{cmd}{text}

The text specified by text will not appear, as it is only used to calculate the appropriate lengths. The command
\settowidth will be used in the next section.
There are many predefined lengths, however you can define your own length using the command

\newlengthcmd

For example: \newlength\mylen will create a new length command called \mylen. The value (in points) of a length
can be displayed using the command:

\thecmd

For example: \the\mylen.


The page layout can be modified by changing the values of the lengths associated with the page layout (e.g.
\textwidth) however it is easier to use the geometry package.

Exercise 16
Go back to the document you created in Exercise 1, and change the paragraph indentation (\parindent) to 0pt,
and change the gap between paragraphs (\parskip) to 3ex.

Introductory LATEX N.L.C.T. 17


17 Boxes and Minipages
Everything on a page can be broken down into boxes, the simplest box being a single character. Each box has an
associated width, height and depth. The width is simply the width of the box, the height is the distance from the
baseline to the top of the box, and the depth is the distance from the baseline to the bottom of the box. This is
illustrated in Figure 16.

height

depth
y
width
height
a
width

Figure 16: Illustration of width, height and depth. The letter ‘y’ has a width, height and depth, whereas the letter
‘a’ has no depth. The baseline is indicated by the dashed line

Each box is treated as a single object, and can never be broken across a line. So if you want to prevent a group
of text from having a line break anywhere within that group, you can place the text in a box. The basic type of box
provided is

\mbox{text}

If you want to specify a size and justification within the box, you can use

\makebox[width][justification]{text}

The justification can either be l (left), r (right) or c (centred). Frames can be placed around the boxes using the
analogous commands:

\fbox{text}
\framebox[width][justification]{text}

The fancybox package provides the following commands, analogous to \fbox:

\ovalbox{text}
\Ovalbox{text}
\doublebox{text}
\shadowbox{text}

The above boxes can not contain more than a single line of text. To typeset a paragraph within a box, you can use
either the command:

\parbox[alignment][height]{width}{contents}

or using the environment:

\begin{minipage}[alignment][height]{width}{contents}

Boxes can be raised or lowered using the command:

\raisebox{lift}[depth][height]{contents}

Rectangular blobs of ink, known as rules, are created using the command:

\rule[lift]{width}{height}

Example:
\newlength\mylen
\settowidth{\mylen}{Some Text}%
Some Text
\makebox[0pt][l]{\rule[0.5ex]{\mylen}{1pt}}%
Some Text
You can store some typeset text for later use using a savebox. First you need to define your new savebox using
the command:

Introductory LATEX N.L.C.T. 18


\newsavebox{cmd}

where cmd is the name of the new command representing this box. Text can then be saved to this box either using
the command:

\sbox{cmd}{text}

or the environment:

\begin{lrbox}{cmd}
text
\end{lrbox}

The contents of a savebox can then be displayed using the command:

\usebox{cmd}

Exercise 17
e Try reproducing the output shown in Figure 17, or ! try reproducing the output shown in Figure 18. Hint:
the command \vfill will produce a vertical space that will stretch to fill the page, and \hfill will do the same
horizontally. The command \dotfill will produce dots that will fill the rest of the available space on the line.

Once upon a
time there were whereas the other was two inches
two minipages. wide, and they lived happily side
The first was 1 by side each inside an fbox.
inch wide

Figure 17: Exercise 17 — e Boxes and Minipages

This is a minipage that


is one and a quarter
inches wide. . . . . . . . . . . . .

And two inches high


//// in
height.
We can put a frame around a minipage:

Figure 18: Exercise 17 — ! Boxes and Minipages

Introductory LATEX N.L.C.T. 19


Self Assessment

• Try changing the alignment of the minipage.

• Try using a \parbox instead of a minipage. What do you think are the relative merits between using a
\parbox and a minipage?
• Try experimenting with different frames around the minipage.
• Try raising or lowering some of the text using the \raisebox command.

• ! Did you remember to specify a height for the minipage?

18 Incorporating Images
It is possible to generate images using LATEX picture drawing commands. The pstricks or pgf set of packages can
create very complex graphics, however most people find this too complicated. A more convenient approach is to
create the image using a graphics application, and import it into your LATEX document using the command:

\includegraphics[option-list]{filename}

which is defined in the graphicx package. Acceptable file types depend on the driver you are using. If you omit the
file extension, LATEX will usually look for a file of that name with the extension .ps or .eps, whereas PDFLATEX will
look for a file of that name with the extension .pdf or .png. For example, if you have the command:
\includegraphics{shapes}
then if you have the files shapes.ps and shapes.pdf, the PostScript image will be loaded if you are using LATEX,
and the PDF version will be loaded if you are using PDFLATEX.
The optional argument option-list is a comma separated list of options used to manipulate the image. Some of
the more common options are listed in Table 10 on page 20

Table 10: Common Options for \includegraphics

angle=x rotate the picture by x◦


width=len scale the picture so that the width is len.
height=len scale the picture so that the height is len.
scale=x scale the picture by x.
trim=lx by rx ty trim the picture so that the bottom left co-ordinate is (lx, by) and the top
right co-ordinate is (rx, ty).
draft don’t display the image, just draw the bounding box with the filename inside.

The graphicx package also provides the following commands:

\rotatebox{angle}{text}

Rotate text by angle.

\scalebox{h scale}[v scale]{text}

Rescales text. If only h scale is specified the aspect ratio is kept, otherwise if h scale and v scale are different, the
aspect ratio will change.

\reflectbox{text}

Reflect text

Introductory LATEX N.L.C.T. 20


\resizebox{h length}{v length}{text}

Resizes text so that it has width h length and height v length. An exclaimation mark ! can be used to maintain the
aspect ratio if only one length is specified.

Exercise 18
For this exercise, you will need to copy over the files shapes.ps and shapes.pdf, as described in the slides.
Create a document called exercise18.tex that includes the PostScript file shapes.ps or the PDF file shapes.pdf,
depending on whether you are using LATEX or PDFLATEX. You can centre it, if you like, using the command
\centerline. You could also try putting a box around it, using the \fbox command that we covered in the previous
section. Try scaling and rotating it.

19 Figures and Tables


Figures and Tables are floats — they are floated to the nearest convenient location according to certain typographical
rules. A figure or table has a caption and an associated number. Captions are produced using the command:

\caption[short caption]{caption text}

As you might expect, LATEX handles the caption numbering automatically, and floats can be cross-referenced using
\label and \ref.
Figures are created using the figure environment. Tables are created using the table environment. Note that figure
and table environments can not have a page break in them.
Subfigures can be created using the command

\subfigure[caption]{contents}

which is defined in the package subfigure.


List of figures and list of tables are created using the commands:

\listoffigures
\listoftables

These commands typically go after the table of contents.

Exercise 19
For this exercise, you will need to copy over the files circle.ps (or circle.pdf) and rectangle.ps (or
rectangle.pdf), as described in the slides. Create a document called exercise19.tex that contains Figures 19
and 20, and Table 11. Remember to refer to them using \ref.

Figure 19: Some shapes

Introductory LATEX N.L.C.T. 21


(a) A Circle (b) A Rectangle

Figure 20: (a) A Circle, (b) A Rectangle

Table 11: An example table

A B
I 0.5 1.0
II 12 14

20 Slides
There are a number of class files available for creating slides. The simplest is slides, but there are far more complex
ones such as beamer and prosper which can produce very professional looking presentations. This course describes
the seminar class file. If you are interested in any of the other class files, you should read their accompanying
documentation.
Each slide is created using a slide (landscape) or slide* (portrait) environment. Any text outside either of these
environments will be treated as notes. The presentation can be converted into an article (e.g. for handouts) using
the article class option.
It is possible to mix landscape and portrait slides within the same document (but not recommended), however
you will have to print the landscape and portrait slides out separately. You can display only the landscape or only
the portrait slides using the commands:

\landscapeonly
\portraitonly

These commands must occur in the preamble.


You can specify only the slides or only the notes by passing the options slidesonly or notesonly to the class
file. (So you can print the slides on transparencies and the notes on paper.)
Slide frames can be changed using the command:

\slideframe{style}

Basic styles are: none and plain. If you use the fancybox package, the following styles are also available: shadow,
double, oval and Oval. New page styles can be defined using the command:

\newpagestyle{name}{header}{footer}

Exercise 20
Try to produce some of the slides that have been used during this course. Make sure you have a title slide,
and try adding some notes outside of the slide environment. Try using the article option to the seminar class file:
\documentclass[article]{seminar}.

21 Defining New Environments


New environments can be defined using the command:

\newenvironment{env-name}[n][default]{begin-code}{end-code}

Introductory LATEX N.L.C.T. 22


where n is the number of arguments and default is the default value of the first argument if an optional argument
is required (as with \newcommand). As with \newcommand each argument is presented by #1, #2 etc, and these
arguments can only be accessed in the begin-code section.

Exercise 21
Define an environment that draws a horizontal line at the start of the environment and a horizontal line at the
end of the environment, like the exercises in this handout.
Note: The command \noindent can be used to suppress paragraph indentation. This will prevent a small space
occurring before the rule if it occurs at the start of a new paragraph.
! Try adding the little vertical stubs at the end of the lines as well.

22 Counters
All the numbers that LATEX automatically generates (such as section numbers) are stored in counters. New counters
can be defined using the command:

\newcounter{ctr-name}[outer-ctr]

For example: \newcounter{exercise}. The optional argument outer-ctr indicates that this new counter should be
reset every time the counter outer-ctr is incremented. For example: \newcounter{exercise}[chapter] will reset
the exercise counter at the start of every chapter.
Counters only store integers, and the value can be changed using one of the following commands:

\stepcounter{ctr}

increments the counter ctr by 1.

\refstepcounter{ctr}

increments the counter by 1, but allows you to reference it using \ref and \label.

\setcounter{ctr}{value}

sets the counter to value.

\addtocounter{ctr}{value}

adds value to the counter. If the value of another counter is needed for the value part, use

\value{ctr}

The value of the counter can be displayed using the command \thectr. For example: \thepage prints the value
of the page counter. By default, \thectr displays the value as an Arabic number, however this command can be
redefined. The following commands are available to display the value of a particular counter:

\arabic{ctr}
\roman{ctr}
\Roman{ctr}
\alph{ctr}
\Alph{ctr}
\fnsymbol{ctr}

These commands display the value of the counter as, respectively, an Arabic number, lower case Roman numeral,
upper case Roman numeral, lower case alphabetical character, upper case alphabetical character and a footnote
symbol. (Note that \fnsymbol can only be used in maths mode.) For example:
\renewcommand{\thechapter}{\Roman{chapter}}
will change the chapter numbers to upper case Roman numerals.

Introductory LATEX N.L.C.T. 23


Exercise 22
Modify the environment you created in Exercise 21 so that it prints the exercise number as in the handouts.
Make sure you have at least 2 exercise environments to make sure the counter is being incremented correctly. Try
referencing them using the \ref command.
Hint: at the start of each exercise, the exercise counter will need to be incremented before its value is printed.
Once you have done this, try redefining \theexercise so that the exercise number appears as an uppercase
Roman numeral.
! Modify your code so that the exercises are dependent on the sections. (Remember to include some \section
commands in your document.)

23 Conditionals
As with all programming languages, TEX has conditionals. The ifthen package defines the conditional commands:

\ifthenelse{test}{then text}{else text}


\whiledo{test}{do text}

The first argument, test, is a boolean statement. Boolean variables can be defined using the command:

\newboolean{name}

The boolean variable can be assigned a value using:

\setboolean{name}{value}

where value is either true or false. The value of a boolean variable can be tested using:

\boolean{name}

Two strings can be tested to see if they are equal using the command:

\equal{string 1}{string 2}

Numbers can be compared using <, = and >. Note that if you want to compare the value of a counter you will need
to use \value{counter-name}. To test whether a counter is odd use the command:

\isodd{counter-name}

For example:
\ifthenelse{\isodd{page}}{This page is odd}{This page is even}
produces the text: This page is even
Lengths can be tested using the command:

\lengthtest{relation}

For example:

This page is in
\ifthenelse{\lengthtest{\textwidth > \textheight}}{landscape}{portrait}
orientation.
produces the text: This page is in portrait orientation.

24 Writing a New Package or Class File


If you want to write a new package, you need to create a file with the extension .sty. The very first line of this file
should be:

Introductory LATEX N.L.C.T. 24


\NeedsTeXFormat{LaTeX2e}
Next you need to specify the name of the package using the command:

\ProvidesPackage{name}

This should be the same name as the name of the file without the .sty extension. The very last line of the file
should have the command:

\endinput

Package options can be defined using the command

\DeclareOption{option name}{code}

The default action for any undefined option is specified using the command:

\DeclareOption*{default-code}

Within default-code, the following commands may be used:


\CurrentOption name of current option
\OptionNotUsed Marks this option as being unprocessed.
Once the options have been defined, they can then be processed using the commands:
\ExecuteOptions{options} list of default options
\ProcessOptions process in order defined
\ProcessOptions* process in order specified.
It is also possible to pass options to another package using

\PassOptionsToPackage{option-list}{package-name}

The named package must later be loaded using:

\RequirePackage{package-name}

Writing a class file is very similar to writing a package, except: you need to give the file the extension .cls
instead of .sty, use \ProvideClass instead of \ProvidePackage, and you can use the command:

\PassOptionsToClass{option-list}{class-name}

in which case you will later need to load the named class file using:

\LoadClass{class-name}

Note that you can only load one class, but you can load as many packages as you like (using \RequirePackage).
One thing to note when you are writing class files or packages is the behaviour of the @ character. In a normal
.tex file, the @ character is treated the same as any other normal punctuation character, however in a class or
package, the @ character is treated as a letter. This means that within a .sty or .cls file, command names can
contain the @ character, whereas they can’t within a .tex file. For example, within a .sty or .cls file \c@page is
a command (the TEX register representing the page counter) whereas within a .tex file \c@page will produce the
output: @ ¸ page. Commands containing the @ character are known as internal commands, and should only be used
in class files or packages.
Sections, subsections etc headings can be changed by redefining \section, \subsection etc. These commands
should use the command:

\@startsection{type}{level}{indent}{before-skip}{after-skip}{style}

To change the chapter or part headings (if you are using the report class file), you need to redefine the commands:
\@makechapterhead (numbered chapters), \@makechapterhead* (unnumbered chapters), \@part (numbered parts)
and \@spart (unnumbered parts). The easiest way to do this is to copy the code over from the class file, and modify
the appropriate formatting commands.

Introductory LATEX N.L.C.T. 25


Exercise 23
Write a class file that loads the report class file and that modifies the chapter headings so that a line appears
above and below the heading and the heading appears in small capitals centred, and modifies the section headings
so that they appear in a large sans-serif font.
Modify the document you used in Exercise 4 so that it uses your new class file instead of the report class file.

Recommended Reading
[1] “A Guide to LATEX 2ε : document preparation for beginners and advanced users”, Helmut Kopka and Patrick W.
Daly, Addison-Wesley (1995).

[2] “The LATEX Companion”, Michel Goossens, Frank Mittelbach and Alexander Samarin (Addison-Wesley, 1994).
[3] “The LATEX Graphics Companion”, Michel Goossens, Sebastian Rahtz and Frank Mittelbach, Addison-Wesley
(1997).
[4] “The LATEX Web Companion”, Michel Goossens and Sebastian Rahtz, Addison-Wesley (1999).

Introductory LATEX N.L.C.T. 26

You might also like